diff --git a/.config/dotnet-tools.json b/.config/dotnet-tools.json new file mode 100644 index 0000000..1490bfb --- /dev/null +++ b/.config/dotnet-tools.json @@ -0,0 +1,13 @@ +{ + "version": 1, + "isRoot": true, + "tools": { + "docfx": { + "version": "2.81.0", + "commands": [ + "docfx" + ], + "rollForward": false + } + } +} diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..36c008d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,19 @@ +--- +name: Bug report +about: The panel, the launcher or an image does not work as described +labels: bug +--- + +**Revit Server Stack version** (the zip name, or the commit): + +**Revit Server version(s) concerned** (2020 to 2027): + +**Docker Desktop version and engine mode** (Windows containers or remote context): + +**What you did**: + +**What you expected**: + +**What happened** (error text, the startup log from the tray icon menu, the job log of the panel): + +Please remove tokens, licence keys and customer paths from logs before attaching them. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..5ee0911 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,11 @@ +--- +name: Feature request +about: Suggest an improvement +labels: enhancement +--- + +**What do you want to do?** + +**What happens today?** + +**Which Revit Server versions or parts (panel, launcher, proxy, Dockerfiles) does it concern?** diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..e8563fb --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,9 @@ +## What changes and why + +## How it was checked + +- [ ] `powershell -NoProfile -ExecutionPolicy Bypass -File panel\tests\Invoke-Tests.ps1` passes +- [ ] A check is added or updated when the behaviour of the panel changes +- [ ] `CHANGELOG.md` has a line about the change under "Unreleased" +- [ ] Dockerfile changes: the versions that were built and started are listed above +- [ ] No installers, Revit models or customer data are added diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..ca79ca5 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..0189b52 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,35 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + +permissions: + contents: read + +jobs: + test: + runs-on: windows-latest + steps: + - uses: actions/checkout@v7 + - name: Tool versions + shell: pwsh + run: | + # The self-checks skip what needs the docker CLI; this shows which ones did. + git --version + if (Get-Command docker -ErrorAction SilentlyContinue) { docker --version; docker compose version } else { 'no docker CLI' } + node --version + exit 0 + - name: Self-checks + shell: pwsh + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File panel/tests/Invoke-Tests.ps1 + if ($LASTEXITCODE -ne 0) { throw "Invoke-Tests.ps1 failed with exit code $LASTEXITCODE" } + - name: Build the launcher + shell: pwsh + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File launcher/Build.ps1 -OutDir "$env:RUNNER_TEMP/launcher" + if ($LASTEXITCODE -ne 0) { throw "Build.ps1 failed with exit code $LASTEXITCODE" } + - name: Syntax of the panel script + run: node --check panel/www/app.js diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml new file mode 100644 index 0000000..ef5b8dd --- /dev/null +++ b/.github/workflows/docs.yml @@ -0,0 +1,56 @@ +name: Docs + +on: + push: + branches: [master] + paths: + - 'docs/**' + - 'docfx.json' + - '.config/dotnet-tools.json' + - '*.md' + - '.github/workflows/docs.yml' + pull_request: + paths: + - 'docs/**' + - 'docfx.json' + - '.config/dotnet-tools.json' + - '*.md' + - '.github/workflows/docs.yml' + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: pages-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-dotnet@v6 + with: + dotnet-version: 8.0.x + - run: dotnet tool restore + - run: dotnet docfx docfx.json --warningsAsErrors + # manifest.json records the build machine paths and is not part of the site. + - run: rm _site/manifest.json + - uses: actions/upload-pages-artifact@v5 + with: + path: _site + + deploy: + if: github.ref == 'refs/heads/master' && github.event_name != 'pull_request' + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v5 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..bb4ec7e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,49 @@ +name: Release + +on: + push: + tags: ['v*'] + +permissions: + contents: write + +jobs: + release: + runs-on: windows-latest + steps: + - uses: actions/checkout@v7 + # The tag must name the newest CHANGELOG entry, and that entry must be a version, not "Unreleased". + - name: Check the tag against CHANGELOG.md + shell: pwsh + run: | + $heading = Get-Content -LiteralPath CHANGELOG.md -Encoding utf8 | Where-Object { $_.StartsWith('## [') } | Select-Object -First 1 + if (-not $heading) { throw 'CHANGELOG.md has no "## [" entry.' } + $version = [regex]::Match($heading, '^## \[([^\]]+)\]').Groups[1].Value + if ($version -eq 'Unreleased') { throw 'The newest CHANGELOG.md entry is "Unreleased": give it a version and a date before tagging.' } + if ($version -notmatch '^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$') { throw "The newest CHANGELOG.md entry [$version] is not a version." } + if ($env:GITHUB_REF_NAME -cne "v$version") { throw "The tag $env:GITHUB_REF_NAME does not match the newest CHANGELOG.md version v$version." } + "VERSION=$version" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append + - name: Self-checks + shell: pwsh + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File panel/tests/Invoke-Tests.ps1 + if ($LASTEXITCODE -ne 0) { throw "Invoke-Tests.ps1 failed with exit code $LASTEXITCODE" } + - name: Build the release archive + shell: pwsh + run: | + powershell -NoProfile -ExecutionPolicy Bypass -File launcher/Build.ps1 -Release + if ($LASTEXITCODE -ne 0) { throw "Build.ps1 failed with exit code $LASTEXITCODE" } + - name: Create the GitHub release + shell: pwsh + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + $zip = "dist/RevitServerStack-$env:VERSION.zip" + foreach ($file in $zip, "$zip.sha256", 'dist/RELEASE_NOTES.md') { + if (-not (Test-Path -LiteralPath $file)) { throw "$file was not built." } + } + # A version with a hyphen is a prerelease. + $flags = @() + if ($env:VERSION.Contains('-')) { $flags += '--prerelease' } + gh release create $env:GITHUB_REF_NAME --title "Revit Server Stack $env:VERSION" --notes-file dist/RELEASE_NOTES.md @flags $zip "$zip.sha256" + if ($LASTEXITCODE -ne 0) { throw "gh release create failed with exit code $LASTEXITCODE" } diff --git a/.gitignore b/.gitignore index a2b4aa6..29f572f 100644 --- a/.gitignore +++ b/.gitignore @@ -10,6 +10,9 @@ # samples. Anchored, so src/rs/Dockerfile stays tracked. /samples/rs20*/ +# Docs site build (docfx) +/_site/ + # Release build: RevitServerStack.exe, the archive and its checksum (launcher/Build.ps1) /dist/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 5d54c2e..2752523 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,20 +2,39 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow [Semantic Versioning](https://semver.org/). -## [Unreleased] +## [1.2.0] - 2026-11-14 ### Added - The panel, the messages it sends and its console window are translated into English, Russian, German, French, Spanish, Brazilian Portuguese, Simplified Chinese and Japanese. The panel starts in the language of the browser (English when it is not available), a selector in the header changes it and the choice is remembered. The menu of the tray icon follows the language of Windows. Texts live in `panel/www/i18n/*.json`, used by the page and by PowerShell alike. How to fix or add a language: [CONTRIBUTING.md](CONTRIBUTING.md#translations). - Self-checks of the translations: every catalog has the keys, placeholders and markup of English, no text is left in code, every key is used, and the tray menu has all languages. +- Documentation site at (built with docfx from the READMEs), a logo, and links to DeepWiki. +- GitHub Actions: CI runs the self-checks and builds the launcher on every push and pull request; a pushed tag `vX.Y.Z` builds the release archive and publishes the GitHub release. How to cut a release: [CONTRIBUTING.md](CONTRIBUTING.md). +- Optional integrity check of the Autodesk installers: when `RS_INSTALLER_SHA256` is set (or `--build-arg INSTALLER_SHA256=...` is given to `docker build`), the Dockerfiles compare the downloaded installer with that SHA-256 and fail the build on a mismatch. No hashes are pinned in the repository, see "Verifying the installers" in the README. +- Self-checks for the panel back end: saving settings, the settings check at start-up, port 808, `$` in paths of the generated compose files, static paths with `:`, job ids, the result of Start all and Stop all, the job runner (exit code, log, `%` in a command line, cancel), the session token. ### Changed +- Upgrade note: the installer step of the Dockerfiles of all eight versions changed (the optional integrity check), so Docker does not reuse the cached installer and later layers of images built before this update. The first build after updating runs the installer again (the images are about 14 GB); later builds use the cache. The check cannot be moved to a separate step to avoid this: any new step in front of the installer changes the cache chain too, and a step after it would run after the installation. - The console window of the panel is no longer Russian only: it speaks the language of Windows. - The English README names buttons and settings as the English interface does, instead of the Russian ones. ### Fixed +- Saving settings with a partial body (or a body that is not a JSON object) reset every setting not mentioned to its default. It now changes only what the body names and refuses a body that is not an object. +- A hand-edited `panel.config.json` with an invalid value (a port that is not a number, a bad context or project name) was not checked at start-up and crashed the panel with a raw .NET error. It is now checked like a save; an invalid file is reported, kept as `panel.config.json.invalid.bak` (the next save overwrites the file) and the default settings are used. +- Settings check: host port 808 is refused when a version needs 808 for Revit, and a disabled version no longer counts as an owner of port 808. +- A `$` in the models folder or in the path of the repository was interpolated by docker compose and mounted another folder. It is now escaped in the generated compose files. +- A request for a static path with `:` (`/C:/x`, `/index.html::$DATA`) answered HTTP 500 with the text of the .NET exception; it answers 404 now. +- Cancelling a job accepted any id and always reported success. The id is validated like the one of the log request, and a job whose process could not be stopped is no longer marked cancelled; the page says when a cancel did not happen. +- A malformed JSON body was reported as an empty body or as missing fields; it is now answered with "not valid JSON". +- The session token came from a time-seeded generator; it is now 32 random bytes of the system's cryptographic generator, and it is compared in constant time. +- A `%` in a path (for example a repository in a folder named `x%TEMP%y`) was expanded by cmd.exe in the job wrapper and corrupted the docker command. +- Start all and Stop all answered `ok: true` even when every target failed; they now answer `ok: false` with HTTP 409 when any target failed. +- The documented run without the panel failed on a fresh clone because `samples\rs` did not exist; the README now creates it first. +- The log of a job could repeat or lose lines when two requests overlapped, and a single failed request stopped the live log and hid the Cancel button. Requests are now one at a time, and a failure is retried and reported after several in a row. +- The page stayed blank without a word when the language files could not be loaded; it now says so and still starts. +- Exit in the tray menu froze the icon for 3 seconds and then killed the panel, leaving its address file behind, and a second start could then open a dead address. The panel is stopped at once, and the address file is removed on exit and when the panel fails. - Settings did not open when docker had exactly one context: the list of contexts was sent as a single string, not as a list. ## [1.1.0] - 2026-10-15 @@ -82,5 +101,6 @@ First public release. - The Dockerfiles for 2026 and 2027 were written against the downloaded installers: the MSI properties, file layout and IIS names were read from them, and the unpacking step was run on the host. No image was built for this release. - The existing names are kept so that images that are already built stay in use: compose project `samples`, containers `rs` and `revit-proxy`, models in `samples/rs`. +[1.2.0]: https://github.com/mahach666/RevitServerStack/compare/v1.1.0...v1.2.0 [1.1.0]: https://github.com/mahach666/RevitServerStack/compare/v1.0.0...v1.1.0 [1.0.0]: https://github.com/mahach666/RevitServerStack/releases/tag/v1.0.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 66a3375..6791211 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,12 +44,28 @@ powershell -NoProfile -ExecutionPolicy Bypass -File launcher\Build.ps1 -Release The version comes from the newest `## [x.y.z]` entry of `CHANGELOG.md`. `-Release` packs the files git would commit (tracked and new, ignored ones left out) plus the exe into `dist\RevitServerStack-.zip`, and writes `.sha256` and `RELEASE_NOTES.md` next to it. -To publish: update `CHANGELOG.md`, commit, run the self-checks and the release build, then +## Cutting a release + +The release workflow (`.github/workflows/release.yml`) builds and publishes everything when a tag `v` is pushed. + +1. In `CHANGELOG.md` turn the "Unreleased" heading into `## [x.y.z] - YYYY-MM-DD` (a hyphen in the version, `x.y.z-rc.1`, makes a prerelease) and add the compare link at the bottom. The newest entry is the version of the release, so keep a new empty "Unreleased" out of the file until the next change. +2. Run the self-checks and the release build locally if you like: `Invoke-Tests.ps1` above, and `launcher\Build.ps1 -Release` (writes to `dist\`). +3. Merge to `master`, then tag that commit and push the tag: + + ``` + git tag -a v -m "Revit Server Stack " + git push origin v + ``` + +The workflow fails before building when the tag is not `v` plus the newest `CHANGELOG.md` version or when that entry is "Unreleased". Otherwise it runs the self-checks, builds `RevitServerStack-.zip` with its `.sha256` and `RELEASE_NOTES.md`, and creates the GitHub release "Revit Server Stack " with the notes and both files. The release workflow has no NuGet or other publishing step. + +## Documentation site + +The site at is built by docfx from `README.md`, `README.ru.md`, `CONTRIBUTING.md`, `CHANGELOG.md`, `CREDITS.md`, `SECURITY.md` and `LICENSE.md` together with `docs/index.md` and `docs/toc.yml`, so there is no second copy of the text. Links in those files must be relative paths between them or absolute URLs (the build runs with warnings as errors). To preview it: ``` -git tag -a v -m "Revit Server Stack " -git push origin v -gh release create v dist\RevitServerStack-.zip dist\RevitServerStack-.zip.sha256 --title "Revit Server Stack " --notes-file dist\RELEASE_NOTES.md +dotnet tool restore +dotnet docfx docfx.json --serve ``` ## Moving Revit Server 2026 or 2027 to a new update diff --git a/README.md b/README.md index ac1016c..ae1e59c 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,17 @@ +

+ Revit Server Stack +

+ +

+ Latest release + CI + Docs + Ask DeepWiki +

+ # Revit Server Stack -[Русская версия](README.ru.md) +[Русская версия](README.ru.md) | [Documentation site](https://mahach666.github.io/RevitServerStack/) Run Autodesk Revit Server 2020 to 2027 in Docker on one Windows machine, several versions side by side, and manage them from a small local web panel. @@ -26,7 +37,7 @@ The Dockerfiles for Revit Server 2020 to 2025 come from [dosymep/revit-server-do ## Quick start -1. Download `RevitServerStack-.zip` from the [Releases](../../releases) page and unpack it. The folder keeps your settings and, by default, the models (`samples\rs`), so unpack it on a disk with enough free space. +1. Download `RevitServerStack-.zip` from the [Releases](https://github.com/mahach666/RevitServerStack/releases) page and unpack it. The folder keeps your settings and, by default, the models (`samples\rs`), so unpack it on a disk with enough free space. 2. Run `RevitServerStack.exe`. An icon appears in the notification area and the panel opens in the browser at `http://localhost:8787/`. The icon menu has "Open the panel", "Startup log" and "Exit". Exit stops the panel, not the containers. 3. Find the card of the version you need and press "Build and start". The output of the build is shown live. 4. When the card shows that the version is running, open the admin page: @@ -76,12 +87,15 @@ Revit Server itself is different. The version ports and the proxy port are publi ## Run without the panel -A Revit Server version, on the Windows engine: +A Revit Server version, on the Windows engine. The models folder has to exist first, because the Windows engine does not create a missing bind source (the panel creates it for you; a fresh clone has no `samples\rs2022`): ``` +if not exist samples\rs2022 mkdir samples\rs2022 docker --context desktop-windows compose -f samples\docker-compose.2022.yml up -d --build ``` +In PowerShell the first line is `New-Item -ItemType Directory -Force samples\rs2022 | Out-Null`. + The proxy, on the Linux engine (the default context): ``` @@ -90,6 +104,16 @@ docker compose -f samples\docker-compose.proxy.yml up -d Replace `up -d --build` with `stop` or `down` to stop or remove. The samples publish only the HTTP port (`2022:80`). To let Revit connect, add `- '808:808'` to the `ports` list of one version. The sample `nginx.conf` routes all eight versions, while the panel generates a config for the enabled ones only. +## Verifying the installers + +The Dockerfiles download the Autodesk installers over HTTPS. The repository does not pin their SHA-256: Autodesk may re-publish a file under the same address, and a hash that was not checked against the vendor would be worse than none. If you want the build to fail when the download is not the file you expect, give it the SHA-256 of that file (from Autodesk, or `Get-FileHash -Algorithm SHA256` on a copy you trust): + +- with the panel or the tray icon: set the environment variable `RS_INSTALLER_SHA256` (for example `RS2022_INSTALLER_SHA256`) before starting them; +- with the compose samples: set the same variable in the shell before `docker compose ... up -d --build`; +- with `docker build` directly: `docker build --build-arg INSTALLER_SHA256= src\rs2022`. + +An empty value, the default, means no check. For 2026 and 2027 the hash is that of the `.sfx.exe` installer (the 7-Zip helper is pinned already). The check runs when the image is built, so rebuild an existing image after setting the value. Note: after updating to this version the first build of every image runs the installer again (about 14 GB), because the installer step of the Dockerfiles changed; later builds use the cache. + ## Docker on another computer The Revit Server containers can run on a server or on another PC while the panel stays on yours. The panel drives Docker through docker contexts, so any engine docker can reach works. diff --git a/README.ru.md b/README.ru.md index 72dd617..a615f18 100644 --- a/README.ru.md +++ b/README.ru.md @@ -1,6 +1,17 @@ +

+ Revit Server Stack +

+ +

+ Latest release + CI + Docs + Ask DeepWiki +

+ # Revit Server Stack -[English version](README.md) +[English version](README.md) | [Сайт документации](https://mahach666.github.io/RevitServerStack/) Запускайте Autodesk Revit Server 2020-2027 в Docker на одном компьютере с Windows, несколько версий одновременно, и управляйте ими из небольшой локальной веб-панели. @@ -26,7 +37,7 @@ Dockerfile для Revit Server 2020-2025 взяты из [dosymep/revit-server-d ## Быстрый старт -1. Скачайте `RevitServerStack-<версия>.zip` на странице [Releases](../../releases) и распакуйте. В этой папке хранятся ваши настройки и, по умолчанию, модели (`samples\rs<год>`), поэтому распакуйте её на диск с достаточным свободным местом. +1. Скачайте `RevitServerStack-<версия>.zip` на странице [Releases](https://github.com/mahach666/RevitServerStack/releases) и распакуйте. В этой папке хранятся ваши настройки и, по умолчанию, модели (`samples\rs<год>`), поэтому распакуйте её на диск с достаточным свободным местом. 2. Запустите `RevitServerStack.exe`. В области уведомлений появится значок, а панель откроется в браузере по адресу `http://localhost:8787/`. В меню значка есть «Открыть панель», «Журнал запуска» и «Выход». Выход останавливает панель, но не контейнеры. 3. Найдите карточку нужной версии и нажмите «Собрать и запустить». Вывод сборки виден в реальном времени. 4. Когда карточка покажет, что версия работает, откройте страницу администратора: @@ -76,12 +87,15 @@ Revit работает с Revit Server по WCF net.tcp через порт 808, ## Работа без панели -Версия Revit Server на Windows-движке: +Версия Revit Server на Windows-движке. Папка с моделями должна существовать заранее: Windows-движок не создаёт отсутствующий источник bind-монтирования (панель создаёт её сама, а в свежем клоне `samples\rs2022` нет): ``` +if not exist samples\rs2022 mkdir samples\rs2022 docker --context desktop-windows compose -f samples\docker-compose.2022.yml up -d --build ``` +В PowerShell первая строка это `New-Item -ItemType Directory -Force samples\rs2022 | Out-Null`. + Прокси на Linux-движке (контекст по умолчанию): ``` @@ -90,6 +104,16 @@ docker compose -f samples\docker-compose.proxy.yml up -d Чтобы остановить или удалить, замените `up -d --build` на `stop` или `down`. Примеры публикуют только HTTP-порт (`2022:80`). Чтобы Revit мог подключиться, добавьте `- '808:808'` в список `ports` одной из версий. Пример `nginx.conf` маршрутизирует все восемь версий, а панель создаёт конфиг только для включённых. +## Проверка установщиков + +Dockerfile скачивают установщики Autodesk по HTTPS. SHA-256 в репозитории не зафиксированы: Autodesk может переопубликовать файл по тому же адресу, а хеш, не сверенный с производителем, хуже его отсутствия. Если нужно, чтобы сборка падала, когда скачан не тот файл, передайте SHA-256 нужного файла (от Autodesk или `Get-FileHash <файл> -Algorithm SHA256` для копии, которой вы доверяете): + +- для панели и значка в трее: задайте переменную окружения `RS<год>_INSTALLER_SHA256` (например `RS2022_INSTALLER_SHA256`) до их запуска; +- для примеров compose: задайте ту же переменную в оболочке перед `docker compose ... up -d --build`; +- для прямого `docker build`: `docker build --build-arg INSTALLER_SHA256=<хеш> src\rs2022`. + +Пустое значение (по умолчанию) означает, что проверки нет. Для 2026 и 2027 хеш относится к установщику `.sfx.exe` (помощник 7-Zip уже закреплён). Проверка выполняется при сборке образа, поэтому после задания значения пересоберите уже существующий образ. Важно: после обновления до этой версии первая сборка каждого образа снова запускает установщик (около 14 ГБ), потому что шаг установщика в Dockerfile изменился; последующие сборки используют кэш. + ## Docker на другом компьютере Контейнеры Revit Server могут работать на сервере или на другом компьютере, а панель остаётся на вашем. Панель управляет Docker через docker-контексты, поэтому подойдёт любой движок, до которого дотягивается docker. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..66f4f11 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,21 @@ +# Security policy + +## Supported versions + +Security fixes are made on the latest release only. + +## Reporting a vulnerability + +Please do not open a public issue for a security problem. Use GitHub private vulnerability reporting: open the Security tab of the repository and choose "Report a vulnerability". Include the version of Revit Server Stack, what you did and what happened. Do not send files with confidential content, logs with tokens or Autodesk installers. + +You can expect an acknowledgement within a few days. Fixes are released as soon as they are verified, and the report is credited unless you prefer otherwise. + +## Scope + +Problems that matter most: + +- a web page or a local program that can drive docker through the control panel without the session token, or reach the panel through another Host header; +- a path or a name that reaches a command line, a compose file or the file system without being validated (command injection, path traversal in the panel); +- a release archive that contains local data, or a Dockerfile step that runs unverified code when `INSTALLER_SHA256` is set. + +Out of scope: the Autodesk installers and Revit Server itself, and exposure of the Revit Server ports to a network, which is how the stack is meant to be used (see "Security" in the README). diff --git a/docfx.json b/docfx.json new file mode 100644 index 0000000..844e16f --- /dev/null +++ b/docfx.json @@ -0,0 +1,24 @@ +{ + "build": { + "content": [ + { "src": "docs", "files": ["index.md", "toc.yml"] }, + { + "src": ".", + "files": ["README.md", "README.ru.md", "CONTRIBUTING.md", "CHANGELOG.md", "CREDITS.md", "SECURITY.md", "LICENSE.md"], + "dest": "." + } + ], + "resource": [ + { "src": "docs", "files": ["images/**"] } + ], + "output": "_site", + "globalMetadata": { + "_appTitle": "Revit Server Stack", + "_appLogoPath": "images/revitserverstack-logo.svg", + "_appFaviconPath": "images/revitserverstack-logo.svg", + "_appFooter": "Revit Server Stack is licensed under the MIT License. Not affiliated with Autodesk or Docker.", + "_enableSearch": true + }, + "template": ["default", "modern"] + } +} diff --git a/docs/images/revitserverstack-banner.png b/docs/images/revitserverstack-banner.png new file mode 100644 index 0000000..563dd74 Binary files /dev/null and b/docs/images/revitserverstack-banner.png differ diff --git a/docs/images/revitserverstack-banner.svg b/docs/images/revitserverstack-banner.svg new file mode 100644 index 0000000..21a9f9d --- /dev/null +++ b/docs/images/revitserverstack-banner.svg @@ -0,0 +1 @@ +RevitServerStackRevit Server 2020-2027 side by side in Docker diff --git a/docs/images/revitserverstack-logo.svg b/docs/images/revitserverstack-logo.svg new file mode 100644 index 0000000..142dce6 --- /dev/null +++ b/docs/images/revitserverstack-logo.svg @@ -0,0 +1 @@ + diff --git a/docs/index.md b/docs/index.md new file mode 100644 index 0000000..ec9bc57 --- /dev/null +++ b/docs/index.md @@ -0,0 +1,17 @@ +--- +title: Revit Server Stack +--- + +# Revit Server Stack + +Run Autodesk Revit Server 2020 to 2027 in Docker on one Windows machine, several versions side by side, and manage them from a small local web panel. + +## Where to go next + +- [Guide](../README.md): requirements, quick start, the control panel, running without it, troubleshooting. Download `RevitServerStack-.zip` from [Releases](https://github.com/mahach666/RevitServerStack/releases). +- [Руководство на русском](../README.ru.md). +- [Contributing](../CONTRIBUTING.md): self-checks, translations, how to cut a release. +- [Changelog](../CHANGELOG.md) and [security policy](../SECURITY.md). +- [Source on GitHub](https://github.com/mahach666/RevitServerStack) and [DeepWiki](https://deepwiki.com/mahach666/RevitServerStack) for an automatically generated overview of the repository. + +Revit Server Stack is not affiliated with, endorsed by or sponsored by Autodesk or Docker. Autodesk and Revit are trademarks of Autodesk, Inc. diff --git a/docs/toc.yml b/docs/toc.yml new file mode 100644 index 0000000..d458980 --- /dev/null +++ b/docs/toc.yml @@ -0,0 +1,14 @@ +- name: Guide + href: ../README.md +- name: Руководство + href: ../README.ru.md +- name: Contributing + href: ../CONTRIBUTING.md +- name: Changelog + href: ../CHANGELOG.md +- name: Security + href: ../SECURITY.md +- name: GitHub + href: https://github.com/mahach666/RevitServerStack +- name: DeepWiki + href: https://deepwiki.com/mahach666/RevitServerStack diff --git a/launcher/Build.ps1 b/launcher/Build.ps1 index d7b2cbd..78d834a 100644 --- a/launcher/Build.ps1 +++ b/launcher/Build.ps1 @@ -8,7 +8,7 @@ Needs nothing but Windows: the C# compiler of .NET Framework 4 is part of it. The version is read from the newest entry of CHANGELOG.md. With -Release the archive holds the exe next to the files git would commit (tracked and - new, minus ignored), without the launcher sources and the tests. + new, minus ignored), without the launcher sources, the tests, the docs site and the GitHub files. .PARAMETER OutDir Output folder, dist\ in the repository by default. .PARAMETER Release @@ -30,9 +30,10 @@ if (-not $OutDir) { $OutDir = Join-Path $repo 'dist' } # ------------------------------------------------------------------ version -- $changelog = Get-Content -LiteralPath (Join-Path $repo 'CHANGELOG.md') -Raw -Encoding UTF8 -$match = [regex]::Match($changelog, '(?m)^## \[(\d+\.\d+\.\d+)\]') +$match = [regex]::Match($changelog, '(?m)^## \[(\d+\.\d+\.\d+)(-[0-9A-Za-z.-]+)?\]') if (-not $match.Success) { throw 'CHANGELOG.md has no "## [x.y.z]" entry to take the version from.' } -$version = $match.Groups[1].Value +$versionNumber = $match.Groups[1].Value +$version = $versionNumber + $match.Groups[2].Value # 1.5.0 or 1.5.0-rc.1 New-Item -ItemType Directory -Path $OutDir -Force | Out-Null $work = Join-Path ([System.IO.Path]::GetTempPath()) ('rss-build-' + [Guid]::NewGuid().ToString('N').Substring(0, 8)) @@ -111,7 +112,7 @@ try { # ------------------------------------------------------------- compile -- $assemblyInfo = Join-Path $work 'AssemblyInfo.cs' - $versionFour = "$version.0" + $versionFour = "$versionNumber.0" [System.IO.File]::WriteAllText($assemblyInfo, @" using System.Reflection; [assembly: AssemblyTitle("Revit Server Stack")] @@ -154,7 +155,9 @@ using System.Reflection; $files = @($listed | Where-Object { $_ -and - $_ -notmatch '^(launcher|panel/tests)/' -and + $_ -notmatch '^(launcher|panel/tests|\.github|\.config)/' -and + $_ -notmatch '^docs/(?!images/)' -and + $_ -notmatch '^docfx\.json$' -and $_ -notmatch '^\.[^/]*$' -and (Test-Path -LiteralPath (Join-Path $repo $_) -PathType Leaf) } | Sort-Object -Unique) diff --git a/launcher/RevitServerStack.cs b/launcher/RevitServerStack.cs index 3ed8edc..43b62dc 100644 --- a/launcher/RevitServerStack.cs +++ b/launcher/RevitServerStack.cs @@ -198,6 +198,10 @@ private void OnTick(object sender, EventArgs e) private void Fail(string message) { + // The panel is gone or going: its address must not be offered any more + // (a crashed PowerShell never gets to remove the file itself). + url = null; + DeleteQuietly(urlFile); SetState(State.Stopped, Title + ": " + L10n.Get("notRunning")); icon.ShowBalloonTip(5000, Title, message, ToolTipIcon.Error); } @@ -208,13 +212,26 @@ private void ExitApp() icon.Visible = false; icon.Dispose(); - // The panel also stops by itself once this process is gone; waiting - // here only makes a quick restart find its port free. - if (server != null && !server.HasExited && !server.WaitForExit(3000)) + // The panel's own watch for this process cannot fire while this process + // is still alive, so it is stopped here, at once. Its port is free by + // the time a quick restart asks for it, and the address file, which + // the panel does not get to remove when killed, goes with it. + try + { + if (server != null && !server.HasExited) + { + server.Kill(); // the server only: docker jobs it started keep running + server.WaitForExit(3000); + } + } + catch (InvalidOperationException) { } // it exited on its own in the meantime + catch (System.ComponentModel.Win32Exception) { } // already terminating, or access denied + finally { - server.Kill(); // the server only: docker jobs it started keep running + // The icon is gone: whatever Kill did, the launcher must not stay alive without it. + DeleteQuietly(urlFile); + ExitThread(); } - ExitThread(); } // --------------------------------------------------------------- menu -- diff --git a/panel/lib/Actions.ps1 b/panel/lib/Actions.ps1 index 6fda784..b856821 100644 --- a/panel/lib/Actions.ps1 +++ b/panel/lib/Actions.ps1 @@ -200,6 +200,12 @@ function Invoke-StartAll { return $results } +# True when every per-target result of StartAll / StopAll succeeded. +function Test-AllResultsOk { + param($Results) + return (@($Results | Where-Object { -not $_.result.ok }).Count -eq 0) +} + function Invoke-StopAll { param( [Parameter(Mandatory = $true)]$Config, diff --git a/panel/lib/Common.ps1 b/panel/lib/Common.ps1 index 8e31ca9..83a7016 100644 --- a/panel/lib/Common.ps1 +++ b/panel/lib/Common.ps1 @@ -223,6 +223,25 @@ function Test-ContextEndpoint { return ($Endpoint -cmatch '^(ssh|tcp)://[A-Za-z0-9\[][A-Za-z0-9._@:\[\]-]*\z') } +# The session token: 32 bytes from the operating system's cryptographic generator +# (Get-Random is a time-seeded System.Random and guessable by a local process). +function New-SessionToken { + $bytes = New-Object byte[] 32 + $rng = New-Object System.Security.Cryptography.RNGCryptoServiceProvider + try { $rng.GetBytes($bytes) } finally { $rng.Dispose() } + return (($bytes | ForEach-Object { $_.ToString('x2') }) -join '') +} + +# Case-sensitive comparison that takes the same time wherever the strings differ. +function Test-SecretEqual { + param([string]$Expected, [string]$Supplied) + + $diff = $Expected.Length -bxor $Supplied.Length + $length = [math]::Min($Expected.Length, $Supplied.Length) + for ($i = 0; $i -lt $length; $i++) { $diff = $diff -bor ([int]$Expected[$i] -bxor [int]$Supplied[$i]) } + return ($diff -eq 0) +} + function Get-UnixMillis { param([datetime]$Value = (Get-Date)) $epoch = [datetime]::SpecifyKind([datetime]'1970-01-01', [System.DateTimeKind]::Utc) diff --git a/panel/lib/Compose.ps1 b/panel/lib/Compose.ps1 index df88bf8..215a8d2 100644 --- a/panel/lib/Compose.ps1 +++ b/panel/lib/Compose.ps1 @@ -55,8 +55,9 @@ function Write-VersionCompose { ) $year = [int]$Version.year - $buildContext = ConvertTo-ComposePath (Join-Path (Join-Path $RepoRoot 'src') "rs$year") - $dataDir = ConvertTo-ComposePath ([string]$Version.dataDir) + # compose interpolates $NAME and ${NAME} in every value: a literal "$" is "$$". + $buildContext = (ConvertTo-ComposePath (Join-Path (Join-Path $RepoRoot 'src') "rs$year")).Replace('$', '$$') + $dataDir = (ConvertTo-ComposePath ([string]$Version.dataDir)).Replace('$', '$$') $target = "C:/ProgramData/Autodesk/Revit Server $year/Projects" $portLines = @(" - $(ConvertTo-YamlSingleQuoted "$([int]$Version.hostPort):80")") @@ -78,7 +79,12 @@ function Write-VersionCompose { '# Manual edits here are overwritten on the next save.', 'services:', " rs${year}:", - " build: $(ConvertTo-YamlSingleQuoted $buildContext)", + ' build:', + " context: $(ConvertTo-YamlSingleQuoted $buildContext)", + # Optional: when RS_INSTALLER_SHA256 is set in the environment of the + # panel, the Dockerfile refuses an installer with another SHA-256. + ' args:', + (' INSTALLER_SHA256: ' + (ConvertTo-YamlSingleQuoted ('${RS' + $year + '_INSTALLER_SHA256:-}'))), " container_name: rs${year}", ' ports:' ) + $portLines + @( diff --git a/panel/lib/Config.ps1 b/panel/lib/Config.ps1 index 1e768d6..0292d0a 100644 --- a/panel/lib/Config.ps1 +++ b/panel/lib/Config.ps1 @@ -138,6 +138,12 @@ function Test-PanelConfig { } } + # net.tcp 808 is baked into the Revit Server protocol - Revit connects to + # net.tcp:///ModelService/... with no port, so it is always 808. + # Two containers cannot publish the same host port. A disabled version + # publishes nothing, so it does not count. + $netTcpOwners = @($Config.versions | Where-Object { $_.enabled -and $_.revitClients } | ForEach-Object { [int]$_.year }) + $seenPorts = @{} foreach ($version in $Config.versions) { $hostPort = 0 @@ -156,6 +162,9 @@ function Test-PanelConfig { if ($hostPort -eq $panelPort) { $errors += (T 'cfg.portPanelClash' $version.year $hostPort) } + if ($version.enabled -and $hostPort -eq 808 -and $netTcpOwners.Count -gt 0) { + $errors += (T 'cfg.port808Version' $version.year ($netTcpOwners -join ', ')) + } if ([string]::IsNullOrWhiteSpace([string]$version.dataDir)) { $errors += (T 'cfg.noDir' $version.year) } @@ -165,17 +174,31 @@ function Test-PanelConfig { $errors += (T 'cfg.proxyPanelClash') } - # net.tcp 808 is baked into the Revit Server protocol - Revit connects to - # net.tcp:///ModelService/... with no port, so it is always 808. - # Two containers cannot publish the same host port. - $netTcpOwners = @($Config.versions | Where-Object { $_.revitClients } | ForEach-Object { [int]$_.year }) if ($netTcpOwners.Count -gt 1) { $errors += (T 'cfg.port808' ($netTcpOwners -join ', ')) } + if ($Config.proxy.enabled -and $proxyPort -eq 808 -and $netTcpOwners.Count -gt 0) { + $errors += (T 'cfg.port808Proxy' ($netTcpOwners -join ', ')) + } return $errors } +# The panel runs on defaults when the saved file is unusable, and its next save +# would overwrite the hand edits: keep the file next to it first. +function Backup-InvalidConfig { + param([Parameter(Mandatory = $true)][string]$ConfigPath) + + $backup = "$ConfigPath.invalid.bak" + try { + Copy-Item -LiteralPath $ConfigPath -Destination $backup -Force + } catch { + Write-Warning (T 'cfg.backupFailed' $backup $_.Exception.Message $ConfigPath) + return + } + Write-Warning (T 'cfg.invalidBackup' $backup $ConfigPath) +} + function Get-PanelConfig { param( [Parameter(Mandatory = $true)][string]$RepoRoot, @@ -192,10 +215,24 @@ function Get-PanelConfig { $loaded = $raw | ConvertFrom-Json } catch { Write-Warning (T 'cfg.unreadable' $ConfigPath $_.Exception.Message) + Backup-InvalidConfig -ConfigPath $ConfigPath return $defaults } - return (Merge-ConfigWithDefaults -Loaded $loaded -Defaults $defaults) + # The file is edited by hand: what the panel would refuse on save it does + # not run with either, because a bad value only surfaces later as a raw + # .NET error or a docker failure. + try { + if ($loaded -isnot [System.Management.Automation.PSCustomObject]) { throw (T 'srv.notObject') } + $merged = Merge-ConfigWithDefaults -Loaded $loaded -Defaults $defaults + $problems = @(Test-PanelConfig -Config $merged) + if ($problems.Count -gt 0) { throw ($problems -join ' ') } + } catch { + Write-Warning (T 'cfg.invalidSaved' $ConfigPath $_.Exception.Message) + Backup-InvalidConfig -ConfigPath $ConfigPath + return (New-DefaultConfig -RepoRoot $RepoRoot) + } + return $merged } function Save-PanelConfig { diff --git a/panel/lib/Jobs.ps1 b/panel/lib/Jobs.ps1 index 6e8fe3d..b50ea0b 100644 --- a/panel/lib/Jobs.ps1 +++ b/panel/lib/Jobs.ps1 @@ -23,6 +23,12 @@ function Initialize-JobStore { } } +# Job ids are generated by Start-PanelJob; anything else must never reach a path. +function Test-JobId { + param([string]$Id) + return ($Id -cmatch '^[0-9a-f]{12}\z') +} + function Get-JobMetaPath { param([string]$Id) return (Join-Path $script:JobsDir "$Id.json") @@ -41,6 +47,7 @@ function Save-JobMeta { function Get-PanelJob { param([Parameter(Mandatory = $true)][string]$Id) + if (-not (Test-JobId $Id)) { return $null } $path = Get-JobMetaPath $Id if (-not (Test-Path -LiteralPath $path)) { return $null } $raw = Read-TextFileUtf8 $path @@ -169,12 +176,17 @@ function Start-PanelJob { ) -join "`r`n" Write-TextFileUtf8 -Path $logPath -Content $header -WithCrLf - $wrapper = @( - '@echo off', - 'chcp 65001 >nul', - "$CommandLine >> $(ConvertTo-CliArg $logPath) 2>&1", - 'exit /b %ERRORLEVEL%' - ) -join "`r`n" + # cmd.exe expands %NAME% in a batch file even inside quotes, and only "%%" + # gives a literal percent sign there. The job runs from the jobs folder, so + # that the path of the wrapper itself (cmd /c, where "%%" does not work) + # holds no percent sign. + $wrapperLines = @('@echo off', 'chcp 65001 >nul') + if ($WorkingDirectory -and (Test-Path -LiteralPath $WorkingDirectory)) { + $wrapperLines += ("cd /d $(ConvertTo-CliArg $WorkingDirectory)").Replace('%', '%%') + } + $wrapperLines += ("$CommandLine >> $(ConvertTo-CliArg $logPath) 2>&1").Replace('%', '%%') + $wrapperLines += 'exit /b %ERRORLEVEL%' + $wrapper = $wrapperLines -join "`r`n" Write-TextFileUtf8 -Path $cmdPath -Content $wrapper -WithCrLf # Deliberately not Start-Process: the Process object it hands back does not @@ -182,12 +194,12 @@ function Start-PanelJob { # panel could never tell success from failure. Owning the Process fixes that. $psi = New-Object System.Diagnostics.ProcessStartInfo $psi.FileName = 'cmd.exe' - $psi.Arguments = "/c $(ConvertTo-CliArg $cmdPath)" + # ".\": cmd does not look in the current folder for a bare name when + # NoDefaultCurrentDirectoryInExePath is set. + $psi.Arguments = "/c .\$id.cmd" $psi.UseShellExecute = $false $psi.CreateNoWindow = $true - if ($WorkingDirectory -and (Test-Path -LiteralPath $WorkingDirectory)) { - $psi.WorkingDirectory = $WorkingDirectory - } + $psi.WorkingDirectory = $script:JobsDir $proc = New-Object System.Diagnostics.Process $proc.StartInfo = $psi @@ -227,6 +239,19 @@ function Stop-PanelJob { # /T kills the docker child too - killing only cmd.exe would orphan it. Invoke-Cli -FilePath 'taskkill.exe' -Arguments @('/PID', [string]$job.pid, '/T', '/F') -TimeoutSec 15 | Out-Null + # Believe the process, not taskkill's exit code: while it is still there the + # job is running and its target must stay busy. + $gone = $false + for ($i = 0; $i -lt 15 -and -not $gone; $i++) { + if ($script:ActiveProcesses.ContainsKey($Id)) { + $gone = $script:ActiveProcesses[$Id].WaitForExit(200) + } else { + $gone = -not (Test-JobProcessAlive $job) + if (-not $gone) { Start-Sleep -Milliseconds 200 } + } + } + if (-not $gone) { return $false } + $job.finishedAt = (Get-Date).ToString('o') $job.finishedReason = 'cancelled' Save-JobMeta $job diff --git a/panel/server.ps1 b/panel/server.ps1 index bab9052..9927031 100644 --- a/panel/server.ps1 +++ b/panel/server.ps1 @@ -73,7 +73,7 @@ $script:StatusCacheLanguage = '' $script:StatusCacheAt = [datetime]::MinValue $script:StatusCacheTtl = [timespan]::FromSeconds(2.5) -$script:Token = -join ((1..32) | ForEach-Object { '{0:x2}' -f (Get-Random -Minimum 0 -Maximum 256) }) +$script:Token = New-SessionToken # ---------------------------------------------------------------- responses -- @@ -139,11 +139,24 @@ function Get-ContentType { function Send-StaticFile { param($Context, [string]$RelativePath) + # No file of www/ has a ":" in its name; in a path it means a drive or an NTFS + # stream ("index.html::$DATA"), and GetFullPath throws on it. + if ($RelativePath.Contains(':')) { + Send-Text -Context $Context -Text 'Not found' -StatusCode 404 + return + } + $full = Join-Path $script:WwwRoot $RelativePath # Trailing separator: without it a sibling folder such as "www-old" would # pass the prefix check below. $resolvedRoot = [System.IO.Path]::GetFullPath($script:WwwRoot).TrimEnd('\') + '\' - $resolvedFull = [System.IO.Path]::GetFullPath($full) + try { + $resolvedFull = [System.IO.Path]::GetFullPath($full) + } catch { + # Characters Windows does not allow in a path: no such file. + Send-Text -Context $Context -Text 'Not found' -StatusCode 404 + return + } # Refuse anything that escapes www/ (path traversal). if (-not $resolvedFull.StartsWith($resolvedRoot, [System.StringComparison]::OrdinalIgnoreCase)) { @@ -184,7 +197,7 @@ function Test-ApiAuthorized { $supplied = [string]$Request.Headers['X-Panel-Token'] if ([string]::IsNullOrWhiteSpace($supplied)) { return $false } - return ($supplied -ceq $script:Token) + return (Test-SecretEqual -Expected $script:Token -Supplied $supplied) } function Read-RequestBody { @@ -196,7 +209,8 @@ function Read-RequestBody { $reader = New-Object System.IO.StreamReader($Request.InputStream, $encoding) try { $text = $reader.ReadToEnd() } finally { $reader.Dispose() } if ([string]::IsNullOrWhiteSpace($text)) { return $null } - try { return ($text | ConvertFrom-Json) } catch { return $null } + # A body that is not JSON is the caller's mistake, not an empty body. + try { return ($text | ConvertFrom-Json) } catch { throw (New-Object System.FormatException (T 'srv.badJson')) } } # ----------------------------------------------------------------- handlers -- @@ -300,10 +314,21 @@ function Invoke-ConfigPost { return } - $defaults = New-DefaultConfig -RepoRoot $script:RepoRoot - $candidate = Merge-ConfigWithDefaults -Loaded $Body -Defaults $defaults + if ($Body -isnot [System.Management.Automation.PSCustomObject]) { + Send-Error -Context $Context -Message (T 'srv.notObject') + return + } - $errors = Test-PanelConfig -Config $candidate + # The body changes what it names; everything else stays as it is now. + try { + $current = Merge-ConfigWithDefaults -Loaded $script:Config -Defaults (New-DefaultConfig -RepoRoot $script:RepoRoot) + $candidate = Merge-ConfigWithDefaults -Loaded $Body -Defaults $current + $errors = @(Test-PanelConfig -Config $candidate) + } catch { + # A value of the wrong type (a year that is not a number, ...). + Send-Json -Context $Context -Data ([pscustomobject]@{ ok = $false; errors = @($_.Exception.Message) }) -StatusCode 400 + return + } if ($errors.Count -gt 0) { Send-Json -Context $Context -Data ([pscustomobject]@{ ok = $false; errors = $errors }) -StatusCode 400 return @@ -359,7 +384,11 @@ function Invoke-ActionPost { Send-Error -Context $Context -Message (T 'srv.allActions') return } - Send-Json -Context $Context -Data ([pscustomobject]@{ ok = $true; results = $results }) + # No top-level "error": the page lists the failed targets from results. + $allOk = Test-AllResultsOk -Results $results + $code = 200 + if (-not $allOk) { $code = 409 } + Send-Json -Context $Context -Data ([pscustomobject]@{ ok = $allOk; results = $results }) -StatusCode $code return } @@ -415,7 +444,7 @@ function Invoke-JobLogRequest { param($Context, $Query) $id = [string]$Query['id'] - if ([string]::IsNullOrWhiteSpace($id) -or $id -notmatch '^[0-9a-f]{12}$') { + if (-not (Test-JobId $id)) { Send-Error -Context $Context -Message (T 'srv.badJobId') return } @@ -450,6 +479,10 @@ function Invoke-JobCancel { Send-Error -Context $Context -Message (T 'srv.noJobId') return } + if (-not (Test-JobId ([string]$Body.id))) { + Send-Error -Context $Context -Message (T 'srv.badJobId') + return + } $stopped = Stop-PanelJob -Id ([string]$Body.id) $script:StatusCache = $null Send-Json -Context $Context -Data ([pscustomobject]@{ ok = $stopped }) @@ -481,7 +514,13 @@ function Invoke-Request { } $body = $null - if ($method -eq 'POST') { $body = Read-RequestBody -Request $request } + if ($method -eq 'POST') { + try { $body = Read-RequestBody -Request $request } + catch [System.FormatException] { + Send-Error -Context $Context -Message $_.Exception.Message + return + } + } switch ($path) { '/api/status' { Invoke-StatusRequest -Context $Context; return } diff --git a/panel/tests/Invoke-Tests.ps1 b/panel/tests/Invoke-Tests.ps1 index 3996235..d56c555 100644 --- a/panel/tests/Invoke-Tests.ps1 +++ b/panel/tests/Invoke-Tests.ps1 @@ -164,6 +164,226 @@ Check 'saved settings overlay the discovered versions' { Assert-True ($null -eq (Get-VersionConfig -Config $merged -Year 2019)) 'a version without a Dockerfile folder appeared' } +Check 'config: port 808 is checked against host ports and the proxy, a disabled version does not own it' { + $config = New-DefaultConfig -RepoRoot (New-FakeRepo) + $config.versions[0].hostPort = 808 + $config.versions[1].revitClients = $true + $errors = @(Test-PanelConfig -Config $config) + Assert-True ($errors -contains (T 'cfg.port808Version' 2022 '2025')) "host port 808 next to a 808 owner was accepted: $($errors -join ' | ')" + + # The version that owns 808 for Revit cannot also publish its own HTTP port there. + $config = New-DefaultConfig -RepoRoot (New-FakeRepo) + $config.versions[0].hostPort = 808 + $config.versions[0].revitClients = $true + Assert-True (@(Test-PanelConfig -Config $config).Count -ge 1) 'hostPort 808 with revitClients on the same version was accepted' + + # Nothing is published for a disabled version, so it clashes with nobody. + $config = New-DefaultConfig -RepoRoot (New-FakeRepo) + $config.versions[0].hostPort = 808 + $config.versions[0].enabled = $false + $config.versions[1].revitClients = $true + Assert-Equal 0 @(Test-PanelConfig -Config $config).Count + $config.versions[0].enabled = $true + $config.versions[0].hostPort = 2022 + $config.versions[0].revitClients = $true + $config.versions[0].enabled = $false + Assert-Equal 0 @(Test-PanelConfig -Config $config).Count # a disabled version with revitClients does not block another one + $config.versions[0].enabled = $true + Assert-True (@(Test-PanelConfig -Config $config).Count -ge 1) 'two enabled port 808 owners were accepted' + + # The proxy port. + $config = New-DefaultConfig -RepoRoot (New-FakeRepo) + $config.proxy.port = 808 + Assert-Equal 0 @(Test-PanelConfig -Config $config).Count + $config.versions[1].revitClients = $true + $errors = @(Test-PanelConfig -Config $config) + Assert-True ($errors -contains (T 'cfg.port808Proxy' '2025')) "proxy port 808 next to a 808 owner was accepted: $($errors -join ' | ')" + $config.proxy.enabled = $false + Assert-Equal 0 @(Test-PanelConfig -Config $config).Count +} + +Check 'config: an invalid saved file is reported and replaced by the defaults, a valid one is kept' { + $repo = New-FakeRepo + $path = Join-Path (New-TempDir) 'panel.config.json' + $bad = @( + '{"versions":[{"year":2022,"hostPort":"abc"}]}', + '{"composeProject":"x&calc"}', + '{"windowsContext":"a|b"}', + '{"panelPort":0}', + '{"versions":[{"year":"zz"}]}', + '5', + '[1]', + 'null', + '{"panelPort": 8787,' + ) + foreach ($text in $bad) { + [System.IO.File]::WriteAllText($path, $text) + Remove-Item -LiteralPath "$path.invalid.bak" -ErrorAction SilentlyContinue + $config = Get-PanelConfig -RepoRoot $repo -ConfigPath $path -WarningVariable warned -WarningAction SilentlyContinue + Assert-True (@($warned).Count -eq 2) "[$text] was not reported with its backup" + # The next save overwrites the file: the hand edits must survive in the backup + Assert-Equal $text ([System.IO.File]::ReadAllText("$path.invalid.bak")) + Assert-Equal 2022 ((Get-VersionConfig -Config $config -Year 2022).hostPort) + Assert-Equal 'samples' $config.composeProject + # What the panel starts with must be usable: this is what used to throw. + Update-GeneratedFiles -Config $config -RepoRoot $repo -ComposeDir (Join-Path (New-TempDir) 'compose') | Out-Null + } + + [System.IO.File]::WriteAllText($path, '{"composeProject":"mine","versions":[{"year":2022,"hostPort":9000}]}') + Remove-Item -LiteralPath "$path.invalid.bak" -ErrorAction SilentlyContinue + $config = Get-PanelConfig -RepoRoot $repo -ConfigPath $path -WarningVariable warned -WarningAction SilentlyContinue + Assert-Equal 0 @($warned).Count + Assert-True (-not (Test-Path -LiteralPath "$path.invalid.bak")) 'a valid file was backed up' + Assert-Equal 'mine' $config.composeProject + Assert-Equal 9000 ((Get-VersionConfig -Config $config -Year 2022).hostPort) +} + +Check 'config: a backup that cannot be written is a warning, the defaults are still used' { + $repo = New-FakeRepo + $path = Join-Path (New-TempDir) 'panel.config.json' + [System.IO.File]::WriteAllText($path, '{"panelPort": 8787,') + [System.IO.File]::WriteAllText("$path.invalid.bak", 'old') + $lock = [System.IO.File]::Open("$path.invalid.bak", 'Open', 'ReadWrite', 'None') + try { + $config = Get-PanelConfig -RepoRoot $repo -ConfigPath $path -WarningVariable warned -WarningAction SilentlyContinue + } finally { $lock.Dispose() } + Assert-Equal 2 @($warned).Count + Assert-True ("$($warned[1])" -match [regex]::Escape("$path.invalid.bak")) 'the failed backup was not reported' + Assert-Equal 'samples' $config.composeProject +} + +Check 'page and launcher: a persistent log error stops polling; Exit never leaves a launcher without icon' { + $js = [System.IO.File]::ReadAllText((Join-Path $panelRoot 'www\app.js'), [System.Text.Encoding]::UTF8) + Assert-True ($js -match 'logFailures >= 3\) \{\s+stopLogPolling\(\)') 'polling is not stopped after repeated errors' + Assert-True ($js -match 'state\.logOffset = 0;\s+state\.logFailures = 0;') 'a new job does not reset the failure count' + $cs = [System.IO.File]::ReadAllText((Join-Path $repoRoot 'launcher\RevitServerStack.cs'), [System.Text.Encoding]::UTF8) + Assert-True ($cs -match 'Win32Exception\) \{ \}.*\s+finally\s+\{[^}]*ExitThread\(\);') 'ExitThread is not in a finally after Kill' +} + +Check 'token: 32 bytes from the cryptographic generator, compared in constant time' { + $seen = New-Object 'System.Collections.Generic.HashSet[string]' + for ($i = 0; $i -lt 200; $i++) { + $token = New-SessionToken + Assert-True ($token -cmatch '^[0-9a-f]{64}\z') "[$token] is not 32 bytes of hex" + [void]$seen.Add($token) + } + Assert-Equal 200 $seen.Count + + $a = New-SessionToken + Assert-True (Test-SecretEqual $a $a) 'equal tokens differ' + Assert-True (-not (Test-SecretEqual $a (New-SessionToken))) 'different tokens are equal' + Assert-True (-not (Test-SecretEqual $a $a.Substring(0, 63))) 'a prefix is equal' + Assert-True (-not (Test-SecretEqual $a ($a + '0'))) 'a longer string is equal' + Assert-True (-not (Test-SecretEqual $a '')) 'an empty string is equal' + Assert-True (-not (Test-SecretEqual 'ab' 'AB')) 'the comparison ignores case' + + $server = [System.IO.File]::ReadAllText((Join-Path $panelRoot 'server.ps1'), [System.Text.Encoding]::UTF8) + Assert-True ($server -notmatch 'Get-Random') 'server.ps1 draws something from Get-Random' + Assert-True ($server -match '\$script:Token = New-SessionToken') 'the token is not made by New-SessionToken' +} + +# Whether "docker compose config" can be used to read back what the panel wrote. +function Test-ComposeCli { + if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { return $false } + & docker compose version 2>$null | Out-Null + return ($LASTEXITCODE -eq 0) +} + +Check 'compose: a "$" in a path or a name is escaped, and the installer hash reaches the build' { + $root = New-TempDir + $repo = Join-Path $root 'repo$x' + New-Item -ItemType Directory -Path (Join-Path $repo 'src\rs2022') -Force | Out-Null + $composeDir = Join-Path $root 'compose' + $config = New-DefaultConfig -RepoRoot $repo + $config.windowsContext = 'rss-test-no-such-context' + $config.versions[0].dataDir = 'D:\a$b\${x}\rs' + + Update-GeneratedFiles -Config $config -RepoRoot $repo -ComposeDir $composeDir | Out-Null + $path = Join-Path $composeDir 'docker-compose.2022.yml' + $yml = [System.IO.File]::ReadAllText($path) + Assert-True ($yml.Contains('source: ''D:/a$$b/$${x}/rs''')) "the data folder is not escaped:`n$yml" + Assert-True ($yml.Contains('repo$$x/src/rs2022''')) "the build context is not escaped:`n$yml" + Assert-True ($yml.Contains('INSTALLER_SHA256: ''${RS2022_INSTALLER_SHA256:-}''')) "the installer hash is not handed to the build:`n$yml" + + if (-not (Test-ComposeCli)) { + Write-Host ' the round trip through "docker compose config" was skipped: no docker compose' + return + } + $saved = $env:RS2022_INSTALLER_SHA256 + $env:RS2022_INSTALLER_SHA256 = 'ABC123' + try { + $model = (& docker compose -p samples -f $path config --format json 2>&1) -join "`n" | ConvertFrom-Json + } finally { + if ($null -eq $saved) { Remove-Item Env:\RS2022_INSTALLER_SHA256 -ErrorAction SilentlyContinue } else { $env:RS2022_INSTALLER_SHA256 = $saved } + } + $service = $model.services.rs2022 + # config prints a literal $ as $$ again, so that its output can be fed back + $source = ([string]$service.volumes[0].source).Replace('$$', '$').Replace('\', '/') + Assert-Equal 'D:/a$b/${x}/rs' $source + $context = ([string]$service.build.context).Replace('$$', '$').Replace('\', '/') + Assert-True ($context.EndsWith('repo$x/src/rs2022')) "the build context is [$context]" + Assert-Equal 'ABC123' ([string]$service.build.args.INSTALLER_SHA256) +} + +Check 'dockerfiles: the installer is compared with INSTALLER_SHA256 when it is set' { + $dockerfiles = @(Get-ChildItem -LiteralPath (Join-Path $repoRoot 'src') -Recurse -Filter 'Dockerfile') + Assert-Equal 8 $dockerfiles.Count + foreach ($file in $dockerfiles) { + $text = [System.IO.File]::ReadAllText($file.FullName, [System.Text.Encoding]::UTF8) + $year = [regex]::Match($file.FullName, 'rs(\d{4})').Groups[1].Value + $installer = [regex]::Match($text, '(?m)^ADD "[^"]+/([^/"]+\.sfx\.exe)"').Groups[1].Value + Assert-True ($installer.Length -gt 0) "rs${year}: no installer in the ADD line" + $check = [regex]::Match($text, '(?m)^RUN powershell -NoProfile -Command "[^"]*Get-FileHash ' + [regex]::Escape($installer) + ' -Algorithm SHA256\)\.Hash -ne \$env:INSTALLER_SHA256\)[^"]*"') + Assert-True $check.Success "rs${year}: the installer is not checked" + $arg = $text.IndexOf("`nARG INSTALLER_SHA256=") + Assert-True ($arg -ge 0 -and $arg -lt $check.Index) "rs${year}: ARG INSTALLER_SHA256 does not come before the check" + # The check and the use of the installer are one instruction: nothing is unpacked unchecked. + $rest = $text.Substring($check.Index + 4) + $next = [regex]::Match($rest, '(?m)^(RUN|WORKDIR|COPY|ADD|ENV|EXPOSE|ARG) ') + $instruction = $check.Value + if ($next.Success) { $instruction = $text.Substring($check.Index, 4 + $next.Index) } + Assert-True ($instruction -match '(START /W|7zr\.exe x)') "rs${year}: the check and the use of the installer are in different layers" + # The compose sample passes the variable of its version on. + $sample = [System.IO.File]::ReadAllText((Join-Path $repoRoot "samples\docker-compose.$year.yml"), [System.Text.Encoding]::UTF8) + Assert-True ($sample.Contains('INSTALLER_SHA256: ${RS' + $year + '_INSTALLER_SHA256:-}')) "samples/docker-compose.$year.yml does not pass the hash" + } + + # Run the very command of a Dockerfile the way docker does (cmd /S /C), against a stand-in file. + $text = [System.IO.File]::ReadAllText((Join-Path $repoRoot 'src\rs2022\Dockerfile'), [System.Text.Encoding]::UTF8) + $installer = [regex]::Match($text, '(?m)^ADD "[^"]+/([^/"]+\.sfx\.exe)"').Groups[1].Value + $command = [regex]::Match($text, '(?m)^RUN (powershell -NoProfile -Command "[^"]*")').Groups[1].Value + $work = New-TempDir + [System.IO.File]::WriteAllText((Join-Path $work $installer), 'not an installer') + $real = (Get-FileHash -LiteralPath (Join-Path $work $installer) -Algorithm SHA256).Hash + $cases = @( + @{ Hash = ''; ExitCode = 0 }, + @{ Hash = $real; ExitCode = 0 }, + @{ Hash = $real.ToLowerInvariant(); ExitCode = 0 }, + @{ Hash = ('0' * 64); ExitCode = 1 } + ) + $savedHash = $env:INSTALLER_SHA256 + try { + foreach ($case in $cases) { + $env:INSTALLER_SHA256 = $case.Hash + $psi = New-Object System.Diagnostics.ProcessStartInfo + $psi.FileName = 'cmd.exe' + $psi.Arguments = '/S /C "' + $command + '"' + $psi.WorkingDirectory = $work + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $proc = [System.Diagnostics.Process]::Start($psi) + $proc.StandardOutput.ReadToEnd() | Out-Null + $proc.StandardError.ReadToEnd() | Out-Null + $proc.WaitForExit() + Assert-Equal ([int]$case.ExitCode -ne 0) ($proc.ExitCode -ne 0) + } + } finally { + if ($null -eq $savedHash) { Remove-Item Env:\INSTALLER_SHA256 -ErrorAction SilentlyContinue } else { $env:INSTALLER_SHA256 = $savedHash } + } +} + # ------------------------------------------------------------ generated files -- Check 'compose and nginx files are generated from the config' { @@ -398,6 +618,170 @@ Check 'engines: remote contexts are created and read back' { } } +# -------------------------------------------------------------------- jobs -- + +# Waits until the job is no longer among the running ones; returns its stored state. +function Wait-TestJob { + param([string]$Id, [int]$Seconds = 30) + for ($i = 0; $i -lt $Seconds * 5; $i++) { + $running = @(Update-JobStates | Where-Object { $_.id -eq $Id }) + if ($running.Count -eq 0) { break } + Start-Sleep -Milliseconds 200 + } + return (Get-PanelJob -Id $Id) +} + +Check 'jobs: ids are validated before they reach a path' { + . (Join-Path $panelRoot 'lib\Jobs.ps1') + foreach ($good in '0123456789ab', 'ffffffffffff') { + Assert-True (Test-JobId $good) "[$good] was refused" + } + foreach ($bad in '', '..\..\x', '0123456789AB', "0123456789ab`n", '0123456789abc', '0123456789a', '01234567/9ab', 'zzzzzzzzzzzz') { + Assert-True (-not (Test-JobId $bad)) "[$bad] was accepted as a job id" + } + + # A .json file outside the jobs folder must not be read as a job, nor written back. + $base = New-TempDir + Initialize-JobStore -Directory (Join-Path $base 'jobs') + $victim = Join-Path $base 'victim.json' + $original = '{"id":"v","pid":0,"finishedAt":null}' + [System.IO.File]::WriteAllText($victim, $original) + Assert-True ($null -eq (Get-PanelJob -Id '..\victim')) 'a file outside the jobs folder was read as a job' + Assert-True (-not (Stop-PanelJob -Id '..\victim')) 'a file outside the jobs folder was taken for a job to cancel' + Assert-Equal $original ([System.IO.File]::ReadAllText($victim)) +} + +Check 'jobs: a command runs, its exit code and log are kept, and % reaches it unchanged' { + . (Join-Path $panelRoot 'lib\Jobs.ps1') + # The jobs folder itself has percent signs in its path: the wrapper must still start. + $base = New-TempDir + Initialize-JobStore -Directory (Join-Path $base 'x%TEMP%y\jobs') + + $ok = Start-PanelJob -Title 'echo' -Kind 'test' -Target 'rs1' -CommandLine 'echo a%TEMP%b' + Assert-True (Test-JobId $ok.id) "[$($ok.id)] is not a job id" + $done = Wait-TestJob $ok.id + Assert-True ($null -ne $done.finishedAt) 'the job did not finish' + Assert-Equal 'completed' ([string]$done.finishedReason) + Assert-Equal 0 ([int]$done.exitCode) + $log = (Get-JobLogChunk -Id $ok.id).text + Assert-True ($log.Contains('a%TEMP%b')) "the percent signs were expanded: $log" + Assert-True ($log.Contains('=== echo ===')) 'the header is missing from the log' + + $fail = Start-PanelJob -Title 'exit' -Kind 'test' -Target 'rs2' -CommandLine 'cmd /c exit 3' + $done = Wait-TestJob $fail.id + Assert-Equal 3 ([int]$done.exitCode) + + # Offsets: what was read is not sent again, and an offset past the end is clamped. + $first = Get-JobLogChunk -Id $ok.id + Assert-True ($first.offset -gt 0) + $again = Get-JobLogChunk -Id $ok.id -Offset $first.offset + Assert-Equal '' $again.text + Assert-Equal $first.offset $again.offset + $past = Get-JobLogChunk -Id $ok.id -Offset 999999 + Assert-Equal '' $past.text + Assert-Equal $first.offset $past.offset + Assert-Equal $first.text (Get-JobLogChunk -Id $ok.id -Offset -5).text +} + +Check 'jobs: a running job keeps its target busy, and cancel stops the process' { + . (Join-Path $panelRoot 'lib\Jobs.ps1') + Initialize-JobStore -Directory (Join-Path (New-TempDir) 'jobs') + + $job = Start-PanelJob -Title 'ping' -Kind 'test' -Target 'rs3' -CommandLine 'ping -n 60 127.0.0.1' + try { + $busy = Get-RunningJobForTarget -Target 'rs3' + Assert-True ($null -ne $busy -and $busy.id -eq $job.id) 'a running job was not found for its target' + Assert-True ($null -eq (Get-RunningJobForTarget -Target 'rs4')) 'another target is busy' + + Assert-True (Stop-PanelJob -Id $job.id) 'a running job was not cancelled' + $stored = Get-PanelJob -Id $job.id + Assert-Equal 'cancelled' ([string]$stored.finishedReason) + Assert-True ($null -eq (Get-Process -Id ([int]$job.pid) -ErrorAction SilentlyContinue)) 'the process of a cancelled job is still running' + Assert-True ($null -eq (Get-RunningJobForTarget -Target 'rs3')) 'a cancelled job keeps its target busy' + Assert-True (-not (Stop-PanelJob -Id $job.id)) 'a finished job was cancelled again' + } finally { + Stop-Process -Id ([int]$job.pid) -Force -ErrorAction SilentlyContinue + } +} + +Check 'jobs: a job that outlived the panel is "detached", and a recycled PID is not the job' { + . (Join-Path $panelRoot 'lib\Jobs.ps1') + Initialize-JobStore -Directory (Join-Path (New-TempDir) 'jobs') + + $job = Start-PanelJob -Title 'short' -Kind 'test' -Target 'rs5' -CommandLine 'ping -n 2 127.0.0.1' + $script:ActiveProcesses.Clear() # as after a restart of the panel: the handle is gone + $done = Wait-TestJob $job.id + Assert-Equal 'detached' ([string]$done.finishedReason) + Assert-True ($null -eq $done.exitCode) 'an exit code was reported that nobody observed' + + $me = Get-Process -Id $PID + $same = [pscustomobject]@{ pid = $PID; pidStartedAt = $me.StartTime.ToString('o') } + $recycled = [pscustomobject]@{ pid = $PID; pidStartedAt = $me.StartTime.AddHours(-3).ToString('o') } + Assert-True (Test-JobProcessAlive $same) 'the process of the job is not seen' + Assert-True (-not (Test-JobProcessAlive $recycled)) 'a process that started later was taken for the job' +} + +Check 'jobs: old finished jobs are removed with their files, unfinished ones stay' { + . (Join-Path $panelRoot 'lib\Jobs.ps1') + $dir = Join-Path (New-TempDir) 'jobs' + Initialize-JobStore -Directory $dir + $old = (Get-Date).AddDays(-30) + foreach ($case in @(@{ Id = 'aaaaaaaaaaaa'; Finished = $true }, @{ Id = 'bbbbbbbbbbbb'; Finished = $false })) { + $finished = $null + if ($case.Finished) { $finished = $old.ToString('o') } + Save-JobMeta ([pscustomobject]@{ id = $case.Id; target = 't'; finishedAt = $finished }) + foreach ($ext in 'json', 'log', 'cmd') { + $file = Join-Path $dir "$($case.Id).$ext" + if (-not (Test-Path -LiteralPath $file)) { [System.IO.File]::WriteAllText($file, 'x') } + (Get-Item -LiteralPath $file).LastWriteTime = $old + } + } + Remove-OldJobs + foreach ($ext in 'json', 'log', 'cmd') { + Assert-True (-not (Test-Path -LiteralPath (Join-Path $dir "aaaaaaaaaaaa.$ext"))) "an old finished job left its .$ext" + Assert-True (Test-Path -LiteralPath (Join-Path $dir "bbbbbbbbbbbb.$ext")) "an unfinished job lost its .$ext" + } +} + +Check 'actions: Start all and Stop all say when a target failed' { + . (Join-Path $panelRoot 'lib\Jobs.ps1') + . (Join-Path $panelRoot 'lib\Actions.ps1') + Initialize-JobStore -Directory (Join-Path (New-TempDir) 'jobs') + # Takes the place of the real one: nothing is started. + function Start-PanelJob { + param($Title, $Kind, $Target, $CommandLine, $WorkingDirectory = '') + return [pscustomobject]@{ id = 'test'; title = $Title } + } + + Assert-True (Test-AllResultsOk @()) 'no results is not a success' + Assert-True (Test-AllResultsOk @([pscustomobject]@{ target = 'a'; result = [pscustomobject]@{ ok = $true } })) 'a success was reported as a failure' + Assert-True (-not (Test-AllResultsOk @( + [pscustomobject]@{ target = 'a'; result = [pscustomobject]@{ ok = $true } }, + [pscustomobject]@{ target = 'b'; result = [pscustomobject]@{ ok = $false } }))) 'a failure among successes was lost' + + $repo = New-FakeRepo + $composeDir = Join-Path (New-TempDir) 'compose' + $config = New-DefaultConfig -RepoRoot $repo + $config.windowsContext = 'rss-test-no-such-context' + + # No compose files yet: every target fails. + $results = @(Invoke-StopAll -Config $config -ComposeDir $composeDir) + Assert-Equal 3 $results.Count + Assert-True (-not (Test-AllResultsOk $results)) 'Stop all with nothing to stop reported success' + Assert-Equal 0 @($results | Where-Object { $_.result.ok }).Count + + Update-GeneratedFiles -Config $config -RepoRoot $repo -ComposeDir $composeDir | Out-Null + Assert-True (Test-AllResultsOk (Invoke-StopAll -Config $config -ComposeDir $composeDir)) 'Stop all failed although every target could be stopped' + Assert-True (Test-AllResultsOk (Invoke-StartAll -Config $config -ComposeDir $composeDir -RepoRoot $repo)) 'Start all failed although every target could be started' + + # One target without a compose file: the rest still goes, and the whole is not "ok". + Remove-Item -LiteralPath (Join-Path $composeDir 'docker-compose.2025.yml') + $results = @(Invoke-StartAll -Config $config -ComposeDir $composeDir -RepoRoot $repo) + Assert-Equal 3 $results.Count + Assert-True (-not (Test-AllResultsOk $results)) 'a failed target did not fail Start all' + Assert-Equal 2 @($results | Where-Object { $_.result.ok }).Count +} + # -------------------------------------------------------------------- server -- function Get-FreePort { @@ -518,6 +902,116 @@ Check 'server: token, Host header, path traversal, shutdown' { } } +Check 'server: settings are merged and checked, bad bodies and paths are refused' { + $copy = New-FakeRepo -Years @(2022) + Copy-Item -LiteralPath $panelRoot -Destination (Join-Path $copy 'panel') -Recurse + $runtimeCopy = Join-Path $copy 'panel\runtime' + if (Test-Path -LiteralPath $runtimeCopy) { Remove-Item -LiteralPath $runtimeCopy -Recurse -Force } + # A hand-edited file with a bad value: the panel has to start anyway, with the defaults. + New-Item -ItemType Directory -Path $runtimeCopy -Force | Out-Null + [System.IO.File]::WriteAllText((Join-Path $runtimeCopy 'panel.config.json'), '{"versions":[{"year":2022,"hostPort":"abc"}]}') + + $hasDocker = [bool](Get-Command docker -ErrorAction SilentlyContinue) + $savedDockerConfig = $env:DOCKER_CONFIG + if ($hasDocker) { $env:DOCKER_CONFIG = New-TempDir } + + $port = Get-FreePort + $base = "http://localhost:$port" + $panelArgs = '-NoProfile -ExecutionPolicy Bypass -File "{0}" -Port {1} -NoBrowser' -f (Join-Path $copy 'panel\server.ps1'), $port + $proc = Start-Process -FilePath 'powershell.exe' -ArgumentList $panelArgs -WindowStyle Hidden -PassThru + + try { + $index = $null + for ($i = 0; $i -lt 40 -and -not $index; $i++) { + Start-Sleep -Milliseconds 500 + if ($proc.HasExited) { throw 'the server exited during start-up (an invalid saved config must not stop it)' } + try { $index = Send-TestRequest -Url "$base/" } catch { } + } + Assert-True ($null -ne $index) 'the server did not answer within 20 seconds' + Assert-True ($index.Body -match 'name="panel-token" content="([0-9a-f]{64})"') 'the token is not in the page' + $auth = @{ 'X-Panel-Token' = $Matches[1] } + $english = Read-Catalog 'en' + + function Get-TestConfig { return ((Send-TestRequest -Url "$base/api/config" -Headers $auth).Body | ConvertFrom-Json).config } + function Save-TestConfig { param([string]$Body) return (Send-TestRequest -Url "$base/api/config" -Method POST -Headers $auth -Body $Body) } + + # Start-up: the bad value was not used. + Assert-Equal 2022 (Get-TestConfig).versions[0].hostPort + + # A body that is not an object changes nothing. + foreach ($body in '5', '"text"', '[1]', 'true') { + $answer = Save-TestConfig $body + Assert-Equal 400 $answer.Status + Assert-Equal $english['srv.notObject'] (($answer.Body | ConvertFrom-Json).error) + } + Assert-Equal 2022 (Get-TestConfig).versions[0].hostPort + + # A partial body changes what it names and nothing else. + Assert-Equal 200 (Save-TestConfig '{"windowsContext":"my-ctx"}').Status + Assert-Equal 'my-ctx' (Get-TestConfig).windowsContext + Assert-Equal 200 (Save-TestConfig '{"composeProject":"zz"}').Status + $now = Get-TestConfig + Assert-Equal 'my-ctx' $now.windowsContext + Assert-Equal 'zz' $now.composeProject + Assert-Equal 200 (Save-TestConfig '{"versions":[{"year":2022,"hostPort":9123}]}').Status + $now = Get-TestConfig + Assert-Equal 9123 $now.versions[0].hostPort + Assert-Equal 'zz' $now.composeProject + Assert-Equal 'my-ctx' $now.windowsContext + $saved = [System.IO.File]::ReadAllText((Join-Path $runtimeCopy 'panel.config.json')) | ConvertFrom-Json + Assert-Equal 'zz' $saved.composeProject + Assert-Equal 9123 $saved.versions[0].hostPort + + # The checks of a save: refused with the list of errors, nothing changes. + $refused = Save-TestConfig '{"panelPort":0}' + Assert-Equal 400 $refused.Status + Assert-True (@(($refused.Body | ConvertFrom-Json).errors) -contains $english['cfg.panelPort']) 'the port error is missing' + $refused = Save-TestConfig '{"versions":[{"year":2022,"hostPort":808,"revitClients":true}]}' + Assert-Equal 400 $refused.Status + $refused = Save-TestConfig '{"versions":[{"year":"zz"}]}' + Assert-Equal 400 $refused.Status + Assert-True (@(($refused.Body | ConvertFrom-Json).errors).Count -ge 1) 'a value of the wrong type gave no error' + Assert-Equal 9123 (Get-TestConfig).versions[0].hostPort + + # A "$" in the folder reaches the compose file escaped. + Assert-Equal 200 (Save-TestConfig '{"versions":[{"year":2022,"dataDir":"D:\\a$b\\rs"}]}').Status + $yml = [System.IO.File]::ReadAllText((Join-Path $runtimeCopy 'compose\docker-compose.2022.yml')) + Assert-True ($yml.Contains('D:/a$$b/rs')) 'the "$" of the folder was not escaped in the compose file' + + # Malformed JSON is said to be malformed, wherever a body is read. + foreach ($path in '/api/config', '/api/action', '/api/job/cancel', '/api/context') { + $answer = Send-TestRequest -Url "$base$path" -Method POST -Headers $auth -Body '{bad' + Assert-Equal 400 $answer.Status + Assert-Equal $english['srv.badJson'] (($answer.Body | ConvertFrom-Json).error) + } + + # Paths with ":" are "not found", not a server error with the text of an exception. + foreach ($path in '/C:/Windows/win.ini', '/index.html::$DATA', '/i18n/en.json:x') { + $answer = Send-TestRequest -Url ($base + $path) + Assert-Equal 404 $answer.Status + Assert-True ($answer.Body -notmatch 'GetFullPath|Exception') "the answer for $path leaks an exception: $($answer.Body)" + } + Assert-True ((Send-TestRequest -Url "$base/C%3A/Windows/win.ini").Status -ne 500) 'an encoded ":" gave a server error' + Assert-Equal 200 (Send-TestRequest -Url "$base/app.js").Status + + # Cancel and log take the same kind of id. + $answer = Send-TestRequest -Url "$base/api/job/cancel" -Method POST -Headers $auth -Body '{"id":"..\\..\\..\\x"}' + Assert-Equal 400 $answer.Status + Assert-Equal $english['srv.badJobId'] (($answer.Body | ConvertFrom-Json).error) + Assert-Equal 400 (Send-TestRequest -Url "$base/api/job/cancel" -Method POST -Headers $auth -Body '{"id":"0123456789AB"}').Status + Assert-Equal 400 (Send-TestRequest -Url "$base/api/job?id=0123456789AB" -Headers $auth).Status + $answer = Send-TestRequest -Url "$base/api/job/cancel" -Method POST -Headers $auth -Body '{"id":"0123456789ab"}' + Assert-Equal 200 $answer.Status + Assert-Equal $false (($answer.Body | ConvertFrom-Json).ok) + + Assert-Equal 200 (Send-TestRequest -Url "$base/api/shutdown" -Method POST -Headers $auth).Status + Assert-True ($proc.WaitForExit(10000)) 'the server did not stop after /api/shutdown' + } finally { + if (-not $proc.HasExited) { try { $proc.Kill() } catch { } } + if ($null -eq $savedDockerConfig) { Remove-Item Env:\DOCKER_CONFIG -ErrorAction SilentlyContinue } else { $env:DOCKER_CONFIG = $savedDockerConfig } + } +} + # --------------------------------------------------------------------- i18n -- $languageCodes = @((([System.IO.File]::ReadAllText((Join-Path $panelRoot 'www\i18n\index.json'), [System.Text.Encoding]::UTF8)) | ConvertFrom-Json) | ForEach-Object { [string]$_.code }) @@ -665,6 +1159,48 @@ Check 'launcher: builds, starts the panel, and the panel stops with it' { } } +Check 'launcher: the address of a panel that died is not left behind' { + $outDir = New-TempDir + & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $buildScript -OutDir $outDir | Out-Null + Assert-Equal 0 $LASTEXITCODE + $exe = Join-Path $outDir 'RevitServerStack.exe' + + $copy = New-FakeRepo -Years @(2022) + Copy-Item -LiteralPath $panelRoot -Destination (Join-Path $copy 'panel') -Recurse + $runtimeCopy = Join-Path $copy 'panel\runtime' + if (Test-Path -LiteralPath $runtimeCopy) { Remove-Item -LiteralPath $runtimeCopy -Recurse -Force } + Copy-Item -LiteralPath $exe -Destination $copy + + $launcher = Start-Process -FilePath (Join-Path $copy 'RevitServerStack.exe') -ArgumentList '--no-browser' -PassThru + $serverId = 0 + try { + $urlFile = Join-Path $copy 'panel\runtime\panel.url' + $found = $false + for ($i = 0; $i -lt 40 -and -not $found; $i++) { + Start-Sleep -Milliseconds 500 + if ($launcher.HasExited) { throw 'the launcher exited during start-up' } + $found = Test-Path -LiteralPath $urlFile + } + Assert-True $found 'the panel address did not appear within 20 seconds' + $server = @(Get-CimInstance Win32_Process -Filter "ParentProcessId=$($launcher.Id)" | Where-Object { $_.Name -eq 'powershell.exe' }) + Assert-Equal 1 $server.Count + $serverId = $server[0].ProcessId + + # The panel is killed, so its own clean-up cannot run: the launcher has to remove the file. + Stop-Process -Id $serverId -Force + $gone = $false + for ($i = 0; $i -lt 20 -and -not $gone; $i++) { + Start-Sleep -Milliseconds 500 + $gone = -not (Test-Path -LiteralPath $urlFile) + } + Assert-True $gone 'the address of a dead panel was left in panel.url' + Assert-True (-not $launcher.HasExited) 'the launcher itself went away (its icon must stay to restart the panel)' + } finally { + if (-not $launcher.HasExited) { try { $launcher.Kill() } catch { } } + if ($serverId) { Stop-Process -Id $serverId -Force -ErrorAction SilentlyContinue } + } +} + Check 'release: the archive has the exe and the panel, and no local data' { $outDir = New-TempDir & powershell.exe -NoProfile -ExecutionPolicy Bypass -File $buildScript -Release -OutDir $outDir | Out-Null @@ -681,7 +1217,7 @@ Check 'release: the archive has the exe and the panel, and no local data' { 'src/rs2027/Dockerfile', 'README.md', 'LICENSE.md', 'Start-Panel.cmd') { Assert-True ($names -contains "$top/$must") "$must is missing from the archive" } - foreach ($mustNot in '^[^/]+/panel/runtime/', '^[^/]+/samples/rs20\d\d/', '^[^/]+/launcher/', '^[^/]+/panel/tests/', '\\') { + foreach ($mustNot in '^[^/]+/panel/runtime/', '^[^/]+/samples/rs20\d\d/', '^[^/]+/launcher/', '^[^/]+/panel/tests/', '^[^/]+/docs/(?!images/)', '^[^/]+/\.github/', '^[^/]+/\.config/', '^[^/]+/docfx\.json$', '^[^/]+/_site/', '\\') { Assert-Equal 0 @($names | Where-Object { $_ -match $mustNot }).Count } Assert-True (Test-Path -LiteralPath (Join-Path $outDir 'RELEASE_NOTES.md')) 'RELEASE_NOTES.md was not written' diff --git a/panel/www/app.js b/panel/www/app.js index b539468..461df7d 100644 --- a/panel/www/app.js +++ b/panel/www/app.js @@ -18,6 +18,8 @@ const state = { activeJobId: null, logOffset: 0, logRunning: false, + logPolling: false, + logFailures: 0, busy: new Set(), statusTimer: null, healthTimer: null, @@ -208,6 +210,7 @@ function attachToJob(jobId) { if (!jobId) return; state.activeJobId = jobId; state.logOffset = 0; + state.logFailures = 0; state.logRunning = true; $('log').textContent = ''; pollLog(); @@ -216,11 +219,22 @@ function attachToJob(jobId) { state.logTimer = setInterval(pollLog, 1000); } +// One request at a time: the offset only moves when an answer arrives, so two +// requests in flight would both get, and append, the same text. async function pollLog() { - if (!state.activeJobId) return; + if (!state.activeJobId || state.logPolling) return; + state.logPolling = true; + const offset = state.logOffset; + let stale = false; try { - const data = await api(`/api/job?id=${encodeURIComponent(state.activeJobId)}&offset=${state.logOffset}`); - if (data.id !== state.activeJobId) return; + const data = await api(`/api/job?id=${encodeURIComponent(state.activeJobId)}&offset=${offset}`); + state.logFailures = 0; + if (data.id !== state.activeJobId || offset !== state.logOffset) { + // The view was switched or reset while this was on its way: the text + // belongs to the old one. Ask again for the current one. + stale = true; + return; + } $('log-title').textContent = data.title || ''; if (data.text) { @@ -241,7 +255,18 @@ async function pollLog() { refreshJobs(); } } catch (err) { - stopLogPolling(); + // One failed request does not end the job: keep polling. A persistent error + // (the job is gone, the panel keeps refusing) stops it; the next job start resumes. + state.logFailures += 1; + if (state.logFailures >= 3) { + stopLogPolling(); + alertBox(t('log.pollStopped', err.message), 'error', 9000); + } else if (!state.logTimer) { + alertBox(err.message, 'error', 9000); + } + } finally { + state.logPolling = false; + if (stale) pollLog(); } } @@ -520,6 +545,7 @@ function renderJobs(jobs) { row.onclick = () => { state.activeJobId = job.id; state.logOffset = 0; + state.logFailures = 0; $('log').textContent = ''; pollLog(); if (!job.finishedAt && !state.logTimer) state.logTimer = setInterval(pollLog, 1000); @@ -717,7 +743,8 @@ $('btn-cancel-job').onclick = async () => { if (!state.activeJobId) return; if (!window.confirm(t('confirm.cancelJob'))) return; try { - await api('/api/job/cancel', { method: 'POST', body: { id: state.activeJobId } }); + const res = await api('/api/job/cancel', { method: 'POST', body: { id: state.activeJobId } }); + if (!res || !res.ok) alertBox(t('job.cancelFailed'), 'error', 9000); } catch (err) { alertBox(err.message, 'error', 9000); } @@ -760,7 +787,10 @@ function startPolling() { } // The texts come first: every render below needs them. -initLanguage().then(() => { +initLanguage().catch((err) => { + // Without texts the panel still works: keys stand in for them. + alertBox(`The interface texts could not be loaded (${err.message}). Reload the page.`, 'error'); +}).then(() => { refreshStatus().then(refreshHealth); refreshJobs(); startPolling(); diff --git a/panel/www/i18n/de.json b/panel/www/i18n/de.json index 6fb8336..891006c 100644 --- a/panel/www/i18n/de.json +++ b/panel/www/i18n/de.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "Container revit-proxy entfernen?", "confirm.stopAll": "Alle Revit-Server-Versionen und den Proxy stoppen?", "confirm.cancelJob": "Den laufenden Vorgang abbrechen?", + "job.cancelFailed": "Der Vorgang wurde nicht abgebrochen: Er ist bereits beendet, oder sein Prozess wurde nicht gestoppt.", "confirm.shutdown": "Die Verwaltungsoberfläche schließen?\n\nLaufende Container laufen weiter.", "jobnote.cancelled": "Vorgang vom Benutzer abgebrochen", "jobnote.detached": "der Prozess endete, während die Oberfläche neu gestartet wurde; der Exitcode ist unbekannt, siehe die Ausgabe oben", "jobnote.done": "fertig (Exitcode 0)", "jobnote.unknown": "beendet, der Exitcode ist unbekannt", + "log.pollStopped": "Das Lesen des Protokolls wurde nach wiederholten Fehlern angehalten ({0}). Es wird beim Start des nächsten Vorgangs fortgesetzt.", "jobnote.failed": "Fehler: Exitcode {0}", "jobnote.bindMissing": "Der Modellordner wurde auf dem Computer, auf dem Docker läuft, nicht gefunden. Docker für Windows legt ihn nicht an: Erstellen Sie den Ordner und starten Sie die Version erneut.", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0}: Es ist kein Modellordner angegeben.", "cfg.proxyPanelClash": "Der Proxy-Port ist derselbe wie der Port der Oberfläche.", "cfg.port808": "Port 808 für Revit ist bei mehreren Versionen gleichzeitig aktiviert ({0}). Port 808 ist durch das Revit-Server-Protokoll festgelegt, daher kann ihn nur eine Version nutzen.", + "cfg.port808Version": "Revit Server {0}: Der Host-Port 808 wird auch für die Revit-Verbindung der Version {1} benötigt.", + "cfg.port808Proxy": "Der Proxy-Port ist 808, aber die Revit-Verbindung der Version {0} benötigt diesen Port.", "cfg.unreadable": "{0} konnte nicht gelesen werden ({1}). Es werden die Standardwerte verwendet.", + "cfg.invalidSaved": "Die gespeicherten Einstellungen in {0} sind ungültig und werden ignoriert (Standardwerte werden verwendet): {1}", + "cfg.invalidBackup": "Eine Kopie der Datei wurde als {0} aufbewahrt, da das nächste Speichern der Einstellungen {1} überschreibt.", + "cfg.backupFailed": "Die Kopie der Datei als {0} konnte nicht erstellt werden ({1}). Das nächste Speichern der Einstellungen überschreibt {2}.", "srv.needContext": "Geben Sie den Namen und die Adresse des Kontexts an.", "srv.emptyBody": "Der Anfragetext ist leer.", + "srv.badJson": "Der Anfragetext ist kein gültiges JSON.", + "srv.notObject": "Die Einstellungen müssen als JSON-Objekt gesendet werden.", "srv.needTargetAction": "Ziel und Aktion sind erforderlich.", "srv.allActions": "Für \"alle\" werden nur up und stop unterstützt.", "srv.unknownTarget": "Unbekanntes Ziel: {0}", diff --git a/panel/www/i18n/en.json b/panel/www/i18n/en.json index a67881a..9e1a1ee 100644 --- a/panel/www/i18n/en.json +++ b/panel/www/i18n/en.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "Remove the container revit-proxy?", "confirm.stopAll": "Stop all Revit Server versions and the proxy?", "confirm.cancelJob": "Cancel the running operation?", + "job.cancelFailed": "The operation was not cancelled: it has already finished, or its process did not stop.", "confirm.shutdown": "Close the control panel?\n\nRunning containers keep running.", "jobnote.cancelled": "operation cancelled by the user", "jobnote.detached": "the process ended while the panel was restarted; the exit code is unknown, see the output above", "jobnote.done": "done (exit code 0)", "jobnote.unknown": "finished, the exit code is unknown", + "log.pollStopped": "Reading the log stopped after repeated errors ({0}). It resumes when you start the next operation.", "jobnote.failed": "error: exit code {0}", "jobnote.bindMissing": "The models folder was not found on the machine where Docker runs. Docker for Windows does not create it: create the folder and start the version again.", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0}: no models folder is set.", "cfg.proxyPanelClash": "The proxy port is the same as the panel port.", "cfg.port808": "Port 808 for Revit is on for several versions at once ({0}). Port 808 is fixed by the Revit Server protocol, so only one version can use it.", + "cfg.port808Version": "Revit Server {0}: host port 808 is also needed for the Revit connection of version {1}.", + "cfg.port808Proxy": "The proxy port is 808, but the Revit connection of version {0} needs that port.", "cfg.unreadable": "Could not read {0} ({1}). Default values are used.", + "cfg.invalidSaved": "The saved settings in {0} are not valid and are ignored (default values are used): {1}", + "cfg.invalidBackup": "A copy of the file was kept as {0}, because the next save of the settings overwrites {1}.", + "cfg.backupFailed": "The copy of the file as {0} could not be made ({1}). The next save of the settings overwrites {2}.", "srv.needContext": "Give the name and the address of the context.", "srv.emptyBody": "The request body is empty.", + "srv.badJson": "The request body is not valid JSON.", + "srv.notObject": "The settings must be sent as a JSON object.", "srv.needTargetAction": "The target and the action are required.", "srv.allActions": "For \"all\" only up and stop are supported.", "srv.unknownTarget": "Unknown target: {0}", diff --git a/panel/www/i18n/es.json b/panel/www/i18n/es.json index f245b48..12b0368 100644 --- a/panel/www/i18n/es.json +++ b/panel/www/i18n/es.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "¿Eliminar el contenedor revit-proxy?", "confirm.stopAll": "¿Detener todas las versiones de Revit Server y el proxy?", "confirm.cancelJob": "¿Cancelar la operación en curso?", + "job.cancelFailed": "La operación no se canceló: ya ha terminado o su proceso no se detuvo.", "confirm.shutdown": "¿Cerrar el panel de control?\n\nLos contenedores en ejecución siguen funcionando.", "jobnote.cancelled": "operación cancelada por el usuario", "jobnote.detached": "el proceso terminó mientras se reiniciaba el panel; el código de salida es desconocido, vea la salida de arriba", "jobnote.done": "listo (código de salida 0)", "jobnote.unknown": "terminado, el código de salida es desconocido", + "log.pollStopped": "La lectura del registro se detuvo tras errores repetidos ({0}). Se reanudará al iniciar la siguiente operación.", "jobnote.failed": "error: código de salida {0}", "jobnote.bindMissing": "No se encontró la carpeta de modelos en el equipo donde se ejecuta Docker. Docker para Windows no la crea: cree la carpeta e inicie la versión de nuevo.", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0}: no se ha indicado la carpeta de modelos.", "cfg.proxyPanelClash": "El puerto del proxy coincide con el del panel.", "cfg.port808": "El puerto 808 para Revit está activado en varias versiones a la vez ({0}). El puerto 808 lo fija el protocolo de Revit Server, por lo que solo una versión puede usarlo.", + "cfg.port808Version": "Revit Server {0}: el puerto 808 del host también se necesita para la conexión de Revit de la versión {1}.", + "cfg.port808Proxy": "El puerto del proxy es 808, pero la conexión de Revit de la versión {0} necesita ese puerto.", "cfg.unreadable": "No se pudo leer {0} ({1}). Se usan los valores predeterminados.", + "cfg.invalidSaved": "La configuración guardada en {0} no es válida y se ignora (se usan los valores predeterminados): {1}", + "cfg.invalidBackup": "Se guardó una copia del archivo como {0}, porque el próximo guardado de la configuración sobrescribe {1}.", + "cfg.backupFailed": "No se pudo crear la copia del archivo como {0} ({1}). El próximo guardado de la configuración sobrescribe {2}.", "srv.needContext": "Indique el nombre y la dirección del contexto.", "srv.emptyBody": "El cuerpo de la solicitud está vacío.", + "srv.badJson": "El cuerpo de la solicitud no es un JSON válido.", + "srv.notObject": "La configuración debe enviarse como un objeto JSON.", "srv.needTargetAction": "Se necesitan el destino y la acción.", "srv.allActions": "Para \"todo\" solo se admiten up y stop.", "srv.unknownTarget": "Destino desconocido: {0}", diff --git a/panel/www/i18n/fr.json b/panel/www/i18n/fr.json index f20c335..f2af74e 100644 --- a/panel/www/i18n/fr.json +++ b/panel/www/i18n/fr.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "Supprimer le conteneur revit-proxy ?", "confirm.stopAll": "Arrêter toutes les versions de Revit Server et le proxy ?", "confirm.cancelJob": "Annuler l'opération en cours ?", + "job.cancelFailed": "L'opération n'a pas été annulée : elle est déjà terminée ou son processus ne s'est pas arrêté.", "confirm.shutdown": "Fermer le panneau de contrôle ?\n\nLes conteneurs en cours continuent de fonctionner.", "jobnote.cancelled": "opération annulée par l'utilisateur", "jobnote.detached": "le processus s'est terminé pendant le redémarrage du panneau ; le code de sortie est inconnu, voir la sortie ci-dessus", "jobnote.done": "terminé (code de sortie 0)", "jobnote.unknown": "terminé, le code de sortie est inconnu", + "log.pollStopped": "La lecture du journal s'est arrêtée après des erreurs répétées ({0}). Elle reprendra au démarrage de la prochaine opération.", "jobnote.failed": "erreur : code de sortie {0}", "jobnote.bindMissing": "Le dossier des modèles est introuvable sur l'ordinateur où Docker fonctionne. Docker pour Windows ne le crée pas : créez le dossier et redémarrez la version.", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0} : aucun dossier des modèles n'est défini.", "cfg.proxyPanelClash": "Le port du proxy est le même que celui du panneau.", "cfg.port808": "Le port 808 pour Revit est activé pour plusieurs versions à la fois ({0}). Le port 808 est fixé par le protocole de Revit Server, une seule version peut donc l'utiliser.", + "cfg.port808Version": "Revit Server {0} : le port hôte 808 est aussi nécessaire à la connexion de Revit de la version {1}.", + "cfg.port808Proxy": "Le port du proxy est 808, mais la connexion de Revit de la version {0} a besoin de ce port.", "cfg.unreadable": "Impossible de lire {0} ({1}). Les valeurs par défaut sont utilisées.", + "cfg.invalidSaved": "Les paramètres enregistrés dans {0} ne sont pas valides et sont ignorés (valeurs par défaut utilisées) : {1}", + "cfg.invalidBackup": "Une copie du fichier a été conservée sous {0}, car le prochain enregistrement des paramètres écrase {1}.", + "cfg.backupFailed": "La copie du fichier sous {0} n'a pas pu être créée ({1}). Le prochain enregistrement des paramètres écrase {2}.", "srv.needContext": "Indiquez le nom et l'adresse du contexte.", "srv.emptyBody": "Le corps de la requête est vide.", + "srv.badJson": "Le corps de la requête n'est pas un JSON valide.", + "srv.notObject": "Les paramètres doivent être envoyés sous forme d'objet JSON.", "srv.needTargetAction": "La cible et l'action sont obligatoires.", "srv.allActions": "Pour \"tout\", seules les actions up et stop sont prises en charge.", "srv.unknownTarget": "Cible inconnue : {0}", diff --git a/panel/www/i18n/ja.json b/panel/www/i18n/ja.json index b830b17..9fa1e49 100644 --- a/panel/www/i18n/ja.json +++ b/panel/www/i18n/ja.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "コンテナー revit-proxy を削除しますか?", "confirm.stopAll": "すべての Revit Server バージョンとプロキシを停止しますか?", "confirm.cancelJob": "実行中の操作を中止しますか?", + "job.cancelFailed": "操作は中止されませんでした。すでに終了しているか、プロセスが停止しませんでした。", "confirm.shutdown": "コントロールパネルを閉じますか?\n\n実行中のコンテナーは動き続けます。", "jobnote.cancelled": "ユーザーが操作を中止しました", "jobnote.detached": "パネルの再起動中にプロセスが終了しました。終了コードは不明です。上の出力を確認してください", "jobnote.done": "完了 (終了コード 0)", "jobnote.unknown": "終了しました。終了コードは不明です", + "log.pollStopped": "エラーが繰り返されたため、ログの読み取りを停止しました({0})。次の操作を開始すると再開します。", "jobnote.failed": "エラー: 終了コード {0}", "jobnote.bindMissing": "Docker が動作しているコンピューターにモデルフォルダーが見つかりません。Windows 用 Docker はフォルダーを作成しません。フォルダーを作成してから、もう一度起動してください。", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0}: モデルフォルダーが指定されていません。", "cfg.proxyPanelClash": "プロキシのポートがパネルのポートと同じです。", "cfg.port808": "Revit 用のポート 808 が複数のバージョンで同時に有効になっています ({0})。ポート 808 は Revit Server のプロトコルで固定されているため、使えるバージョンは 1 つだけです。", + "cfg.port808Version": "Revit Server {0}: ホストのポート 808 は、バージョン {1} の Revit 接続にも必要です。", + "cfg.port808Proxy": "プロキシのポートが 808 ですが、バージョン {0} の Revit 接続がそのポートを必要としています。", "cfg.unreadable": "{0} を読み込めませんでした ({1})。既定値を使用します。", + "cfg.invalidSaved": "{0} に保存された設定が無効なため無視され、既定値が使われます: {1}", + "cfg.invalidBackup": "次に設定を保存すると {1} が上書きされるため、ファイルのコピーを {0} として残しました。", + "cfg.backupFailed": "ファイルのコピーを {0} として保存できませんでした({1})。次に設定を保存すると {2} が上書きされます。", "srv.needContext": "コンテキストの名前とアドレスを指定してください。", "srv.emptyBody": "リクエストの本文が空です。", + "srv.badJson": "リクエスト本文が正しい JSON ではありません。", + "srv.notObject": "設定は JSON オブジェクトとして送信してください。", "srv.needTargetAction": "対象と操作の指定が必要です。", "srv.allActions": "「すべて」では up と stop のみ使えます。", "srv.unknownTarget": "不明な対象: {0}", diff --git a/panel/www/i18n/pt-BR.json b/panel/www/i18n/pt-BR.json index 620d4c0..f618bf0 100644 --- a/panel/www/i18n/pt-BR.json +++ b/panel/www/i18n/pt-BR.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "Remover o contêiner revit-proxy?", "confirm.stopAll": "Parar todas as versões do Revit Server e o proxy?", "confirm.cancelJob": "Cancelar a operação em andamento?", + "job.cancelFailed": "A operação não foi cancelada: ela já terminou ou o processo não parou.", "confirm.shutdown": "Fechar o painel de controle?\n\nOs contêineres em execução continuam funcionando.", "jobnote.cancelled": "operação cancelada pelo usuário", "jobnote.detached": "o processo terminou enquanto o painel era reiniciado; o código de saída é desconhecido, veja a saída acima", "jobnote.done": "concluído (código de saída 0)", "jobnote.unknown": "terminado, o código de saída é desconhecido", + "log.pollStopped": "A leitura do log parou após erros repetidos ({0}). Ela continua quando você inicia a próxima operação.", "jobnote.failed": "erro: código de saída {0}", "jobnote.bindMissing": "A pasta de modelos não foi encontrada no computador onde o Docker está em execução. O Docker para Windows não a cria: crie a pasta e inicie a versão novamente.", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0}: nenhuma pasta de modelos foi definida.", "cfg.proxyPanelClash": "A porta do proxy é a mesma do painel.", "cfg.port808": "A porta 808 para o Revit está ativada em várias versões ao mesmo tempo ({0}). A porta 808 é fixada pelo protocolo do Revit Server, então apenas uma versão pode usá-la.", + "cfg.port808Version": "Revit Server {0}: a porta 808 do host também é necessária para a conexão do Revit da versão {1}.", + "cfg.port808Proxy": "A porta do proxy é 808, mas a conexão do Revit da versão {0} precisa dessa porta.", "cfg.unreadable": "Não foi possível ler {0} ({1}). Os valores padrão são usados.", + "cfg.invalidSaved": "As configurações salvas em {0} não são válidas e foram ignoradas (valores padrão em uso): {1}", + "cfg.invalidBackup": "Uma cópia do arquivo foi mantida como {0}, porque o próximo salvamento das configurações substitui {1}.", + "cfg.backupFailed": "Não foi possível criar a cópia do arquivo como {0} ({1}). O próximo salvamento das configurações substitui {2}.", "srv.needContext": "Informe o nome e o endereço do contexto.", "srv.emptyBody": "O corpo da requisição está vazio.", + "srv.badJson": "O corpo da requisição não é um JSON válido.", + "srv.notObject": "As configurações devem ser enviadas como um objeto JSON.", "srv.needTargetAction": "O destino e a ação são obrigatórios.", "srv.allActions": "Para \"tudo\" só são aceitos up e stop.", "srv.unknownTarget": "Destino desconhecido: {0}", diff --git a/panel/www/i18n/ru.json b/panel/www/i18n/ru.json index f780a5d..5ae583e 100644 --- a/panel/www/i18n/ru.json +++ b/panel/www/i18n/ru.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "Удалить контейнер revit-proxy?", "confirm.stopAll": "Остановить все версии Revit Server и прокси?", "confirm.cancelJob": "Прервать выполняющуюся операцию?", + "job.cancelFailed": "Операция не прервана: она уже завершилась, или её процесс не остановился.", "confirm.shutdown": "Закрыть панель управления?\n\nЗапущенные контейнеры продолжат работать.", "jobnote.cancelled": "операция прервана пользователем", "jobnote.detached": "процесс завершился, пока панель была перезапущена; код возврата неизвестен, см. вывод выше", "jobnote.done": "готово (код возврата 0)", "jobnote.unknown": "завершено, код возврата неизвестен", + "log.pollStopped": "Чтение журнала остановлено после повторных ошибок ({0}). Оно возобновится при запуске следующей операции.", "jobnote.failed": "ошибка: код возврата {0}", "jobnote.bindMissing": "Папка моделей не найдена на машине, где работает Docker. Docker для Windows сам её не создаёт: создайте папку и запустите версию снова.", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0}: не задана папка с моделями.", "cfg.proxyPanelClash": "Порт прокси совпадает с портом панели.", "cfg.port808": "Порт 808 для Revit включён сразу у нескольких версий ({0}). Порт 808 фиксирован в протоколе Revit Server, поэтому его может занимать только одна версия.", + "cfg.port808Version": "Revit Server {0}: порт хоста 808 нужен также для подключения Revit версии {1}.", + "cfg.port808Proxy": "Порт прокси равен 808, но этот порт нужен для подключения Revit версии {0}.", "cfg.unreadable": "Не удалось прочитать {0} ({1}). Используются значения по умолчанию.", + "cfg.invalidSaved": "Сохранённые настройки в {0} недопустимы и игнорируются (используются значения по умолчанию): {1}", + "cfg.invalidBackup": "Копия файла сохранена как {0}, потому что следующее сохранение настроек перезапишет {1}.", + "cfg.backupFailed": "Не удалось сохранить копию файла как {0} ({1}). Следующее сохранение настроек перезапишет {2}.", "srv.needContext": "Нужно указать имя контекста и адрес.", "srv.emptyBody": "Пустое тело запроса.", + "srv.badJson": "Тело запроса не является корректным JSON.", + "srv.notObject": "Настройки нужно передавать как JSON-объект.", "srv.needTargetAction": "Нужно указать цель и действие.", "srv.allActions": "Для «всех» поддерживаются только up и stop.", "srv.unknownTarget": "Неизвестная цель: {0}", diff --git a/panel/www/i18n/zh-CN.json b/panel/www/i18n/zh-CN.json index 64866ea..7115b66 100644 --- a/panel/www/i18n/zh-CN.json +++ b/panel/www/i18n/zh-CN.json @@ -64,12 +64,14 @@ "confirm.removeProxy": "删除容器 revit-proxy?", "confirm.stopAll": "停止所有 Revit Server 版本和代理?", "confirm.cancelJob": "中止正在执行的操作?", + "job.cancelFailed": "操作未中止:它已经结束,或其进程未停止。", "confirm.shutdown": "关闭控制面板?\n\n正在运行的容器会继续运行。", "jobnote.cancelled": "操作已被用户中止", "jobnote.detached": "面板重启期间进程已结束;退出代码未知,请查看上面的输出", "jobnote.done": "完成(退出代码 0)", "jobnote.unknown": "已结束,退出代码未知", + "log.pollStopped": "日志读取在多次出错后已停止({0})。开始下一个操作时会恢复。", "jobnote.failed": "错误:退出代码 {0}", "jobnote.bindMissing": "在运行 Docker 的计算机上找不到模型文件夹。Windows 版 Docker 不会自动创建它:请先创建该文件夹,然后重新启动此版本。", @@ -163,10 +165,17 @@ "cfg.noDir": "Revit Server {0}:未设置模型文件夹。", "cfg.proxyPanelClash": "代理端口与面板端口相同。", "cfg.port808": "多个版本同时启用了 Revit 的端口 808({0})。端口 808 由 Revit Server 协议固定,因此只有一个版本可以使用。", + "cfg.port808Version": "Revit Server {0}:主机端口 808 也是版本 {1} 的 Revit 连接所需要的。", + "cfg.port808Proxy": "代理端口为 808,但版本 {0} 的 Revit 连接需要该端口。", "cfg.unreadable": "无法读取 {0}({1})。将使用默认值。", + "cfg.invalidSaved": "{0} 中保存的设置无效,已被忽略(使用默认值):{1}", + "cfg.invalidBackup": "已将该文件的副本保存为 {0},因为下次保存设置时会覆盖 {1}。", + "cfg.backupFailed": "无法将该文件的副本保存为 {0}({1})。下次保存设置时会覆盖 {2}。", "srv.needContext": "请填写上下文的名称和地址。", "srv.emptyBody": "请求内容为空。", + "srv.badJson": "请求正文不是有效的 JSON。", + "srv.notObject": "设置必须以 JSON 对象的形式发送。", "srv.needTargetAction": "必须指定目标和操作。", "srv.allActions": "对于“全部”,只支持 up 和 stop。", "srv.unknownTarget": "未知目标:{0}", diff --git a/samples/docker-compose.2020.yml b/samples/docker-compose.2020.yml index 4042a0d..e0ec08e 100644 --- a/samples/docker-compose.2020.yml +++ b/samples/docker-compose.2020.yml @@ -1,6 +1,9 @@ services: rs2020: - build: ../src/rs2020 + build: + context: ../src/rs2020 + args: + INSTALLER_SHA256: ${RS2020_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2020 ports: - 2020:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/samples/docker-compose.2021.yml b/samples/docker-compose.2021.yml index d1616e4..25f61d8 100644 --- a/samples/docker-compose.2021.yml +++ b/samples/docker-compose.2021.yml @@ -1,6 +1,9 @@ services: rs2021: - build: ../src/rs2021 + build: + context: ../src/rs2021 + args: + INSTALLER_SHA256: ${RS2021_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2021 ports: - 2021:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/samples/docker-compose.2022.yml b/samples/docker-compose.2022.yml index 9fffe6f..4ffa602 100644 --- a/samples/docker-compose.2022.yml +++ b/samples/docker-compose.2022.yml @@ -1,6 +1,9 @@ services: rs2022: - build: ../src/rs2022 + build: + context: ../src/rs2022 + args: + INSTALLER_SHA256: ${RS2022_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2022 ports: - 2022:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/samples/docker-compose.2023.yml b/samples/docker-compose.2023.yml index 57bf41c..675fa10 100644 --- a/samples/docker-compose.2023.yml +++ b/samples/docker-compose.2023.yml @@ -1,6 +1,9 @@ services: rs2023: - build: ../src/rs2023 + build: + context: ../src/rs2023 + args: + INSTALLER_SHA256: ${RS2023_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2023 ports: - 2023:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/samples/docker-compose.2024.yml b/samples/docker-compose.2024.yml index 84f3c01..3fa6890 100644 --- a/samples/docker-compose.2024.yml +++ b/samples/docker-compose.2024.yml @@ -1,6 +1,9 @@ services: rs2024: - build: ../src/rs2024 + build: + context: ../src/rs2024 + args: + INSTALLER_SHA256: ${RS2024_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2024 ports: - 2024:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/samples/docker-compose.2025.yml b/samples/docker-compose.2025.yml index 674fd70..79fb006 100644 --- a/samples/docker-compose.2025.yml +++ b/samples/docker-compose.2025.yml @@ -1,6 +1,9 @@ services: rs2025: - build: ../src/rs2025 + build: + context: ../src/rs2025 + args: + INSTALLER_SHA256: ${RS2025_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2025 ports: - 2025:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/samples/docker-compose.2026.yml b/samples/docker-compose.2026.yml index bae7ed3..9144513 100644 --- a/samples/docker-compose.2026.yml +++ b/samples/docker-compose.2026.yml @@ -1,6 +1,9 @@ services: rs2026: - build: ../src/rs2026 + build: + context: ../src/rs2026 + args: + INSTALLER_SHA256: ${RS2026_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2026 ports: - 2026:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/samples/docker-compose.2027.yml b/samples/docker-compose.2027.yml index 3b6e83f..a6556bc 100644 --- a/samples/docker-compose.2027.yml +++ b/samples/docker-compose.2027.yml @@ -1,6 +1,9 @@ services: rs2027: - build: ../src/rs2027 + build: + context: ../src/rs2027 + args: + INSTALLER_SHA256: ${RS2027_INSTALLER_SHA256:-} # optional, see README.md container_name: rs2027 ports: - 2027:80 # upstream for the reverse proxy (docker-compose.proxy.yml) diff --git a/src/rs2020/Dockerfile b/src/rs2020/Dockerfile index ec25bf5..32d3f12 100644 --- a/src/rs2020/Dockerfile +++ b/src/rs2020/Dockerfile @@ -21,7 +21,12 @@ SHELL ["CMD", "/C"] WORKDIR /Autodesk # ADD Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe ADD "https://efulfillment.autodesk.com/NetSWDLD/2020/RVTRS/20210709_1515/SFX/Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe" Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe -RUN START /W Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe does not match INSTALLER_SHA256' }" && ` + START /W Revit_Server_2020_1_G1_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" WORKDIR /Autodesk/Revit_Server_2020_1_G1_Win_64bit_dlm/x64/RS2021 RUN START /wait msiexec /i RevitServer.msi /q ` diff --git a/src/rs2021/Dockerfile b/src/rs2021/Dockerfile index 595bcf2..52918a9 100644 --- a/src/rs2021/Dockerfile +++ b/src/rs2021/Dockerfile @@ -21,7 +21,12 @@ SHELL ["CMD", "/C"] WORKDIR /Autodesk # ADD Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe ADD "https://efulfillment.autodesk.com/NetSWDLD/2021/RVTRS/20210709_1515/SFX/Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe" Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe -RUN START /W Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe does not match INSTALLER_SHA256' }" && ` + START /W Revit_Server_2021_1_G1_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" WORKDIR /Autodesk/Revit_Server_2021_1_G1_Win_64bit_dlm/x64/RS2021 RUN START /wait msiexec /i RevitServer.msi /q ` diff --git a/src/rs2022/Dockerfile b/src/rs2022/Dockerfile index 6fd3de9..d390f0d 100644 --- a/src/rs2022/Dockerfile +++ b/src/rs2022/Dockerfile @@ -21,7 +21,12 @@ SHELL ["CMD", "/C"] WORKDIR /Autodesk # ADD Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe ADD "https://efulfillment.autodesk.com/NetSWDLD/2022/RVTRS/20210709_1515/SFX/Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe" Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe -RUN START /W Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe does not match INSTALLER_SHA256' }" && ` + START /W Revit_Server_2022_1_G1_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" WORKDIR /Autodesk/Revit_Server_2022_1_G1_Win_64bit_dlm/x64/RS2022 RUN START /wait msiexec /i RevitServer.msi /q ` diff --git a/src/rs2023/Dockerfile b/src/rs2023/Dockerfile index 0b21bd4..00c8a3e 100644 --- a/src/rs2023/Dockerfile +++ b/src/rs2023/Dockerfile @@ -21,7 +21,12 @@ SHELL ["CMD", "/C"] WORKDIR /Autodesk # ADD Revit_Server_2023_Win_64bit_dlm.sfx.exe Revit_Server_2023_Win_64bit_dlm.sfx.exe ADD "https://up.autodesk.com/2023/RVT/5A37FF7C-EA37-3FE6-8EF6-7382D03DEE46/Revit_Server_2023_Win_64bit_dlm.sfx.exe" Revit_Server_2023_Win_64bit_dlm.sfx.exe -RUN START /W Revit_Server_2023_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2023_Win_64bit_dlm.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2023_Win_64bit_dlm.sfx.exe does not match INSTALLER_SHA256' }" && ` + START /W Revit_Server_2023_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" WORKDIR /Autodesk/Revit_Server_2023_Win_64bit_dlm/x64/RS2023 RUN START /wait msiexec /i RevitServer.msi /q ` diff --git a/src/rs2024/Dockerfile b/src/rs2024/Dockerfile index 79ef5cf..4b61d7c 100644 --- a/src/rs2024/Dockerfile +++ b/src/rs2024/Dockerfile @@ -21,7 +21,12 @@ SHELL ["CMD", "/C"] WORKDIR /Autodesk # ADD Revit_Server_2024_Win_64bit_dlm.sfx.exe Revit_Server_2024_Win_64bit_dlm.sfx.exe ADD "https://up1.autodesk.com/2024/RVT/5A37FF7C-EA37-3FE6-8EF6-7382D03DEE46/Revit_Server_2024_Win_64bit_dlm.sfx.exe" Revit_Server_2024_Win_64bit_dlm.sfx.exe -RUN START /W Revit_Server_2024_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2024_Win_64bit_dlm.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2024_Win_64bit_dlm.sfx.exe does not match INSTALLER_SHA256' }" && ` + START /W Revit_Server_2024_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" WORKDIR /Autodesk/Revit_Server_2024_Win_64bit_dlm/x64/RS2024 RUN START /wait msiexec /i RevitServer.msi /q ` diff --git a/src/rs2025/Dockerfile b/src/rs2025/Dockerfile index 5174cb9..8dd9bc5 100644 --- a/src/rs2025/Dockerfile +++ b/src/rs2025/Dockerfile @@ -21,7 +21,12 @@ SHELL ["CMD", "/C"] WORKDIR /Autodesk # ADD Revit_Server_2025_Win_64bit_dlm.sfx.exe Revit_Server_2025_Win_64bit_dlm.sfx.exe ADD "https://up1.autodesk.com/NetSWCOM/RVT/2025/Revit_Server_2025_Win_64bit_dlm.sfx.exe" Revit_Server_2025_Win_64bit_dlm.sfx.exe -RUN START /W Revit_Server_2025_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2025_Win_64bit_dlm.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2025_Win_64bit_dlm.sfx.exe does not match INSTALLER_SHA256' }" && ` + START /W Revit_Server_2025_Win_64bit_dlm.sfx.exe -suppresslaunch -d "C:\Autodesk" WORKDIR /Autodesk/Revit_Server_2025_Win_64bit_dlm/x64/RS2025 RUN START /wait msiexec /i RevitServer.msi /q ` diff --git a/src/rs2026/Dockerfile b/src/rs2026/Dockerfile index c8bdffb..f2d7344 100644 --- a/src/rs2026/Dockerfile +++ b/src/rs2026/Dockerfile @@ -26,7 +26,11 @@ WORKDIR /Autodesk # (see CONTRIBUTING.md before changing the file names below). ADD https://github.com/ip7z/7zip/releases/download/26.04/7zr.exe 7zr.exe ADD "https://damassets.autodesk.net/content/dam/autodesk/external-assets/support-articles/autodesk-revit-server-2026/Revit_Server_2026_4_win_db.sfx.exe" Revit_Server_2026_4_win_db.sfx.exe -RUN powershell -NoProfile -Command "if ((Get-FileHash 7zr.exe -Algorithm SHA256).Hash -ne '256FECA8E274E5DA655E2A284FABAFD9F554365EB164862089DACD4E8276D282') { throw '7zr.exe does not match the SHA-256 published for 7-Zip 26.04' }" && ` +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ((Get-FileHash 7zr.exe -Algorithm SHA256).Hash -ne '256FECA8E274E5DA655E2A284FABAFD9F554365EB164862089DACD4E8276D282') { throw '7zr.exe does not match the SHA-256 published for 7-Zip 26.04' }; if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2026_4_win_db.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2026_4_win_db.sfx.exe does not match INSTALLER_SHA256' }" && ` .\7zr.exe x Revit_Server_2026_4_win_db.sfx.exe -oC:\Autodesk\bundle -y RVT_2026_4_NA_win_db_002_002.7z && ` .\7zr.exe x C:\Autodesk\bundle\RVT_2026_4_NA_win_db_002_002.7z -oC:\Autodesk\image -y -r x64\RSVR\* && ` rd /s /q C:\Autodesk\bundle diff --git a/src/rs2027/Dockerfile b/src/rs2027/Dockerfile index 1b30370..bdb2d2d 100644 --- a/src/rs2027/Dockerfile +++ b/src/rs2027/Dockerfile @@ -26,7 +26,11 @@ WORKDIR /Autodesk # (see CONTRIBUTING.md before changing the file names below). ADD https://github.com/ip7z/7zip/releases/download/26.04/7zr.exe 7zr.exe ADD "https://damassets.autodesk.net/content/dam/autodesk/external-assets/support-articles/autodesk-revit-server-2027/Revit_Server_2027_win_db.sfx.exe" Revit_Server_2027_win_db.sfx.exe -RUN powershell -NoProfile -Command "if ((Get-FileHash 7zr.exe -Algorithm SHA256).Hash -ne '256FECA8E274E5DA655E2A284FABAFD9F554365EB164862089DACD4E8276D282') { throw '7zr.exe does not match the SHA-256 published for 7-Zip 26.04' }" && ` +# Optional integrity check: docker build --build-arg INSTALLER_SHA256= +# fails the build when the downloaded installer is another file. Empty = not checked +# (see "Verifying the installers" in README.md). +ARG INSTALLER_SHA256= +RUN powershell -NoProfile -Command "if ((Get-FileHash 7zr.exe -Algorithm SHA256).Hash -ne '256FECA8E274E5DA655E2A284FABAFD9F554365EB164862089DACD4E8276D282') { throw '7zr.exe does not match the SHA-256 published for 7-Zip 26.04' }; if ($env:INSTALLER_SHA256 -and (Get-FileHash Revit_Server_2027_win_db.sfx.exe -Algorithm SHA256).Hash -ne $env:INSTALLER_SHA256) { throw 'Revit_Server_2027_win_db.sfx.exe does not match INSTALLER_SHA256' }" && ` .\7zr.exe x Revit_Server_2027_win_db.sfx.exe -oC:\Autodesk\bundle -y RVT_2027_NA_win_db_002_002.7z && ` .\7zr.exe x C:\Autodesk\bundle\RVT_2027_NA_win_db_002_002.7z -oC:\Autodesk\image -y -r x64\RSVR\* && ` rd /s /q C:\Autodesk\bundle