fix(generator): align local builds with provider capabilities

Resolve embedded artifacts from the validated manifest, expose only targets supported by the local toolchain, and keep per-target failures isolated. Update generator APIs, UI, documentation, and regression coverage.

Thanks: INSOLVE (Honorary); Marco Jakobs (@jacotec); MyNameisStitch (@MyNameisStitch); Redspin (@playerumpknow)
This commit is contained in:
UNITRONIX
2026-10-05 06:55:49 +02:00
parent cfcbc9f535
commit bea83ba2e9
41 changed files with 2567 additions and 105 deletions
+15 -8
View File
@@ -23,15 +23,22 @@
- **Migration:** a root operator must rerun the ensure script once to replace older broad sudoers entries and remove any legacy `ExecStartPre=+...linux-ensure-console-user.js` line from the console unit. Verify with `sudo visudo -cf /etc/sudoers.d/betterdesk-console-updates` and `sudo systemctl cat betterdesk-console`.
- **Windows path root (#272):** `resolveProjectRoot()` must never resolve to a drive root (`C:\`). Default layout `C:\BetterDeskConsole` + `C:\BetterDesk` writes Scripts & Docker files under the console directory. `ensureParentDirForFile()` skips `mkdir` on filesystem roots (Node throws `EPERM` on `mkdir('C:\\')`). NSSM OpenService Access Denied when restarting `BetterDeskServer` is non-critical — restart the Go service manually or via `betterdesk.ps1` if needed.
### Support Agent generator phase
### Embedded Support Client rebuild phase
When an update changes Support Agent inputs, `applyUpdate()` records
`.agent_rebuild_pending` with the deployed commit and returns without syncing
or queueing agent builds. After the console restarts,
`agentBuildWorker.processPendingRebuildOnStartup()` synchronizes the complete
agent source tree first and then requeues non-revoked Support Agent bundles.
The worker retries safely if either step fails, while Agent Client and RdClient
workers remain independent.
When embedded Client generation is enabled, `applyUpdate()` checks the pinned
BetterDesk-Client ref separately from the BetterDesk ref. A changed Client
commit is downloaded into `data/modules/betterdesk-client-builder/` outside
the BetterDesk checkout, verified, and passed to the embedded build provider.
The worker then queues one new generation for every non-revoked Support
configuration. Each generation contains every target exposed by the active
build provider and is promoted only after every artifact passes its
manifest/checksum/SKU and no-`custom.txt` checks. The built-in local provider
is host-only; it does not queue unsupported cross-platform targets.
The update does not rebuild on every download. Existing public links continue
to serve their previous active generation until the replacement is complete.
After a restart, `clientBuilderService.syncAndQueueRebuilds()` resumes
retryable work without changing an active link to a partial generation.
## Issue #158 — server build / config preservation
+52 -21
View File
@@ -1,6 +1,6 @@
# Client Generator
The **BetterDesk Support Generator** in the web console builds **incoming-only** desktop installers from BetterDesk-Client portable templates. Each build injects a server-locked `custom.txt` (rendezvous, relay, API, public key). End users download from a public hub page — no manual network configuration.
The **BetterDesk Support Generator** in the web console builds **incoming-only** desktop installers from the independent BetterDesk-Client repository. In embedded mode, the signed server profile is supplied at compile time and stored inside the client binary; the delivered archive contains no `custom.txt` or other external server configuration file. End users download a stable artifact from a public hub page — downloading does not trigger another build.
Appearance (logo, colors) is **not** baked into installers. The desktop client loads branding at runtime from the Console **Client Branding API**.
@@ -12,7 +12,7 @@ Each Support bundle produces portable artifacts that:
- Use BetterDesk-Client desktop binaries (AGPL)
- Force **incoming-only** (`conn-type: incoming`)
- Override server settings via signed or plain `custom.txt`
- Embed server settings and the permanent incoming-only policy in the binary
- Target Windows / Linux / macOS (x64 + ARM64 portable)
| Platform | Format |
@@ -23,23 +23,24 @@ Each Support bundle produces portable artifacts that:
---
## Module install (first run)
## Builder install (first run)
Before creating bundles, admins install the **betterdesk-support-generator** module:
Before creating embedded bundles, admins configure the **BetterDesk-Client builder**:
1. Open **Generator**
2. Read the AGPL / incoming-only notice and click **Accept terms**
3. Click **Install from GitHub** — downloads and verifies `generator-templates-*.tar.gz` from [BetterDesk-Client](https://github.com/UNITRONIX/BetterDesk-Client) Releases (`BETTERDESK_CLIENT_REPO`, default `UNITRONIX/BetterDesk-Client`)
4. Alternatively choose **Install local package** and upload the archive downloaded from a Client release
5. Click **Finish installation** when status is `ready`
1. Open **Generator** and accept the AGPL / incoming-only notice.
2. Configure the public [BetterDesk-Client](https://github.com/UNITRONIX/BetterDesk-Client) repository and branch/ref.
3. The BetterDesk server uses its built-in local builder. It receives one JSON request, downloads/uses the pinned Client source, compiles the incoming-only profile and writes verified target archives to the runtime output directory.
4. Run the builder connection/source check. The console downloads a pinned source snapshot outside the BetterDesk checkout.
5. Create a Support config. The config is built once per Client commit and reused by its download link.
Module data lives under:
Builder data lives under:
```text
{dataDir}/modules/betterdesk-support-generator/
{dataDir}/modules/betterdesk-client-builder/
state.json
templates/ # extracted generator-templates layout + manifest.json
custom-client-signing.seed # required for production Support builds; from env or file
source/ # pinned BetterDesk-Client snapshot; never part of the BetterDesk repo
requests/ # private, short-lived build requests
outputs/ # provider output before verification
```
Signing seed:
@@ -47,7 +48,7 @@ Signing seed:
- Env: `BETTERDESK_CUSTOM_CLIENT_SIGNING_SEED` (base64 32-byte NaCl seed)
- Or file `custom-client-signing.seed` copied into the module dir
The module refuses to become ready without a valid seed. Every production Support bundle contains a signed base64 `custom.txt` (Phase B); unsigned plain JSON is available only to debug builds of the client.
The signing seed is never sent to the builder. The console signs the payload, sends only the signed value, and the Client build embeds it. Plain JSON and external `custom.txt` are not accepted by the embedded production path.
---
@@ -67,7 +68,21 @@ Defaults come from `/api/generator/defaults` (`keyService` + `clientConfigHost`)
- HTTPS toggle + API port
- Server public key (`id_ed25519.pub`)
The worker writes `custom.txt` beside the binary (or under `Contents/MacOS` on macOS) using the Support Agent example shape (`override-settings`, `conn-type: incoming`).
The worker sends the signed Support payload to the build provider. The provider embeds it in the binary; the final archive contains no `custom.txt`.
### Build generations and automatic updates
The console stores each Support configuration as a reusable profile. It does not rebuild when somebody downloads a client. A profile has one artifact set per Client commit and target.
When the BetterDesk-Client ref changes, the panel update flow:
1. resolves and downloads the new commit into the data directory;
2. queues one new generation for every non-revoked Support profile;
3. builds every target exposed by the configured provider in the background;
4. verifies the manifest, checksum, Support SKU and absence of `custom.txt`;
5. atomically switches each profile's existing link only after all required targets are ready.
If a target fails, the previous generation remains active and the worker retries after restart. Existing links are never switched to a partial generation.
### Service and autostart
@@ -84,14 +99,29 @@ For native, Docker and Windows installations configure these values in the Bette
```text
BETTERDESK_CLIENT_REPO=UNITRONIX/BetterDesk-Client
BETTERDESK_CLIENT_RELEASE_TAG=
BETTERDESK_CLIENT_ALLOWED_REPOS=UNITRONIX/BetterDesk-Client
BETTERDESK_CLIENT_REF=master
BETTERDESK_GITHUB_TOKEN=
BETTERDESK_CUSTOM_CLIENT_SIGNING_SEED=
BETTERDESK_CLIENT_GENERATOR_MODE=embedded
# Optional remote fallback; local server builder is the default.
BETTERDESK_CLIENT_GITHUB_ACTIONS=off
BETTERDESK_CLIENT_BUILD_WORKFLOW=support-build.yml
# Optional trusted local provider override:
# BETTERDESK_CLIENT_BUILD_COMMAND=/path/to/trusted-builder
BETTERDESK_CLIENT_BUILD_TIMEOUT_MS=3600000
AGENT_ARTIFACT_DIR=<dataDir>/agent-builds
AGENT_BUILD_WORKER=on
```
The signing seed is secret. The console service account needs read/write access to the module, build cache and artifact directories, while the seed should be readable only by the console service. Do not expose `agent-builds` or the module directory as a static web directory.
The signing seed is secret. The console service account needs read/write access to the builder, build cache and artifact directories, while the seed should be readable only by the console service. Do not expose `agent-builds`, builder requests or the source directory as static web directories. The build command must be an operator-installed, trusted provider; never accept it from a web request.
The built-in local provider is host-only: it exposes a target only when the
host platform and its required Cargo, Flutter and vcpkg toolchain are
available. On a Linux console this normally means Linux x64. Unsupported
platforms are omitted from the generator instead of being queued and later
reported with a misleading artifact error. A complete cross-platform matrix
requires a provider that supplies those targets.
---
@@ -99,9 +129,9 @@ The signing seed is secret. The console service account needs read/write access
| Piece | Role |
|-------|------|
| `supportGeneratorModule.js` | Terms + GitHub template install gate |
| `customTxtBuilder.js` | Build / sign `custom.txt` (`tweetnacl`) |
| `clientTemplateWorker.js` | Queue builds, inject templates, store artifacts in `data/agent-builds/` |
| `clientBuilderService.js` | Pinned Client source sync, provider request and generation identity |
| `customTxtBuilder.js` | Create the signed payload that is embedded during the Client build |
| `clientTemplateWorker.js` | Queue embedded builds, verify artifacts, promote complete generations |
| `agent_bundles` / `agent_bundle_builds` | Existing DB tables (product_type `betterdesk-support`) |
Legacy Go **Support Agent** (`betterdesk-support-agent`) and compile-on-console workers are removed. Old product types (`support-agent`, `agent`, `agent-client`, `rdclient`) normalize to `betterdesk-support` for compatibility.
@@ -115,4 +145,5 @@ Legacy Go **Support Agent** (`betterdesk-support-agent`) and compile-on-console
- Support clients are **inbound-only** — end users cannot browse or connect outbound to other devices on your infrastructure
- Support clients load company name, colors and logo at runtime from `GET /api/branding`; branding images are sent through the Client Branding API and are not baked into the bundle.
- The server does not push generic heartbeat strategy settings to `betterdesk-support` devices.
- The signing seed on the console must match the public key baked into Client releases.
- The signing seed on the console must match the public key baked into the BetterDesk-Client source revision.
- Generated archives must not contain `custom.txt`; the server refuses to promote an artifact that contains the old external configuration marker.
+10
View File
@@ -25,9 +25,19 @@ DATA_DIR=__DATA_DIR__
# BetterDesk Support Generator (module templates and signed Support Agent bundles)
# The signing seed is a secret and must never be committed or exposed in logs.
BETTERDESK_CLIENT_REPO=UNITRONIX/BetterDesk-Client
BETTERDESK_CLIENT_ALLOWED_REPOS=UNITRONIX/BetterDesk-Client
BETTERDESK_CLIENT_RELEASE_TAG=
BETTERDESK_GITHUB_TOKEN=
BETTERDESK_CUSTOM_CLIENT_SIGNING_SEED=
# Set to embedded only after configuring a trusted provider command. The
# provider builds BetterDesk-Client with signed config embedded in each binary.
BETTERDESK_CLIENT_GENERATOR_MODE=embedded
BETTERDESK_CLIENT_REF=master
BETTERDESK_CLIENT_BUILD_COMMAND=
BETTERDESK_CLIENT_GITHUB_ACTIONS=off
BETTERDESK_CLIENT_BUILD_WORKFLOW=support-build.yml
BETTERDESK_CLIENT_BUILD_TIMEOUT_MS=3600000
BETTERDESK_CLIENT_BUILD_MIN_FREE_MB=3072
AGENT_ARTIFACT_DIR=__DATA_DIR__/agent-builds
AGENT_BUILD_WORKER=on
AGENT_BUILD_POLL_MS=5000
+1
View File
@@ -878,6 +878,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "????? ??????? (???? ??????? ??? ??????) ? ????? ?????? ?????? ??? ????? ????? Client ????",
"bundle_name": "اسم الحزمة",
"bundle_name_hint": "التسمية الداخلية فقط - لا تظهر للمستخدمين النهائيين.",
"short_link": "رابط تنزيل قصير",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Z?stupn? ?ablony (bez desktopov?ch bin?rek) ? sestaven? sel?ou, dokud nebude nainstalov?na ?pln? verze Clientu",
"bundle_name": "Název balíčku",
"bundle_name_hint": "Pouze interní označení — nezobrazuje se koncovým uživatelům.",
"short_link": "Krátký odkaz ke stažení",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stubs-skabeloner (uden desktop-bin?re filer) ? builds mislykkes, indtil en komplet Client-udgivelse er installeret",
"bundle_name": "Bundens navn",
"bundle_name_hint": "Kun intern etiket — vises ikke til slutbrugere.",
"short_link": "Kort downloadlink",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stub-Vorlagen (keine Desktop-Bin?rdateien) ? Builds schlagen fehl, bis ein vollst?ndiges Client-Release installiert ist",
"bundle_name": "Paketname",
"bundle_name_hint": "Nur interne Bezeichnung — wird Endbenutzern nicht angezeigt.",
"short_link": "Kurzer Download-Link",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Plantillas stub (sin binarios de escritorio) ? las compilaciones fallar?n hasta instalar una versi?n completa de Client",
"bundle_name": "Nombre del paquete",
"bundle_name_hint": "Solo una etiqueta interna; no se muestra a los usuarios finales.",
"short_link": "Enlace de descarga corto",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stub-mallit (ei ty?p?yt?bin??rej?) ? koontiversiot ep?onnistuvat, kunnes t?ysi Client-julkaisu on asennettu",
"bundle_name": "Paketin nimi",
"bundle_name_hint": "Vain sisäinen tarra – ei näytetä loppukäyttäjille.",
"short_link": "Lyhyt latauslinkki",
+1
View File
@@ -860,6 +860,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Mod?les stub (sans binaires de bureau) ? les builds ?choueront jusqu?? l?installation d?une version compl?te de Client",
"bundle_name": "Paketname",
"bundle_name_hint": "Nur interne Bezeichnung — wird Endbenutzern nicht angezeigt.",
"short_link": "Kurzer Download-Link",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "???? ???????? (???????? ?????? ????) ? ???? Client ?????? ??????? ???? ?? ????? ???? ?????",
"bundle_name": "बंडल का नाम",
"bundle_name_hint": "केवल आंतरिक लेबल - अंतिम उपयोगकर्ताओं को नहीं दिखाया गया।",
"short_link": "लघु डाउनलोड लिंक",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stub sablonok (nincsenek asztali bin?risok) ? a buildel?s meghi?sul egy teljes Client-kiad?s telep?t?s?ig",
"bundle_name": "A csomag neve",
"bundle_name_hint": "Csak belső címke – nem jelenik meg a végfelhasználók számára.",
"short_link": "Rövid letöltési link",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Template stub (tanpa biner desktop) ? build akan gagal sampai rilis Client lengkap dipasang",
"bundle_name": "Nama bundel",
"bundle_name_hint": "Hanya label internal — tidak ditampilkan kepada pengguna akhir.",
"short_link": "Tautan unduhan pendek",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Modelli stub (nessun binario desktop) ? le build falliranno finch? non verr? installata una release completa di Client",
"bundle_name": "Nome pacchetto",
"bundle_name_hint": "Solo etichetta interna — non viene mostrata agli utenti finali.",
"short_link": "Link di download breve",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "???????????????????????? ???Client????????????????????????",
"bundle_name": "バンドル名",
"bundle_name_hint": "内部ラベルのみ - エンドユーザーには表示されません。",
"short_link": "短いダウンロードリンク",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "?? ???(???? ???? ??) ? ?? Client ???? ??? ??? ??? ?????",
"bundle_name": "번들 이름",
"bundle_name_hint": "내부 라벨만 — 최종 사용자에게는 표시되지 않습니다.",
"short_link": "짧은 다운로드 링크",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stub-maler (ingen skrivebordsbin?rfiler) ? bygg vil mislykkes til en komplett Client-utgave er installert",
"bundle_name": "Navn på pakke",
"bundle_name_hint": "Kun intern etikett – ikke vist til sluttbrukere.",
"short_link": "Kort nedlastingslenke",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stub-sjablonen (geen desktopbinaries) ? builds mislukken totdat een volledige Client-release is ge?nstalleerd",
"bundle_name": "Pakketnaam",
"bundle_name_hint": "Alleen een intern label — wordt niet aan eindgebruikers getoond.",
"short_link": "Korte downloadlink",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Modelos stub (sem bin?rios de desktop) ? as compila??es falhar?o at? que uma vers?o completa do Client seja instalada",
"bundle_name": "Nome do pacote",
"bundle_name_hint": "Apenas um rótulo interno — não é exibido aos usuários finais.",
"short_link": "Link de download curto",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "?abloane stub (f?r? binare desktop) ? buildurile vor e?ua p?n? la instalarea unei versiuni complete de Client",
"bundle_name": "Numele pachetului",
"bundle_name_hint": "Numai etichetă internă — nu este afișată utilizatorilor finali.",
"short_link": "Link de descărcare scurt",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stubmallar (inga skrivbordsbin?rer) ? byggen misslyckas tills en fullst?ndig Client-version har installerats",
"bundle_name": "Paketens namn",
"bundle_name_hint": "Endast intern etikett – visas inte för slutanvändare.",
"short_link": "Kort nedladdningslänk",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "??????? Stub (????????????????????) ? ???????????????????????????????????? Client ???????",
"bundle_name": "ชื่อชุด",
"bundle_name_hint": "ป้ายกำกับภายในเท่านั้น — ไม่แสดงต่อผู้ใช้ปลายทาง",
"short_link": "ลิงก์ดาวน์โหลดแบบสั้น",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stub ?ablonlar (masa?st? ikili dosyalar? yok) ? tam bir Client s?r?m? y?klenene kadar derlemeler ba?ar?s?z olur",
"bundle_name": "Paket adı",
"bundle_name_hint": "Yalnızca dahili etiket — son kullanıcılara gösterilmez.",
"short_link": "Kısa indirme bağlantısı",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "???????-???????? (??? ?????????? ???????? ??????) ? ?????? ????????????????? ????????, ???? ?? ???? ??????????? ?????? ????? Client",
"bundle_name": "Назва комплекту",
"bundle_name_hint": "Лише внутрішня мітка — не відображається кінцевим користувачам.",
"short_link": "Коротке посилання для завантаження",
+1
View File
@@ -877,6 +877,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "M?u stub (kh?ng c? t?p nh? ph?n m?y t?nh) ? b?n d?ng s? th?t b?i cho ??n khi c?i ??t b?n ph?t h?nh Client ??y ??",
"bundle_name": "Tên gói",
"bundle_name_hint": "Chỉ nhãn nội bộ - không hiển thị cho người dùng cuối.",
"short_link": "Liên kết tải xuống ngắn",
+1
View File
@@ -860,6 +860,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "Stub ????????????? ????? Client ???????????",
"bundle_name": "安裝包名稱",
"bundle_name_hint": "僅用於內部標識,不會顯示給最終用戶。",
"short_link": "短下載鏈接",
+1
View File
@@ -871,6 +871,7 @@
"module_seed_missing": "Signing seed missing (plain JSON Phase A)",
"module_error_prefix": "Error",
"module_no_release": "No GitHub release with generator templates found. Publish BetterDesk-Client release assets first.",
"module_stub_warning": "???????????????? ????? Client ??????????",
"bundle_name": "安装包名称",
"bundle_name_hint": "仅用于内部标识,不会显示给最终用户。",
"short_link": "短下载链接",
+95
View File
@@ -35,6 +35,79 @@
gap: 10px;
}
.gen-operation-modal {
position: fixed;
inset: 0;
z-index: 2000;
display: grid;
place-items: center;
}
.gen-operation-modal.hidden {
display: none;
}
.gen-operation-backdrop {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.68);
}
.gen-operation-dialog {
position: relative;
width: min(440px, calc(100vw - 32px));
padding: 28px;
border: 1px solid var(--color-border, rgba(255, 255, 255, 0.14));
border-radius: 14px;
background: var(--color-bg-card, #17202b);
box-shadow: 0 24px 80px rgba(0, 0, 0, 0.45);
}
.gen-operation-dialog h2 {
margin: 0 0 8px;
}
.gen-operation-dialog p {
margin: 0 0 16px;
line-height: 1.45;
}
.gen-operation-spinner {
width: 30px;
height: 30px;
margin-bottom: 18px;
border: 3px solid rgba(255, 255, 255, 0.2);
border-top-color: var(--color-primary, #4dabf7);
border-radius: 50%;
animation: gen-operation-spin 0.8s linear infinite;
}
.gen-operation-progress {
height: 6px;
overflow: hidden;
margin-bottom: 12px;
border-radius: 99px;
background: rgba(255, 255, 255, 0.12);
}
.gen-operation-progress span {
display: block;
width: 38%;
height: 100%;
border-radius: inherit;
background: var(--color-primary, #4dabf7);
animation: gen-operation-progress 1.5s ease-in-out infinite;
}
@keyframes gen-operation-spin {
to { transform: rotate(360deg); }
}
@keyframes gen-operation-progress {
0% { transform: translateX(-120%); }
100% { transform: translateX(330%); }
}
.generator-layout {
display: grid;
grid-template-columns: 320px 1fr;
@@ -230,6 +303,28 @@
gap: 8px;
}
.build-progress {
height: 6px;
overflow: hidden;
margin-top: 10px;
border-radius: 99px;
background: rgba(255, 255, 255, 0.12);
}
.build-progress span {
display: block;
height: 100%;
border-radius: inherit;
background: var(--color-primary, #4dabf7);
transition: width 0.35s ease;
}
.build-progress-meta {
margin-top: 4px;
font-size: 11px;
color: var(--color-text-muted, #94a3b8);
}
.build-error {
margin-top: 6px;
font-size: 12px;
+110 -6
View File
@@ -73,11 +73,72 @@
const $ = (id) => document.getElementById(id);
const els = {};
let operationPollTimer = null;
let operationErrorTimer = null;
function stopOperationPoll() {
if (operationPollTimer) {
clearInterval(operationPollTimer);
operationPollTimer = null;
}
}
function hideOperationModal() {
stopOperationPoll();
if (operationErrorTimer) clearTimeout(operationErrorTimer);
operationErrorTimer = null;
if (els['gen-operation-modal']) {
els['gen-operation-modal'].classList.add('hidden');
els['gen-operation-modal'].setAttribute('aria-hidden', 'true');
}
}
function showOperationModal(title, message, { poll = false } = {}) {
if (!els['gen-operation-modal']) return;
if (operationErrorTimer) clearTimeout(operationErrorTimer);
operationErrorTimer = null;
els['gen-operation-title'].textContent = title;
els['gen-operation-message'].textContent = message;
els['gen-operation-detail'].textContent = '';
els['gen-operation-modal'].classList.remove('hidden');
els['gen-operation-modal'].setAttribute('aria-hidden', 'false');
if (poll) {
stopOperationPoll();
operationPollTimer = setInterval(async () => {
try {
const data = await api('GET', '/api/generator/module/status');
const status = data.data || {};
const phase = status.phase || status.status || 'working';
const phaseText = {
syncing_source: 'Downloading BetterDesk-Client source…',
syncing_submodules: 'Downloading Client submodules…',
ready: 'Source synchronization complete.',
error: status.error || 'Builder reported an error.',
}[phase] || `Builder status: ${phase}`;
els['gen-operation-detail'].textContent = phaseText;
} catch (err) {
els['gen-operation-detail'].textContent = `Status check failed: ${err.message}`;
}
}, 2000);
}
}
function showOperationError(error) {
stopOperationPoll();
if (!els['gen-operation-modal']) return;
els['gen-operation-title'].textContent = 'Builder operation failed';
els['gen-operation-message'].textContent = error.message || String(error);
els['gen-operation-detail'].textContent = 'Check the console log and server builder status, then try again.';
els['gen-operation-modal'].classList.remove('hidden');
els['gen-operation-modal'].setAttribute('aria-hidden', 'false');
operationErrorTimer = setTimeout(hideOperationModal, 7000);
}
function cacheEls() {
[
'gen-module-gate', 'gen-module-status', 'gen-accept-terms', 'gen-install-module',
'gen-install-local-file',
'gen-operation-modal', 'gen-operation-title', 'gen-operation-message', 'gen-operation-detail',
'gen-finish-install', 'gen-main',
'gen-legacy-leftovers', 'gen-legacy-leftovers-list', 'gen-legacy-hint',
'gen-new-support', 'gen-bundle-list', 'gen-editor-title', 'gen-revoke-btn', 'gen-delete-btn',
@@ -321,6 +382,13 @@
const key = `${b.platform}/${b.arch}/${b.format}`;
const label = (state.platforms.find((p) => platformKey(p) === key) || {}).label || key;
const err = b.error_message ? `<div class="build-error">${escapeText(b.error_message)}</div>` : '';
const percent = Math.max(0, Math.min(100, Number(b.progress_percent || 0)));
const progress = b.status === 'building'
? `<div class="build-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${percent}">
<span style="width:${percent}%"></span>
</div>
<div class="build-progress-meta">${percent}% · ${escapeText(b.progress_phase || 'building')}</div>`
: '';
const retry = !isCurrentLegacy() && b.status === 'failed'
? `<button type="button" class="btn btn-sm btn-secondary gen-retry-build"
data-platform="${escapeText(b.platform)}" data-arch="${escapeText(b.arch)}" data-format="${escapeText(b.format)}">Retry</button>`
@@ -331,6 +399,7 @@
<span class="build-status badge">${escapeText(buildStatusLabel(b.status))}</span>
${retry}
</div>
${progress}
${err}
</div>`;
}).join('');
@@ -494,6 +563,7 @@
function renderModuleStatus(status) {
state.moduleStatus = status;
state.moduleReady = !!(status && status.ready);
const embedded = status && status.mode === 'embedded';
const el = els['gen-module-status'];
if (!el) return;
const parts = [
@@ -502,14 +572,29 @@
? t('generator.module_terms_ok', 'Terms accepted')
: t('generator.module_terms_pending', 'Terms not accepted'),
status.templatesPresent
? t('generator.module_templates_ok', 'Templates present')
: t('generator.module_templates_missing', 'Templates missing'),
? (embedded
? 'BetterDesk-Client source present'
: t('generator.module_templates_ok', 'Templates present'))
: (embedded
? 'BetterDesk-Client source missing'
: t('generator.module_templates_missing', 'Templates missing')),
status.installedVersion
? t('generator.module_version', 'Version {{v}}').replace('{{v}}', status.installedVersion)
: null,
status.signingSeedPresent
? t('generator.module_seed_ok', 'Signing seed present')
: t('generator.module_seed_missing', 'Signing seed missing — Support builds disabled'),
: (t('generator.module_seed_missing', 'Signing seed missing — Support builds disabled')
+ (status.signingSeedPath ? ` (${status.signingSeedPath})` : '')),
status.mode === 'embedded'
? (status.providerConfigured
? 'Embedded build provider configured'
: 'Configure GitHub Actions token or a trusted local provider')
: null,
status.mode === 'embedded' && status.buildCapabilities?.mode === 'local'
? `Local targets: ${(status.buildCapabilities.targets || [])
.map((p) => `${p.platform}/${p.arch}`)
.join(', ') || 'none — check Cargo, Flutter and vcpkg'}`
: null,
status.error
? t('generator.module_error_prefix', 'Error') + ': ' + status.error
: null,
@@ -526,10 +611,17 @@
const installLabel = els['gen-install-module']
&& els['gen-install-module'].querySelector('.gen-install-label');
if (els['gen-install-module']) {
els['gen-install-module'].disabled = !status.termsAccepted || status.status === 'downloading';
const seedMissing = embedded && !status.signingSeedPresent;
els['gen-install-module'].disabled = !status.termsAccepted
|| status.status === 'downloading'
|| seedMissing;
const label = status.status === 'downloading'
? t('generator.module_downloading', 'Downloading…')
: t('generator.module_install', 'Install from GitHub');
: seedMissing
? 'Configure signing seed first'
: (embedded
? 'Sync BetterDesk-Client source'
: t('generator.module_install', 'Install from GitHub'));
if (installLabel) installLabel.textContent = label;
else {
// Keep icon; replace trailing text nodes if label span missing
@@ -541,6 +633,8 @@
}
if (els['gen-install-local-file']) {
els['gen-install-local-file'].disabled = !status.termsAccepted || status.status === 'downloading';
const localLabel = els['gen-install-local-file'].closest('label');
if (localLabel) localLabel.classList.toggle('hidden', !!embedded);
}
if (els['gen-finish-install']) {
els['gen-finish-install'].classList.toggle('hidden', !status.ready);
@@ -714,12 +808,15 @@
if (els['gen-accept-terms']) {
els['gen-accept-terms'].addEventListener('click', async () => {
showOperationModal('Accepting terms', 'Saving AGPL acceptance…');
try {
await api('POST', '/api/generator/module/accept-terms');
notify.success(t('generator.module_terms_ok', 'Terms accepted'));
await refreshModuleStatus();
hideOperationModal();
} catch (err) {
notify.error(err.message);
showOperationError(err);
}
});
}
@@ -728,12 +825,19 @@
els['gen-install-module'].addEventListener('click', async () => {
try {
els['gen-install-module'].disabled = true;
notify.info(t('generator.module_downloading', 'Downloading templates from GitHub…'));
showOperationModal(
'Synchronizing BetterDesk-Client',
'The server is downloading the pinned Client source and submodules. This can take several minutes.',
{ poll: true }
);
notify.info('Synchronizing BetterDesk-Client source…');
await api('POST', '/api/generator/module/install', {});
notify.success(t('generator.module_installed', 'Module installed'));
await refreshModuleStatus();
hideOperationModal();
} catch (err) {
notify.error(err.message);
showOperationError(err);
await refreshModuleStatus();
}
});
+113 -28
View File
@@ -20,12 +20,16 @@ const keyService = require('../services/keyService');
const bundleService = require('../services/agentBundleService');
const clientTemplateWorker = require('../services/clientTemplateWorker');
const supportModule = require('../services/supportGeneratorModule');
const clientBuilder = require('../services/clientBuilderService');
const db = require('../services/database');
const config = require('../config/config');
const brandingService = require('../services/brandingService');
const conn = require('../services/agentBundleConnection');
const clientConfigHost = require('../services/clientConfigHost');
const { PRODUCT_TYPES, normalizeProductType, isBetterDeskSupportBundle } = require('../lib/generatorBuildTypes');
const EMBEDDED_MODE = String(
process.env.BETTERDESK_CLIENT_GENERATOR_MODE || 'embedded'
).trim().toLowerCase() === 'embedded';
const moduleUpload = multer({
storage: multer.diskStorage({
destination: (_req, _file, cb) => {
@@ -71,9 +75,36 @@ function serializeBundle(row) {
updated_at: row.updated_at,
download_url: `/d/${publicId}`,
product_type: normalizeProductType(row.product_type),
client_commit: row.client_commit || null,
active_generation_hash: row.active_generation_hash || row.branding_hash || null,
};
}
function activeBuildHash(row) {
return row?.active_generation_hash || row?.branding_hash || '';
}
function generatorReady() {
return EMBEDDED_MODE ? clientBuilder.isReady() : supportModule.isReady();
}
function generatorNotReadyError() {
return EMBEDDED_MODE
? 'betterdesk_client_builder_not_ready'
: 'module_not_ready';
}
function currentClientRevision() {
if (!EMBEDDED_MODE) return null;
const commit = String(clientBuilder.readState().installedCommit || '').trim();
return /^[a-f0-9]{40}$/i.test(commit) ? commit : null;
}
function generationForConfig(configFingerprint, clientCommit = currentClientRevision()) {
if (!EMBEDDED_MODE || !clientCommit) return configFingerprint;
return clientBuilder.generationKey(configFingerprint, clientCommit);
}
async function resolvePublicBundle(publicId) {
return db.getAgentBundleByPublicId(publicId);
}
@@ -100,8 +131,8 @@ async function resolveBundleSlug({ preferred, name, fallbackId, excludeBundleId
}
/**
* Inject server host / API / public key for BetterDesk Support custom.txt builds.
* Branding colors/logos are no longer baked into installers — Client Branding API
* Prepare the signed server profile for BetterDesk Support embedded builds.
* Branding colors/logos are not embedded in the binary — Client Branding API
* supplies runtime appearance.
*/
async function finalizeSupportBranding(input) {
@@ -158,6 +189,19 @@ function resolveBuildWorker() {
return clientTemplateWorker;
}
function availablePlatformKeys() {
return new Set(clientTemplateWorker.getAvailablePlatforms().map((p) => (
`${p.platform}/${p.arch}/${p.format}`
)));
}
function filterAvailableBuilds(builds) {
const keys = availablePlatformKeys();
return (builds || []).filter((build) => (
keys.has(`${build.platform}/${build.arch}/${build.format}`)
));
}
// =========================================================================
// Generator page
// =========================================================================
@@ -177,7 +221,9 @@ router.get('/generator', requireAuth, requireAdmin, (req, res) => {
router.get('/api/generator/module/status', requireAuth, requireAdmin, async (req, res) => {
try {
const status = await supportModule.getStatus();
const status = EMBEDDED_MODE
? await clientBuilder.getStatus()
: await supportModule.getStatus();
res.json({ success: true, data: status });
} catch (err) {
console.error('[generator] module status error:', err);
@@ -187,7 +233,9 @@ router.get('/api/generator/module/status', requireAuth, requireAdmin, async (req
router.post('/api/generator/module/accept-terms', requireAuth, requireAdmin, async (req, res) => {
try {
const state = await supportModule.acceptTerms();
const state = EMBEDDED_MODE
? await clientBuilder.acceptTerms()
: await supportModule.acceptTerms();
res.json({ success: true, data: state });
} catch (err) {
console.error('[generator] accept-terms error:', err);
@@ -197,6 +245,21 @@ router.post('/api/generator/module/accept-terms', requireAuth, requireAdmin, asy
router.post('/api/generator/module/install', requireAuth, requireAdmin, async (req, res) => {
try {
if (EMBEDDED_MODE) {
clientBuilder.ensureSigningKeySync();
if (!require('../services/supportGeneratorModule').isSigningSeedValid()) {
return res.status(400).json({
success: false,
error: 'custom_client_signing_seed_required',
});
}
const state = await clientBuilder.syncSource({
repo: req.body?.repo,
ref: req.body?.ref || req.body?.tag,
force: true,
});
return res.json({ success: true, data: state });
}
const repo = req.body?.repo ? String(req.body.repo).trim() : undefined;
const tag = req.body?.tag ? String(req.body.tag).trim() : undefined;
const state = await supportModule.installFromGitHub({ repo, tag });
@@ -235,6 +298,12 @@ router.post(
async (req, res) => {
const uploaded = req.file?.path;
try {
if (EMBEDDED_MODE) {
return res.status(400).json({
success: false,
error: 'embedded_builder_requires_client_source_sync',
});
}
if (!uploaded) {
return res.status(400).json({ success: false, error: 'generator_archive_required' });
}
@@ -275,8 +344,8 @@ router.get('/api/generator/bundles/:bundleId', requireAuth, requireAdmin, async
const row = await db.getAgentBundle(req.params.bundleId);
if (!row) return res.status(404).json({ success: false, error: req.t('errors.not_found') });
const bundle = serializeBundle(row);
const builds = await db.listAgentBundleBuildsForHash(row.branding_hash);
bundle.builds = builds || [];
const builds = await db.listAgentBundleBuildsForHash(activeBuildHash(row));
bundle.builds = filterAvailableBuilds(builds);
res.json({ success: true, data: { bundle } });
} catch (err) {
console.error('[generator] get bundle error:', err);
@@ -301,8 +370,8 @@ router.get('/api/generator/defaults', requireAuth, requireAdmin, async (req, res
router.post('/api/generator/bundles', requireAuth, requireAdmin, async (req, res) => {
try {
if (!supportModule.isReady()) {
return res.status(400).json({ success: false, error: 'module_not_ready' });
if (!generatorReady()) {
return res.status(400).json({ success: false, error: generatorNotReadyError() });
}
const name = String(req.body.name || '').trim().slice(0, 100);
if (!name) {
@@ -329,13 +398,17 @@ router.post('/api/generator/bundles', requireAuth, requireAdmin, async (req, res
}
const normalized = await finalizeSupportBranding(base);
normalized.bundle_id = bundleId;
const brandingHash = bundleService.hashBranding(normalized);
const configFingerprint = bundleService.hashBranding(normalized);
const clientCommit = currentClientRevision();
const brandingHash = generationForConfig(configFingerprint, clientCommit);
const created = await db.createAgentBundle({
bundleId,
slug: slugResult.slug,
name,
branding: JSON.stringify(normalized),
brandingHash,
configFingerprint,
clientCommit,
createdBy: req.session?.userId || null,
productType,
});
@@ -361,8 +434,8 @@ router.post('/api/generator/bundles', requireAuth, requireAdmin, async (req, res
router.put('/api/generator/bundles/:bundleId', requireAuth, requireAdmin, async (req, res) => {
try {
if (!supportModule.isReady()) {
return res.status(400).json({ success: false, error: 'module_not_ready' });
if (!generatorReady()) {
return res.status(400).json({ success: false, error: generatorNotReadyError() });
}
const existing = await db.getAgentBundle(req.params.bundleId);
if (!existing) return res.status(404).json({ success: false, error: req.t('errors.not_found') });
@@ -377,7 +450,13 @@ router.put('/api/generator/bundles/:bundleId', requireAuth, requireAdmin, async
}
const normalized = await finalizeSupportBranding(base);
normalized.bundle_id = req.params.bundleId;
const brandingHash = bundleService.hashBranding(normalized);
const configFingerprint = bundleService.hashBranding(normalized);
const clientCommit = currentClientRevision();
const existingFingerprint = existing.config_fingerprint || existing.branding_hash;
const configChanged = existingFingerprint !== configFingerprint;
const brandingHash = configChanged
? generationForConfig(configFingerprint, clientCommit)
: existing.branding_hash;
let slug = existing.slug || '';
if (req.body.slug !== undefined) {
const slugResult = await resolveBundleSlug({
@@ -409,8 +488,10 @@ router.put('/api/generator/bundles/:bundleId', requireAuth, requireAdmin, async
slug,
branding: JSON.stringify(normalized),
brandingHash,
configFingerprint,
clientCommit: clientCommit || existing.client_commit || null,
});
if (existing.branding_hash !== brandingHash) {
if (existing.branding_hash !== brandingHash || configChanged) {
const platformsFilter = Array.isArray(req.body.platforms) ? req.body.platforms : null;
resolveBuildWorker().enqueueBuildsForHash(brandingHash, {
platforms: platformsFilter,
@@ -432,8 +513,8 @@ router.post('/api/generator/bundles/:bundleId/rebuild', requireAuth, requireAdmi
if (row.revoked) {
return res.status(400).json({ success: false, error: req.t('generator.errors.rebuild_revoked') });
}
if (!supportModule.isReady()) {
return res.status(400).json({ success: false, error: 'module_not_ready' });
if (!generatorReady()) {
return res.status(400).json({ success: false, error: generatorNotReadyError() });
}
const platformsFilter = Array.isArray(req.body?.platforms) ? req.body.platforms : null;
const result = await resolveBuildWorker().rebuildBundleById(
@@ -449,7 +530,7 @@ router.post('/api/generator/bundles/:bundleId/rebuild', requireAuth, requireAdmi
success: true,
data: {
queued: result.platforms,
builds: builds || [],
builds: filterAvailableBuilds(builds),
},
});
} catch (err) {
@@ -472,12 +553,12 @@ router.post(
if (!row.branding_hash) {
return res.status(400).json({ success: false, error: req.t('generator.errors.missing_hash') });
}
if (!supportModule.isReady()) {
return res.status(400).json({ success: false, error: 'module_not_ready' });
if (!generatorReady()) {
return res.status(400).json({ success: false, error: generatorNotReadyError() });
}
const worker = resolveBuildWorker();
const result = await worker.requeuePlatformBuild(
row.branding_hash,
activeBuildHash(row),
req.params.platform,
req.params.arch,
req.params.format
@@ -488,7 +569,7 @@ router.post(
: 'errors.bad_request';
return res.status(400).json({ success: false, error: req.t(errKey) });
}
const listHash = result.brandingHash || row.branding_hash;
const listHash = result.brandingHash || activeBuildHash(row);
const builds = await db.listAgentBundleBuildsForHash(listHash);
res.json({ success: true, data: { builds: builds || [] } });
} catch (err) {
@@ -543,7 +624,7 @@ router.post('/api/generator/preview', requireAuth, requireAdmin, async (req, res
});
router.get('/api/generator/platforms', requireAuth, requireAdmin, (req, res) => {
res.json({ success: true, data: { platforms: bundleService.PLATFORMS } });
res.json({ success: true, data: { platforms: clientTemplateWorker.getAvailablePlatforms() } });
});
// =========================================================================
@@ -560,12 +641,14 @@ router.get('/d/:publicId', async (req, res) => {
});
}
const bundle = serializeBundle(row);
const builds = await db.listAgentBundleBuildsForHash(row.branding_hash);
const builds = filterAvailableBuilds(
await db.listAgentBundleBuildsForHash(activeBuildHash(row))
);
const buildMap = {};
for (const b of (builds || [])) {
buildMap[`${b.platform}/${b.arch}/${b.format}`] = b.status;
}
const platforms = bundleService.PLATFORMS.map(p => ({
const platforms = clientTemplateWorker.getAvailablePlatforms().map(p => ({
...p,
status: buildMap[`${p.platform}/${p.arch}/${p.format}`] || 'pending',
}));
@@ -593,7 +676,9 @@ router.get('/api/d/:publicId/manifest', async (req, res) => {
try {
const row = await resolvePublicBundle(req.params.publicId);
if (!row || row.revoked) return res.status(404).json({ success: false });
const builds = await db.listAgentBundleBuildsForHash(row.branding_hash);
const builds = filterAvailableBuilds(
await db.listAgentBundleBuildsForHash(activeBuildHash(row))
);
const buildMap = {};
for (const b of (builds || [])) {
buildMap[`${b.platform}/${b.arch}/${b.format}`] = {
@@ -602,7 +687,7 @@ router.get('/api/d/:publicId/manifest', async (req, res) => {
sha256: b.artifact_sha256 || null,
};
}
const platforms = bundleService.PLATFORMS.map(p => ({
const platforms = clientTemplateWorker.getAvailablePlatforms().map(p => ({
...p,
...(buildMap[`${p.platform}/${p.arch}/${p.format}`] || { status: 'pending' }),
}));
@@ -626,13 +711,13 @@ router.get('/api/d/:publicId/download/:platform/:arch/:format', async (req, res)
try {
const row = await resolvePublicBundle(req.params.publicId);
if (!row || row.revoked) return res.status(404).json({ success: false });
const build = await db.getAgentBundleBuild({
brandingHash: row.branding_hash,
const build = await resolveBuildWorker().getReadyArtifact({
brandingHash: activeBuildHash(row),
platform: req.params.platform,
arch: req.params.arch,
format: req.params.format,
});
if (!build || build.status !== 'ready' || !build.artifact_path) {
if (!build || !build.artifact_path) {
return res.status(503).json({
success: false,
error: 'build_pending',
+19 -2
View File
@@ -592,12 +592,29 @@ async function startServer() {
// Defer build workers until after listen + event-bus WS connect settle
// (#353): toolchain/DB work racing native addon init can abort Node 24.
setImmediate(() => {
// BetterDesk Support Generator — patches Client templates with custom.txt.
// Disabled when AGENT_BUILD_WORKER=off (small consoles without templates).
// BetterDesk Support Generator — local embedded Client builder.
// Disabled when AGENT_BUILD_WORKER=off.
if (process.env.AGENT_BUILD_WORKER !== 'off') {
try {
const clientTemplateWorker = require('./services/clientTemplateWorker');
clientTemplateWorker.startWorker();
if (String(
process.env.BETTERDESK_CLIENT_GENERATOR_MODE || 'embedded'
).trim().toLowerCase() === 'embedded') {
const clientBuilder = require('./services/clientBuilderService');
clientBuilder.syncAndQueueRebuilds()
.then((result) => {
if (result.queued) {
console.log(
`[server] BetterDesk-Client ${result.sha} changed; `
+ 'embedded Support rebuild queued'
);
}
})
.catch((err) => {
console.warn('[server] BetterDesk-Client sync/rebuild deferred:', err.message);
});
}
} catch (err) {
console.warn('[server] client template worker disabled:', err.message);
}
+4 -7
View File
@@ -7,12 +7,9 @@
* - hashing the normalized branding (Phase 2 build-artifact cache key)
* - generating short, URL-safe bundle IDs
*
* The build pipeline itself (Tauri cross-compile, dpkg-deb, rpmbuild,
* appimagetool, cargo-xwin + wine) is intentionally NOT implemented here.
* Phase 1 stores the bundle definition + serves a public download portal
* that reports each platform as "pending". Phase 2 will plug a queue
* into this service and start producing real artifacts keyed by
* `branding_hash`.
* The build pipeline is owned by clientTemplateWorker/localClientBuilder.
* This service validates profiles and provides deterministic config
* fingerprints for the local embedded build queue.
*/
'use strict';
@@ -22,7 +19,7 @@ const config = require('../config/config');
const conn = require('./agentBundleConnection');
// Supported delivery targets. The portal renders one card per entry.
// BetterDesk Support Generator patches portable desktop templates + custom.txt.
// BetterDesk Support Generator builds incoming-only Client binaries.
const PLATFORMS = [
{ platform: 'windows', arch: 'x64', format: 'portable', label: 'Windows x64 portable (.zip + installer)' },
{ platform: 'windows', arch: 'arm64', format: 'portable', label: 'Windows ARM64 portable (.zip + installer)' },
+826
View File
@@ -0,0 +1,826 @@
/**
* BetterDesk-Client source synchronisation and embedded-build provider.
*
* This service deliberately keeps the Client repository outside the
* BetterDesk checkout. It only stores a pinned source snapshot and invokes an
* built-in local build provider (or an explicitly configured replacement)
* with a request file. The provider is responsible for producing platform
* artifacts with the signed Support payload compiled into the binary.
*/
'use strict';
const fs = require('fs');
const fsp = fs.promises;
const path = require('path');
const crypto = require('crypto');
const https = require('https');
const http = require('http');
const { spawn } = require('child_process');
const AdmZip = require('adm-zip');
const nacl = require('tweetnacl');
const config = require('../config/config');
const localClientBuilder = require('./localClientBuilder');
const DEFAULT_REPO = 'UNITRONIX/BetterDesk-Client';
const DEFAULT_REF = 'master';
const MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
const BUILD_TIMEOUT_MS = Math.max(
60_000,
Number.parseInt(process.env.BETTERDESK_CLIENT_BUILD_TIMEOUT_MS || '3600000', 10)
);
function dataRoot() {
return path.join(
config.dataDir || path.join(__dirname, '..', 'data'),
'modules',
'betterdesk-client-builder'
);
}
function sourceRoot() {
return path.join(dataRoot(), 'source');
}
function statePath() {
return path.join(dataRoot(), 'state.json');
}
function requestRoot() {
return path.join(dataRoot(), 'requests');
}
function signingSeedPath() {
return require('./supportGeneratorModule').signingSeedPath();
}
function signingPublicKeyPath() {
return path.join(dataRoot(), 'custom-client-signing.pub');
}
function outputRoot() {
return path.join(dataRoot(), 'outputs');
}
function normalizeRepo(value) {
const repo = String(value || process.env.BETTERDESK_CLIENT_REPO || DEFAULT_REPO).trim();
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) {
throw new Error('betterdesk_client_repo_invalid');
}
const allowed = String(
process.env.BETTERDESK_CLIENT_ALLOWED_REPOS || DEFAULT_REPO
).split(',').map((entry) => entry.trim()).filter(Boolean);
if (!allowed.includes(repo)) {
throw new Error('betterdesk_client_repo_not_allowed');
}
return repo;
}
function clientRef(value) {
const ref = String(value || process.env.BETTERDESK_CLIENT_REF || DEFAULT_REF).trim();
if (!ref || ref.length > 200 || /[\0\r\n]/.test(ref)) {
throw new Error('betterdesk_client_ref_invalid');
}
return ref;
}
function decodeSigningSeed(value) {
const text = String(value || '').replace(/\s+/g, '');
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text)) return null;
try {
const seed = Buffer.from(text, 'base64');
return seed.length === 32 ? seed : null;
} catch (_) {
return null;
}
}
function readStoredSigningSeed() {
try {
return decodeSigningSeed(fs.readFileSync(signingSeedPath(), 'utf8'));
} catch (_) {
return null;
}
}
function writeSigningFile(filePath, value, mode) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
const temporary = `${filePath}.tmp-${process.pid}-${Date.now()}`;
fs.writeFileSync(temporary, `${value}\n`, { encoding: 'utf8', mode });
try { fs.chmodSync(temporary, mode); } catch (_) { /* Windows */ }
try { if (fs.existsSync(filePath)) fs.unlinkSync(filePath); } catch (_) { /* replace below */ }
fs.renameSync(temporary, filePath);
}
/**
* Generate an instance-specific signing key on first use. A configured
* environment seed remains supported for managed deployments, but the
* default path never downloads or reuses a public test seed.
*/
function ensureSigningKeySync() {
const configured = decodeSigningSeed(process.env.BETTERDESK_CUSTOM_CLIENT_SIGNING_SEED);
const existing = readStoredSigningSeed();
const seed = configured || existing || Buffer.from(nacl.randomBytes(32));
const generated = !configured && !existing;
const publicKey = Buffer.from(
nacl.sign.keyPair.fromSeed(new Uint8Array(seed)).publicKey
).toString('base64');
const seedText = seed.toString('base64');
const currentSeed = existing ? existing.toString('base64') : '';
if (configured || !existing || currentSeed !== seedText) {
writeSigningFile(signingSeedPath(), seedText, 0o600);
}
const currentPublic = fs.existsSync(signingPublicKeyPath())
? fs.readFileSync(signingPublicKeyPath(), 'utf8').trim()
: '';
if (currentPublic !== publicKey) {
writeSigningFile(signingPublicKeyPath(), publicKey, 0o644);
}
return { seed: seedText, publicKey, generated };
}
function prepareClientSigningPublicKey() {
const key = ensureSigningKeySync();
const target = path.join(sourceRoot(), 'res', 'betterdesk', 'custom-client-signing.pub');
if (!fs.existsSync(sourceRoot()) || !fs.existsSync(path.dirname(target))) {
throw new Error('betterdesk_client_source_missing_for_signing_key');
}
const stat = fs.lstatSync(target);
if (stat.isSymbolicLink()) throw new Error('betterdesk_client_signing_key_symlink');
const current = fs.readFileSync(target, 'utf8').trim();
if (current !== key.publicKey) {
const temporary = `${target}.tmp-${process.pid}-${Date.now()}`;
fs.writeFileSync(temporary, `${key.publicKey}\n`, { encoding: 'utf8', mode: 0o644 });
try { if (fs.existsSync(target)) fs.unlinkSync(target); } catch (_) { /* replace below */ }
fs.renameSync(temporary, target);
}
return key;
}
function githubHeaders(accept = 'application/vnd.github+json', requestUrl = 'https://api.github.com') {
const headers = {
'User-Agent': 'BetterDesk-Console-Client-Builder',
Accept: accept,
'X-GitHub-Api-Version': '2022-11-28',
};
const token = String(
process.env.BETTERDESK_GITHUB_TOKEN || process.env.GITHUB_TOKEN || ''
).trim();
let host = '';
try { host = new URL(requestUrl).hostname.toLowerCase(); } catch (_) { /* use no token */ }
if (token && host === 'api.github.com') headers.Authorization = `Bearer ${token}`;
return headers;
}
function githubJson(url) {
return new Promise((resolve, reject) => {
const lib = String(url).startsWith('https:') ? https : http;
const req = lib.get(url, { headers: githubHeaders(), timeout: 30_000 }, (res) => {
const chunks = [];
let size = 0;
res.on('data', (chunk) => {
size += chunk.length;
if (size <= MAX_RESPONSE_BYTES) chunks.push(chunk);
});
res.on('end', () => {
if (res.statusCode !== 200) {
const err = new Error(`GitHub HTTP ${res.statusCode}`);
err.statusCode = res.statusCode;
reject(err);
return;
}
if (size > MAX_RESPONSE_BYTES) {
reject(new Error('github_response_too_large'));
return;
}
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
} catch (err) {
reject(new Error(`github_json_invalid:${err.message}`));
}
});
res.on('error', reject);
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy();
reject(new Error('github_request_timeout'));
});
});
}
function githubRequest(method, url, body = null) {
return new Promise((resolve, reject) => {
const target = new URL(url);
const lib = target.protocol === 'https:' ? https : http;
const payload = body === null ? null : Buffer.from(JSON.stringify(body));
const req = lib.request(target, {
method,
headers: {
...githubHeaders('application/vnd.github+json'),
...(payload ? {
'Content-Type': 'application/json',
'Content-Length': payload.length,
} : {}),
},
timeout: 30_000,
}, (res) => {
const chunks = [];
let size = 0;
res.on('data', (chunk) => {
size += chunk.length;
if (size <= MAX_RESPONSE_BYTES) chunks.push(chunk);
});
res.on('end', () => {
const response = Buffer.concat(chunks);
if (res.statusCode < 200 || res.statusCode >= 300) {
const err = new Error(`GitHub HTTP ${res.statusCode}`);
err.statusCode = res.statusCode;
err.body = response.toString('utf8').slice(0, 4000);
reject(err);
return;
}
if (!response.length) {
resolve(null);
return;
}
try {
resolve(JSON.parse(response.toString('utf8')));
} catch (_) {
resolve(response);
}
});
res.on('error', reject);
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy();
reject(new Error('github_request_timeout'));
});
if (payload) req.write(payload);
req.end();
});
}
function downloadToFile(url, destination, redirects = 0) {
return new Promise((resolve, reject) => {
if (redirects > 8) {
reject(new Error('too_many_redirects'));
return;
}
const lib = String(url).startsWith('https:') ? https : http;
const req = lib.get(url, {
headers: githubHeaders('application/octet-stream', url),
timeout: 120_000,
}, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume();
downloadToFile(res.headers.location, destination, redirects + 1).then(resolve, reject);
return;
}
if (res.statusCode !== 200) {
res.resume();
reject(new Error(`GitHub HTTP ${res.statusCode}`));
return;
}
const output = fs.createWriteStream(destination, { mode: 0o600 });
let settled = false;
const fail = (err) => {
if (settled) return;
settled = true;
output.destroy();
reject(err);
};
res.on('error', fail);
output.on('error', fail);
output.on('finish', () => {
if (!settled) {
settled = true;
resolve();
}
});
res.pipe(output);
});
req.on('error', reject);
req.on('timeout', () => {
req.destroy();
reject(new Error('github_download_timeout'));
});
});
}
function runCommand(command, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env || process.env,
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
child.on('error', reject);
child.on('close', (code) => resolve({
code,
stdout: stdout.slice(-16_000),
stderr: stderr.slice(-16_000),
}));
});
}
function runTar(args, cwd) {
return new Promise((resolve, reject) => {
const child = spawn('tar', args, {
cwd,
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
let stderr = '';
child.stderr.on('data', (chunk) => {
stderr += chunk.toString();
if (stderr.length > 16_000) stderr = stderr.slice(-16_000);
});
child.on('error', reject);
child.on('close', (code) => {
if (code === 0) resolve();
else reject(new Error(`tar_failed:${code}:${stderr.trim() || 'unknown'}`));
});
});
}
async function safeExtractTarGz(archivePath, destination) {
const listing = await new Promise((resolve, reject) => {
const child = spawn('tar', ['-tzf', archivePath], {
cwd: path.dirname(archivePath),
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
let output = '';
let error = '';
child.stdout.on('data', (chunk) => { output += chunk.toString(); });
child.stderr.on('data', (chunk) => { error += chunk.toString(); });
child.on('error', reject);
child.on('close', (code) => {
if (code === 0) resolve(output);
else reject(new Error(`tar_list_failed:${code}:${error.trim() || 'unknown'}`));
});
});
for (const raw of listing.split(/\r?\n/).filter(Boolean)) {
const entry = raw.replace(/\\/g, '/');
if (
entry.startsWith('/')
|| /^[A-Za-z]:/.test(entry)
|| entry.split('/').includes('..')
) {
throw new Error('betterdesk_client_archive_path_traversal');
}
}
await fsp.mkdir(destination, { recursive: true });
await runTar(['-xzf', archivePath, '-C', destination], path.dirname(archivePath));
}
function readState() {
try {
return JSON.parse(fs.readFileSync(statePath(), 'utf8'));
} catch (_) {
return {
repo: normalizeRepo(),
ref: clientRef(),
termsAccepted: false,
installedCommit: null,
status: 'not_installed',
error: null,
};
}
}
async function writeState(patch) {
await fsp.mkdir(dataRoot(), { recursive: true });
const next = { ...readState(), ...patch };
const temporary = `${statePath()}.tmp-${process.pid}-${Date.now()}`;
await fsp.writeFile(temporary, JSON.stringify(next, null, 2) + '\n', {
encoding: 'utf8',
mode: 0o600,
});
await fsp.rename(temporary, statePath());
return next;
}
async function getRemoteRevision({ repo, ref } = {}) {
const targetRepo = normalizeRepo(repo);
const targetRef = clientRef(ref);
const commit = await githubJson(
`https://api.github.com/repos/${targetRepo}/commits/${encodeURIComponent(targetRef)}`
);
const sha = String(commit?.sha || '').trim();
if (!/^[a-f0-9]{40}$/i.test(sha)) throw new Error('betterdesk_client_commit_invalid');
return { repo: targetRepo, ref: targetRef, sha };
}
async function syncSource({ repo, ref, force = false } = {}) {
const remote = await getRemoteRevision({ repo, ref });
const state = readState();
if (
!force
&& state.installedCommit === remote.sha
&& fs.existsSync(path.join(sourceRoot(), 'Cargo.toml'))
) {
if (state.status !== 'ready' || state.phase !== 'ready') {
await writeState({ status: 'ready', phase: 'ready', error: null });
}
return { changed: false, ...remote, sourceDir: sourceRoot() };
}
const temporary = path.join(dataRoot(), `.sync-${process.pid}-${Date.now()}`);
const stagedSource = path.join(temporary, 'source');
try {
await writeState({
status: 'downloading',
phase: 'syncing_source',
error: null,
syncStartedAt: new Date().toISOString(),
});
await fsp.rm(temporary, { recursive: true, force: true });
await fsp.mkdir(temporary, { recursive: true });
const clone = await runCommand('git', [
'clone',
'--filter=blob:none',
'--no-tags',
'--no-checkout',
`https://github.com/${remote.repo}.git`,
stagedSource,
]);
if (clone.code !== 0) {
throw new Error(`betterdesk_client_git_clone_failed:${clone.stderr}`);
}
await writeState({ phase: 'syncing_submodules' });
let checkout = await runCommand('git', [
'-C', stagedSource, 'checkout', '--detach', remote.sha,
]);
if (checkout.code !== 0) {
const fetch = await runCommand('git', [
'-C', stagedSource, 'fetch', '--depth', '1', 'origin', remote.sha,
]);
if (fetch.code === 0) {
checkout = await runCommand('git', [
'-C', stagedSource, 'checkout', '--detach', remote.sha,
]);
}
}
if (checkout.code !== 0) {
throw new Error(`betterdesk_client_git_checkout_failed:${checkout.stderr}`);
}
const submodules = await runCommand('git', [
'-C', stagedSource, 'submodule', 'update', '--init', '--recursive',
]);
if (submodules.code !== 0) {
throw new Error(`betterdesk_client_submodule_failed:${submodules.stderr}`);
}
if (
!fs.existsSync(path.join(stagedSource, 'Cargo.toml'))
|| !fs.existsSync(path.join(stagedSource, 'libs', 'hbb_common', 'Cargo.toml'))
) {
throw new Error('betterdesk_client_source_invalid');
}
const previous = path.join(dataRoot(), '.source.previous');
await fsp.rm(previous, { recursive: true, force: true });
if (fs.existsSync(sourceRoot())) await fsp.rename(sourceRoot(), previous);
try {
await fsp.rename(stagedSource, sourceRoot());
} catch (err) {
if (fs.existsSync(previous) && !fs.existsSync(sourceRoot())) {
await fsp.rename(previous, sourceRoot()).catch(() => {});
}
throw err;
}
await fsp.rm(previous, { recursive: true, force: true });
await writeState({
repo: remote.repo,
ref: remote.ref,
installedCommit: remote.sha,
syncedAt: new Date().toISOString(),
status: 'ready',
phase: 'ready',
error: null,
});
return { changed: state.installedCommit !== remote.sha, ...remote, sourceDir: sourceRoot() };
} catch (err) {
await writeState({
status: 'error',
phase: 'error',
error: err.message || String(err),
});
throw err;
} finally {
await fsp.rm(temporary, { recursive: true, force: true }).catch(() => {});
}
}
/**
* Startup/update hook. Source synchronisation is completed before requests
* are queued, but the actual six-target builds remain in the background
* worker. Existing active generations are never changed by this function.
*/
async function syncAndQueueRebuilds({ force = false } = {}) {
const result = await syncSource({ force });
if (!result.changed && !force) {
return { ...result, queued: false };
}
const worker = require('./clientTemplateWorker');
const rebuild = await worker.rebuildAllForClientRevision(result.sha, { force: false });
return { ...result, queued: true, rebuild };
}
function providerCommand() {
return String(process.env.BETTERDESK_CLIENT_BUILD_COMMAND || '').trim()
|| path.join(__dirname, 'localClientBuilder.js');
}
function externalProviderCommand() {
return String(process.env.BETTERDESK_CLIENT_BUILD_COMMAND || '').trim();
}
function githubActionsEnabled() {
return String(process.env.BETTERDESK_CLIENT_GITHUB_ACTIONS || 'off').trim().toLowerCase() !== 'off';
}
function githubTokenPresent() {
return !!String(
process.env.BETTERDESK_GITHUB_TOKEN || process.env.GITHUB_TOKEN || ''
).trim();
}
function usesRemoteProvider() {
return !!(
externalProviderCommand()
|| (githubActionsEnabled() && githubTokenPresent())
);
}
function getBuildCapabilities() {
if (usesRemoteProvider()) {
return {
mode: 'remote',
targets: null,
host: null,
toolchain: { ready: true, missing: [] },
};
}
return localClientBuilder.getCapabilities();
}
function signingSeedPresent() {
try {
ensureSigningKeySync();
return require('./supportGeneratorModule').isSigningSeedValid();
} catch (_) {
return false;
}
}
function isReady() {
const state = readState();
return !!(
state.termsAccepted
&& state.installedCommit
&& state.status === 'ready'
&& fs.existsSync(path.join(sourceRoot(), 'Cargo.toml'))
&& fs.existsSync(path.join(__dirname, 'localClientBuilder.js'))
&& signingSeedPresent()
);
}
async function acceptTerms() {
return writeState({ termsAccepted: true, error: null });
}
async function runBuild(request, { onProgress } = {}) {
if (!isReady()) throw new Error('betterdesk_client_builder_not_ready');
const signingKey = prepareClientSigningPublicKey();
request = { ...request, signing_public_key: signingKey.publicKey };
const requestId = String(request?.generationId || '').trim();
if (!/^[a-f0-9-]{8,128}$/i.test(requestId)) {
throw new Error('betterdesk_client_generation_id_invalid');
}
await fsp.mkdir(requestRoot(), { recursive: true });
await fsp.mkdir(outputRoot(), { recursive: true });
const requestPath = path.join(requestRoot(), `${requestId}.json`);
const outputDir = path.join(outputRoot(), requestId);
await fsp.rm(outputDir, { recursive: true, force: true });
await fsp.mkdir(outputDir, { recursive: true });
await fsp.writeFile(requestPath, JSON.stringify(request, null, 2) + '\n', {
encoding: 'utf8',
mode: 0o600,
});
if (!externalProviderCommand() && githubActionsEnabled() && githubTokenPresent()) {
onProgress?.({ percent: 10, phase: 'queued_remote_build' });
const remoteResult = await runGithubActionsBuild(request, requestPath, outputDir);
onProgress?.({ percent: 100, phase: 'complete' });
return remoteResult;
}
const externalCommand = externalProviderCommand();
const command = externalCommand || process.execPath;
const args = externalCommand
? [requestPath]
: [path.join(__dirname, 'localClientBuilder.js'), requestPath];
const child = spawn(command, args, {
cwd: sourceRoot(),
env: {
...process.env,
BETTERDESK_CLIENT_SOURCE_DIR: sourceRoot(),
BETTERDESK_CLIENT_OUTPUT_DIR: outputDir,
BETTERDESK_CLIENT_BUILD_REQUEST: requestPath,
},
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => {
const text = chunk.toString();
stdout += text;
for (const line of text.split(/\r?\n/)) {
const match = line.match(/^BETTERDESK_BUILD_PROGRESS\|(\d{1,3})\|(.+)$/);
if (!match) continue;
onProgress?.({
percent: Math.max(0, Math.min(100, Number(match[1]))),
phase: match[2].trim(),
});
}
});
child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
const result = await new Promise((resolve, reject) => {
const timer = setTimeout(() => {
child.kill();
reject(new Error('betterdesk_client_build_timeout'));
}, BUILD_TIMEOUT_MS);
child.on('error', reject);
child.on('close', (code) => {
clearTimeout(timer);
resolve({ code, stdout, stderr });
});
});
if (result.code !== 0) {
throw new Error(
`betterdesk_client_build_failed:${result.code}:${result.stderr.slice(-4000)}`
);
}
return { outputDir, stdout: result.stdout.slice(-4000), stderr: result.stderr.slice(-4000) };
}
async function runGithubActionsBuild(request, requestPath, outputDir) {
const state = readState();
const repo = normalizeRepo(state.repo);
const workflow = String(
process.env.BETTERDESK_CLIENT_BUILD_WORKFLOW || 'support-build.yml'
).trim();
if (!/^[A-Za-z0-9_.-]+$/.test(workflow)) {
throw new Error('betterdesk_client_workflow_invalid');
}
const startedAt = Date.now();
await githubRequest(
'POST',
`https://api.github.com/repos/${repo}/actions/workflows/${workflow}/dispatches`,
{
ref: state.ref || DEFAULT_REF,
inputs: {
generation_id: request.generationId,
config_b64: request.signed_config_b64,
client_commit: request.clientCommit || state.installedCommit,
},
}
);
const runsUrl = `https://api.github.com/repos/${repo}/actions/workflows/${workflow}/runs?event=workflow_dispatch&per_page=20`;
const deadline = Date.now() + BUILD_TIMEOUT_MS;
let run = null;
while (Date.now() < deadline) {
const data = await githubJson(runsUrl);
const runs = Array.isArray(data?.workflow_runs) ? data.workflow_runs : [];
run = runs.find((candidate) => (
String(candidate.head_sha || '').toLowerCase()
=== String(request.clientCommit || state.installedCommit).toLowerCase()
&& new Date(candidate.created_at || 0).getTime() >= startedAt - 90_000
)) || null;
if (run) break;
await new Promise((resolve) => setTimeout(resolve, 5000));
}
if (!run) throw new Error('betterdesk_client_workflow_run_not_found');
let runState = run;
while (Date.now() < deadline) {
runState = await githubJson(
`https://api.github.com/repos/${repo}/actions/runs/${run.id}`
);
if (runState.status === 'completed') break;
await new Promise((resolve) => setTimeout(resolve, 10_000));
}
if (runState.status !== 'completed' || runState.conclusion !== 'success') {
throw new Error(
`betterdesk_client_workflow_failed:${runState.status || 'unknown'}:${runState.conclusion || 'unknown'}`
);
}
const artifacts = await githubJson(
`https://api.github.com/repos/${repo}/actions/runs/${run.id}/artifacts?per_page=100`
);
const artifact = (artifacts?.artifacts || []).find((candidate) => (
candidate.name === `betterdesk-support-${request.generationId}` && !candidate.expired
));
if (!artifact?.archive_download_url) {
throw new Error('betterdesk_client_workflow_artifact_missing');
}
const archivePath = path.join(requestRoot(), `${request.generationId}.actions.zip`);
await downloadToFile(artifact.archive_download_url, archivePath);
const zip = new AdmZip(archivePath);
for (const entry of zip.getEntries()) {
const name = String(entry.entryName || '').replace(/\\/g, '/');
if (
name.startsWith('/')
|| /^[A-Za-z]:/.test(name)
|| name.split('/').includes('..')
|| name.toLowerCase().endsWith('/custom.txt')
) {
throw new Error('betterdesk_client_workflow_artifact_invalid');
}
}
zip.extractAllTo(outputDir, true);
await fsp.rm(archivePath, { force: true });
return {
outputDir,
stdout: `GitHub Actions run ${run.id}`,
stderr: '',
requestPath,
};
}
async function getStatus() {
const state = readState();
const signingKey = ensureSigningKeySync();
let remote = null;
let updateError = null;
try {
remote = await getRemoteRevision({ repo: state.repo, ref: state.ref });
} catch (err) {
updateError = err.message || String(err);
}
return {
...state,
mode: 'embedded',
sourceDir: sourceRoot(),
providerConfigured: !!(providerCommand() || (githubActionsEnabled() && githubTokenPresent())),
buildCapabilities: getBuildCapabilities(),
templatesPresent: fs.existsSync(path.join(sourceRoot(), 'Cargo.toml')),
binariesPresent: fs.existsSync(path.join(sourceRoot(), 'Cargo.toml')),
signingSeedPresent: signingSeedPresent(),
signingKeyGenerated: !!signingKey.generated,
signingPublicKey: signingKey.publicKey,
signingSeedPath: signingSeedPath(),
ready: isReady(),
remoteCommit: remote?.sha || null,
updateAvailable: !!(remote?.sha && remote.sha !== state.installedCommit),
updateError,
};
}
function generationKey(configFingerprint, clientCommit) {
return crypto.createHash('sha256')
.update(`${String(configFingerprint || '')}:${String(clientCommit || '')}`)
.digest('hex');
}
module.exports = {
DEFAULT_REPO,
DEFAULT_REF,
dataRoot,
sourceRoot,
statePath,
requestRoot,
outputRoot,
normalizeRepo,
clientRef,
ensureSigningKeySync,
readState,
writeState,
acceptTerms,
getRemoteRevision,
syncSource,
syncAndQueueRebuilds,
getStatus,
getBuildCapabilities,
isReady,
runBuild,
generationKey,
_internals: {
safeExtractTarGz,
providerCommand,
githubActionsEnabled,
githubTokenPresent,
usesRemoteProvider,
},
};
+425 -15
View File
@@ -1,9 +1,9 @@
/**
* BetterDesk Support Generator — template worker
* BetterDesk Support Generator — embedded local build worker
*
* Patches portable desktop templates from the Support Generator module with
* a signed/plain custom.txt and packages artifacts under data/agent-builds/.
* Replaces agentBuildWorker for product_type=betterdesk-support.
* Builds BetterDesk-Client with a signed Support payload embedded at compile
* time and packages artifacts under data/agent-builds/.
* The legacy template path remains available only when explicitly selected.
*/
'use strict';
@@ -19,6 +19,7 @@ const AdmZip = require('adm-zip');
const db = require('./database');
const bundleService = require('./agentBundleService');
const supportModule = require('./supportGeneratorModule');
const clientBuilder = require('./clientBuilderService');
const windowsSupportInstaller = require('./windowsSupportInstaller');
const customTxt = require('./customTxtBuilder');
const keyService = require('./keyService');
@@ -41,6 +42,9 @@ const WORK_ROOT = path.join(
const POLL_INTERVAL_MS = parseInt(process.env.AGENT_BUILD_POLL_MS || '5000', 10);
const BUILD_COOLDOWN_MS = parseInt(process.env.AGENT_BUILD_COOLDOWN_MS || '1000', 10);
const IS_WINDOWS = process.platform === 'win32';
const EMBEDDED_MODE = String(
process.env.BETTERDESK_CLIENT_GENERATOR_MODE || 'embedded'
).trim().toLowerCase() === 'embedded';
let _pollHandle = null;
let _running = false;
@@ -59,29 +63,53 @@ function _parseBranding(raw) {
try { return JSON.parse(raw); } catch (_) { return {}; }
}
function _filterPlatforms(only) {
function _availablePlatforms() {
const all = bundleService.PLATFORMS || [];
if (!EMBEDDED_MODE) return all;
const capabilities = clientBuilder.getBuildCapabilities();
if (capabilities.mode === 'remote') return all;
const supported = new Set((capabilities.targets || []).map((p) => (
`${p.platform}/${p.arch}/${p.format}`
)));
return all.filter((p) => supported.has(`${p.platform}/${p.arch}/${p.format}`));
}
function _filterPlatforms(only) {
const all = _availablePlatforms();
if (!Array.isArray(only) || only.length === 0) return all;
const filtered = all.filter((p) => only.some((o) => (
return all.filter((p) => only.some((o) => (
String(o.platform || o.os || '') === p.platform
&& String(o.arch || 'x64') === p.arch
&& String(o.format || 'portable') === p.format
)));
return filtered.length ? filtered : all;
}
function _hostPlatformKey() {
const platform = process.platform === 'win32'
? 'windows'
: process.platform === 'darwin' ? 'macos' : 'linux';
const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
return `${platform}/${arch}/portable`;
}
async function enqueueBuildsForHash(brandingHash, { force = false, platforms: onlyPlatforms = null } = {}) {
if (!brandingHash) throw new Error('brandingHash required');
if (!supportModule.isReady()) {
if (EMBEDDED_MODE && !clientBuilder.isReady()) {
throw new Error('betterdesk_client_builder_not_ready');
}
if (!EMBEDDED_MODE && !supportModule.isReady()) {
throw new Error('support_generator_module_not_ready');
}
if (!supportModule.templatesHaveBinaries()) {
if (!EMBEDDED_MODE && !supportModule.templatesHaveBinaries()) {
throw new Error(
'support_generator_templates_incomplete: installed templates have no BetterDesk desktop binaries. '
+ 'Publish a full Client release with generator-templates, then reinstall the module.'
);
}
const platforms = _filterPlatforms(onlyPlatforms);
if (!platforms.length) {
throw new Error('local_builder_no_supported_targets');
}
for (const p of platforms) {
const existing = await db.getAgentBundleBuild({
brandingHash, platform: p.platform, arch: p.arch, format: p.format,
@@ -113,6 +141,38 @@ async function rebuildBundleById(bundleId, { platforms: onlyPlatforms = null } =
return { success: true, platforms: platforms.length, brandingHash: row.branding_hash };
}
/**
* Prepare a new Client generation for every non-revoked Support config.
* Existing active_generation_hash values are deliberately left untouched
* until all target builds for the new generation are ready.
*/
async function rebuildAllForClientRevision(clientCommit, { force = false } = {}) {
const commit = String(clientCommit || '').trim();
if (!/^[a-f0-9]{40}$/i.test(commit)) {
throw new Error('betterdesk_client_commit_invalid');
}
const bundles = await db.listAgentBundles();
const queued = [];
for (const bundle of bundles || []) {
if (bundle.revoked || !_isSupportProduct(bundle)) continue;
const configFingerprint = bundle.config_fingerprint || bundle.branding_hash;
const generationHash = clientBuilder.generationKey(configFingerprint, commit);
if (!force && bundle.branding_hash === generationHash) continue;
await db.prepareAgentBundleGeneration(bundle.bundle_id, {
brandingHash: generationHash,
configFingerprint,
clientCommit: commit,
});
await enqueueBuildsForHash(generationHash, { force, platforms: null });
queued.push({
bundleId: bundle.bundle_id,
configFingerprint,
brandingHash: generationHash,
});
}
return { clientCommit: commit, queued };
}
async function requeuePlatformBuild(brandingHash, platform, arch, format) {
if (!brandingHash || !platform || !arch || !format) {
return { success: false, error: 'missing_args' };
@@ -121,6 +181,10 @@ async function requeuePlatformBuild(brandingHash, platform, arch, format) {
(p) => p.platform === platform && p.arch === arch && p.format === format
);
if (!allowed) return { success: false, error: 'unsupported_platform' };
const available = _availablePlatforms().some(
(p) => p.platform === platform && p.arch === arch && p.format === format
);
if (!available) return { success: false, error: 'unsupported_platform' };
await db.upsertAgentBundleBuild({
brandingHash,
platform,
@@ -149,24 +213,36 @@ function getBuildWorkerStatus() {
return {
workerEnabled: process.env.AGENT_BUILD_WORKER !== 'off',
kind: 'client-template',
mode: EMBEDDED_MODE ? 'embedded' : 'legacy-custom-txt',
clientBuilderReady: EMBEDDED_MODE ? clientBuilder.isReady() : false,
moduleReady: moduleStatus.ready,
templatesPresent: moduleStatus.templatesPresent,
templatesDir: supportModule.templatesDir(),
artifactRoot: ARTIFACT_ROOT,
platforms: (bundleService.PLATFORMS || []).map((p) => ({
platforms: _availablePlatforms().map((p) => ({
platform: p.platform,
arch: p.arch,
format: p.format,
label: p.label,
})),
capabilities: EMBEDDED_MODE ? clientBuilder.getBuildCapabilities() : null,
activeBuilds: _activeBuilds,
startupReady: _startupReady,
};
}
function _isArtifactPathSafe(filePath) {
if (!filePath) return false;
const root = path.resolve(ARTIFACT_ROOT);
const candidate = path.resolve(String(filePath));
const relative = path.relative(root, candidate);
return !!relative && !relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative);
}
async function getReadyArtifact({ brandingHash, platform, arch, format }) {
const row = await db.getAgentBundleBuild({ brandingHash, platform, arch, format });
if (!row || row.status !== 'ready' || !row.artifact_path) return null;
if (!_isArtifactPathSafe(row.artifact_path)) return null;
try {
await fsp.access(row.artifact_path, fs.constants.R_OK);
} catch {
@@ -175,14 +251,50 @@ async function getReadyArtifact({ brandingHash, platform, arch, format }) {
return row;
}
async function recoverInterruptedBuilds() {
const bundles = await db.listAgentBundles({ includeRevoked: true });
let recovered = 0;
for (const bundle of bundles || []) {
const builds = await db.listAgentBundleBuildsForHash(bundle.branding_hash);
for (const build of builds || []) {
if (build.status !== 'building') continue;
await db.upsertAgentBundleBuild({
brandingHash: build.branding_hash,
platform: build.platform,
arch: build.arch,
format: build.format,
status: 'queued',
artifactPath: null,
artifactSize: 0,
artifactSha256: null,
errorMessage: 'requeued_after_worker_restart',
clientCommit: build.client_commit || bundle.client_commit || null,
generationId: build.generation_id || null,
configFingerprint: build.config_fingerprint || bundle.config_fingerprint || null,
progressPercent: 0,
progressPhase: 'requeued_after_restart',
});
recovered++;
}
}
if (recovered) {
console.log(`[clientTemplateWorker] recovered ${recovered} interrupted build(s)`);
}
}
function startWorker() {
if (_pollHandle) return;
console.log(`[clientTemplateWorker] templates=${supportModule.templatesDir()}`);
_startupReady = true;
_startupReady = false;
_pollHandle = setInterval(() => {
_tick().catch((e) => console.error('[clientTemplateWorker] tick error:', e.message));
}, POLL_INTERVAL_MS);
_tick().catch(() => {});
recoverInterruptedBuilds()
.catch((err) => console.error('[clientTemplateWorker] recovery error:', err.message))
.finally(() => {
_startupReady = true;
_tick().catch(() => {});
});
console.log(`[clientTemplateWorker] started (poll ${POLL_INTERVAL_MS}ms)`);
}
@@ -237,13 +349,19 @@ async function _listPendingBuilds(limit = 50) {
}
async function _claimNextBuild() {
if (!supportModule.isReady()) return null;
if (EMBEDDED_MODE ? !clientBuilder.isReady() : !supportModule.isReady()) return null;
const candidates = await _listPendingBuilds(50);
candidates.sort((a, b) => String(a.created_at || '').localeCompare(String(b.created_at || '')));
const hostKey = _hostPlatformKey();
candidates.sort((a, b) => {
const aHost = `${a.platform}/${a.arch}/${a.format}` === hostKey ? 0 : 1;
const bHost = `${b.platform}/${b.arch}/${b.format}` === hostKey ? 0 : 1;
return aHost - bHost
|| String(a.created_at || '').localeCompare(String(b.created_at || ''));
});
for (const row of candidates) {
const bundleRow = await _findBundleForHash(row.branding_hash);
if (!bundleRow || !_isSupportProduct(bundleRow)) continue;
if (!supportModule.resolveTemplateDir(row.platform, row.arch)) {
if (!EMBEDDED_MODE && !supportModule.resolveTemplateDir(row.platform, row.arch)) {
await db.upsertAgentBundleBuild({
brandingHash: row.branding_hash,
platform: row.platform,
@@ -436,6 +554,10 @@ function _templateHasBinary(stageDir, platform) {
}
async function _runOne(buildRow) {
if (EMBEDDED_MODE) {
return _runEmbeddedOne(buildRow);
}
const key = `${buildRow.platform}/${buildRow.arch}/${buildRow.format}`;
const startTs = Date.now();
console.log(`[clientTemplateWorker] build start hash=${String(buildRow.branding_hash).slice(0, 12)} ${key}`);
@@ -526,20 +648,308 @@ async function _runOne(buildRow) {
}
}
function _findManifestArtifact(root, manifest, platform, arch) {
const providerArch = {
x64: 'x86_64',
amd64: 'x86_64',
arm64: 'aarch64',
}[String(arch).toLowerCase()] || String(arch).toLowerCase();
const target = `${String(platform).toLowerCase()}/${providerArch}`;
const assets = (manifest?.assets || []).filter((asset) => (
`${String(asset.platform || '').toLowerCase()}/${String(asset.arch || '').toLowerCase()}` === target
));
if (assets.length !== 1) {
throw new Error(`embedded_manifest_asset_target_count_invalid:${platform}/${arch}`);
}
const assetName = assets[0].name;
const candidate = path.resolve(root, assetName);
const relative = path.relative(path.resolve(root), candidate);
const expectedExt = String(platform).toLowerCase() === 'windows' ? '.zip' : '.tar.gz';
if (
!relative
|| relative.startsWith(`..${path.sep}`)
|| relative === '..'
|| path.isAbsolute(relative)
|| !candidate.toLowerCase().endsWith(expectedExt)
|| !fs.existsSync(candidate)
|| !fs.statSync(candidate).isFile()
) {
throw new Error(`embedded_manifest_asset_invalid:${assetName}`);
}
return candidate;
}
function _failedPlatformsForError(message, buildRow) {
const localSingleTarget = EMBEDDED_MODE
&& clientBuilder.getBuildCapabilities().mode === 'local';
return localSingleTarget || String(message).startsWith('local_builder')
? [{
platform: buildRow.platform,
arch: buildRow.arch,
format: buildRow.format,
}]
: bundleService.PLATFORMS;
}
async function _assertEmbeddedArtifact(artifactPath) {
if (artifactPath.endsWith('.zip')) {
const zip = new AdmZip(artifactPath);
for (const entry of zip.getEntries()) {
const name = String(entry.entryName || '').replace(/\\/g, '/').toLowerCase();
if (name.endsWith('/custom.txt') || name.endsWith('/.custom-txt-here')) {
throw new Error('embedded_artifact_contains_external_config');
}
}
return;
}
const listing = await new Promise((resolve, reject) => {
const child = spawn('tar', ['-tzf', artifactPath], {
cwd: path.dirname(artifactPath),
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
let output = '';
let error = '';
child.stdout.on('data', (chunk) => { output += chunk.toString(); });
child.stderr.on('data', (chunk) => { error += chunk.toString(); });
child.on('error', reject);
child.on('close', (code) => code === 0
? resolve(output)
: reject(new Error(`embedded_artifact_list_failed:${error.trim() || code}`)));
});
for (const line of listing.split(/\r?\n/)) {
const name = line.replace(/\\/g, '/').toLowerCase();
if (name.endsWith('/custom.txt') || name.endsWith('/.custom-txt-here')) {
throw new Error('embedded_artifact_contains_external_config');
}
}
}
async function _validateEmbeddedManifest(outputDir, buildRow) {
const manifestPath = path.join(outputDir, 'manifest.json');
let manifest;
try {
manifest = JSON.parse(await fsp.readFile(manifestPath, 'utf8'));
} catch (err) {
throw new Error(`embedded_manifest_invalid:${err.message || String(err)}`);
}
if (manifest.schema_version !== 1 || manifest.sku !== 'betterdesk-support') {
throw new Error('embedded_manifest_contract_invalid');
}
if (manifest.external_config !== false) {
throw new Error('embedded_manifest_external_config');
}
if (
buildRow._bundle?.client_commit
&& String(manifest.client_commit || '').toLowerCase()
!== String(buildRow._bundle.client_commit).toLowerCase()
) {
throw new Error('embedded_manifest_client_commit_mismatch');
}
if (!Array.isArray(manifest.assets)) throw new Error('embedded_manifest_assets_missing');
for (const asset of manifest.assets) {
if (!asset || typeof asset.name !== 'string' || !/^[a-zA-Z0-9._-]+$/.test(asset.name)) {
throw new Error('embedded_manifest_asset_invalid');
}
const assetPath = path.join(outputDir, asset.name);
if (!fs.existsSync(assetPath) || !fs.statSync(assetPath).isFile()) {
throw new Error(`embedded_manifest_asset_missing:${asset.name}`);
}
if (asset.sha256) {
const actual = await _sha256OfFile(assetPath);
if (actual.toLowerCase() !== String(asset.sha256).toLowerCase()) {
throw new Error(`embedded_manifest_asset_checksum_mismatch:${asset.name}`);
}
}
}
return manifest;
}
async function _runEmbeddedOne(buildRow) {
const key = `${buildRow.platform}/${buildRow.arch}/${buildRow.format}`;
const startTs = Date.now();
const generationId = buildRow.branding_hash.slice(0, 48);
try {
await db.upsertAgentBundleBuild({
brandingHash: buildRow.branding_hash,
platform: buildRow.platform,
arch: buildRow.arch,
format: buildRow.format,
status: 'building',
artifactPath: null,
artifactSize: 0,
artifactSha256: null,
errorMessage: '',
clientCommit: buildRow._bundle?.client_commit || null,
generationId,
configFingerprint: buildRow._bundle?.config_fingerprint || null,
progressPercent: 0,
progressPhase: 'preparing',
});
const branding = _parseBranding(buildRow._bundle?.branding);
const { content } = await _buildCustomTxtContent(branding);
const buildPlatforms = _availablePlatforms();
if (!buildPlatforms.length) {
throw new Error('local_builder_no_supported_targets');
}
const result = await clientBuilder.runBuild({
schema_version: 1,
product_sku: 'betterdesk-support',
generationId,
clientCommit: buildRow._bundle?.client_commit || null,
configFingerprint: buildRow._bundle?.config_fingerprint || null,
targets: buildPlatforms.map((platform) => ({
platform: platform.platform,
arch: platform.arch,
format: platform.format,
})),
signed_config_b64: content,
}, {
onProgress: async ({ percent, phase }) => {
await db.upsertAgentBundleBuild({
brandingHash: buildRow.branding_hash,
platform: buildRow.platform,
arch: buildRow.arch,
format: buildRow.format,
status: 'building',
artifactPath: null,
artifactSize: 0,
artifactSha256: null,
errorMessage: '',
clientCommit: buildRow._bundle?.client_commit || null,
generationId,
configFingerprint: buildRow._bundle?.config_fingerprint || null,
progressPercent: percent,
progressPhase: phase,
});
},
});
const manifest = await _validateEmbeddedManifest(result.outputDir, buildRow);
await fsp.mkdir(ARTIFACT_ROOT, { recursive: true });
const availableTargets = new Set((manifest.assets || []).map((asset) => (
`${asset.platform}/${asset.arch}`
)));
const localProvider = manifest.builder === 'betterdesk-local';
for (const platform of buildPlatforms) {
const targetKey = `${platform.platform}/${platform.arch === 'x64' ? 'x86_64' : 'aarch64'}`;
if (!availableTargets.has(targetKey)) {
if (!localProvider) {
throw new Error(`embedded_build_target_missing:${targetKey}`);
}
await db.upsertAgentBundleBuild({
brandingHash: buildRow.branding_hash,
platform: platform.platform,
arch: platform.arch,
format: platform.format,
status: 'failed',
artifactPath: null,
artifactSize: 0,
artifactSha256: null,
errorMessage: `local_builder_target_unavailable:${targetKey}`,
clientCommit: buildRow._bundle?.client_commit || null,
generationId,
configFingerprint: buildRow._bundle?.config_fingerprint || null,
progressPercent: 0,
progressPhase: 'target_unavailable',
});
continue;
}
const sourceArtifact = _findManifestArtifact(
result.outputDir,
manifest,
platform.platform,
platform.arch
);
await _assertEmbeddedArtifact(sourceArtifact);
const ext = platform.platform === 'windows' ? 'zip' : 'tar.gz';
const artifactPath = path.join(
ARTIFACT_ROOT,
`betterdesk-support-${buildRow.branding_hash.slice(0, 12)}-${platform.platform}-${platform.arch}.${ext}`
);
const temporaryArtifact = `${artifactPath}.tmp-${process.pid}-${Date.now()}`;
await fsp.copyFile(sourceArtifact, temporaryArtifact);
await fsp.rename(temporaryArtifact, artifactPath);
const stat = await fsp.stat(artifactPath);
const sha = await _sha256OfFile(artifactPath);
await db.upsertAgentBundleBuild({
brandingHash: buildRow.branding_hash,
platform: platform.platform,
arch: platform.arch,
format: platform.format,
status: 'ready',
artifactPath,
artifactSize: stat.size,
artifactSha256: sha,
errorMessage: '',
clientCommit: buildRow._bundle?.client_commit || null,
generationId,
configFingerprint: buildRow._bundle?.config_fingerprint || null,
progressPercent: 100,
progressPhase: 'complete',
});
}
await _promoteIfComplete(buildRow.branding_hash);
console.log(
`[clientTemplateWorker] embedded build ready ${key}`
+ ` (${((Date.now() - startTs) / 1000).toFixed(1)}s)`
);
} catch (err) {
const msg = err.message || String(err);
console.error(`[clientTemplateWorker] embedded build FAILED ${key}: ${msg}`);
const failedPlatforms = _failedPlatformsForError(msg, buildRow);
await Promise.all(failedPlatforms.map((platform) => (
db.upsertAgentBundleBuild({
brandingHash: buildRow.branding_hash,
platform: platform.platform,
arch: platform.arch,
format: platform.format,
status: 'failed',
artifactPath: null,
artifactSize: 0,
artifactSha256: null,
errorMessage: msg.slice(0, 2000),
clientCommit: buildRow._bundle?.client_commit || null,
generationId,
configFingerprint: buildRow._bundle?.config_fingerprint || null,
progressPercent: 0,
progressPhase: 'failed',
})
)));
}
}
async function _promoteIfComplete(brandingHash) {
const builds = await db.listAgentBundleBuildsForHash(brandingHash);
const required = _availablePlatforms().map((p) => (
`${p.platform}/${p.arch}/${p.format}`
));
const ready = new Set((builds || [])
.filter((row) => row.status === 'ready')
.map((row) => `${row.platform}/${row.arch}/${row.format}`));
if (required.every((key) => ready.has(key))) {
await db.promoteAgentBundleGeneration(brandingHash);
}
}
module.exports = {
enqueueBuildsForHash,
rebuildBundleById,
rebuildAllForClientRevision,
requeuePlatformBuild,
startWorker,
stopWorker,
getBuildWorkerStatus,
getAvailablePlatforms: _availablePlatforms,
getReadyArtifact,
_internals: {
isSupportProduct: _isSupportProduct,
buildCustomTxtContent: _buildCustomTxtContent,
findCustomTxtTarget: _findCustomTxtTarget,
filterPlatforms: _filterPlatforms,
findManifestArtifact: _findManifestArtifact,
failedPlatformsForError: _failedPlatformsForError,
hasWindowsSupportInstallers: windowsSupportInstaller.hasWindowsSupportInstallers,
isArtifactPathSafe: _isArtifactPathSafe,
ARTIFACT_ROOT,
WORK_ROOT,
IS_WINDOWS,
+259 -18
View File
@@ -1028,6 +1028,9 @@ function createSqliteAdapter(config) {
name TEXT NOT NULL,
branding TEXT NOT NULL DEFAULT '{}',
branding_hash TEXT NOT NULL DEFAULT '',
config_fingerprint TEXT NOT NULL DEFAULT '',
client_commit TEXT DEFAULT NULL,
active_generation_hash TEXT DEFAULT NULL,
created_by INTEGER DEFAULT NULL,
product_type TEXT NOT NULL DEFAULT 'betterdesk-support',
revoked INTEGER NOT NULL DEFAULT 0,
@@ -1049,6 +1052,11 @@ function createSqliteAdapter(config) {
artifact_size INTEGER DEFAULT 0,
artifact_sha256 TEXT DEFAULT NULL,
error_message TEXT DEFAULT '',
client_commit TEXT DEFAULT NULL,
generation_id TEXT DEFAULT NULL,
config_fingerprint TEXT DEFAULT NULL,
progress_percent INTEGER NOT NULL DEFAULT 0,
progress_phase TEXT DEFAULT '',
started_at TEXT DEFAULT NULL,
finished_at TEXT DEFAULT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
@@ -1058,6 +1066,32 @@ function createSqliteAdapter(config) {
CREATE INDEX IF NOT EXISTS idx_agent_bundle_builds_hash ON agent_bundle_builds (branding_hash);
CREATE INDEX IF NOT EXISTS idx_agent_bundle_builds_status ON agent_bundle_builds (status);
`);
const bundleColumns = new Set(
db.prepare('PRAGMA table_info(agent_bundles)').all().map(c => c.name)
);
for (const [column, type] of [
['config_fingerprint', "TEXT NOT NULL DEFAULT ''"],
['client_commit', 'TEXT DEFAULT NULL'],
['active_generation_hash', 'TEXT DEFAULT NULL'],
]) {
if (!bundleColumns.has(column)) {
db.exec(`ALTER TABLE agent_bundles ADD COLUMN ${column} ${type}`);
}
}
const buildColumns = new Set(
db.prepare('PRAGMA table_info(agent_bundle_builds)').all().map(c => c.name)
);
for (const [column, type] of [
['client_commit', 'TEXT DEFAULT NULL'],
['generation_id', 'TEXT DEFAULT NULL'],
['config_fingerprint', 'TEXT DEFAULT NULL'],
['progress_percent', 'INTEGER NOT NULL DEFAULT 0'],
['progress_phase', "TEXT DEFAULT ''"],
]) {
if (!buildColumns.has(column)) {
db.exec(`ALTER TABLE agent_bundle_builds ADD COLUMN ${column} ${type}`);
}
}
migrateAgentBundleSlugsSqlite(db);
migrateAgentBundleProductTypesSqlite(db);
}
@@ -3623,33 +3657,98 @@ function createSqliteAdapter(config) {
return excludeBundleId ? row.bundle_id !== excludeBundleId : true;
},
async createAgentBundle({ bundleId, slug, name, branding, brandingHash, createdBy, productType }) {
async createAgentBundle({
bundleId,
slug,
name,
branding,
brandingHash,
configFingerprint,
clientCommit,
createdBy,
productType,
}) {
const db = openMain();
const r = db.prepare(`
INSERT INTO agent_bundles (bundle_id, slug, name, branding, branding_hash, created_by, product_type)
VALUES (?, ?, ?, ?, ?, ?, ?)
INSERT INTO agent_bundles (
bundle_id, slug, name, branding, branding_hash,
config_fingerprint, client_commit, created_by, product_type
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`).run(
bundleId,
slug || null,
name,
branding,
brandingHash,
configFingerprint || brandingHash,
clientCommit || null,
createdBy || null,
normalizeProductType(productType)
);
return db.prepare('SELECT * FROM agent_bundles WHERE id = ?').get(r.lastInsertRowid);
},
async updateAgentBundle(bundleId, { name, slug, branding, brandingHash }) {
async updateAgentBundle(bundleId, {
name,
slug,
branding,
brandingHash,
configFingerprint,
clientCommit,
}) {
const db = openMain();
db.prepare(`
UPDATE agent_bundles
SET name = ?, slug = ?, branding = ?, branding_hash = ?, updated_at = datetime('now')
SET name = ?, slug = ?, branding = ?, branding_hash = ?,
config_fingerprint = ?, client_commit = ?, updated_at = datetime('now')
WHERE bundle_id = ?
`).run(name, slug || null, branding, brandingHash, bundleId);
`).run(
name,
slug || null,
branding,
brandingHash,
configFingerprint || brandingHash,
clientCommit || null,
bundleId
);
return db.prepare('SELECT * FROM agent_bundles WHERE bundle_id = ?').get(bundleId) || null;
},
async prepareAgentBundleGeneration(bundleId, {
brandingHash,
configFingerprint,
clientCommit,
}) {
const db = openMain();
db.prepare(`
UPDATE agent_bundles
SET branding_hash = ?, config_fingerprint = ?, client_commit = ?,
updated_at = datetime('now')
WHERE bundle_id = ?
`).run(
brandingHash,
configFingerprint || brandingHash,
clientCommit || null,
bundleId
);
return db.prepare('SELECT * FROM agent_bundles WHERE bundle_id = ?').get(bundleId) || null;
},
async promoteAgentBundleGeneration(brandingHash) {
const db = openMain();
db.prepare(`
UPDATE agent_bundles
SET active_generation_hash = ?, updated_at = datetime('now')
WHERE branding_hash = ? AND revoked = 0
`).run(brandingHash, brandingHash);
return db.prepare(`
SELECT * FROM agent_bundles
WHERE branding_hash = ? AND revoked = 0
ORDER BY created_at DESC
`).all(brandingHash);
},
async setAgentBundleRevoked(bundleId, revoked) {
const db = openMain();
db.prepare(`
@@ -3683,27 +3782,52 @@ function createSqliteAdapter(config) {
`).get(brandingHash, platform, arch, format) || null;
},
async upsertAgentBundleBuild({ brandingHash, platform, arch, format, status, artifactPath, artifactSize, artifactSha256, errorMessage }) {
async upsertAgentBundleBuild({
brandingHash,
platform,
arch,
format,
status,
artifactPath,
artifactSize,
artifactSha256,
errorMessage,
clientCommit,
generationId,
configFingerprint,
progressPercent,
progressPhase,
}) {
const db = openMain();
const buildStatus = normalizeBuildStatus(status);
db.prepare(`
INSERT INTO agent_bundle_builds (
branding_hash, platform, arch, format, status,
artifact_path, artifact_size, artifact_sha256, error_message,
client_commit, generation_id, config_fingerprint,
progress_percent, progress_phase,
started_at, finished_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ${buildStatus === 'building' ? "datetime('now')" : 'NULL'}, ${buildStatus === 'ready' || buildStatus === 'failed' ? "datetime('now')" : 'NULL'})
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ${buildStatus === 'building' ? "datetime('now')" : 'NULL'}, ${buildStatus === 'ready' || buildStatus === 'failed' ? "datetime('now')" : 'NULL'})
ON CONFLICT(branding_hash, platform, arch, format) DO UPDATE SET
status = excluded.status,
artifact_path = COALESCE(excluded.artifact_path, agent_bundle_builds.artifact_path),
artifact_size = COALESCE(excluded.artifact_size, agent_bundle_builds.artifact_size),
artifact_sha256 = COALESCE(excluded.artifact_sha256, agent_bundle_builds.artifact_sha256),
error_message = excluded.error_message,
client_commit = COALESCE(excluded.client_commit, agent_bundle_builds.client_commit),
generation_id = COALESCE(excluded.generation_id, agent_bundle_builds.generation_id),
config_fingerprint = COALESCE(excluded.config_fingerprint, agent_bundle_builds.config_fingerprint),
progress_percent = excluded.progress_percent,
progress_phase = excluded.progress_phase,
started_at = CASE WHEN excluded.status = 'building' THEN datetime('now') ELSE agent_bundle_builds.started_at END,
finished_at = CASE WHEN excluded.status IN ('ready','failed') THEN datetime('now') ELSE agent_bundle_builds.finished_at END,
updated_at = datetime('now')
`).run(
brandingHash, platform, arch, format, buildStatus,
artifactPath || null, artifactSize || 0, artifactSha256 || null, errorMessage || ''
artifactPath || null, artifactSize || 0, artifactSha256 || null, errorMessage || '',
clientCommit || null, generationId || null, configFingerprint || null,
Math.max(0, Math.min(100, Number(progressPercent || 0))),
String(progressPhase || '')
);
return this.getAgentBundleBuild({ brandingHash, platform, arch, format });
},
@@ -4251,6 +4375,9 @@ function createPostgresAdapter() {
name TEXT NOT NULL,
branding TEXT NOT NULL DEFAULT '{}',
branding_hash TEXT NOT NULL DEFAULT '',
config_fingerprint TEXT NOT NULL DEFAULT '',
client_commit TEXT DEFAULT NULL,
active_generation_hash TEXT DEFAULT NULL,
created_by INTEGER DEFAULT NULL,
product_type TEXT NOT NULL DEFAULT 'betterdesk-support',
revoked BOOLEAN NOT NULL DEFAULT FALSE,
@@ -4259,6 +4386,9 @@ function createPostgresAdapter() {
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`);
await q("ALTER TABLE agent_bundles ADD COLUMN IF NOT EXISTS config_fingerprint TEXT NOT NULL DEFAULT ''");
await q('ALTER TABLE agent_bundles ADD COLUMN IF NOT EXISTS client_commit TEXT DEFAULT NULL');
await q('ALTER TABLE agent_bundles ADD COLUMN IF NOT EXISTS active_generation_hash TEXT DEFAULT NULL');
await q('CREATE INDEX IF NOT EXISTS idx_agent_bundles_bundle_id ON agent_bundles (bundle_id)');
await q('CREATE INDEX IF NOT EXISTS idx_agent_bundles_hash ON agent_bundles (branding_hash)');
try {
@@ -4331,6 +4461,11 @@ function createPostgresAdapter() {
artifact_size BIGINT DEFAULT 0,
artifact_sha256 TEXT DEFAULT NULL,
error_message TEXT DEFAULT '',
client_commit TEXT DEFAULT NULL,
generation_id TEXT DEFAULT NULL,
config_fingerprint TEXT DEFAULT NULL,
progress_percent INTEGER NOT NULL DEFAULT 0,
progress_phase TEXT DEFAULT '',
started_at TIMESTAMPTZ DEFAULT NULL,
finished_at TIMESTAMPTZ DEFAULT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
@@ -4338,6 +4473,11 @@ function createPostgresAdapter() {
UNIQUE(branding_hash, platform, arch, format)
)
`);
await q('ALTER TABLE agent_bundle_builds ADD COLUMN IF NOT EXISTS client_commit TEXT DEFAULT NULL');
await q('ALTER TABLE agent_bundle_builds ADD COLUMN IF NOT EXISTS generation_id TEXT DEFAULT NULL');
await q('ALTER TABLE agent_bundle_builds ADD COLUMN IF NOT EXISTS config_fingerprint TEXT DEFAULT NULL');
await q("ALTER TABLE agent_bundle_builds ADD COLUMN IF NOT EXISTS progress_percent INTEGER NOT NULL DEFAULT 0");
await q("ALTER TABLE agent_bundle_builds ADD COLUMN IF NOT EXISTS progress_phase TEXT DEFAULT ''");
await q('CREATE INDEX IF NOT EXISTS idx_agent_bundle_builds_hash ON agent_bundle_builds (branding_hash)');
await q('CREATE INDEX IF NOT EXISTS idx_agent_bundle_builds_status ON agent_bundle_builds (status)');
@@ -7000,10 +7140,23 @@ function createPostgresAdapter() {
return excludeBundleId ? row.bundle_id !== excludeBundleId : true;
},
async createAgentBundle({ bundleId, slug, name, branding, brandingHash, createdBy, productType }) {
async createAgentBundle({
bundleId,
slug,
name,
branding,
brandingHash,
configFingerprint,
clientCommit,
createdBy,
productType,
}) {
return one(`
INSERT INTO agent_bundles (bundle_id, slug, name, branding, branding_hash, created_by, product_type)
VALUES ($1, $2, $3, $4, $5, $6, $7)
INSERT INTO agent_bundles (
bundle_id, slug, name, branding, branding_hash,
config_fingerprint, client_commit, created_by, product_type
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING *
`, [
bundleId,
@@ -7011,18 +7164,68 @@ function createPostgresAdapter() {
name,
branding,
brandingHash,
configFingerprint || brandingHash,
clientCommit || null,
createdBy || null,
normalizeProductType(productType),
]);
},
async updateAgentBundle(bundleId, { name, slug, branding, brandingHash }) {
async updateAgentBundle(bundleId, {
name,
slug,
branding,
brandingHash,
configFingerprint,
clientCommit,
}) {
return one(`
UPDATE agent_bundles
SET name = $1, slug = $2, branding = $3, branding_hash = $4, updated_at = NOW()
WHERE bundle_id = $5
SET name = $1, slug = $2, branding = $3, branding_hash = $4,
config_fingerprint = $5, client_commit = $6, updated_at = NOW()
WHERE bundle_id = $7
RETURNING *
`, [name, slug || null, branding, brandingHash, bundleId]);
`, [
name,
slug || null,
branding,
brandingHash,
configFingerprint || brandingHash,
clientCommit || null,
bundleId,
]);
},
async prepareAgentBundleGeneration(bundleId, {
brandingHash,
configFingerprint,
clientCommit,
}) {
return one(`
UPDATE agent_bundles
SET branding_hash = $1, config_fingerprint = $2,
client_commit = $3, updated_at = NOW()
WHERE bundle_id = $4
RETURNING *
`, [
brandingHash,
configFingerprint || brandingHash,
clientCommit || null,
bundleId,
]);
},
async promoteAgentBundleGeneration(brandingHash) {
await q(`
UPDATE agent_bundles
SET active_generation_hash = $1, updated_at = NOW()
WHERE branding_hash = $1 AND revoked = FALSE
`, [brandingHash]);
return all(`
SELECT * FROM agent_bundles
WHERE branding_hash = $1 AND revoked = FALSE
ORDER BY created_at DESC
`, [brandingHash]);
},
async setAgentBundleRevoked(bundleId, revoked) {
@@ -7058,15 +7261,33 @@ function createPostgresAdapter() {
`, [brandingHash, platform, arch, format]);
},
async upsertAgentBundleBuild({ brandingHash, platform, arch, format, status, artifactPath, artifactSize, artifactSha256, errorMessage }) {
async upsertAgentBundleBuild({
brandingHash,
platform,
arch,
format,
status,
artifactPath,
artifactSize,
artifactSha256,
errorMessage,
clientCommit,
generationId,
configFingerprint,
progressPercent,
progressPhase,
}) {
const buildStatus = normalizeBuildStatus(status);
return one(`
INSERT INTO agent_bundle_builds (
branding_hash, platform, arch, format, status,
artifact_path, artifact_size, artifact_sha256, error_message,
client_commit, generation_id, config_fingerprint,
progress_percent, progress_phase,
started_at, finished_at
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9,
$10, $11, $12, $13, $14,
CASE WHEN $5 = 'building' THEN NOW() ELSE NULL END,
CASE WHEN $5 IN ('ready','failed') THEN NOW() ELSE NULL END
)
@@ -7076,11 +7297,31 @@ function createPostgresAdapter() {
artifact_size = COALESCE(EXCLUDED.artifact_size, agent_bundle_builds.artifact_size),
artifact_sha256 = COALESCE(EXCLUDED.artifact_sha256, agent_bundle_builds.artifact_sha256),
error_message = EXCLUDED.error_message,
client_commit = COALESCE(EXCLUDED.client_commit, agent_bundle_builds.client_commit),
generation_id = COALESCE(EXCLUDED.generation_id, agent_bundle_builds.generation_id),
config_fingerprint = COALESCE(EXCLUDED.config_fingerprint, agent_bundle_builds.config_fingerprint),
progress_percent = EXCLUDED.progress_percent,
progress_phase = EXCLUDED.progress_phase,
started_at = CASE WHEN EXCLUDED.status = 'building' THEN NOW() ELSE agent_bundle_builds.started_at END,
finished_at = CASE WHEN EXCLUDED.status IN ('ready','failed') THEN NOW() ELSE agent_bundle_builds.finished_at END,
updated_at = NOW()
RETURNING *
`, [brandingHash, platform, arch, format, buildStatus, artifactPath || null, artifactSize || 0, artifactSha256 || null, errorMessage || '']);
`, [
brandingHash,
platform,
arch,
format,
buildStatus,
artifactPath || null,
artifactSize || 0,
artifactSha256 || null,
errorMessage || '',
clientCommit || null,
generationId || null,
configFingerprint || null,
Math.max(0, Math.min(100, Number(progressPercent || 0))),
String(progressPhase || ''),
]);
},
// ---- Integration Housekeeping ----
+392
View File
@@ -0,0 +1,392 @@
/**
* Local BetterDesk-Client build provider.
*
* Invoked by clientBuilderService with one request JSON path. The source
* tree is always the runtime snapshot outside the BetterDesk checkout.
* This provider never builds or publishes the full client profile: it
* requires the signed Support payload and passes it to Cargo through the
* compile-time environment.
*/
'use strict';
const fs = require('fs');
const fsp = fs.promises;
const path = require('path');
const crypto = require('crypto');
const { spawn } = require('child_process');
const AdmZip = require('adm-zip');
const requestPath = path.resolve(process.argv[2] || '');
const sourceDir = path.resolve(process.env.BETTERDESK_CLIENT_SOURCE_DIR || '');
const outputDir = path.resolve(process.env.BETTERDESK_CLIENT_OUTPUT_DIR || '');
function toolPath(name, configured) {
const candidates = [
configured,
process.env.BETTERDESK_CLIENT_TOOLCHAIN_BIN
? path.join(process.env.BETTERDESK_CLIENT_TOOLCHAIN_BIN, name)
: '',
`/opt/betterdesk-toolchain/bin/${name}`,
`/opt/betterdesk-toolchain/cargo/bin/${name}`,
`/opt/flutter-3.24.5/bin/${name}`,
...(process.env.PATH || '')
.split(path.delimiter)
.filter(Boolean)
.map((dir) => path.join(dir, name)),
].filter(Boolean);
return candidates.find((candidate) => fs.existsSync(candidate)) || '';
}
function resolveVcpkgRoot() {
const configured = String(process.env.VCPKG_ROOT || '').trim();
if (configured) return configured;
const conventional = process.platform === 'win32' ? 'C:\\vcpkg' : '/opt/vcpkg';
return fs.existsSync(path.join(conventional, process.platform === 'win32' ? 'vcpkg.exe' : 'vcpkg'))
? conventional
: '';
}
function buildEnvironment() {
const cargo = toolPath('cargo', process.env.BETTERDESK_CLIENT_CARGO);
const flutter = toolPath('flutter', process.env.BETTERDESK_CLIENT_FLUTTER);
if (!cargo) throw new Error('local_builder_toolchain_missing:cargo');
if (!flutter) throw new Error('local_builder_toolchain_missing:flutter');
const vcpkgRoot = resolveVcpkgRoot();
if (!vcpkgRoot) {
throw new Error('local_builder_toolchain_missing:VCPKG_ROOT');
}
if (!fs.existsSync(path.join(vcpkgRoot, process.platform === 'win32' ? 'vcpkg.exe' : 'vcpkg'))) {
throw new Error('local_builder_toolchain_invalid:VCPKG_ROOT');
}
const binDir = path.dirname(cargo);
const flutterDir = path.dirname(flutter);
const dartDir = path.join(flutterDir, 'cache', 'dart-sdk', 'bin');
const pubCache = process.env.PUB_CACHE
|| path.join(process.env.BETTERDESK_CLIENT_TOOLCHAIN_BIN || '/opt/betterdesk-toolchain', 'flutter-pub-cache');
const pubBin = path.join(pubCache, 'bin');
const libclangPath = process.env.LIBCLANG_PATH
|| (fs.existsSync('/usr/lib/llvm-18/lib') ? '/usr/lib/llvm-18/lib' : '');
return {
...process.env,
VCPKG_ROOT: vcpkgRoot,
PUB_CACHE: pubCache,
...(libclangPath ? { LIBCLANG_PATH: libclangPath } : {}),
PATH: [
binDir,
flutterDir,
fs.existsSync(dartDir) ? dartDir : '',
pubBin,
process.env.PATH || '',
].filter(Boolean).join(path.delimiter),
BETTERDESK_CLIENT_SUPPORT_BUILD: '1',
};
}
async function ensureFlutterRustBridge(sourceDir, environment) {
const bridgeRust = path.join(sourceDir, 'src', 'bridge_generated.rs');
const bridgeDart = path.join(sourceDir, 'flutter', 'lib', 'generated_bridge.dart');
if (fs.existsSync(bridgeRust) && fs.existsSync(bridgeDart)) return;
const codegenRoot = process.env.BETTERDESK_CLIENT_BRIDGE_CODEGEN_ROOT
|| '/opt/betterdesk-toolchain/bridge-codegen';
const codegen = path.join(codegenRoot, 'bin', 'flutter_rust_bridge_codegen');
await fsp.mkdir(codegenRoot, { recursive: true });
if (!fs.existsSync(codegen)) {
const install = await run('cargo', [
'install', 'flutter_rust_bridge_codegen',
'--version', '1.80.1',
'--features', 'uuid',
'--locked',
'--root', codegenRoot,
], { cwd: sourceDir, env: environment });
if (install.code !== 0) {
throw new Error(`local_builder_bridge_codegen_install_failed:${install.stderr.slice(-4000)}`);
}
}
const pub = await run('flutter', ['pub', 'get'], {
cwd: path.join(sourceDir, 'flutter'),
env: environment,
});
if (pub.code !== 0) {
throw new Error(`local_builder_flutter_pub_get_failed:${pub.stderr.slice(-4000)}`);
}
const ffigen = await run('dart', [
'pub', 'global', 'activate', 'ffigen', '--version', '5.0.1',
], { cwd: sourceDir, env: environment });
if (ffigen.code !== 0) {
throw new Error(`local_builder_ffigen_install_failed:${ffigen.stderr.slice(-4000)}`);
}
const codegenArgs = [
'--rust-input', './src/flutter_ffi.rs',
'--dart-output', './flutter/lib/generated_bridge.dart',
'--c-output', './flutter/macos/Runner/bridge_generated.h',
];
if (fs.existsSync('/usr/lib/llvm-18')) {
codegenArgs.push('--llvm-path', '/usr/lib/llvm-18');
}
const generated = await run(codegen, codegenArgs, { cwd: sourceDir, env: environment });
if (generated.code !== 0) {
throw new Error(`local_builder_bridge_codegen_failed:${generated.stderr.slice(-4000)}`);
}
const macHeader = path.join(sourceDir, 'flutter', 'macos', 'Runner', 'bridge_generated.h');
const iosHeader = path.join(sourceDir, 'flutter', 'ios', 'Runner', 'bridge_generated.h');
if (fs.existsSync(macHeader)) await fsp.copyFile(macHeader, iosHeader);
if (!fs.existsSync(bridgeRust) || !fs.existsSync(bridgeDart)) {
throw new Error('local_builder_bridge_codegen_incomplete');
}
}
function ensureBuildCapacity() {
const minimumMb = Math.max(
512,
Number.parseInt(process.env.BETTERDESK_CLIENT_BUILD_MIN_FREE_MB || '3072', 10)
);
const stats = fs.statfsSync(outputDir);
const freeMb = Math.floor((Number(stats.bavail) * Number(stats.bsize)) / (1024 * 1024));
if (freeMb < minimumMb) {
throw new Error(
`local_builder_disk_space_insufficient:${freeMb}MB<${minimumMb}MB`
);
}
return freeMb;
}
function fail(message) {
console.error(message);
process.exitCode = 1;
}
function hostTarget() {
const platform = process.platform === 'win32'
? 'windows'
: process.platform === 'darwin' ? 'macos' : 'linux';
const arch = process.arch === 'arm64' ? 'arm64' : 'x64';
return { platform, arch };
}
function providerArch(arch) {
return arch === 'x64' ? 'x86_64' : 'aarch64';
}
function localToolchainStatus() {
const missing = [];
if (!toolPath('cargo', process.env.BETTERDESK_CLIENT_CARGO)) missing.push('cargo');
if (!toolPath('flutter', process.env.BETTERDESK_CLIENT_FLUTTER)) missing.push('flutter');
const vcpkgRoot = resolveVcpkgRoot();
if (!vcpkgRoot) {
missing.push('VCPKG_ROOT');
} else if (!fs.existsSync(path.join(vcpkgRoot, process.platform === 'win32' ? 'vcpkg.exe' : 'vcpkg'))) {
missing.push('VCPKG_ROOT');
}
return { ready: missing.length === 0, missing };
}
function getCapabilities() {
const host = hostTarget();
const toolchain = localToolchainStatus();
return {
mode: 'local',
host,
toolchain,
targets: toolchain.ready ? [{
platform: host.platform,
arch: host.arch,
format: 'portable',
}] : [],
};
}
function run(command, args, options = {}) {
return new Promise((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: ['ignore', 'pipe', 'pipe'],
windowsHide: true,
});
let stdout = '';
let stderr = '';
child.stdout.on('data', (chunk) => { stdout += chunk.toString(); });
child.stderr.on('data', (chunk) => { stderr += chunk.toString(); });
child.on('error', reject);
child.on('close', (code) => resolve({ code, stdout, stderr }));
});
}
async function sha256(filePath) {
const hash = crypto.createHash('sha256');
const stream = fs.createReadStream(filePath);
for await (const chunk of stream) hash.update(chunk);
return hash.digest('hex');
}
function assertNoExternalConfig(root) {
const stack = [root];
while (stack.length) {
const current = stack.pop();
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
const full = path.join(current, entry.name);
if (entry.isDirectory()) stack.push(full);
else if (
entry.name.toLowerCase() === 'custom.txt'
|| entry.name === '.custom-txt-here'
) {
throw new Error('local_builder_external_config_present');
}
}
}
}
async function packageTarget(request, target) {
const arch = providerArch(target.arch);
const targetName = `${target.platform}-${arch}`;
const stage = path.join(outputDir, 'stage', targetName);
await fsp.rm(stage, { recursive: true, force: true });
await fsp.mkdir(stage, { recursive: true });
if (target.platform === 'windows') {
const source = path.join(
sourceDir,
'flutter',
'build',
'windows',
target.arch,
'runner',
'Release'
);
if (!fs.existsSync(source)) throw new Error(`local_builder_output_missing:${source}`);
await fsp.cp(source, stage, { recursive: true });
assertNoExternalConfig(stage);
const zipPath = path.join(
outputDir,
`betterdesk-support-${request.generationId}-${targetName}.zip`
);
const zip = new AdmZip();
zip.addLocalFolder(stage, targetName);
zip.writeZip(zipPath);
return zipPath;
}
let source;
if (target.platform === 'linux') {
source = path.join(
sourceDir,
'flutter',
'build',
'linux',
target.arch,
'release',
'bundle'
);
} else {
source = path.join(
sourceDir,
'flutter',
'build',
'macos',
'Build',
'Products',
'Release',
'BetterDesk Client.app'
);
}
if (!fs.existsSync(source)) throw new Error(`local_builder_output_missing:${source}`);
await fsp.cp(source, path.join(stage, path.basename(source)), { recursive: true });
assertNoExternalConfig(stage);
const archivePath = path.join(
outputDir,
`betterdesk-support-${request.generationId}-${targetName}.tar.gz`
);
const result = await run('tar', ['-czf', archivePath, targetName], {
cwd: path.dirname(stage),
env: process.env,
});
if (result.code !== 0) throw new Error(`local_builder_tar_failed:${result.stderr.slice(-2000)}`);
return archivePath;
}
async function main() {
if (!fs.existsSync(requestPath) || !fs.existsSync(path.join(sourceDir, 'build.py'))) {
throw new Error('local_builder_source_or_request_missing');
}
const request = JSON.parse(await fsp.readFile(requestPath, 'utf8'));
if (request.product_sku !== 'betterdesk-support' || !request.signed_config_b64) {
throw new Error('local_builder_support_payload_required');
}
if (!Array.isArray(request.targets) || request.targets.length !== 1) {
throw new Error('local_builder_single_target_required');
}
const host = hostTarget();
const target = request.targets.find((candidate) => (
candidate.platform === host.platform && candidate.arch === host.arch
));
if (!target) {
throw new Error(`local_builder_target_unsupported:${request.targets[0]?.platform || 'unknown'}/${request.targets[0]?.arch || 'unknown'}`);
}
await fsp.mkdir(outputDir, { recursive: true });
ensureBuildCapacity();
const toolchainEnv = buildEnvironment();
const progress = (percent, phase) => {
console.log(`BETTERDESK_BUILD_PROGRESS|${percent}|${phase}`);
};
progress(5, 'preparing');
await ensureFlutterRustBridge(sourceDir, toolchainEnv);
const python = process.platform === 'win32' ? 'python' : 'python3';
const args = ['build.py', '--flutter'];
if (
String(process.env.BETTERDESK_CLIENT_BUILD_HWCODEC || '').trim().toLowerCase() === 'on'
&& process.env.VCPKG_ROOT
) {
args.push('--hwcodec');
}
if (process.platform === 'win32') args.push('--skip-portable-pack');
progress(10, 'compiling');
const build = await run(python, args, {
cwd: sourceDir,
env: {
...toolchainEnv,
BETTERDESK_SUPPORT_CONFIG_B64: request.signed_config_b64,
BETTERDESK_FORCE_LOCAL_CARGO_TARGET: '1',
},
});
if (build.code !== 0) {
throw new Error(`local_builder_compile_failed:${build.stderr.slice(-4000)}`);
}
progress(78, 'packaging');
const artifact = await packageTarget(request, target);
progress(94, 'verifying');
const manifest = {
schema_version: 1,
sku: 'betterdesk-support',
generation_id: request.generationId,
client_commit: request.clientCommit || null,
external_config: false,
assets: [{
name: path.basename(artifact),
sha256: await sha256(artifact),
size: (await fsp.stat(artifact)).size,
platform: target.platform,
arch: providerArch(target.arch),
}],
builder: 'betterdesk-local',
};
await fsp.writeFile(
path.join(outputDir, 'manifest.json'),
JSON.stringify(manifest, null, 2) + '\n',
{ encoding: 'utf8', mode: 0o600 }
);
progress(100, 'complete');
}
if (require.main === module) {
main().catch(fail);
}
module.exports = {
hostTarget,
providerArch,
getCapabilities,
};
+20
View File
@@ -2706,6 +2706,26 @@ async function applyUpdate(remoteSHA, changedData, opts = {}) {
saveLocalSHA(remoteSHA);
results.shaSaved = true;
// BetterDesk-Client is an external runtime module. When embedded
// generation is enabled, synchronize its pinned source during the
// same panel update and queue all existing Support configs. The
// worker promotes a new generation only after every target succeeds,
// so an interrupted update cannot break an active download link.
if (String(
process.env.BETTERDESK_CLIENT_GENERATOR_MODE || 'embedded'
).trim().toLowerCase() === 'embedded') {
try {
const clientBuilder = require('./clientBuilderService');
results.clientRebuild = await clientBuilder.syncAndQueueRebuilds();
} catch (clientErr) {
results.clientRebuild = {
queued: false,
error: clientErr.message || String(clientErr),
};
console.warn(`[UPDATE] BetterDesk-Client sync/rebuild deferred: ${clientErr.message}`);
}
}
// ---- Pull remote VERSION file ----
try {
const versionContent = await ghDownloadFile(GITHUB_OWNER, GITHUB_REPO, remoteSHA, 'VERSION');
@@ -0,0 +1,73 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
describe('clientBuilderService', () => {
let dataDir;
let builder;
beforeEach(() => {
jest.resetModules();
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'betterdesk-client-builder-'));
jest.doMock('../config/config', () => ({ dataDir }));
builder = require('../services/clientBuilderService');
});
afterEach(() => {
jest.dontMock('../config/config');
fs.rmSync(dataDir, { recursive: true, force: true });
});
test('creates stable, distinct generation keys', () => {
const fingerprint = 'a'.repeat(64);
const first = builder.generationKey(fingerprint, '1'.repeat(40));
const same = builder.generationKey(fingerprint, '1'.repeat(40));
const changed = builder.generationKey(fingerprint, '2'.repeat(40));
expect(first).toMatch(/^[a-f0-9]{64}$/);
expect(same).toBe(first);
expect(changed).not.toBe(first);
});
test('rejects unsafe repository and ref values', () => {
expect(() => builder.normalizeRepo('https://github.com/example/repo')).toThrow(
'betterdesk_client_repo_invalid'
);
expect(() => builder.normalizeRepo('example/repo/extra')).toThrow(
'betterdesk_client_repo_invalid'
);
expect(() => builder.clientRef('master\r\nTOKEN=leak')).toThrow(
'betterdesk_client_ref_invalid'
);
});
test('writes state atomically outside the project checkout', async () => {
const state = await builder.writeState({
repo: 'UNITRONIX/BetterDesk-Client',
ref: 'master',
installedCommit: 'a'.repeat(40),
status: 'ready',
});
expect(state.installedCommit).toBe('a'.repeat(40));
expect(fs.existsSync(builder.statePath())).toBe(true);
expect(builder.statePath()).toContain(path.join('modules', 'betterdesk-client-builder'));
expect(fs.readdirSync(builder.dataRoot()).some((name) => name.endsWith('.tmp'))).toBe(false);
});
test('generates an instance signing seed without exposing it in state', () => {
const key = builder.ensureSigningKeySync();
const seedPath = path.join(
dataDir,
'modules',
'betterdesk-support-generator',
'custom-client-signing.seed'
);
expect(key.generated).toBe(true);
expect(key.publicKey).toMatch(/^[A-Za-z0-9+/]+=*$/);
expect(fs.readFileSync(seedPath, 'utf8').trim()).toMatch(/^[A-Za-z0-9+/]+=*$/);
expect(JSON.stringify(builder.readState())).not.toContain(key.seed);
});
});
@@ -0,0 +1,84 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
jest.mock('../config/config', () => ({
dataDir: 'C:\\betterdesk-worker-test-data',
}));
jest.mock('../services/database', () => ({}));
jest.mock('../services/agentBundleService', () => ({
PLATFORMS: [
{ platform: 'windows', arch: 'x64', format: 'portable', label: 'Windows x64' },
{ platform: 'linux', arch: 'x64', format: 'portable', label: 'Linux x64' },
],
}));
jest.mock('../services/supportGeneratorModule', () => ({
isReady: () => false,
templatesExist: () => false,
templatesDir: () => '',
resolveTemplateDir: () => null,
}));
jest.mock('../services/clientBuilderService', () => ({
isReady: () => true,
getBuildCapabilities: () => ({
mode: 'local',
targets: [{ platform: 'linux', arch: 'x64', format: 'portable' }],
}),
}));
jest.mock('../services/windowsSupportInstaller', () => ({
hasWindowsSupportInstallers: () => false,
}));
jest.mock('../services/customTxtBuilder', () => ({}));
jest.mock('../services/keyService', () => ({}));
jest.mock('../services/agentBundleConnection', () => ({}));
jest.mock('../services/platformSupportInstaller', () => ({}));
const worker = require('../services/clientTemplateWorker');
describe('clientTemplateWorker embedded artifacts', () => {
let root;
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), 'betterdesk-worker-artifacts-'));
});
afterEach(() => {
fs.rmSync(root, { recursive: true, force: true });
});
test('selects the manifest asset when unrelated archives are also present', () => {
const selected = path.join(root, 'betterdesk-support-linux-x86_64.tar.gz');
fs.writeFileSync(selected, 'selected');
fs.writeFileSync(path.join(root, 'unrelated-linux-x86_64.tar.gz'), 'unrelated');
expect(worker._internals.findManifestArtifact(
root,
{
assets: [{
name: 'betterdesk-support-linux-x86_64.tar.gz',
platform: 'linux',
arch: 'x86_64',
}],
},
'linux',
'x64',
)).toBe(selected);
});
test('exposes only locally supported target platforms', () => {
expect(worker.getAvailablePlatforms()).toEqual([
{ platform: 'linux', arch: 'x64', format: 'portable', label: 'Linux x64' },
]);
});
test('does not copy a local provider failure to every platform row', () => {
expect(worker._internals.failedPlatformsForError(
'betterdesk_client_build_failed:1:toolchain error',
{ platform: 'linux', arch: 'x64', format: 'portable' },
)).toEqual([
{ platform: 'linux', arch: 'x64', format: 'portable' },
]);
});
});
@@ -89,9 +89,40 @@ describe('dbAdapter generator bundle compatibility', () => {
check.close();
expect(columns).toContain('product_type');
expect(columns).toContain('config_fingerprint');
expect(columns).toContain('active_generation_hash');
expect(legacyRow.product_type).toBe('betterdesk-support');
expect(created.product_type).toBe('betterdesk-support');
expect(client.product_type).toBe('betterdesk-support');
expect(build.status).toBe('queued');
});
test('keeps the previous generation active until promotion', async () => {
const { getAdapter } = require('../services/dbAdapter');
adapter = getAdapter();
await adapter.init();
await adapter.createAgentBundle({
bundleId: 'generation-bundle',
slug: 'generation-bundle',
name: 'Generation bundle',
branding: '{}',
brandingHash: 'generation-v2',
configFingerprint: 'config-v1',
clientCommit: 'a'.repeat(40),
productType: 'betterdesk-support',
});
const staged = await adapter.prepareAgentBundleGeneration('generation-bundle', {
brandingHash: 'generation-v3',
configFingerprint: 'config-v1',
clientCommit: 'b'.repeat(40),
});
expect(staged.branding_hash).toBe('generation-v3');
expect(staged.active_generation_hash).toBeNull();
const promoted = await adapter.promoteAgentBundleGeneration('generation-v3');
expect(promoted).toHaveLength(1);
expect(promoted[0].active_generation_hash).toBe('generation-v3');
});
});
+15
View File
@@ -58,6 +58,21 @@
</div>
</div>
<div id="gen-operation-modal" class="gen-operation-modal hidden" aria-hidden="true">
<div class="gen-operation-backdrop"></div>
<div class="gen-operation-dialog" role="dialog" aria-modal="true"
aria-labelledby="gen-operation-title">
<div class="gen-operation-spinner" aria-hidden="true"></div>
<h2 id="gen-operation-title">BetterDesk Client builder</h2>
<p id="gen-operation-message">Preparing the operation…</p>
<div class="gen-operation-progress" role="progressbar"
aria-label="Builder progress">
<span></span>
</div>
<p id="gen-operation-detail" class="text-muted"></p>
</div>
</div>
<div id="gen-main" class="generator-layout hidden">
<!-- Left column: bundle list -->
<aside class="generator-bundles card">