Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4a76e520e7 | |||
| d9e1fc17f8 | |||
| 3b179075a8 | |||
| a3327cdd98 | |||
| 432a5c2264 | |||
| f36d20b8dd | |||
| baba892353 | |||
| d2c1bed82c | |||
| 3e68e875ac | |||
| a30260e336 | |||
| be53f179ab | |||
| db52934f35 | |||
| d29257dcf7 | |||
| 3b2b806165 | |||
| 070c936a69 | |||
| 3f15cbda80 | |||
| 4b48f0056e | |||
| d91fda084b | |||
| a86d83f835 | |||
| 05235ec284 | |||
| 4812621376 | |||
| 8b98706d27 | |||
| e36207347f | |||
| 5228eeaa23 | |||
| e6ebac76b4 | |||
| 27888a9fd1 | |||
| 3f6b058ce5 | |||
| ba370cbce8 | |||
| 43c8f261cc | |||
| 2984c41081 | |||
| d143d73ea9 | |||
| 9f8a6eaa76 | |||
| 0af8da2c9d | |||
| fa96d371d6 | |||
| 9e4dcc18a2 | |||
| 15574b8629 | |||
| b9c90eca3d | |||
| dc37a71802 | |||
| 595e84cdb6 | |||
| 5e04001790 | |||
| 7fe63541b3 |
+165
@@ -1,5 +1,170 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## Pending
|
||||||
|
|
||||||
|
|
||||||
|
## 2026-05-25 - 2.1.2
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- keep self-upgrades alive after stopping the service (upgrade)
|
||||||
|
- Launch dashboard-triggered upgrades as transient systemd units outside the service cgroup.
|
||||||
|
- Download and validate installer binaries before stopping the running service.
|
||||||
|
- Restart the previous service if installation fails after it was stopped.
|
||||||
|
|
||||||
|
## 2026-05-25 - 2.1.1
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- disable dees-catalog build scripts in workspace config (pnpm-workspace)
|
||||||
|
- Adds @design.estate/dees-catalog to pnpm allowBuilds with a false value to explicitly prevent its build scripts from running.
|
||||||
|
|
||||||
|
## 2026-05-25 - 2.1.0
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- add App Store upgrade progress tracking and interactive workspace processes (appstore,workspace)
|
||||||
|
- Track App Store upgrade operations with async start/list requests and streamed progress updates.
|
||||||
|
- Show running and failed upgrade status in App Store and service detail views while preventing duplicate upgrade actions.
|
||||||
|
- Route App Store upgrades through the shared service update flow to restore service routes before gateway sync.
|
||||||
|
- Add backend workspace shell discovery plus interactive process start/input/kill/output/exit APIs backed by Docker exec streams.
|
||||||
|
- Bump Docker and workspace UI dependencies for interactive stdin streaming and shell selection support.
|
||||||
|
|
||||||
|
## 2026-05-25 - 2.0.0
|
||||||
|
|
||||||
|
### Breaking Changes
|
||||||
|
|
||||||
|
- switch Onebox App Store resolution to the shared appstore client
|
||||||
|
- Uses `@serve.zone/appstore` and `@serve.zone/interfaces` for App Store metadata, parsing, and Docker digest resolution
|
||||||
|
- Renames App Store typed request methods to `getAppStoreTemplates`, `getAppStoreConfig`, `installAppStoreApp`, and `getUpgradeableAppStoreServices`
|
||||||
|
- Removes local duplicated App Store DTO and resolver code while preserving Onebox install and upgrade behavior
|
||||||
|
|
||||||
|
## 2026-05-25 - 1.31.0
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- resolve repo manifests and docker digest-tracked images (appstore)
|
||||||
|
- Add catalog source, resolved source, channel, runtime, upgrade strategy, and version metadata types for appstore manifests.
|
||||||
|
- Resolve catalog entries from repo manifests and pin digest-tracked Docker images using registry digests.
|
||||||
|
- Propagate resolved image digests into app version configs and service creation options.
|
||||||
|
- Add runtime coverage for repo manifest resolution and digest-tracked latest images.
|
||||||
|
|
||||||
|
## 2026-05-24 - 1.30.2
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- reduce remaining reverse proxy wording to required legacy SmartProxy cleanup and migration identifiers
|
||||||
|
- clean up legacy reverse proxy naming for SmartProxy (smartproxy)
|
||||||
|
- Update legacy reverse proxy service naming and logs used during SmartProxy startup cleanup.
|
||||||
|
- Clarify migration and documentation wording for the legacy reverse proxy to SmartProxy transition.
|
||||||
|
- Bump @serve.zone/catalog to ^2.12.6 and add pnpm workspace build dependency settings.
|
||||||
|
|
||||||
|
## 2026-05-24 - 1.30.1
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- align Onebox settings gateway cards with the dees-tile footer action pattern
|
||||||
|
- align settings gateway cards with dees-tile footer actions (settings-ui)
|
||||||
|
- Replaces custom gateway card wrappers with dees-tile header and footer slots.
|
||||||
|
- Uses tile-styled action buttons for Admin UI and dcrouter settings saves.
|
||||||
|
|
||||||
|
## 2026-05-24 - 1.30.0
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- add configurable Onebox Admin UI domain
|
||||||
|
- expose Admin UI domain in settings
|
||||||
|
- sync the Admin UI route as a first-class dcrouter gateway route
|
||||||
|
- keep Admin UI routing separate from app service routes
|
||||||
|
- add configurable Admin UI domain routing (admin-ui)
|
||||||
|
- Expose and validate the Admin UI domain in settings
|
||||||
|
- Sync the Admin UI as a dedicated dcrouter gateway route and SmartProxy route
|
||||||
|
- Preserve configured and legacy Admin UI routes during stale-route reconciliation
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- preserve Onebox Admin UI routes during external gateway stale-route reconciliation
|
||||||
|
|
||||||
|
## 2026-05-24 - 1.29.0
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- add Onebox runtime update prompts and admin-triggered self-upgrades
|
||||||
|
- expose Onebox update status through system status
|
||||||
|
- reuse the CLI upgrade logic for web-triggered detached upgrades
|
||||||
|
- show an update banner and guided DeesUpdater flow in the dashboard
|
||||||
|
|
||||||
|
## 2026-05-24 - 1.28.0
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- add enterprise-ready App Store runtime support for declared volumes and raw published ports
|
||||||
|
- validate app template schemas before install, fail invalid port/volume declarations early, and preserve declarations across upgrades and backups
|
||||||
|
- preflight Docker/host published port conflicts and back up declared service volume data
|
||||||
|
- show App Store volume mounts and raw host port exposure before deploy
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- fix Onebox dashboard system metrics rendering and traffic polling
|
||||||
|
- update `@serve.zone/catalog` to `^2.12.5`
|
||||||
|
- preserve an existing managed dcrouter config file instead of rewriting it on container creation
|
||||||
|
- remove stale external gateway routes during route reconciliation
|
||||||
|
|
||||||
|
## 2026-05-21 - 1.27.0
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- group Onebox sidebar navigation into Apps, Network, and Registry sections (web)
|
||||||
|
- add parent/subview routes for grouped app, network, and registry pages
|
||||||
|
|
||||||
|
## 2026-05-21 - 1.26.3
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- use `dees-table` for gateway domains and DNS records views (web)
|
||||||
|
- replace custom row grids with catalog tables, filtering, refresh, and row actions
|
||||||
|
- use dees-table for gateway domains and DNS records views (web)
|
||||||
|
- replace custom row layouts with dees-table in gateway domains and DNS records views
|
||||||
|
- add table filtering, refresh actions, and row/context actions for dcrouter management
|
||||||
|
|
||||||
|
## 2026-05-20 - 1.26.2
|
||||||
|
|
||||||
|
### Fixes
|
||||||
|
|
||||||
|
- reload SmartProxy routes after managed startup (proxy)
|
||||||
|
- reloads SmartProxy routes immediately after the admin API is ready during startup, avoiding an empty route table when Docker task state lags behind service readiness
|
||||||
|
|
||||||
|
## 2026-05-09 - 1.26.1 - fix(external-gateway)
|
||||||
|
derive gateway client identity from the dcrouter token and make the settings UI read-only
|
||||||
|
|
||||||
|
- Resolves external gateway ownership and domain sync to use the gateway client context returned by dcrouter instead of a locally entered client ID.
|
||||||
|
- Falls back to stored gateway client settings only when token context is unavailable.
|
||||||
|
- Removes editable Gateway Client ID fields from settings and shows them as diagnostic read-only values for managed and external modes.
|
||||||
|
- Updates external gateway tests to validate token-derived gateway client IDs and admin-token behavior.
|
||||||
|
|
||||||
|
## 2026-05-09 - 1.26.0 - feat(dcrouter)
|
||||||
|
add managed local dcrouter mode with status controls and gateway integration
|
||||||
|
|
||||||
|
- Adds a ManagedDcRouterManager to provision and control a local dcrouter container with default gateway settings.
|
||||||
|
- Updates gateway sync logic to support managed, external, and disabled dcrouter modes, including managed local route targets.
|
||||||
|
- Exposes managed dcrouter status, start, stop, and restart operations through OpsServer typed requests.
|
||||||
|
- Extends settings APIs and the settings UI to configure managed dcrouter ports, image, data directory, and mode selection.
|
||||||
|
- Adjusts Onebox startup to prepare managed dcrouter settings, shift proxy ports when managed mode is active, and initialize the local gateway before route sync.
|
||||||
|
|
||||||
|
## 2026-05-09 - 1.25.0 - feat(external-gateway)
|
||||||
|
add gateway client domain and DNS record support for dcrouter integration
|
||||||
|
|
||||||
|
- switch dcrouter route syncing to gateway-client APIs with fallback to legacy workHoster endpoints
|
||||||
|
- add admin endpoints and frontend views for browsing gateway domains and DNS records
|
||||||
|
- introduce dcrouterGatewayClientId settings support while preserving compatibility with the legacy workHoster ID
|
||||||
|
|
||||||
|
## 2026-05-08 - 1.24.7 - fix(web-ui)
|
||||||
|
|
||||||
|
align Delegate Routing settings with the Dees catalog control and theme conventions
|
||||||
|
|
||||||
|
- replace raw Delegate Routing inputs and save button with `dees-input-text` and `dees-button`
|
||||||
|
- style the Delegate Routing card with explicit `cssManager.bdTheme(...)` colors
|
||||||
|
|
||||||
## 2026-05-08 - 1.24.6 - fix(auth)
|
## 2026-05-08 - 1.24.6 - fix(auth)
|
||||||
|
|
||||||
avoid bcrypt worker crashes in compiled binaries during login and password creation
|
avoid bcrypt worker crashes in compiled binaries during login and password creation
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@serve.zone/onebox",
|
"name": "@serve.zone/onebox",
|
||||||
"version": "1.24.6",
|
"version": "2.1.2",
|
||||||
"exports": "./mod.ts",
|
"exports": "./mod.ts",
|
||||||
"tasks": {
|
"tasks": {
|
||||||
"test": "deno test --allow-all test/",
|
"test": "deno test --allow-all test/",
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
"@std/assert": "jsr:@std/assert@^1.0.19",
|
"@std/assert": "jsr:@std/assert@^1.0.19",
|
||||||
"@std/encoding": "jsr:@std/encoding@^1.0.10",
|
"@std/encoding": "jsr:@std/encoding@^1.0.10",
|
||||||
"@db/sqlite": "jsr:@db/sqlite@0.13.0",
|
"@db/sqlite": "jsr:@db/sqlite@0.13.0",
|
||||||
"@apiclient.xyz/docker": "npm:@apiclient.xyz/docker@^5.1.4",
|
"@apiclient.xyz/docker": "npm:@apiclient.xyz/docker@^5.1.5",
|
||||||
"@apiclient.xyz/cloudflare": "npm:@apiclient.xyz/cloudflare@7.1.0",
|
"@apiclient.xyz/cloudflare": "npm:@apiclient.xyz/cloudflare@7.1.0",
|
||||||
"@push.rocks/smartacme": "npm:@push.rocks/smartacme@^9.5.0",
|
"@push.rocks/smartacme": "npm:@push.rocks/smartacme@^9.5.0",
|
||||||
"@push.rocks/smartregistry": "npm:@push.rocks/smartregistry@^2.9.2",
|
"@push.rocks/smartregistry": "npm:@push.rocks/smartregistry@^2.9.2",
|
||||||
@@ -27,7 +27,9 @@
|
|||||||
"@push.rocks/smartguard": "npm:@push.rocks/smartguard@^3.1.0",
|
"@push.rocks/smartguard": "npm:@push.rocks/smartguard@^3.1.0",
|
||||||
"@push.rocks/smartjwt": "npm:@push.rocks/smartjwt@^2.2.2",
|
"@push.rocks/smartjwt": "npm:@push.rocks/smartjwt@^2.2.2",
|
||||||
"@api.global/typedsocket": "npm:@api.global/typedsocket@^4.1.3",
|
"@api.global/typedsocket": "npm:@api.global/typedsocket@^4.1.3",
|
||||||
"@serve.zone/containerarchive": "npm:@serve.zone/containerarchive@^0.1.3"
|
"@serve.zone/containerarchive": "npm:@serve.zone/containerarchive@^0.1.3",
|
||||||
|
"@serve.zone/interfaces": "npm:@serve.zone/interfaces@^6.0.0",
|
||||||
|
"@serve.zone/appstore": "npm:@serve.zone/appstore@^0.2.0"
|
||||||
},
|
},
|
||||||
"compilerOptions": {
|
"compilerOptions": {
|
||||||
"lib": [
|
"lib": [
|
||||||
|
|||||||
+50
-40
@@ -170,14 +170,55 @@ DOWNLOAD_URL="${GITEA_BASE_URL}/${GITEA_REPO}/releases/download/${VERSION}/${BIN
|
|||||||
echo "Download URL: $DOWNLOAD_URL"
|
echo "Download URL: $DOWNLOAD_URL"
|
||||||
echo ""
|
echo ""
|
||||||
|
|
||||||
# Check if service is running and stop it
|
# Check whether the service should be restarted after a successful install.
|
||||||
SERVICE_WAS_RUNNING=0
|
SERVICE_WAS_RUNNING=0
|
||||||
if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null || systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
if systemctl is-enabled --quiet "$SERVICE_NAME" 2>/dev/null || systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
||||||
SERVICE_WAS_RUNNING=1
|
SERVICE_WAS_RUNNING=1
|
||||||
if systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
fi
|
||||||
|
|
||||||
|
# Download and validate the new binary before touching the running service.
|
||||||
|
echo "Downloading Onebox binary..."
|
||||||
|
TEMP_DIR=$(mktemp -d)
|
||||||
|
TEMP_FILE="$TEMP_DIR/$BINARY_NAME"
|
||||||
|
cleanup_temp() {
|
||||||
|
rm -rf "$TEMP_DIR"
|
||||||
|
}
|
||||||
|
trap cleanup_temp EXIT
|
||||||
|
|
||||||
|
if ! curl -fSL "$DOWNLOAD_URL" -o "$TEMP_FILE"; then
|
||||||
|
echo "Error: Failed to download binary from $DOWNLOAD_URL"
|
||||||
|
echo ""
|
||||||
|
echo "Please check:"
|
||||||
|
echo " 1. Your internet connection"
|
||||||
|
echo " 2. The specified version exists: ${GITEA_BASE_URL}/${GITEA_REPO}/releases"
|
||||||
|
echo " 3. The platform binary is available for this release"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ ! -s "$TEMP_FILE" ]; then
|
||||||
|
echo "Error: Downloaded file is empty or does not exist"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
chmod +x "$TEMP_FILE"
|
||||||
|
if ! "$TEMP_FILE" --version >/dev/null 2>&1; then
|
||||||
|
echo "Error: Downloaded file is not an executable Onebox binary"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
SERVICE_STOPPED=0
|
||||||
|
restart_previous_service_on_error() {
|
||||||
|
if [ $SERVICE_STOPPED -eq 1 ]; then
|
||||||
|
echo "Installation failed after stopping Onebox; restarting previous service..."
|
||||||
|
systemctl start "$SERVICE_NAME" || true
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
trap 'restart_previous_service_on_error; cleanup_temp' ERR
|
||||||
|
|
||||||
|
if [ $SERVICE_WAS_RUNNING -eq 1 ] && systemctl is-active --quiet "$SERVICE_NAME" 2>/dev/null; then
|
||||||
echo "Stopping Onebox service..."
|
echo "Stopping Onebox service..."
|
||||||
systemctl stop "$SERVICE_NAME"
|
systemctl stop "$SERVICE_NAME"
|
||||||
fi
|
SERVICE_STOPPED=1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Clean installation directory - ensure only binary exists
|
# Clean installation directory - ensure only binary exists
|
||||||
@@ -190,44 +231,10 @@ fi
|
|||||||
echo "Creating installation directory: $INSTALL_DIR"
|
echo "Creating installation directory: $INSTALL_DIR"
|
||||||
mkdir -p "$INSTALL_DIR"
|
mkdir -p "$INSTALL_DIR"
|
||||||
|
|
||||||
# Download binary
|
# Install binary
|
||||||
echo "Downloading Onebox binary..."
|
|
||||||
TEMP_FILE="$INSTALL_DIR/onebox.download"
|
|
||||||
curl -sSL "$DOWNLOAD_URL" -o "$TEMP_FILE"
|
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo "Error: Failed to download binary from $DOWNLOAD_URL"
|
|
||||||
echo ""
|
|
||||||
echo "Please check:"
|
|
||||||
echo " 1. Your internet connection"
|
|
||||||
echo " 2. The specified version exists: ${GITEA_BASE_URL}/${GITEA_REPO}/releases"
|
|
||||||
echo " 3. The platform binary is available for this release"
|
|
||||||
rm -f "$TEMP_FILE"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Check if download was successful (file exists and not empty)
|
|
||||||
if [ ! -s "$TEMP_FILE" ]; then
|
|
||||||
echo "Error: Downloaded file is empty or does not exist"
|
|
||||||
rm -f "$TEMP_FILE"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Move to final location
|
|
||||||
BINARY_PATH="$INSTALL_DIR/onebox"
|
BINARY_PATH="$INSTALL_DIR/onebox"
|
||||||
mv "$TEMP_FILE" "$BINARY_PATH"
|
if ! install -m 0755 "$TEMP_FILE" "$BINARY_PATH" || [ ! -f "$BINARY_PATH" ]; then
|
||||||
|
echo "Error: Failed to install binary to $BINARY_PATH"
|
||||||
if [ $? -ne 0 ] || [ ! -f "$BINARY_PATH" ]; then
|
|
||||||
echo "Error: Failed to move binary to $BINARY_PATH"
|
|
||||||
rm -f "$TEMP_FILE" 2>/dev/null
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
|
|
||||||
# Make executable
|
|
||||||
chmod +x "$BINARY_PATH"
|
|
||||||
|
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo "Error: Failed to make binary executable"
|
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
@@ -256,10 +263,13 @@ if [ $SERVICE_WAS_RUNNING -eq 1 ]; then
|
|||||||
onebox systemd enable
|
onebox systemd enable
|
||||||
echo "Restarting Onebox service..."
|
echo "Restarting Onebox service..."
|
||||||
systemctl restart "$SERVICE_NAME"
|
systemctl restart "$SERVICE_NAME"
|
||||||
|
SERVICE_STOPPED=0
|
||||||
echo "Service restarted successfully."
|
echo "Service restarted successfully."
|
||||||
echo ""
|
echo ""
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
trap - ERR
|
||||||
|
|
||||||
echo "================================================"
|
echo "================================================"
|
||||||
echo " Onebox Installation Complete!"
|
echo " Onebox Installation Complete!"
|
||||||
echo "================================================"
|
echo "================================================"
|
||||||
|
|||||||
+10
-11
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@serve.zone/onebox",
|
"name": "@serve.zone/onebox",
|
||||||
"version": "1.24.6",
|
"version": "2.1.2",
|
||||||
"description": "Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers",
|
"description": "Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers",
|
||||||
"main": "mod.ts",
|
"main": "mod.ts",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
@@ -52,21 +52,20 @@
|
|||||||
"x64",
|
"x64",
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"packageManager": "pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34",
|
"packageManager": "pnpm@11.1.2",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@api.global/typedrequest-interfaces": "^3.0.19",
|
"@api.global/typedrequest-interfaces": "^3.0.19",
|
||||||
"@api.global/typedsocket": "^4.1.3",
|
"@api.global/typedsocket": "^4.1.3",
|
||||||
"@design.estate/dees-catalog": "^3.81.0",
|
"@design.estate/dees-catalog": "^3.82.0",
|
||||||
"@design.estate/dees-element": "^2.2.4",
|
"@design.estate/dees-element": "^2.2.4",
|
||||||
"@serve.zone/catalog": "^2.12.4"
|
"@serve.zone/appstore": "^0.2.0",
|
||||||
|
"@serve.zone/catalog": "^2.12.6",
|
||||||
|
"@serve.zone/interfaces": "^6.0.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@git.zone/tsbundle": "^2.10.1",
|
"@git.zone/tsbundle": "^2.10.4",
|
||||||
"@git.zone/tsdeno": "^1.3.1",
|
"@git.zone/tsdeno": "^1.3.2",
|
||||||
"@git.zone/tswatch": "^3.3.3"
|
"@git.zone/tswatch": "^3.3.5"
|
||||||
},
|
},
|
||||||
"private": true,
|
"private": true
|
||||||
"pnpm": {
|
|
||||||
"overrides": {}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+493
-225
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
|||||||
|
allowBuilds:
|
||||||
|
'@design.estate/dees-catalog': false
|
||||||
|
esbuild: true
|
||||||
|
ignoredBuiltDependencies:
|
||||||
|
- '@design.estate/dees-catalog'
|
||||||
+1
-1
@@ -46,7 +46,7 @@ ts/database/
|
|||||||
|
|
||||||
## Current Migration Version: 15
|
## Current Migration Version: 15
|
||||||
|
|
||||||
Migration 15 renames the core reverse proxy platform service from `caddy` to `smartproxy`.
|
Migration 15 renames the legacy core reverse proxy platform service type to `smartproxy`.
|
||||||
|
|
||||||
## Reverse Proxy (April 2026 - SmartProxy Docker Service)
|
## Reverse Proxy (April 2026 - SmartProxy Docker Service)
|
||||||
|
|
||||||
|
|||||||
@@ -183,7 +183,7 @@ onebox config set cloudflareZoneId zone-id
|
|||||||
|
|
||||||
## App Store
|
## App Store
|
||||||
|
|
||||||
The App Store manager fetches catalog data from `serve.zone/appstore-apptemplates` and caches it briefly. Templates can declare platform requirements, so installing an app can automatically provision MongoDB, S3-compatible storage, ClickHouse, Redis, or MariaDB resources and inject the resulting credentials as environment variables.
|
The App Store manager fetches metadata from `serve.zone/appstore` through `@serve.zone/appstore` and caches it briefly. Templates can declare platform requirements, so installing an app can automatically provision MongoDB, S3-compatible storage, ClickHouse, Redis, or MariaDB resources and inject the resulting credentials as environment variables.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
onebox appstore list
|
onebox appstore list
|
||||||
|
|||||||
@@ -0,0 +1,205 @@
|
|||||||
|
import { assertEquals, assertThrows } from '@std/assert';
|
||||||
|
|
||||||
|
import { AppStoreManager } from '../ts/classes/appstore.ts';
|
||||||
|
import { OneboxDockerManager } from '../ts/classes/docker.ts';
|
||||||
|
import type * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||||
|
import type { IService } from '../ts/types.ts';
|
||||||
|
|
||||||
|
type IAppStoreVersionConfig = servezoneInterfaces.appstore.IAppStoreVersionConfig;
|
||||||
|
|
||||||
|
const createAppStore = () => new AppStoreManager({} as any);
|
||||||
|
|
||||||
|
const baseConfig: IAppStoreVersionConfig = {
|
||||||
|
image: 'example/app:1.0.0',
|
||||||
|
port: 3000,
|
||||||
|
envVars: [
|
||||||
|
{
|
||||||
|
key: 'APP_PORT',
|
||||||
|
value: '3000',
|
||||||
|
description: 'Application port',
|
||||||
|
required: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const baseService: IService = {
|
||||||
|
id: 1,
|
||||||
|
name: 'test-service',
|
||||||
|
image: 'example/app:1.0.0',
|
||||||
|
envVars: {},
|
||||||
|
port: 3000,
|
||||||
|
status: 'stopped',
|
||||||
|
createdAt: Date.now(),
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
Deno.test('appstore normalizes and validates app template runtime fields', () => {
|
||||||
|
const appStore = createAppStore();
|
||||||
|
|
||||||
|
const normalizedVolumes = appStore.normalizeVolumes([
|
||||||
|
'/data/app',
|
||||||
|
{ mountPath: '/config', readOnly: true },
|
||||||
|
]);
|
||||||
|
|
||||||
|
assertEquals(normalizedVolumes, [
|
||||||
|
{ mountPath: '/data/app' },
|
||||||
|
{ mountPath: '/config', readOnly: true },
|
||||||
|
]);
|
||||||
|
|
||||||
|
appStore.validateAppVersionConfig({
|
||||||
|
...baseConfig,
|
||||||
|
volumes: normalizedVolumes,
|
||||||
|
publishedPorts: [
|
||||||
|
{ targetPort: 3000, publishedPort: 3000, protocol: 'tcp' },
|
||||||
|
{ targetPort: 20000, targetPortEnd: 20002, publishedPort: 20000, publishedPortEnd: 20002, protocol: 'udp' },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('appstore rejects invalid template ports and volumes', () => {
|
||||||
|
const appStore = createAppStore();
|
||||||
|
|
||||||
|
assertThrows(
|
||||||
|
() => appStore.validateAppVersionConfig({ ...baseConfig, port: 70000 }),
|
||||||
|
Error,
|
||||||
|
'Invalid app config port',
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThrows(
|
||||||
|
() => appStore.normalizeVolumes([{ mountPath: 'relative/path' }]),
|
||||||
|
Error,
|
||||||
|
'mountPath must be an absolute path',
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThrows(
|
||||||
|
() => appStore.validateAppVersionConfig({
|
||||||
|
...baseConfig,
|
||||||
|
publishedPorts: [
|
||||||
|
{ targetPort: 3000, targetPortEnd: 3002, publishedPort: 3000, publishedPortEnd: 3001, protocol: 'tcp' },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
Error,
|
||||||
|
'ranges must have the same size',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('appstore resolves repo manifests and docker digest-tracked latest images', async () => {
|
||||||
|
const appStoreBaseUrl = 'https://appstore.example.test';
|
||||||
|
const manifestUrl = 'https://code.example.test/cloudly/servezone.appstore.json';
|
||||||
|
const digest = 'sha256:1234567890abcdef';
|
||||||
|
|
||||||
|
const fakeFetch: typeof fetch = async (input, init) => {
|
||||||
|
const url = input instanceof Request ? input.url : input.toString();
|
||||||
|
const method = init?.method || 'GET';
|
||||||
|
|
||||||
|
if (url === `${appStoreBaseUrl}/appstore.resolved.json`) {
|
||||||
|
return new Response('not found', { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url === `${appStoreBaseUrl}/appstore.json`) {
|
||||||
|
return Response.json({
|
||||||
|
schemaVersion: 1,
|
||||||
|
updatedAt: '2026-05-24T00:00:00Z',
|
||||||
|
apps: [
|
||||||
|
{
|
||||||
|
id: 'cloudly',
|
||||||
|
name: 'Cloudly',
|
||||||
|
description: 'Central metadata can stay curated.',
|
||||||
|
category: 'Dev Tools',
|
||||||
|
latestVersion: '1.0.0',
|
||||||
|
source: {
|
||||||
|
type: 'repoManifest',
|
||||||
|
url: manifestUrl,
|
||||||
|
ref: 'main',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (url === manifestUrl) {
|
||||||
|
return Response.json({
|
||||||
|
schemaVersion: 1,
|
||||||
|
app: {
|
||||||
|
id: 'cloudly',
|
||||||
|
name: 'Cloudly',
|
||||||
|
description: 'Manifest-owned app metadata.',
|
||||||
|
category: 'Dev Tools',
|
||||||
|
maintainer: 'serve.zone',
|
||||||
|
},
|
||||||
|
latestVersion: 'latest',
|
||||||
|
source: {
|
||||||
|
type: 'dockerImage',
|
||||||
|
image: 'registry.example.test/serve.zone/cloudly:latest',
|
||||||
|
tracking: 'digest',
|
||||||
|
},
|
||||||
|
runtime: {
|
||||||
|
image: 'registry.example.test/serve.zone/cloudly:latest',
|
||||||
|
port: 80,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
url === 'https://registry.example.test/v2/serve.zone/cloudly/manifests/latest' &&
|
||||||
|
method === 'HEAD'
|
||||||
|
) {
|
||||||
|
return new Response(null, {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'docker-content-digest': digest },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(`unexpected ${method} ${url}`, { status: 500 });
|
||||||
|
};
|
||||||
|
|
||||||
|
const appStore = new AppStoreManager({} as any, {
|
||||||
|
baseUrl: appStoreBaseUrl,
|
||||||
|
fetch: fakeFetch,
|
||||||
|
});
|
||||||
|
|
||||||
|
const appStoreIndex = await appStore.getAppStore();
|
||||||
|
assertEquals(appStoreIndex.apps[0].latestVersion, `latest@${digest}`);
|
||||||
|
assertEquals(appStoreIndex.apps[0].resolvedSource?.manifestHash?.length, 64);
|
||||||
|
assertEquals(appStoreIndex.apps[0].upgradeStrategy, 'dockerDigest');
|
||||||
|
|
||||||
|
const appMeta = await appStore.getAppMeta('cloudly');
|
||||||
|
assertEquals(appMeta.latestVersion, `latest@${digest}`);
|
||||||
|
assertEquals(appMeta.versions, [`latest@${digest}`]);
|
||||||
|
|
||||||
|
const config = await appStore.getAppVersionConfig('cloudly', appMeta.latestVersion);
|
||||||
|
assertEquals(config.image, 'registry.example.test/serve.zone/cloudly:latest');
|
||||||
|
assertEquals(config.appStoreVersion, `latest@${digest}`);
|
||||||
|
assertEquals(config.resolvedImageDigest, digest);
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('docker service spec validation rejects unsafe volume and port declarations', () => {
|
||||||
|
const dockerManager = new OneboxDockerManager();
|
||||||
|
|
||||||
|
dockerManager.validateServiceSpec({
|
||||||
|
...baseService,
|
||||||
|
volumes: [{ mountPath: '/data/app' }],
|
||||||
|
publishedPorts: [{ targetPort: 3000, publishedPort: 3000, protocol: 'tcp' }],
|
||||||
|
});
|
||||||
|
|
||||||
|
assertThrows(
|
||||||
|
() => dockerManager.validateServiceSpec({
|
||||||
|
...baseService,
|
||||||
|
volumes: [{ mountPath: 'relative/path' }],
|
||||||
|
}),
|
||||||
|
Error,
|
||||||
|
'must be an absolute path',
|
||||||
|
);
|
||||||
|
|
||||||
|
assertThrows(
|
||||||
|
() => dockerManager.validateServiceSpec({
|
||||||
|
...baseService,
|
||||||
|
publishedPorts: [
|
||||||
|
{ targetPort: 3001, publishedPort: 3000, hostIp: '127.0.0.1', protocol: 'tcp' },
|
||||||
|
{ targetPort: 3000, publishedPort: 3000, protocol: 'tcp' },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
Error,
|
||||||
|
'Duplicate published port',
|
||||||
|
);
|
||||||
|
});
|
||||||
+391
-10
@@ -7,6 +7,7 @@ class FakeDatabase {
|
|||||||
public settings = new Map<string, string>();
|
public settings = new Map<string, string>();
|
||||||
public secretSettings = new Map<string, string>();
|
public secretSettings = new Map<string, string>();
|
||||||
public domains: IDomain[] = [];
|
public domains: IDomain[] = [];
|
||||||
|
public services: IService[] = [];
|
||||||
public certificates = new Map<string, ISslCertificate>();
|
public certificates = new Map<string, ISslCertificate>();
|
||||||
private nextDomainId = 1;
|
private nextDomainId = 1;
|
||||||
|
|
||||||
@@ -42,6 +43,10 @@ class FakeDatabase {
|
|||||||
return this.domains.filter((entry) => entry.dnsProvider === provider);
|
return this.domains.filter((entry) => entry.dnsProvider === provider);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getAllServices(): IService[] {
|
||||||
|
return this.services;
|
||||||
|
}
|
||||||
|
|
||||||
getSSLCertificate(domain: string): ISslCertificate | null {
|
getSSLCertificate(domain: string): ISslCertificate | null {
|
||||||
return this.certificates.get(domain) ?? null;
|
return this.certificates.get(domain) ?? null;
|
||||||
}
|
}
|
||||||
@@ -62,7 +67,6 @@ class FakeDatabase {
|
|||||||
const makeOneboxRef = () => {
|
const makeOneboxRef = () => {
|
||||||
const database = new FakeDatabase();
|
const database = new FakeDatabase();
|
||||||
database.settings.set('dcrouterGatewayUrl', 'https://edge.example.com');
|
database.settings.set('dcrouterGatewayUrl', 'https://edge.example.com');
|
||||||
database.settings.set('dcrouterWorkHosterId', 'onebox-1');
|
|
||||||
database.secretSettings.set('dcrouterGatewayApiToken', 'dcr-token');
|
database.secretSettings.set('dcrouterGatewayApiToken', 'dcr-token');
|
||||||
|
|
||||||
let reloadCount = 0;
|
let reloadCount = 0;
|
||||||
@@ -92,8 +96,12 @@ Deno.test('ExternalGatewayManager syncs dcrouter domains into Onebox domains', a
|
|||||||
});
|
});
|
||||||
|
|
||||||
const manager = new ExternalGatewayManager(oneboxRef as any);
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
(manager as any).fireDcRouterRequest = async (method: string) => {
|
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||||
assertEquals(method, 'getWorkHosterDomains');
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
|
||||||
|
}
|
||||||
|
assertEquals(method, 'getGatewayClientDomains');
|
||||||
|
assertEquals(requestData.gatewayClientId, 'onebox-token');
|
||||||
return {
|
return {
|
||||||
domains: [
|
domains: [
|
||||||
{
|
{
|
||||||
@@ -117,7 +125,7 @@ Deno.test('ExternalGatewayManager syncs dcrouter domains into Onebox domains', a
|
|||||||
assertEquals(oneboxRef.database.getDomainByName('old.example.com')?.isObsolete, true);
|
assertEquals(oneboxRef.database.getDomainByName('old.example.com')?.isObsolete, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster API', async () => {
|
Deno.test('ExternalGatewayManager syncs service routes to dcrouter gatewayClient API', async () => {
|
||||||
const oneboxRef = makeOneboxRef();
|
const oneboxRef = makeOneboxRef();
|
||||||
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
||||||
oneboxRef.database.settings.set('httpPort', '8080');
|
oneboxRef.database.settings.set('httpPort', '8080');
|
||||||
@@ -137,6 +145,9 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
|
|||||||
const requests: Array<{ method: string; requestData: Record<string, unknown> }> = [];
|
const requests: Array<{ method: string; requestData: Record<string, unknown> }> = [];
|
||||||
const manager = new ExternalGatewayManager(oneboxRef as any);
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
|
||||||
|
}
|
||||||
requests.push({ method, requestData });
|
requests.push({ method, requestData });
|
||||||
if (method === 'exportCertificate') {
|
if (method === 'exportCertificate') {
|
||||||
return { success: false };
|
return { success: false };
|
||||||
@@ -146,14 +157,14 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
|
|||||||
|
|
||||||
await manager.syncServiceRoute(service);
|
await manager.syncServiceRoute(service);
|
||||||
|
|
||||||
const syncRequest = requests.find((request) => request.method === 'syncWorkAppRoute')!;
|
const syncRequest = requests.find((request) => request.method === 'syncGatewayClientRoute')!;
|
||||||
const route = syncRequest.requestData.route as any;
|
const route = syncRequest.requestData.route as any;
|
||||||
const ownership = syncRequest.requestData.ownership as any;
|
const ownership = syncRequest.requestData.ownership as any;
|
||||||
|
|
||||||
assertEquals(ownership, {
|
assertEquals(ownership, {
|
||||||
workHosterType: 'onebox',
|
gatewayClientType: 'onebox',
|
||||||
workHosterId: 'onebox-1',
|
gatewayClientId: 'onebox-token',
|
||||||
workAppId: 'hello',
|
appId: 'hello',
|
||||||
hostname: 'hello.example.com',
|
hostname: 'hello.example.com',
|
||||||
});
|
});
|
||||||
assertEquals(route.match, { ports: [443], domains: ['hello.example.com'] });
|
assertEquals(route.match, { ports: [443], domains: ['hello.example.com'] });
|
||||||
@@ -162,13 +173,103 @@ Deno.test('ExternalGatewayManager syncs service routes to dcrouter WorkHoster AP
|
|||||||
assertEquals(syncRequest.requestData.enabled, true);
|
assertEquals(syncRequest.requestData.enabled, true);
|
||||||
});
|
});
|
||||||
|
|
||||||
Deno.test('ExternalGatewayManager deletes service routes through dcrouter WorkHoster API', async () => {
|
Deno.test('ExternalGatewayManager syncs Admin UI route to dcrouter gatewayClient API', async () => {
|
||||||
|
const oneboxRef = makeOneboxRef();
|
||||||
|
oneboxRef.database.settings.set('adminUiDomain', 'Onebox.Example.com');
|
||||||
|
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
||||||
|
oneboxRef.database.settings.set('httpPort', '8080');
|
||||||
|
|
||||||
|
const requests: Array<{ method: string; requestData: Record<string, unknown> }> = [];
|
||||||
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
|
(manager as any).fireDcRouterRequest = async (
|
||||||
|
method: string,
|
||||||
|
requestData: Record<string, unknown>,
|
||||||
|
) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return {
|
||||||
|
context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
requests.push({ method, requestData });
|
||||||
|
if (method === 'exportCertificate') {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
return { success: true, action: 'created', routeId: 'admin-route' };
|
||||||
|
};
|
||||||
|
|
||||||
|
await manager.syncAdminUiRoute();
|
||||||
|
|
||||||
|
const syncRequest = requests.find((request) => request.method === 'syncGatewayClientRoute')!;
|
||||||
|
const route = syncRequest.requestData.route as any;
|
||||||
|
const ownership = syncRequest.requestData.ownership as any;
|
||||||
|
|
||||||
|
assertEquals(ownership, {
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'onebox-admin-ui',
|
||||||
|
hostname: 'onebox.example.com',
|
||||||
|
});
|
||||||
|
assertEquals(route.match, { ports: [443], domains: ['onebox.example.com'] });
|
||||||
|
assertEquals(route.action.targets, [{ host: '203.0.113.10', port: 8080 }]);
|
||||||
|
assertEquals(syncRequest.requestData.enabled, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('ExternalGatewayManager uses managed dcrouter local target in managed mode', async () => {
|
||||||
|
const oneboxRef = makeOneboxRef();
|
||||||
|
(oneboxRef as any).managedDcRouter = {
|
||||||
|
getMode: () => 'managed',
|
||||||
|
getGatewayUrl: () => 'http://127.0.0.1:3300',
|
||||||
|
getAdminToken: async () => 'dcr-managed-token',
|
||||||
|
ensureGatewayClientId: () => 'onebox-managed',
|
||||||
|
getRouteTarget: () => ({ host: 'onebox-smartproxy', port: 80 }),
|
||||||
|
};
|
||||||
|
|
||||||
|
const service: IService = {
|
||||||
|
id: 1,
|
||||||
|
name: 'hello',
|
||||||
|
image: 'nginx:latest',
|
||||||
|
envVars: {},
|
||||||
|
port: 3000,
|
||||||
|
domain: 'hello.example.com',
|
||||||
|
status: 'running',
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
let syncRequest: Record<string, unknown> | null = null;
|
||||||
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
|
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>, config: any) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return { context: { role: 'admin' } };
|
||||||
|
}
|
||||||
|
if (method === 'exportCertificate') {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
assertEquals(config.url, 'http://127.0.0.1:3300');
|
||||||
|
assertEquals(config.apiToken, 'dcr-managed-token');
|
||||||
|
syncRequest = requestData;
|
||||||
|
return { success: true, action: 'created', routeId: 'route-1' };
|
||||||
|
};
|
||||||
|
|
||||||
|
await manager.syncServiceRoute(service);
|
||||||
|
|
||||||
|
assert(syncRequest);
|
||||||
|
const route = (syncRequest as Record<string, unknown>).route as any;
|
||||||
|
const ownership = (syncRequest as Record<string, unknown>).ownership as any;
|
||||||
|
assertEquals(ownership.gatewayClientId, 'onebox-managed');
|
||||||
|
assertEquals(route.action.targets, [{ host: 'onebox-smartproxy', port: 80 }]);
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('ExternalGatewayManager deletes service routes through dcrouter gatewayClient API', async () => {
|
||||||
const oneboxRef = makeOneboxRef();
|
const oneboxRef = makeOneboxRef();
|
||||||
const manager = new ExternalGatewayManager(oneboxRef as any);
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
let deleteRequest: Record<string, unknown> | null = null;
|
let deleteRequest: Record<string, unknown> | null = null;
|
||||||
|
|
||||||
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||||
assertEquals(method, 'syncWorkAppRoute');
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
|
||||||
|
}
|
||||||
|
assertEquals(method, 'syncGatewayClientRoute');
|
||||||
deleteRequest = requestData;
|
deleteRequest = requestData;
|
||||||
return { success: true, action: 'deleted', routeId: 'route-1' };
|
return { success: true, action: 'deleted', routeId: 'route-1' };
|
||||||
};
|
};
|
||||||
@@ -182,13 +283,293 @@ Deno.test('ExternalGatewayManager deletes service routes through dcrouter WorkHo
|
|||||||
assert(deleteRequest);
|
assert(deleteRequest);
|
||||||
const capturedDeleteRequest = deleteRequest as Record<string, unknown>;
|
const capturedDeleteRequest = deleteRequest as Record<string, unknown>;
|
||||||
assertEquals(capturedDeleteRequest.delete, true);
|
assertEquals(capturedDeleteRequest.delete, true);
|
||||||
|
assertEquals((capturedDeleteRequest.ownership as any).gatewayClientId, 'onebox-token');
|
||||||
assertEquals((capturedDeleteRequest.ownership as any).hostname, 'hello.example.com');
|
assertEquals((capturedDeleteRequest.ownership as any).hostname, 'hello.example.com');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Deno.test('ExternalGatewayManager removes stale gateway routes during reconciliation', async () => {
|
||||||
|
const oneboxRef = makeOneboxRef();
|
||||||
|
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
||||||
|
oneboxRef.database.services.push({
|
||||||
|
id: 1,
|
||||||
|
name: 'active',
|
||||||
|
image: 'nginx:latest',
|
||||||
|
envVars: {},
|
||||||
|
port: 3000,
|
||||||
|
domain: 'active.example.com',
|
||||||
|
status: 'running',
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const deletes: Record<string, unknown>[] = [];
|
||||||
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
|
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
|
||||||
|
}
|
||||||
|
if (method === 'syncGatewayClientRoute') {
|
||||||
|
if (requestData.delete) {
|
||||||
|
deletes.push(requestData);
|
||||||
|
return { success: true, action: 'deleted' };
|
||||||
|
}
|
||||||
|
return { success: true, action: 'updated', routeId: 'active-route' };
|
||||||
|
}
|
||||||
|
if (method === 'exportCertificate') {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
if (method === 'getGatewayClientDnsRecords') {
|
||||||
|
return {
|
||||||
|
records: [
|
||||||
|
{
|
||||||
|
id: 'active-record',
|
||||||
|
domainId: 'domain-1',
|
||||||
|
name: 'active',
|
||||||
|
type: 'A',
|
||||||
|
value: '203.0.113.10',
|
||||||
|
ttl: 300,
|
||||||
|
source: 'route',
|
||||||
|
status: 'active',
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'active',
|
||||||
|
hostname: 'active.example.com',
|
||||||
|
routeId: 'active-route',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'stale-record',
|
||||||
|
domainId: 'domain-1',
|
||||||
|
name: 'stale',
|
||||||
|
type: 'A',
|
||||||
|
value: '203.0.113.10',
|
||||||
|
ttl: 300,
|
||||||
|
source: 'route',
|
||||||
|
status: 'active',
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'stale',
|
||||||
|
hostname: 'stale.example.com',
|
||||||
|
routeId: 'stale-route',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected method: ${method}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
await manager.syncServiceRoutes();
|
||||||
|
|
||||||
|
assertEquals(deletes.length, 1);
|
||||||
|
assertEquals((deletes[0].ownership as any).hostname, 'stale.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('ExternalGatewayManager preserves configured Admin UI route during reconciliation', async () => {
|
||||||
|
const oneboxRef = makeOneboxRef();
|
||||||
|
oneboxRef.database.settings.set('adminUiDomain', 'onebox.example.com');
|
||||||
|
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
||||||
|
oneboxRef.database.services.push({
|
||||||
|
id: 1,
|
||||||
|
name: 'active',
|
||||||
|
image: 'nginx:latest',
|
||||||
|
envVars: {},
|
||||||
|
port: 3000,
|
||||||
|
domain: 'active.example.com',
|
||||||
|
status: 'running',
|
||||||
|
createdAt: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
});
|
||||||
|
|
||||||
|
const deletes: Record<string, unknown>[] = [];
|
||||||
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
|
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
|
||||||
|
}
|
||||||
|
if (method === 'syncGatewayClientRoute') {
|
||||||
|
if (requestData.delete) {
|
||||||
|
deletes.push(requestData);
|
||||||
|
return { success: true, action: 'deleted' };
|
||||||
|
}
|
||||||
|
return { success: true, action: 'updated' };
|
||||||
|
}
|
||||||
|
if (method === 'exportCertificate') {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
if (method === 'getGatewayClientDnsRecords') {
|
||||||
|
return {
|
||||||
|
records: [
|
||||||
|
{
|
||||||
|
id: 'admin-record',
|
||||||
|
domainId: 'domain-1',
|
||||||
|
name: 'onebox',
|
||||||
|
type: 'A',
|
||||||
|
value: '203.0.113.10',
|
||||||
|
ttl: 300,
|
||||||
|
source: 'route',
|
||||||
|
status: 'active',
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'onebox-admin-ui',
|
||||||
|
hostname: 'onebox.example.com',
|
||||||
|
routeId: 'admin-route',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'stale-record',
|
||||||
|
domainId: 'domain-1',
|
||||||
|
name: 'stale',
|
||||||
|
type: 'A',
|
||||||
|
value: '203.0.113.10',
|
||||||
|
ttl: 300,
|
||||||
|
source: 'route',
|
||||||
|
status: 'active',
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'stale',
|
||||||
|
hostname: 'stale.example.com',
|
||||||
|
routeId: 'stale-route',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected method: ${method}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
await manager.syncServiceRoutes();
|
||||||
|
|
||||||
|
assertEquals(deletes.length, 1);
|
||||||
|
assertEquals((deletes[0].ownership as any).hostname, 'stale.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('ExternalGatewayManager preserves legacy Admin UI route when setting is absent', async () => {
|
||||||
|
const oneboxRef = makeOneboxRef();
|
||||||
|
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
||||||
|
|
||||||
|
const deletes: Record<string, unknown>[] = [];
|
||||||
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
|
(manager as any).fireDcRouterRequest = async (
|
||||||
|
method: string,
|
||||||
|
requestData: Record<string, unknown>,
|
||||||
|
) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return {
|
||||||
|
context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (method === 'syncGatewayClientRoute') {
|
||||||
|
if (requestData.delete) {
|
||||||
|
deletes.push(requestData);
|
||||||
|
return { success: true, action: 'deleted' };
|
||||||
|
}
|
||||||
|
return { success: true, action: 'updated' };
|
||||||
|
}
|
||||||
|
if (method === 'getGatewayClientDnsRecords') {
|
||||||
|
return {
|
||||||
|
records: [
|
||||||
|
{
|
||||||
|
id: 'legacy-admin-record',
|
||||||
|
domainId: 'domain-1',
|
||||||
|
name: 'onebox',
|
||||||
|
type: 'A',
|
||||||
|
value: '203.0.113.10',
|
||||||
|
ttl: 300,
|
||||||
|
source: 'route',
|
||||||
|
status: 'active',
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'onebox',
|
||||||
|
hostname: 'onebox.example.com',
|
||||||
|
routeId: 'legacy-admin-route',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'stale-record',
|
||||||
|
domainId: 'domain-1',
|
||||||
|
name: 'stale',
|
||||||
|
type: 'A',
|
||||||
|
value: '203.0.113.10',
|
||||||
|
ttl: 300,
|
||||||
|
source: 'route',
|
||||||
|
status: 'active',
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'stale',
|
||||||
|
hostname: 'stale.example.com',
|
||||||
|
routeId: 'stale-route',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected method: ${method}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
await manager.syncServiceRoutes();
|
||||||
|
|
||||||
|
assertEquals(deletes.length, 1);
|
||||||
|
assertEquals((deletes[0].ownership as any).hostname, 'stale.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('ExternalGatewayManager deletes old Admin UI route after domain change', async () => {
|
||||||
|
const oneboxRef = makeOneboxRef();
|
||||||
|
oneboxRef.database.settings.set('adminUiDomain', 'new.example.com');
|
||||||
|
oneboxRef.database.settings.set('serverIP', '203.0.113.10');
|
||||||
|
|
||||||
|
const deletes: Record<string, unknown>[] = [];
|
||||||
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
|
(manager as any).fireDcRouterRequest = async (
|
||||||
|
method: string,
|
||||||
|
requestData: Record<string, unknown>,
|
||||||
|
) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return {
|
||||||
|
context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (method === 'syncGatewayClientRoute') {
|
||||||
|
if (requestData.delete) {
|
||||||
|
deletes.push(requestData);
|
||||||
|
return { success: true, action: 'deleted' };
|
||||||
|
}
|
||||||
|
return { success: true, action: 'updated' };
|
||||||
|
}
|
||||||
|
if (method === 'exportCertificate') {
|
||||||
|
return { success: false };
|
||||||
|
}
|
||||||
|
if (method === 'getGatewayClientDnsRecords') {
|
||||||
|
return {
|
||||||
|
records: [
|
||||||
|
{
|
||||||
|
id: 'old-admin-record',
|
||||||
|
domainId: 'domain-1',
|
||||||
|
name: 'onebox',
|
||||||
|
type: 'A',
|
||||||
|
value: '203.0.113.10',
|
||||||
|
ttl: 300,
|
||||||
|
source: 'route',
|
||||||
|
status: 'active',
|
||||||
|
gatewayClientType: 'onebox',
|
||||||
|
gatewayClientId: 'onebox-token',
|
||||||
|
appId: 'onebox-admin-ui',
|
||||||
|
hostname: 'old.example.com',
|
||||||
|
routeId: 'old-admin-route',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new Error(`Unexpected method: ${method}`);
|
||||||
|
};
|
||||||
|
|
||||||
|
await manager.syncServiceRoutes();
|
||||||
|
|
||||||
|
assertEquals(deletes.length, 1);
|
||||||
|
assertEquals((deletes[0].ownership as any).hostname, 'old.example.com');
|
||||||
|
});
|
||||||
|
|
||||||
Deno.test('ExternalGatewayManager imports exported dcrouter certificates into Onebox', async () => {
|
Deno.test('ExternalGatewayManager imports exported dcrouter certificates into Onebox', async () => {
|
||||||
const oneboxRef = makeOneboxRef();
|
const oneboxRef = makeOneboxRef();
|
||||||
const manager = new ExternalGatewayManager(oneboxRef as any);
|
const manager = new ExternalGatewayManager(oneboxRef as any);
|
||||||
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
(manager as any).fireDcRouterRequest = async (method: string, requestData: Record<string, unknown>) => {
|
||||||
|
if (method === 'getGatewayClientContext') {
|
||||||
|
return { context: { role: 'gatewayClient', gatewayClient: { type: 'onebox', id: 'onebox-token' } } };
|
||||||
|
}
|
||||||
assertEquals(method, 'exportCertificate');
|
assertEquals(method, 'exportCertificate');
|
||||||
assertEquals(requestData.domain, 'hello.example.com');
|
assertEquals(requestData.domain, 'hello.example.com');
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { assert, assertEquals } from '@std/assert';
|
||||||
|
|
||||||
|
import { ManagedDcRouterManager } from '../ts/classes/managed-dcrouter.ts';
|
||||||
|
|
||||||
|
class FakeDatabase {
|
||||||
|
public settings = new Map<string, string>();
|
||||||
|
public secretSettings = new Map<string, string>();
|
||||||
|
|
||||||
|
getSetting(key: string): string | null {
|
||||||
|
return this.settings.get(key) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSetting(key: string, value: string): void {
|
||||||
|
this.settings.set(key, value);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSecretSetting(key: string): Promise<string | null> {
|
||||||
|
return this.secretSettings.get(key) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async setSecretSetting(key: string, value: string): Promise<void> {
|
||||||
|
this.secretSettings.set(key, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.test('ManagedDcRouterManager persists default managed gateway settings', async () => {
|
||||||
|
const database = new FakeDatabase();
|
||||||
|
const manager = new ManagedDcRouterManager({ database } as any);
|
||||||
|
|
||||||
|
assertEquals(manager.getMode(), 'managed');
|
||||||
|
|
||||||
|
await manager.prepareGatewaySettings();
|
||||||
|
|
||||||
|
assertEquals(database.getSetting('dcrouterMode'), 'managed');
|
||||||
|
assertEquals(manager.getMode(), 'managed');
|
||||||
|
assertEquals(database.getSetting('dcrouterGatewayUrl'), 'http://127.0.0.1:3300');
|
||||||
|
assertEquals(database.getSetting('dcrouterTargetHost'), 'onebox-smartproxy');
|
||||||
|
assertEquals(database.getSetting('dcrouterTargetPort'), '80');
|
||||||
|
assert(database.getSetting('dcrouterGatewayClientId')?.startsWith('onebox-'));
|
||||||
|
assert((await database.getSecretSetting('dcrouterManagedAdminApiToken'))?.startsWith('dcr_'));
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test('ManagedDcRouterManager keeps existing external gateway default external', async () => {
|
||||||
|
const database = new FakeDatabase();
|
||||||
|
database.setSetting('dcrouterGatewayUrl', 'https://edge.example.com');
|
||||||
|
const manager = new ManagedDcRouterManager({ database } as any);
|
||||||
|
|
||||||
|
assertEquals(manager.getMode(), 'external');
|
||||||
|
|
||||||
|
await manager.prepareGatewaySettings();
|
||||||
|
|
||||||
|
assertEquals(database.getSetting('dcrouterMode'), null);
|
||||||
|
assertEquals(database.getSetting('dcrouterTargetHost'), null);
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { assertEquals } from '@std/assert';
|
||||||
|
|
||||||
|
import { OneboxReverseProxy } from '../ts/classes/reverseproxy.ts';
|
||||||
|
import type { IService } from '../ts/types.ts';
|
||||||
|
|
||||||
|
class FakeDatabase {
|
||||||
|
public settings = new Map<string, string>();
|
||||||
|
public services: IService[] = [];
|
||||||
|
|
||||||
|
getSetting(key: string): string | null {
|
||||||
|
return this.settings.get(key) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllServices(): IService[] {
|
||||||
|
return this.services;
|
||||||
|
}
|
||||||
|
|
||||||
|
getServiceByID(id: number): IService | null {
|
||||||
|
return this.services.find((service) => service.id === id) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAllSSLCertificates(): [] {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Deno.test('OneboxReverseProxy loads Admin UI domain as local SmartProxy route', async () => {
|
||||||
|
const database = new FakeDatabase();
|
||||||
|
database.settings.set('adminUiDomain', 'onebox.example.com');
|
||||||
|
database.settings.set('serverIP', '203.0.113.10');
|
||||||
|
|
||||||
|
const reverseProxy = new OneboxReverseProxy({ database } as any);
|
||||||
|
const routes: Array<{ domain: string; upstream: string }> = [];
|
||||||
|
(reverseProxy as any).smartProxy = {
|
||||||
|
clear: () => routes.splice(0, routes.length),
|
||||||
|
addRoute: async (domain: string, upstream: string) => {
|
||||||
|
routes.push({ domain, upstream });
|
||||||
|
},
|
||||||
|
getCertificates: () => [],
|
||||||
|
};
|
||||||
|
|
||||||
|
await reverseProxy.reloadRoutes();
|
||||||
|
|
||||||
|
assertEquals(routes, [
|
||||||
|
{
|
||||||
|
domain: 'onebox.example.com',
|
||||||
|
upstream: '203.0.113.10:3000',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@serve.zone/onebox',
|
name: '@serve.zone/onebox',
|
||||||
version: '1.24.2',
|
version: '2.1.2',
|
||||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
/**
|
|
||||||
* App Store type definitions
|
|
||||||
*/
|
|
||||||
|
|
||||||
export interface ICatalog {
|
|
||||||
schemaVersion: number;
|
|
||||||
updatedAt: string;
|
|
||||||
apps: ICatalogApp[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ICatalogApp {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
category: string;
|
|
||||||
iconName?: string;
|
|
||||||
iconUrl?: string;
|
|
||||||
latestVersion: string;
|
|
||||||
tags?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IAppMeta {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
category: string;
|
|
||||||
iconName?: string;
|
|
||||||
latestVersion: string;
|
|
||||||
versions: string[];
|
|
||||||
maintainer?: string;
|
|
||||||
links?: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IAppVersionConfig {
|
|
||||||
image: string;
|
|
||||||
port: number;
|
|
||||||
envVars?: Array<{ key: string; value: string; description: string; required?: boolean }>;
|
|
||||||
volumes?: string[];
|
|
||||||
platformRequirements?: {
|
|
||||||
mongodb?: boolean;
|
|
||||||
s3?: boolean;
|
|
||||||
clickhouse?: boolean;
|
|
||||||
redis?: boolean;
|
|
||||||
mariadb?: boolean;
|
|
||||||
};
|
|
||||||
minOneboxVersion?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IMigrationContext {
|
|
||||||
service: {
|
|
||||||
name: string;
|
|
||||||
image: string;
|
|
||||||
envVars: Record<string, string>;
|
|
||||||
port: number;
|
|
||||||
};
|
|
||||||
fromVersion: string;
|
|
||||||
toVersion: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IMigrationResult {
|
|
||||||
success: boolean;
|
|
||||||
envVars?: Record<string, string>;
|
|
||||||
image?: string;
|
|
||||||
warnings: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IUpgradeableService {
|
|
||||||
serviceName: string;
|
|
||||||
appTemplateId: string;
|
|
||||||
currentVersion: string;
|
|
||||||
latestVersion: string;
|
|
||||||
hasMigration: boolean;
|
|
||||||
}
|
|
||||||
+284
-175
@@ -1,193 +1,258 @@
|
|||||||
/**
|
/**
|
||||||
* App Store Manager
|
* App Store Manager
|
||||||
* Fetches, caches, and serves app templates from the remote appstore-apptemplates repo.
|
* Fetches, caches, and serves app templates from the remote App Store repo.
|
||||||
* The remote repo is the single source of truth — no fallback catalog.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type {
|
import * as plugins from '../plugins.ts';
|
||||||
ICatalog,
|
|
||||||
ICatalogApp,
|
|
||||||
IAppMeta,
|
|
||||||
IAppVersionConfig,
|
|
||||||
IMigrationContext,
|
|
||||||
IMigrationResult,
|
|
||||||
IUpgradeableService,
|
|
||||||
} from './appstore-types.ts';
|
|
||||||
import { logger } from '../logging.ts';
|
import { logger } from '../logging.ts';
|
||||||
import { getErrorMessage } from '../utils/error.ts';
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
import type { Onebox } from './onebox.ts';
|
import type { Onebox } from './onebox.ts';
|
||||||
import type { IService } from '../types.ts';
|
import type { IService, IServicePublishedPort, IServiceVolume } from '../types.ts';
|
||||||
|
import { projectInfo } from '../info.ts';
|
||||||
|
|
||||||
export class AppStoreManager {
|
type IAppStoreIndex = plugins.servezoneInterfaces.appstore.IAppStoreIndex;
|
||||||
private oneboxRef: Onebox;
|
type IAppStoreApp = plugins.servezoneInterfaces.appstore.IAppStoreApp;
|
||||||
private catalogCache: ICatalog | null = null;
|
type IAppStoreAppMeta = plugins.servezoneInterfaces.appstore.IAppStoreAppMeta;
|
||||||
private lastFetchTime = 0;
|
type IAppStoreVersionConfig = plugins.servezoneInterfaces.appstore.IAppStoreVersionConfig;
|
||||||
private readonly repoBaseUrl = 'https://code.foss.global/serve.zone/appstore-apptemplates/raw/branch/main';
|
type IAppStoreInstallOptions = plugins.servezoneInterfaces.appstore.IAppStoreInstallRequest & {
|
||||||
private readonly cacheTtlMs = 5 * 60 * 1000; // 5 minutes
|
autoDNS?: boolean;
|
||||||
|
};
|
||||||
|
type IUpgradeableAppStoreService = plugins.servezoneInterfaces.appstore.IUpgradeableAppStoreService;
|
||||||
|
|
||||||
constructor(oneboxRef: Onebox) {
|
export interface IAppStoreManagerOptions {
|
||||||
this.oneboxRef = oneboxRef;
|
baseUrl?: string;
|
||||||
|
fetch?: typeof fetch;
|
||||||
|
resolveDockerDigests?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
async init(): Promise<void> {
|
export interface IMigrationContext {
|
||||||
|
service: {
|
||||||
|
name: string;
|
||||||
|
image: string;
|
||||||
|
envVars: Record<string, string>;
|
||||||
|
port: number;
|
||||||
|
};
|
||||||
|
fromVersion: string;
|
||||||
|
toVersion: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IMigrationResult {
|
||||||
|
success: boolean;
|
||||||
|
envVars?: Record<string, string>;
|
||||||
|
image?: string;
|
||||||
|
imageDigest?: string;
|
||||||
|
port?: number;
|
||||||
|
volumes?: IServiceVolume[];
|
||||||
|
publishedPorts?: IServicePublishedPort[];
|
||||||
|
warnings: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IAppStoreUpgradeApplyOptions {
|
||||||
|
onProgress?: (progressArg: { step: string; message: string }) => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AppStoreManager {
|
||||||
|
private appStoreCache: IAppStoreIndex | null = null;
|
||||||
|
private appStoreResolver: plugins.servezoneAppstore.AppStoreResolver;
|
||||||
|
private lastFetchTime = 0;
|
||||||
|
private readonly appStoreBaseUrl: string;
|
||||||
|
private readonly fetchRef: typeof fetch;
|
||||||
|
private readonly resolveDockerDigests: boolean;
|
||||||
|
private readonly cacheTtlMs = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private oneboxRef: Onebox,
|
||||||
|
optionsArg: IAppStoreManagerOptions = {},
|
||||||
|
) {
|
||||||
|
this.appStoreBaseUrl = optionsArg.baseUrl || 'https://code.foss.global/serve.zone/appstore/raw/branch/main';
|
||||||
|
this.fetchRef = optionsArg.fetch || fetch;
|
||||||
|
this.resolveDockerDigests = optionsArg.resolveDockerDigests ?? true;
|
||||||
|
this.appStoreResolver = this.createAppStoreResolver();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async init(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await this.getCatalog();
|
await this.getAppStore();
|
||||||
logger.info(`App Store initialized with ${this.catalogCache?.apps.length || 0} templates`);
|
logger.info(`App Store initialized with ${this.appStoreCache?.apps.length || 0} templates`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.warn(`App Store initialization failed: ${getErrorMessage(error)}`);
|
logger.warn(`App Store initialization failed: ${getErrorMessage(error)}`);
|
||||||
logger.warn('App Store will retry on next request');
|
logger.warn('App Store will retry on next request');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async getAppStore(): Promise<IAppStoreIndex> {
|
||||||
* Get the catalog (cached, refreshes after TTL)
|
|
||||||
*/
|
|
||||||
async getCatalog(): Promise<ICatalog> {
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
if (this.catalogCache && (now - this.lastFetchTime) < this.cacheTtlMs) {
|
if (this.appStoreCache && (now - this.lastFetchTime) < this.cacheTtlMs) {
|
||||||
return this.catalogCache;
|
return this.appStoreCache;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const catalog = await this.fetchJson('catalog.json') as ICatalog;
|
const resolver = this.createAppStoreResolver();
|
||||||
if (catalog && catalog.apps && Array.isArray(catalog.apps)) {
|
const appStore = await resolver.getAppStoreIndex();
|
||||||
this.catalogCache = catalog;
|
this.appStoreResolver = resolver;
|
||||||
|
this.appStoreCache = appStore;
|
||||||
this.lastFetchTime = now;
|
this.lastFetchTime = now;
|
||||||
return catalog;
|
return appStore;
|
||||||
}
|
|
||||||
throw new Error('Invalid catalog format');
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.warn(`Failed to fetch remote catalog: ${getErrorMessage(error)}`);
|
logger.warn(`Failed to fetch remote App Store: ${getErrorMessage(error)}`);
|
||||||
// Return cached if available, otherwise return empty catalog
|
if (this.appStoreCache) {
|
||||||
if (this.catalogCache) {
|
return this.appStoreCache;
|
||||||
return this.catalogCache;
|
|
||||||
}
|
}
|
||||||
return { schemaVersion: 1, updatedAt: '', apps: [] };
|
return { schemaVersion: 1, updatedAt: '', apps: [] };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async getApps(): Promise<IAppStoreApp[]> {
|
||||||
* Get the catalog apps list (convenience method for the API)
|
return (await this.getAppStore()).apps;
|
||||||
*/
|
|
||||||
async getApps(): Promise<ICatalogApp[]> {
|
|
||||||
const catalog = await this.getCatalog();
|
|
||||||
return catalog.apps;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async getAppMeta(appIdArg: string): Promise<IAppStoreAppMeta> {
|
||||||
* Fetch app metadata (versions list, etc.)
|
|
||||||
*/
|
|
||||||
async getAppMeta(appId: string): Promise<IAppMeta> {
|
|
||||||
try {
|
try {
|
||||||
return await this.fetchJson(`apps/${appId}/app.json`) as IAppMeta;
|
await this.getAppStore();
|
||||||
|
return await this.appStoreResolver.getAppMeta(appIdArg);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(`Failed to fetch metadata for app '${appId}': ${getErrorMessage(error)}`);
|
throw new Error(`Failed to fetch metadata for app '${appIdArg}': ${getErrorMessage(error)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async getAppVersionConfig(
|
||||||
* Fetch full config for an app version
|
appIdArg: string,
|
||||||
*/
|
versionArg?: string,
|
||||||
async getAppVersionConfig(appId: string, version: string): Promise<IAppVersionConfig> {
|
): Promise<IAppStoreVersionConfig> {
|
||||||
try {
|
try {
|
||||||
return await this.fetchJson(`apps/${appId}/versions/${version}/config.json`) as IAppVersionConfig;
|
const version = versionArg || (await this.getAppMeta(appIdArg)).latestVersion;
|
||||||
|
await this.getAppStore();
|
||||||
|
return await this.appStoreResolver.getAppVersionConfig(appIdArg, version);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new Error(`Failed to fetch config for ${appId}@${version}: ${getErrorMessage(error)}`);
|
throw new Error(`Failed to fetch config for ${appIdArg}@${versionArg || 'latest'}: ${getErrorMessage(error)}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async installApp(optionsArg: IAppStoreInstallOptions): Promise<IService> {
|
||||||
* Compare deployed services against catalog to find those with available upgrades
|
this.validateInstallOptions(optionsArg);
|
||||||
*/
|
const appMeta = await this.getAppMeta(optionsArg.appId);
|
||||||
async getUpgradeableServices(): Promise<IUpgradeableService[]> {
|
const version = optionsArg.version || appMeta.latestVersion;
|
||||||
const catalog = await this.getCatalog();
|
const config = await this.getAppVersionConfig(optionsArg.appId, version);
|
||||||
|
const appStoreVersion = config.appStoreVersion || version;
|
||||||
|
this.assertRuntimeCompatibility(config);
|
||||||
|
const servicePort = optionsArg.port || config.port;
|
||||||
|
this.assertValidPort(servicePort, 'install service port');
|
||||||
|
const volumes = this.normalizeVolumes(config.volumes);
|
||||||
|
const publishedPorts = optionsArg.publishedPorts || config.publishedPorts || [];
|
||||||
|
this.validateAppVersionConfig(
|
||||||
|
{ ...config, port: servicePort, publishedPorts },
|
||||||
|
`${optionsArg.appId}@${version} install`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const envVars = this.getAppStoreEnvVars(config, optionsArg.envVars || {});
|
||||||
|
if (this.requiresTemplateValue(envVars, 'SERVICE_DOMAIN') && !optionsArg.domain) {
|
||||||
|
throw new Error('A domain is required because the app template uses ${SERVICE_DOMAIN}');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.oneboxRef.services.deployService({
|
||||||
|
name: optionsArg.serviceName,
|
||||||
|
image: config.image,
|
||||||
|
port: servicePort,
|
||||||
|
domain: optionsArg.domain,
|
||||||
|
autoDNS: optionsArg.autoDNS,
|
||||||
|
envVars,
|
||||||
|
volumes,
|
||||||
|
publishedPorts,
|
||||||
|
enableMongoDB: Boolean(config.platformRequirements?.mongodb),
|
||||||
|
enableS3: Boolean(config.platformRequirements?.s3),
|
||||||
|
enableClickHouse: Boolean(config.platformRequirements?.clickhouse),
|
||||||
|
enableRedis: Boolean(config.platformRequirements?.redis),
|
||||||
|
enableMariaDB: Boolean(config.platformRequirements?.mariadb),
|
||||||
|
appTemplateId: optionsArg.appId,
|
||||||
|
appTemplateVersion: appStoreVersion,
|
||||||
|
imageDigest: config.resolvedImageDigest,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getUpgradeableAppStoreServices(): Promise<IUpgradeableAppStoreService[]> {
|
||||||
|
const appStore = await this.getAppStore();
|
||||||
const services = this.oneboxRef.database.getAllServices();
|
const services = this.oneboxRef.database.getAllServices();
|
||||||
const upgradeable: IUpgradeableService[] = [];
|
const upgradeable: IUpgradeableAppStoreService[] = [];
|
||||||
|
|
||||||
for (const service of services) {
|
for (const service of services) {
|
||||||
if (!service.appTemplateId || !service.appTemplateVersion) continue;
|
if (!service.appTemplateId || !service.appTemplateVersion) continue;
|
||||||
|
|
||||||
const catalogApp = catalog.apps.find(a => a.id === service.appTemplateId);
|
const appStoreApp = appStore.apps.find((appArg: IAppStoreApp) => appArg.id === service.appTemplateId);
|
||||||
if (!catalogApp) continue;
|
if (!appStoreApp || appStoreApp.latestVersion === service.appTemplateVersion) continue;
|
||||||
|
|
||||||
if (catalogApp.latestVersion !== service.appTemplateVersion) {
|
|
||||||
// Check if a migration script exists
|
|
||||||
const hasMigration = await this.hasMigrationScript(
|
|
||||||
service.appTemplateId,
|
|
||||||
service.appTemplateVersion,
|
|
||||||
catalogApp.latestVersion,
|
|
||||||
);
|
|
||||||
|
|
||||||
upgradeable.push({
|
upgradeable.push({
|
||||||
serviceName: service.name,
|
serviceName: service.name,
|
||||||
appTemplateId: service.appTemplateId,
|
appTemplateId: service.appTemplateId,
|
||||||
currentVersion: service.appTemplateVersion,
|
currentVersion: service.appTemplateVersion,
|
||||||
latestVersion: catalogApp.latestVersion,
|
latestVersion: appStoreApp.latestVersion,
|
||||||
hasMigration,
|
hasMigration: await this.hasMigrationScript(
|
||||||
|
service.appTemplateId,
|
||||||
|
service.appTemplateVersion,
|
||||||
|
appStoreApp.latestVersion,
|
||||||
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
return upgradeable;
|
return upgradeable;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async hasMigrationScript(
|
||||||
* Check if a migration script exists for a specific version transition
|
appIdArg: string,
|
||||||
*/
|
fromVersionArg: string,
|
||||||
async hasMigrationScript(appId: string, fromVersion: string, toVersion: string): Promise<boolean> {
|
toVersionArg: string,
|
||||||
|
): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const scriptPath = `apps/${appId}/versions/${toVersion}/migrate-from-${fromVersion}.ts`;
|
await this.fetchText(`apps/${appIdArg}/versions/${toVersionArg}/migrate-from-${fromVersionArg}.ts`);
|
||||||
await this.fetchText(scriptPath);
|
|
||||||
return true;
|
return true;
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async executeMigration(
|
||||||
* Execute a migration in a sandboxed Deno child process
|
serviceArg: IService,
|
||||||
*/
|
fromVersionArg: string,
|
||||||
async executeMigration(service: IService, fromVersion: string, toVersion: string): Promise<IMigrationResult> {
|
toVersionArg: string,
|
||||||
const appId = service.appTemplateId;
|
): Promise<IMigrationResult> {
|
||||||
|
const appId = serviceArg.appTemplateId;
|
||||||
if (!appId) {
|
if (!appId) {
|
||||||
throw new Error('Service has no appTemplateId');
|
throw new Error('Service has no appTemplateId');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fetch the migration script
|
const scriptPath = `apps/${appId}/versions/${toVersionArg}/migrate-from-${fromVersionArg}.ts`;
|
||||||
const scriptPath = `apps/${appId}/versions/${toVersion}/migrate-from-${fromVersion}.ts`;
|
|
||||||
let scriptContent: string;
|
let scriptContent: string;
|
||||||
try {
|
try {
|
||||||
scriptContent = await this.fetchText(scriptPath);
|
scriptContent = await this.fetchText(scriptPath);
|
||||||
} catch {
|
} catch {
|
||||||
// No migration script — do a simple config-based upgrade
|
logger.info(`No migration script for ${appId} ${fromVersionArg} -> ${toVersionArg}, using config-only upgrade`);
|
||||||
logger.info(`No migration script for ${appId} ${fromVersion} -> ${toVersion}, using config-only upgrade`);
|
const config = await this.getAppVersionConfig(appId, toVersionArg);
|
||||||
const config = await this.getAppVersionConfig(appId, toVersion);
|
|
||||||
return {
|
return {
|
||||||
success: true,
|
success: true,
|
||||||
image: config.image,
|
image: config.image,
|
||||||
envVars: undefined, // Keep existing env vars
|
imageDigest: config.resolvedImageDigest,
|
||||||
|
port: config.port,
|
||||||
|
volumes: this.normalizeVolumes(config.volumes),
|
||||||
|
publishedPorts: config.publishedPorts,
|
||||||
|
envVars: undefined,
|
||||||
warnings: [],
|
warnings: [],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write to temp file
|
|
||||||
const tempFile = `/tmp/onebox-migration-${crypto.randomUUID()}.ts`;
|
const tempFile = `/tmp/onebox-migration-${crypto.randomUUID()}.ts`;
|
||||||
await Deno.writeTextFile(tempFile, scriptContent);
|
await Deno.writeTextFile(tempFile, scriptContent);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Prepare context
|
|
||||||
const context: IMigrationContext = {
|
const context: IMigrationContext = {
|
||||||
service: {
|
service: {
|
||||||
name: service.name,
|
name: serviceArg.name,
|
||||||
image: service.image,
|
image: serviceArg.image,
|
||||||
envVars: service.envVars,
|
envVars: serviceArg.envVars,
|
||||||
port: service.port,
|
port: serviceArg.port,
|
||||||
},
|
},
|
||||||
fromVersion,
|
fromVersion: fromVersionArg,
|
||||||
toVersion,
|
toVersion: toVersionArg,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Execute in sandboxed Deno child process
|
|
||||||
const cmd = new Deno.Command('deno', {
|
const cmd = new Deno.Command('deno', {
|
||||||
args: ['run', '--allow-env', '--allow-net=none', '--allow-read=none', '--allow-write=none', tempFile],
|
args: ['run', '--allow-env', '--allow-net=none', '--allow-read=none', '--allow-write=none', tempFile],
|
||||||
stdin: 'piped',
|
stdin: 'piped',
|
||||||
@@ -196,27 +261,22 @@ export class AppStoreManager {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const child = cmd.spawn();
|
const child = cmd.spawn();
|
||||||
|
|
||||||
// Write context to stdin
|
|
||||||
const writer = child.stdin.getWriter();
|
const writer = child.stdin.getWriter();
|
||||||
await writer.write(new TextEncoder().encode(JSON.stringify(context)));
|
await writer.write(new TextEncoder().encode(JSON.stringify(context)));
|
||||||
await writer.close();
|
await writer.close();
|
||||||
|
|
||||||
// Read result
|
|
||||||
const output = await child.output();
|
const output = await child.output();
|
||||||
const exitCode = output.code;
|
|
||||||
const stdout = new TextDecoder().decode(output.stdout);
|
const stdout = new TextDecoder().decode(output.stdout);
|
||||||
const stderr = new TextDecoder().decode(output.stderr);
|
const stderr = new TextDecoder().decode(output.stderr);
|
||||||
|
|
||||||
if (exitCode !== 0) {
|
if (output.code !== 0) {
|
||||||
logger.error(`Migration script failed (exit ${exitCode}): ${stderr.substring(0, 500)}`);
|
logger.error(`Migration script failed (exit ${output.code}): ${stderr.substring(0, 500)}`);
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
warnings: [`Migration script failed: ${stderr.substring(0, 200)}`],
|
warnings: [`Migration script failed: ${stderr.substring(0, 200)}`],
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse result from stdout
|
|
||||||
try {
|
try {
|
||||||
const result = JSON.parse(stdout) as IMigrationResult;
|
const result = JSON.parse(stdout) as IMigrationResult;
|
||||||
result.success = true;
|
result.success = true;
|
||||||
@@ -229,46 +289,46 @@ export class AppStoreManager {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
// Cleanup temp file
|
|
||||||
try {
|
try {
|
||||||
await Deno.remove(tempFile);
|
await Deno.remove(tempFile);
|
||||||
} catch {
|
} catch {
|
||||||
// Ignore cleanup errors
|
// Ignore cleanup errors.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
public async applyUpgrade(
|
||||||
* Apply an upgrade: update image, env vars, recreate container
|
serviceNameArg: string,
|
||||||
*/
|
migrationResultArg: IMigrationResult,
|
||||||
async applyUpgrade(
|
newVersionArg: string,
|
||||||
serviceName: string,
|
optionsArg: IAppStoreUpgradeApplyOptions = {},
|
||||||
migrationResult: IMigrationResult,
|
|
||||||
newVersion: string,
|
|
||||||
): Promise<IService> {
|
): Promise<IService> {
|
||||||
const service = this.oneboxRef.database.getServiceByName(serviceName);
|
const service = this.oneboxRef.database.getServiceByName(serviceNameArg);
|
||||||
if (!service) {
|
if (!service) {
|
||||||
throw new Error(`Service not found: ${serviceName}`);
|
throw new Error(`Service not found: ${serviceNameArg}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Stop the existing container
|
|
||||||
if (service.containerID && service.status === 'running') {
|
|
||||||
await this.oneboxRef.services.stopService(serviceName);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Update service record
|
|
||||||
const updates: Partial<IService> = {
|
const updates: Partial<IService> = {
|
||||||
appTemplateVersion: newVersion,
|
appTemplateVersion: newVersionArg,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (migrationResult.image) {
|
if (migrationResultArg.image) {
|
||||||
updates.image = migrationResult.image;
|
updates.image = migrationResultArg.image;
|
||||||
}
|
}
|
||||||
|
if (migrationResultArg.imageDigest !== undefined) {
|
||||||
if (migrationResult.envVars) {
|
updates.imageDigest = migrationResultArg.imageDigest;
|
||||||
// Merge: migration result provides base, user overrides preserved
|
}
|
||||||
const mergedEnvVars = { ...migrationResult.envVars };
|
if (migrationResultArg.port) {
|
||||||
// Keep any user-set env vars that aren't in the migration result
|
updates.port = migrationResultArg.port;
|
||||||
|
}
|
||||||
|
if (migrationResultArg.volumes) {
|
||||||
|
updates.volumes = migrationResultArg.volumes;
|
||||||
|
}
|
||||||
|
if (migrationResultArg.publishedPorts) {
|
||||||
|
updates.publishedPorts = migrationResultArg.publishedPorts;
|
||||||
|
}
|
||||||
|
if (migrationResultArg.envVars) {
|
||||||
|
const mergedEnvVars = { ...migrationResultArg.envVars };
|
||||||
for (const [key, value] of Object.entries(service.envVars)) {
|
for (const [key, value] of Object.entries(service.envVars)) {
|
||||||
if (!(key in mergedEnvVars)) {
|
if (!(key in mergedEnvVars)) {
|
||||||
mergedEnvVars[key] = value;
|
mergedEnvVars[key] = value;
|
||||||
@@ -277,59 +337,108 @@ export class AppStoreManager {
|
|||||||
updates.envVars = mergedEnvVars;
|
updates.envVars = mergedEnvVars;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.oneboxRef.database.updateService(service.id!, updates);
|
const updatedService = await this.oneboxRef.services.updateService(
|
||||||
|
serviceNameArg,
|
||||||
|
updates,
|
||||||
|
{
|
||||||
|
onProgress: async (progressArg) => {
|
||||||
|
await optionsArg.onProgress?.(progressArg);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
// Pull new image if changed
|
logger.success(`Service '${serviceNameArg}' upgraded to App Store version ${newVersionArg}`);
|
||||||
const newImage = migrationResult.image || service.image;
|
return updatedService;
|
||||||
if (migrationResult.image && migrationResult.image !== service.image) {
|
|
||||||
await this.oneboxRef.docker.pullImage(newImage);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Recreate and start container
|
public normalizeVolumes(volumesArg: IAppStoreVersionConfig['volumes'] = []): IServiceVolume[] {
|
||||||
const updatedService = this.oneboxRef.database.getServiceByName(serviceName)!;
|
return this.appStoreResolver.normalizeVolumes(volumesArg) as IServiceVolume[];
|
||||||
|
|
||||||
// Remove old container
|
|
||||||
if (service.containerID) {
|
|
||||||
try {
|
|
||||||
await this.oneboxRef.docker.removeContainer(service.containerID, true);
|
|
||||||
} catch {
|
|
||||||
// Container might already be gone
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create new container
|
public validateAppVersionConfig(configArg: IAppStoreVersionConfig, labelArg = 'app config'): void {
|
||||||
const containerID = await this.oneboxRef.docker.createContainer(updatedService);
|
this.appStoreResolver.validateAppStoreVersionConfig(configArg, labelArg);
|
||||||
this.oneboxRef.database.updateService(service.id!, { containerID, status: 'starting' });
|
|
||||||
|
|
||||||
// Start container
|
|
||||||
await this.oneboxRef.docker.startContainer(containerID);
|
|
||||||
this.oneboxRef.database.updateService(service.id!, { status: 'running' });
|
|
||||||
|
|
||||||
logger.success(`Service '${serviceName}' upgraded to template version ${newVersion}`);
|
|
||||||
return this.oneboxRef.database.getServiceByName(serviceName)!;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private createAppStoreResolver(): plugins.servezoneAppstore.AppStoreResolver {
|
||||||
* Fetch JSON from the remote repo
|
return new plugins.servezoneAppstore.AppStoreResolver({
|
||||||
*/
|
baseUrl: this.appStoreBaseUrl,
|
||||||
private async fetchJson(path: string): Promise<unknown> {
|
fetch: this.fetchRef,
|
||||||
const url = `${this.repoBaseUrl}/${path}`;
|
resolveDockerDigests: this.resolveDockerDigests,
|
||||||
const response = await fetch(url);
|
});
|
||||||
if (!response.ok) {
|
|
||||||
throw new Error(`HTTP ${response.status} for ${url}`);
|
|
||||||
}
|
|
||||||
return response.json();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private async fetchText(pathArg: string): Promise<string> {
|
||||||
* Fetch text from the remote repo
|
const url = `${this.appStoreBaseUrl}/${pathArg}`;
|
||||||
*/
|
const response = await this.fetchRef(url);
|
||||||
private async fetchText(path: string): Promise<string> {
|
|
||||||
const url = `${this.repoBaseUrl}/${path}`;
|
|
||||||
const response = await fetch(url);
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(`HTTP ${response.status} for ${url}`);
|
throw new Error(`HTTP ${response.status} for ${url}`);
|
||||||
}
|
}
|
||||||
return response.text();
|
return response.text();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private validateInstallOptions(optionsArg: IAppStoreInstallOptions): void {
|
||||||
|
if (!optionsArg.appId || !/^[a-z0-9][a-z0-9-]*$/.test(optionsArg.appId)) {
|
||||||
|
throw new Error(`Invalid app id: ${optionsArg.appId}`);
|
||||||
|
}
|
||||||
|
if (!optionsArg.serviceName || !/^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,119}$/.test(optionsArg.serviceName)) {
|
||||||
|
throw new Error(`Invalid service name: ${optionsArg.serviceName}`);
|
||||||
|
}
|
||||||
|
if (optionsArg.port !== undefined) {
|
||||||
|
this.assertValidPort(optionsArg.port, 'install service port');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertValidPort(portArg: number, labelArg: string): void {
|
||||||
|
if (!Number.isInteger(portArg) || portArg < 1 || portArg > 65535) {
|
||||||
|
throw new Error(`Invalid ${labelArg}: ${portArg}. Expected an integer port between 1 and 65535.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private getAppStoreEnvVars(
|
||||||
|
configArg: IAppStoreVersionConfig,
|
||||||
|
overridesArg: Record<string, string>,
|
||||||
|
): Record<string, string> {
|
||||||
|
const envVars: Record<string, string> = {};
|
||||||
|
const missingRequiredEnvVars: string[] = [];
|
||||||
|
|
||||||
|
for (const envVar of configArg.envVars || []) {
|
||||||
|
const value = overridesArg[envVar.key] ?? envVar.value ?? '';
|
||||||
|
if (envVar.required && !value) {
|
||||||
|
missingRequiredEnvVars.push(envVar.key);
|
||||||
|
}
|
||||||
|
envVars[envVar.key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
Object.assign(envVars, overridesArg);
|
||||||
|
|
||||||
|
if (missingRequiredEnvVars.length > 0) {
|
||||||
|
throw new Error(`Missing required app env var(s): ${missingRequiredEnvVars.join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return envVars;
|
||||||
|
}
|
||||||
|
|
||||||
|
private requiresTemplateValue(envVarsArg: Record<string, string>, templateNameArg: string): boolean {
|
||||||
|
return Object.values(envVarsArg).some((value) => value.includes(`\${${templateNameArg}}`));
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertRuntimeCompatibility(configArg: IAppStoreVersionConfig): void {
|
||||||
|
if (!configArg.minOneboxVersion) return;
|
||||||
|
if (this.compareVersions(projectInfo.version, configArg.minOneboxVersion) < 0) {
|
||||||
|
throw new Error(
|
||||||
|
`App requires Onebox >= ${configArg.minOneboxVersion}; current version is ${projectInfo.version}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private compareVersions(versionAArg: string, versionBArg: string): number {
|
||||||
|
const normalize = (versionArg: string) => versionArg.replace(/^v/, '').split('.').map((partArg) => Number(partArg) || 0);
|
||||||
|
const a = normalize(versionAArg);
|
||||||
|
const b = normalize(versionBArg);
|
||||||
|
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
||||||
|
const diff = (a[i] || 0) - (b[i] || 0);
|
||||||
|
if (diff !== 0) return diff > 0 ? 1 : -1;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -185,7 +185,12 @@ export class BackupManager {
|
|||||||
await this.exportDockerImage(service.image, `${tempDir}/data/image/image.tar`);
|
await this.exportDockerImage(service.image, `${tempDir}/data/image/image.tar`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. Build ingest items from temp directory files
|
// 4. Export declared service volume data when the volume opts into backup.
|
||||||
|
if (service.volumes?.some((volumeArg) => volumeArg.backup !== false)) {
|
||||||
|
await this.exportServiceVolumes(service, tempDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Build ingest items from temp directory files
|
||||||
const items: Array<{ stream: NodeJS.ReadableStream; name: string; type?: string }> = [];
|
const items: Array<{ stream: NodeJS.ReadableStream; name: string; type?: string }> = [];
|
||||||
|
|
||||||
// Service config
|
// Service config
|
||||||
@@ -218,6 +223,19 @@ export class BackupManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const volumeDataDir = `${tempDir}/data/volumes`;
|
||||||
|
try {
|
||||||
|
for await (const filePath of this.walkFiles(volumeDataDir)) {
|
||||||
|
items.push({
|
||||||
|
stream: plugins.nodeFs.createReadStream(filePath),
|
||||||
|
name: plugins.path.relative(tempDir, filePath).replaceAll('\\', '/'),
|
||||||
|
type: 'volume',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// No service volume data was exported.
|
||||||
|
}
|
||||||
|
|
||||||
// Docker image
|
// Docker image
|
||||||
if (includeImage && service.image) {
|
if (includeImage && service.image) {
|
||||||
const imagePath = `${tempDir}/data/image/image.tar`;
|
const imagePath = `${tempDir}/data/image/image.tar`;
|
||||||
@@ -233,7 +251,7 @@ export class BackupManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. Build snapshot tags
|
// 6. Build snapshot tags
|
||||||
const tags: Record<string, string> = {
|
const tags: Record<string, string> = {
|
||||||
serviceName: service.name,
|
serviceName: service.name,
|
||||||
serviceId: String(service.id),
|
serviceId: String(service.id),
|
||||||
@@ -245,10 +263,10 @@ export class BackupManager {
|
|||||||
tags.scheduleId = String(options.scheduleId);
|
tags.scheduleId = String(options.scheduleId);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 6. Ingest multi-item snapshot into containerarchive
|
// 7. Ingest multi-item snapshot into containerarchive
|
||||||
const snapshot = await this.archive.ingestMulti(items, { tags });
|
const snapshot = await this.archive.ingestMulti(items, { tags });
|
||||||
|
|
||||||
// 7. Store backup record in database
|
// 8. Store backup record in database
|
||||||
const backup: IBackup = {
|
const backup: IBackup = {
|
||||||
serviceId: service.id!,
|
serviceId: service.id!,
|
||||||
serviceName: service.name,
|
serviceName: service.name,
|
||||||
@@ -675,6 +693,8 @@ export class BackupManager {
|
|||||||
registry: serviceConfig.registry,
|
registry: serviceConfig.registry,
|
||||||
port: serviceConfig.port,
|
port: serviceConfig.port,
|
||||||
domain: serviceConfig.domain,
|
domain: serviceConfig.domain,
|
||||||
|
volumes: serviceConfig.volumes,
|
||||||
|
publishedPorts: serviceConfig.publishedPorts,
|
||||||
useOneboxRegistry: serviceConfig.useOneboxRegistry,
|
useOneboxRegistry: serviceConfig.useOneboxRegistry,
|
||||||
registryRepository: serviceConfig.registryRepository,
|
registryRepository: serviceConfig.registryRepository,
|
||||||
registryImageTag: serviceConfig.registryImageTag,
|
registryImageTag: serviceConfig.registryImageTag,
|
||||||
@@ -705,6 +725,8 @@ export class BackupManager {
|
|||||||
port: serviceConfig.port,
|
port: serviceConfig.port,
|
||||||
domain: options.mode === 'clone' ? undefined : serviceConfig.domain,
|
domain: options.mode === 'clone' ? undefined : serviceConfig.domain,
|
||||||
envVars: serviceConfig.envVars,
|
envVars: serviceConfig.envVars,
|
||||||
|
volumes: serviceConfig.volumes,
|
||||||
|
publishedPorts: serviceConfig.publishedPorts,
|
||||||
useOneboxRegistry: serviceConfig.useOneboxRegistry,
|
useOneboxRegistry: serviceConfig.useOneboxRegistry,
|
||||||
registryImageTag: serviceConfig.registryImageTag,
|
registryImageTag: serviceConfig.registryImageTag,
|
||||||
autoUpdateOnPush: serviceConfig.autoUpdateOnPush,
|
autoUpdateOnPush: serviceConfig.autoUpdateOnPush,
|
||||||
@@ -729,6 +751,8 @@ export class BackupManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await this.restoreServiceVolumes(service, serviceConfig.volumes || [], tempDir, warnings);
|
||||||
|
|
||||||
// Cleanup
|
// Cleanup
|
||||||
await Deno.remove(tempDir, { recursive: true });
|
await Deno.remove(tempDir, { recursive: true });
|
||||||
|
|
||||||
@@ -791,6 +815,8 @@ export class BackupManager {
|
|||||||
image: service.image,
|
image: service.image,
|
||||||
registry: service.registry,
|
registry: service.registry,
|
||||||
envVars: service.envVars,
|
envVars: service.envVars,
|
||||||
|
volumes: service.volumes,
|
||||||
|
publishedPorts: service.publishedPorts,
|
||||||
port: service.port,
|
port: service.port,
|
||||||
domain: service.domain,
|
domain: service.domain,
|
||||||
useOneboxRegistry: service.useOneboxRegistry,
|
useOneboxRegistry: service.useOneboxRegistry,
|
||||||
@@ -802,6 +828,62 @@ export class BackupManager {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getVolumeBackupName(volumeArg: { mountPath: string }, indexArg: number): string {
|
||||||
|
const safeMountPath = volumeArg.mountPath
|
||||||
|
.replace(/^\/+/, '')
|
||||||
|
.replace(/\/+$/g, '')
|
||||||
|
.replace(/[^a-zA-Z0-9_.-]+/g, '-') || 'root';
|
||||||
|
return `${String(indexArg).padStart(3, '0')}-${safeMountPath}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async exportServiceVolumes(serviceArg: IService, tempDirArg: string): Promise<void> {
|
||||||
|
if (!serviceArg.containerID) {
|
||||||
|
throw new Error(`Cannot export service volumes for ${serviceArg.name}: service has no container ID`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const volumes = (serviceArg.volumes || []).filter((volumeArg) => volumeArg.backup !== false);
|
||||||
|
for (let i = 0; i < volumes.length; i++) {
|
||||||
|
const volume = volumes[i];
|
||||||
|
const backupName = this.getVolumeBackupName(volume, i);
|
||||||
|
const outputPath = `${tempDirArg}/data/volumes/${backupName}`;
|
||||||
|
await Deno.mkdir(outputPath, { recursive: true });
|
||||||
|
await this.copyFromContainer(serviceArg.containerID, `${volume.mountPath}/.`, outputPath);
|
||||||
|
logger.info(`Exported volume ${volume.mountPath} for service ${serviceArg.name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async restoreServiceVolumes(
|
||||||
|
serviceArg: IService,
|
||||||
|
volumesArg: NonNullable<IBackupServiceConfig['volumes']>,
|
||||||
|
tempDirArg: string,
|
||||||
|
warningsArg: string[],
|
||||||
|
): Promise<void> {
|
||||||
|
if (!serviceArg.containerID) {
|
||||||
|
if (volumesArg.some((volumeArg) => volumeArg.backup !== false)) {
|
||||||
|
warningsArg.push(`Could not restore service volumes for ${serviceArg.name}: service has no container ID`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const volumes = volumesArg.filter((volumeArg) => volumeArg.backup !== false);
|
||||||
|
for (let i = 0; i < volumes.length; i++) {
|
||||||
|
const volume = volumes[i];
|
||||||
|
const backupName = this.getVolumeBackupName(volume, i);
|
||||||
|
const inputPath = `${tempDirArg}/data/volumes/${backupName}`;
|
||||||
|
try {
|
||||||
|
await Deno.stat(inputPath);
|
||||||
|
} catch {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await this.copyToContainer(`${inputPath}/.`, serviceArg.containerID, volume.mountPath);
|
||||||
|
logger.info(`Restored volume ${volume.mountPath} for service ${serviceArg.name}`);
|
||||||
|
} catch (error) {
|
||||||
|
warningsArg.push(`Volume restore failed for ${volume.mountPath}: ${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Export MongoDB database
|
* Export MongoDB database
|
||||||
*/
|
*/
|
||||||
|
|||||||
+305
-22
@@ -5,14 +5,264 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import * as plugins from '../plugins.ts';
|
import * as plugins from '../plugins.ts';
|
||||||
import type { IService, IContainerStats } from '../types.ts';
|
import type { IService, IContainerStats, IServicePublishedPort } from '../types.ts';
|
||||||
import { logger } from '../logging.ts';
|
import { logger } from '../logging.ts';
|
||||||
import { getErrorMessage } from '../utils/error.ts';
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
|
|
||||||
|
type TExpandedPublishedPort = Required<Pick<
|
||||||
|
IServicePublishedPort,
|
||||||
|
'targetPort' | 'publishedPort' | 'protocol' | 'hostIp'
|
||||||
|
>>;
|
||||||
|
|
||||||
|
export interface IInteractiveContainerExec {
|
||||||
|
stream: plugins.nodeStream.Duplex;
|
||||||
|
close: () => Promise<void>;
|
||||||
|
inspect: () => Promise<{ ExitCode?: number | null; Running?: boolean }>;
|
||||||
|
}
|
||||||
|
|
||||||
export class OneboxDockerManager {
|
export class OneboxDockerManager {
|
||||||
private dockerClient: InstanceType<typeof plugins.docker.Docker> | null = null;
|
private dockerClient: InstanceType<typeof plugins.docker.Docker> | null = null;
|
||||||
private networkName = 'onebox-network';
|
private networkName = 'onebox-network';
|
||||||
|
|
||||||
|
private getDockerSafeName(valueArg: string, maxLengthArg = 120): string {
|
||||||
|
const safeName = valueArg
|
||||||
|
.replace(/[^a-zA-Z0-9_.-]+/g, '-')
|
||||||
|
.replace(/^[^a-zA-Z0-9]+|[^a-zA-Z0-9]+$/g, '')
|
||||||
|
.slice(0, maxLengthArg)
|
||||||
|
.replace(/[^a-zA-Z0-9]+$/g, '');
|
||||||
|
return safeName || 'data';
|
||||||
|
}
|
||||||
|
|
||||||
|
private getServiceVolumeSource(serviceArg: IService, mountPathArg: string, requestedSourceArg?: string): string {
|
||||||
|
if (requestedSourceArg) {
|
||||||
|
return this.getDockerSafeName(requestedSourceArg);
|
||||||
|
}
|
||||||
|
const mountName = this.getDockerSafeName(mountPathArg.replace(/^\/+/, '').replace(/\/+$/g, ''), 40);
|
||||||
|
return this.getDockerSafeName(`onebox-${serviceArg.name}-${mountName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getStandaloneVolumeBinds(serviceArg: IService): string[] {
|
||||||
|
return (serviceArg.volumes || []).map((volumeArg) => {
|
||||||
|
const source = this.getServiceVolumeSource(serviceArg, volumeArg.mountPath, volumeArg.source || volumeArg.name);
|
||||||
|
return `${source}:${volumeArg.mountPath}${volumeArg.readOnly ? ':ro' : ''}`;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private getSwarmVolumeMounts(serviceArg: IService): Array<Record<string, unknown>> {
|
||||||
|
return (serviceArg.volumes || []).map((volumeArg) => ({
|
||||||
|
Type: 'volume',
|
||||||
|
Source: this.getServiceVolumeSource(serviceArg, volumeArg.mountPath, volumeArg.source || volumeArg.name),
|
||||||
|
Target: volumeArg.mountPath,
|
||||||
|
ReadOnly: Boolean(volumeArg.readOnly),
|
||||||
|
VolumeOptions: {
|
||||||
|
DriverConfig: {
|
||||||
|
Name: volumeArg.driver || 'local',
|
||||||
|
Options: volumeArg.options || {},
|
||||||
|
},
|
||||||
|
Labels: {
|
||||||
|
'managed-by': 'onebox',
|
||||||
|
'onebox-service': serviceArg.name,
|
||||||
|
'onebox-mount-path': volumeArg.mountPath,
|
||||||
|
'onebox-backup': String(volumeArg.backup !== false),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
public validateServiceSpec(serviceArg: IService): void {
|
||||||
|
this.assertValidPort(serviceArg.port, `service port for ${serviceArg.name}`);
|
||||||
|
|
||||||
|
for (const volumeArg of serviceArg.volumes || []) {
|
||||||
|
if (!volumeArg.mountPath || !volumeArg.mountPath.startsWith('/')) {
|
||||||
|
throw new Error(`Volume mountPath for service ${serviceArg.name} must be an absolute path`);
|
||||||
|
}
|
||||||
|
if (volumeArg.mountPath.includes(':')) {
|
||||||
|
throw new Error(`Volume mountPath for service ${serviceArg.name} must not contain ':'`);
|
||||||
|
}
|
||||||
|
if ((volumeArg.source || volumeArg.name)?.includes(':')) {
|
||||||
|
throw new Error(`Volume source/name for service ${serviceArg.name} must not contain ':'`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.expandPublishedPorts(serviceArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertValidPort(portArg: number, labelArg: string): void {
|
||||||
|
if (!Number.isInteger(portArg) || portArg < 1 || portArg > 65535) {
|
||||||
|
throw new Error(`Invalid ${labelArg}: ${portArg}. Expected an integer port between 1 and 65535.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private expandPublishedPorts(serviceArg: IService): TExpandedPublishedPort[] {
|
||||||
|
const expandedPorts: TExpandedPublishedPort[] = [];
|
||||||
|
const seenPublishedPorts = new Set<string>();
|
||||||
|
|
||||||
|
for (const portArg of serviceArg.publishedPorts || []) {
|
||||||
|
const protocol = portArg.protocol || 'tcp';
|
||||||
|
const targetStart = portArg.targetPort;
|
||||||
|
const targetEnd = portArg.targetPortEnd || targetStart;
|
||||||
|
const publishedStart = portArg.publishedPort || targetStart;
|
||||||
|
const publishedEnd = portArg.publishedPortEnd || (publishedStart + (targetEnd - targetStart));
|
||||||
|
const hostIp = portArg.hostIp || '0.0.0.0';
|
||||||
|
|
||||||
|
if (!['tcp', 'udp'].includes(protocol)) {
|
||||||
|
throw new Error(`Invalid published port protocol for service ${serviceArg.name}: ${protocol}`);
|
||||||
|
}
|
||||||
|
this.assertValidPort(targetStart, `published targetPort for service ${serviceArg.name}`);
|
||||||
|
this.assertValidPort(targetEnd, `published targetPortEnd for service ${serviceArg.name}`);
|
||||||
|
this.assertValidPort(publishedStart, `published publishedPort for service ${serviceArg.name}`);
|
||||||
|
this.assertValidPort(publishedEnd, `published publishedPortEnd for service ${serviceArg.name}`);
|
||||||
|
if (targetEnd < targetStart) {
|
||||||
|
throw new Error(`Invalid target port range for service ${serviceArg.name}: ${targetStart}-${targetEnd}`);
|
||||||
|
}
|
||||||
|
if (publishedEnd < publishedStart) {
|
||||||
|
throw new Error(`Invalid published port range for service ${serviceArg.name}: ${publishedStart}-${publishedEnd}`);
|
||||||
|
}
|
||||||
|
if ((targetEnd - targetStart) !== (publishedEnd - publishedStart)) {
|
||||||
|
throw new Error(
|
||||||
|
`Published port range size must match target port range size for service ${serviceArg.name}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!this.isValidHostIp(hostIp)) {
|
||||||
|
throw new Error(`Invalid hostIp for service ${serviceArg.name}: ${hostIp}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let offset = 0; offset <= targetEnd - targetStart; offset++) {
|
||||||
|
const publishedPort = publishedStart + offset;
|
||||||
|
const publishedKey = `${hostIp}/${protocol}/${publishedPort}`;
|
||||||
|
const wildcardKey = `0.0.0.0/${protocol}/${publishedPort}`;
|
||||||
|
const conflictsWithWildcard = hostIp === '0.0.0.0'
|
||||||
|
? Array.from(seenPublishedPorts).some((keyArg) => keyArg.endsWith(`/${protocol}/${publishedPort}`))
|
||||||
|
: seenPublishedPorts.has(wildcardKey);
|
||||||
|
if (seenPublishedPorts.has(publishedKey) || conflictsWithWildcard) {
|
||||||
|
throw new Error(`Duplicate published port for service ${serviceArg.name}: ${hostIp}:${publishedPort}/${protocol}`);
|
||||||
|
}
|
||||||
|
seenPublishedPorts.add(publishedKey);
|
||||||
|
expandedPorts.push({
|
||||||
|
targetPort: targetStart + offset,
|
||||||
|
publishedPort,
|
||||||
|
protocol,
|
||||||
|
hostIp,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return expandedPorts;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isValidHostIp(hostIpArg: string): boolean {
|
||||||
|
if (['0.0.0.0', '127.0.0.1', '::', '::1', 'localhost'].includes(hostIpArg)) return true;
|
||||||
|
if (/^(\d{1,3}\.){3}\d{1,3}$/.test(hostIpArg)) {
|
||||||
|
return hostIpArg.split('.').every((partArg) => Number(partArg) >= 0 && Number(partArg) <= 255);
|
||||||
|
}
|
||||||
|
return /^[0-9a-fA-F:]+$/.test(hostIpArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertPublishedPortsAvailable(serviceArg: IService): Promise<void> {
|
||||||
|
const publishedPorts = this.expandPublishedPorts(serviceArg);
|
||||||
|
if (publishedPorts.length === 0) return;
|
||||||
|
|
||||||
|
await this.assertPublishedPortsNotUsedByDocker(serviceArg, publishedPorts);
|
||||||
|
await this.assertPublishedPortsNotUsedByHost(serviceArg, publishedPorts);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertPublishedPortsNotUsedByDocker(
|
||||||
|
serviceArg: IService,
|
||||||
|
publishedPortsArg: TExpandedPublishedPort[],
|
||||||
|
): Promise<void> {
|
||||||
|
const requestedPorts = new Set(
|
||||||
|
publishedPortsArg.map((portArg) => `${portArg.protocol}/${portArg.publishedPort}`),
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const containersResponse = await this.dockerClient!.request('GET', '/containers/json?all=true', {});
|
||||||
|
if (containersResponse.statusCode === 200 && Array.isArray(containersResponse.body)) {
|
||||||
|
for (const containerArg of containersResponse.body) {
|
||||||
|
const labels = containerArg.Labels || {};
|
||||||
|
if (labels['onebox-service'] === serviceArg.name) continue;
|
||||||
|
for (const portArg of containerArg.Ports || []) {
|
||||||
|
if (!portArg.PublicPort || !portArg.Type) continue;
|
||||||
|
if (requestedPorts.has(`${portArg.Type}/${portArg.PublicPort}`)) {
|
||||||
|
throw new Error(
|
||||||
|
`Published port ${portArg.PublicPort}/${portArg.Type} is already used by container ${containerArg.Names?.[0] || containerArg.Id}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const servicesResponse = await this.dockerClient!.request('GET', '/services', {});
|
||||||
|
if (servicesResponse.statusCode === 200 && Array.isArray(servicesResponse.body)) {
|
||||||
|
for (const service of servicesResponse.body) {
|
||||||
|
if (service.Spec?.Name === `onebox-${serviceArg.name}`) continue;
|
||||||
|
for (const portArg of service.Endpoint?.Ports || []) {
|
||||||
|
if (!portArg.PublishedPort || !portArg.Protocol) continue;
|
||||||
|
if (requestedPorts.has(`${portArg.Protocol}/${portArg.PublishedPort}`)) {
|
||||||
|
throw new Error(
|
||||||
|
`Published port ${portArg.PublishedPort}/${portArg.Protocol} is already used by Docker service ${service.Spec?.Name || service.ID}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof Error && error.message.startsWith('Published port ')) throw error;
|
||||||
|
logger.warn(`Could not complete Docker published-port preflight: ${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertPublishedPortsNotUsedByHost(
|
||||||
|
serviceArg: IService,
|
||||||
|
publishedPortsArg: TExpandedPublishedPort[],
|
||||||
|
): Promise<void> {
|
||||||
|
for (const portArg of publishedPortsArg) {
|
||||||
|
try {
|
||||||
|
if (portArg.protocol === 'udp') {
|
||||||
|
await this.assertUdpPortAvailable(portArg.hostIp, portArg.publishedPort);
|
||||||
|
} else {
|
||||||
|
const listener = Deno.listen({ hostname: portArg.hostIp, port: portArg.publishedPort });
|
||||||
|
listener.close();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(
|
||||||
|
`Published port ${portArg.hostIp}:${portArg.publishedPort}/${portArg.protocol} for service ${serviceArg.name} is not available: ${getErrorMessage(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertUdpPortAvailable(hostIpArg: string, portArg: number): Promise<void> {
|
||||||
|
const dgram = await import('node:dgram');
|
||||||
|
const socket = dgram.createSocket(hostIpArg.includes(':') ? 'udp6' : 'udp4');
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
socket.once('error', reject);
|
||||||
|
socket.bind(portArg, hostIpArg, () => {
|
||||||
|
socket.close();
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private getStandalonePortConfig(serviceArg: IService): {
|
||||||
|
exposedPorts: Record<string, Record<string, never>>;
|
||||||
|
portBindings: Record<string, Array<{ HostIp: string; HostPort: string }>>;
|
||||||
|
} {
|
||||||
|
const exposedPorts: Record<string, Record<string, never>> = {
|
||||||
|
[`${serviceArg.port}/tcp`]: {},
|
||||||
|
};
|
||||||
|
const portBindings: Record<string, Array<{ HostIp: string; HostPort: string }>> = {
|
||||||
|
[`${serviceArg.port}/tcp`]: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const publishedPort of this.expandPublishedPorts(serviceArg)) {
|
||||||
|
const key = `${publishedPort.targetPort}/${publishedPort.protocol}`;
|
||||||
|
exposedPorts[key] = {};
|
||||||
|
portBindings[key] = [{ HostIp: publishedPort.hostIp, HostPort: String(publishedPort.publishedPort) }];
|
||||||
|
}
|
||||||
|
|
||||||
|
return { exposedPorts, portBindings };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initialize Docker client and create onebox network
|
* Initialize Docker client and create onebox network
|
||||||
*/
|
*/
|
||||||
@@ -122,6 +372,9 @@ export class OneboxDockerManager {
|
|||||||
*/
|
*/
|
||||||
async createContainer(service: IService): Promise<string> {
|
async createContainer(service: IService): Promise<string> {
|
||||||
try {
|
try {
|
||||||
|
this.validateServiceSpec(service);
|
||||||
|
await this.assertPublishedPortsAvailable(service);
|
||||||
|
|
||||||
// Check if Docker is in Swarm mode
|
// Check if Docker is in Swarm mode
|
||||||
let isSwarmMode = false;
|
let isSwarmMode = false;
|
||||||
try {
|
try {
|
||||||
@@ -158,6 +411,8 @@ export class OneboxDockerManager {
|
|||||||
env.push(`${key}=${value}`);
|
env.push(`${key}=${value}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const portConfig = this.getStandalonePortConfig(service);
|
||||||
|
|
||||||
// Create container using Docker REST API directly
|
// Create container using Docker REST API directly
|
||||||
const response = await this.dockerClient!.request('POST', `/containers/create?name=onebox-${service.name}`, {
|
const response = await this.dockerClient!.request('POST', `/containers/create?name=onebox-${service.name}`, {
|
||||||
Image: fullImage,
|
Image: fullImage,
|
||||||
@@ -166,18 +421,14 @@ export class OneboxDockerManager {
|
|||||||
'managed-by': 'onebox',
|
'managed-by': 'onebox',
|
||||||
'onebox-service': service.name,
|
'onebox-service': service.name,
|
||||||
},
|
},
|
||||||
ExposedPorts: {
|
ExposedPorts: portConfig.exposedPorts,
|
||||||
[`${service.port}/tcp`]: {},
|
|
||||||
},
|
|
||||||
HostConfig: {
|
HostConfig: {
|
||||||
NetworkMode: this.networkName,
|
NetworkMode: this.networkName,
|
||||||
RestartPolicy: {
|
RestartPolicy: {
|
||||||
Name: 'unless-stopped',
|
Name: 'unless-stopped',
|
||||||
},
|
},
|
||||||
PortBindings: {
|
PortBindings: portConfig.portBindings,
|
||||||
// Don't bind to host ports - nginx will proxy
|
Binds: this.getStandaloneVolumeBinds(service),
|
||||||
[`${service.port}/tcp`]: [],
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -207,6 +458,25 @@ export class OneboxDockerManager {
|
|||||||
env.push(`${key}=${value}`);
|
env.push(`${key}=${value}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const expandedPublishedPorts = this.expandPublishedPorts(service);
|
||||||
|
const endpointPorts: Array<Record<string, unknown>> = [];
|
||||||
|
if (!expandedPublishedPorts.some((publishedPort) => publishedPort.protocol === 'tcp' && publishedPort.targetPort === service.port)) {
|
||||||
|
endpointPorts.push({
|
||||||
|
Protocol: 'tcp',
|
||||||
|
TargetPort: service.port,
|
||||||
|
PublishMode: 'host',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const publishedPort of expandedPublishedPorts) {
|
||||||
|
endpointPorts.push({
|
||||||
|
Protocol: publishedPort.protocol,
|
||||||
|
TargetPort: publishedPort.targetPort,
|
||||||
|
PublishedPort: publishedPort.publishedPort,
|
||||||
|
PublishMode: 'host',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Create Swarm service using Docker REST API
|
// Create Swarm service using Docker REST API
|
||||||
const response = await this.dockerClient!.request('POST', '/services/create', {
|
const response = await this.dockerClient!.request('POST', '/services/create', {
|
||||||
Name: `onebox-${service.name}`,
|
Name: `onebox-${service.name}`,
|
||||||
@@ -218,6 +488,7 @@ export class OneboxDockerManager {
|
|||||||
ContainerSpec: {
|
ContainerSpec: {
|
||||||
Image: fullImage,
|
Image: fullImage,
|
||||||
Env: env,
|
Env: env,
|
||||||
|
Mounts: this.getSwarmVolumeMounts(service),
|
||||||
Labels: {
|
Labels: {
|
||||||
'managed-by': 'onebox',
|
'managed-by': 'onebox',
|
||||||
'onebox-service': service.name,
|
'onebox-service': service.name,
|
||||||
@@ -239,13 +510,7 @@ export class OneboxDockerManager {
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
EndpointSpec: {
|
EndpointSpec: {
|
||||||
Ports: [
|
Ports: endpointPorts,
|
||||||
{
|
|
||||||
Protocol: 'tcp',
|
|
||||||
TargetPort: service.port,
|
|
||||||
PublishMode: 'host',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -869,16 +1134,12 @@ export class OneboxDockerManager {
|
|||||||
/**
|
/**
|
||||||
* Execute a command in a running container
|
* Execute a command in a running container
|
||||||
*/
|
*/
|
||||||
async execInContainer(
|
private async resolveContainer(containerID: string): Promise<any> {
|
||||||
containerID: string,
|
|
||||||
cmd: string[]
|
|
||||||
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
|
||||||
try {
|
|
||||||
let container: any = null;
|
let container: any = null;
|
||||||
try {
|
try {
|
||||||
container = await this.dockerClient!.getContainerById(containerID);
|
container = await this.dockerClient!.getContainerById(containerID);
|
||||||
} catch {
|
} catch {
|
||||||
// Not a direct container ID — try Swarm service lookup
|
// Not a direct container ID — try Swarm service lookup.
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!container) {
|
if (!container) {
|
||||||
@@ -887,7 +1148,7 @@ export class OneboxDockerManager {
|
|||||||
try {
|
try {
|
||||||
container = await this.dockerClient!.getContainerById(serviceContainerId);
|
container = await this.dockerClient!.getContainerById(serviceContainerId);
|
||||||
} catch {
|
} catch {
|
||||||
// Service container also not found
|
// Service container also not found.
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -895,6 +1156,15 @@ export class OneboxDockerManager {
|
|||||||
if (!container) {
|
if (!container) {
|
||||||
throw new Error(`Container not found: ${containerID}`);
|
throw new Error(`Container not found: ${containerID}`);
|
||||||
}
|
}
|
||||||
|
return container;
|
||||||
|
}
|
||||||
|
|
||||||
|
async execInContainer(
|
||||||
|
containerID: string,
|
||||||
|
cmd: string[]
|
||||||
|
): Promise<{ stdout: string; stderr: string; exitCode: number }> {
|
||||||
|
try {
|
||||||
|
const container = await this.resolveContainer(containerID);
|
||||||
|
|
||||||
const { stream, inspect } = await container.exec(cmd, {
|
const { stream, inspect } = await container.exec(cmd, {
|
||||||
attachStdout: true,
|
attachStdout: true,
|
||||||
@@ -931,6 +1201,19 @@ export class OneboxDockerManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async startInteractiveExecInContainer(
|
||||||
|
containerID: string,
|
||||||
|
cmd: string[],
|
||||||
|
): Promise<IInteractiveContainerExec> {
|
||||||
|
const container = await this.resolveContainer(containerID);
|
||||||
|
return await container.exec(cmd, {
|
||||||
|
tty: true,
|
||||||
|
attachStdin: true,
|
||||||
|
attachStdout: true,
|
||||||
|
attachStderr: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a platform service container (MongoDB, MinIO, etc.)
|
* Create a platform service container (MongoDB, MinIO, etc.)
|
||||||
* Platform containers are long-running infrastructure services
|
* Platform containers are long-running infrastructure services
|
||||||
|
|||||||
+347
-31
@@ -1,21 +1,48 @@
|
|||||||
import * as plugins from '../plugins.ts';
|
import * as plugins from '../plugins.ts';
|
||||||
import { logger } from '../logging.ts';
|
import { logger } from '../logging.ts';
|
||||||
import { getErrorMessage } from '../utils/error.ts';
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
|
import { normalizeHostname } from '../utils/domain.ts';
|
||||||
import { OneboxDatabase } from './database.ts';
|
import { OneboxDatabase } from './database.ts';
|
||||||
import type { IDomain, IService } from '../types.ts';
|
import type { IDomain, IService } from '../types.ts';
|
||||||
|
import type { TDcRouterMode } from './managed-dcrouter.ts';
|
||||||
|
|
||||||
|
const adminUiRouteName = 'onebox-admin-ui';
|
||||||
|
|
||||||
type TWorkHosterType = 'onebox';
|
type TWorkHosterType = 'onebox';
|
||||||
|
type TExternalGatewayRoute = Pick<IService, 'id' | 'name' | 'domain' | 'status'> & {
|
||||||
|
domain: string;
|
||||||
|
};
|
||||||
|
|
||||||
interface IExternalGatewayConfig {
|
interface IExternalGatewayConfig {
|
||||||
url: string;
|
url: string;
|
||||||
apiToken: string;
|
apiToken: string;
|
||||||
workHosterId: string;
|
gatewayClientType?: TWorkHosterType;
|
||||||
|
gatewayClientId?: string;
|
||||||
|
/** @deprecated Use gatewayClientId. */
|
||||||
|
workHosterId?: string;
|
||||||
targetHost?: string;
|
targetHost?: string;
|
||||||
targetPort?: number;
|
targetPort?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface IGatewayClientContextResponse {
|
||||||
|
context: {
|
||||||
|
role: 'admin' | 'gatewayClient' | 'operator';
|
||||||
|
gatewayClient?: {
|
||||||
|
type: 'onebox' | 'cloudly' | 'custom';
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
interface IWorkHosterDomain {
|
interface IWorkHosterDomain {
|
||||||
|
id?: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
source?: 'dcrouter' | 'provider';
|
||||||
|
authoritative?: boolean;
|
||||||
|
providerId?: string;
|
||||||
|
serviceCount?: number;
|
||||||
|
managePath?: string;
|
||||||
|
manageUrl?: string;
|
||||||
capabilities?: {
|
capabilities?: {
|
||||||
canCreateSubdomains: boolean;
|
canCreateSubdomains: boolean;
|
||||||
canManageDnsRecords: boolean;
|
canManageDnsRecords: boolean;
|
||||||
@@ -24,6 +51,26 @@ interface IWorkHosterDomain {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface IGatewayDnsRecord {
|
||||||
|
id: string;
|
||||||
|
domainId: string;
|
||||||
|
domainName?: string;
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
value: string;
|
||||||
|
ttl: number;
|
||||||
|
source: string;
|
||||||
|
status: 'active' | 'missing';
|
||||||
|
gatewayClientType: 'onebox' | 'cloudly' | 'custom';
|
||||||
|
gatewayClientId: string;
|
||||||
|
appId: string;
|
||||||
|
hostname: string;
|
||||||
|
routeId?: string;
|
||||||
|
serviceName?: string;
|
||||||
|
managePath?: string;
|
||||||
|
manageUrl?: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface IWorkAppRouteOwnership {
|
interface IWorkAppRouteOwnership {
|
||||||
workHosterType: TWorkHosterType;
|
workHosterType: TWorkHosterType;
|
||||||
workHosterId: string;
|
workHosterId: string;
|
||||||
@@ -31,6 +78,13 @@ interface IWorkAppRouteOwnership {
|
|||||||
hostname: string;
|
hostname: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface IGatewayClientOwnership {
|
||||||
|
gatewayClientType?: TWorkHosterType;
|
||||||
|
gatewayClientId?: string;
|
||||||
|
appId: string;
|
||||||
|
hostname: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface IWorkAppRouteSyncResult {
|
interface IWorkAppRouteSyncResult {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
action?: 'created' | 'updated' | 'deleted' | 'unchanged';
|
action?: 'created' | 'updated' | 'deleted' | 'unchanged';
|
||||||
@@ -85,20 +139,90 @@ export class ExternalGatewayManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
await this.syncDomains();
|
await this.syncDomains();
|
||||||
|
await this.syncServiceRoutes();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async syncServiceRoutes(): Promise<void> {
|
||||||
|
const adminUiRoute = this.getAdminUiRoute();
|
||||||
|
const adminUiDomain = adminUiRoute?.domain;
|
||||||
|
const services = this.database.getAllServices()
|
||||||
|
.filter((service) =>
|
||||||
|
service.domain && service.status === 'running' && service.domain !== adminUiDomain
|
||||||
|
);
|
||||||
|
const activeHostnames = new Set(services.map((service) => service.domain!));
|
||||||
|
|
||||||
|
if (adminUiRoute) {
|
||||||
|
activeHostnames.add(adminUiRoute.domain);
|
||||||
|
try {
|
||||||
|
await this.syncGatewayRoute(adminUiRoute);
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(
|
||||||
|
`Failed to sync external gateway route for ${adminUiRoute.domain}: ${
|
||||||
|
getErrorMessage(error)
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const service of services) {
|
||||||
|
try {
|
||||||
|
await this.syncServiceRoute(service);
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(
|
||||||
|
`Failed to sync external gateway route for ${service.domain}: ${getErrorMessage(error)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.deleteStaleServiceRoutes(activeHostnames);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async deleteStaleServiceRoutes(activeHostnamesArg: Set<string>): Promise<void> {
|
||||||
|
const records = await this.getGatewayDnsRecords();
|
||||||
|
const staleRecordsByHostname = new Map<string, IGatewayDnsRecord>();
|
||||||
|
|
||||||
|
for (const record of records) {
|
||||||
|
if (!record.hostname || activeHostnamesArg.has(record.hostname)) continue;
|
||||||
|
if (this.shouldPreserveUnconfiguredAdminUiRecord(record)) continue;
|
||||||
|
if (!record.routeId && !record.appId && !record.serviceName) continue;
|
||||||
|
staleRecordsByHostname.set(record.hostname, record);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const record of staleRecordsByHostname.values()) {
|
||||||
|
try {
|
||||||
|
await this.deleteServiceRoute({
|
||||||
|
name: record.serviceName || record.appId,
|
||||||
|
domain: record.hostname,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(
|
||||||
|
`Failed to delete stale external gateway route for ${record.hostname}: ${
|
||||||
|
getErrorMessage(error)
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async isConfigured(): Promise<boolean> {
|
public async isConfigured(): Promise<boolean> {
|
||||||
const config = await this.getConfig({ requireTarget: false });
|
if (this.getMode() === 'disabled') {
|
||||||
return Boolean(config);
|
return false;
|
||||||
|
}
|
||||||
|
const mode = this.getMode();
|
||||||
|
const url = mode === 'managed'
|
||||||
|
? this.oneboxRef.managedDcRouter.getGatewayUrl()
|
||||||
|
: this.normalizeUrl(this.database.getSetting('dcrouterGatewayUrl') || '');
|
||||||
|
const apiToken = mode === 'managed'
|
||||||
|
? await this.oneboxRef.managedDcRouter.getAdminToken()
|
||||||
|
: await this.database.getSecretSetting('dcrouterGatewayApiToken');
|
||||||
|
return Boolean(url && apiToken);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async syncDomains(): Promise<IDomain[]> {
|
public async syncDomains(): Promise<IDomain[]> {
|
||||||
const config = await this.requireConfig({ requireTarget: false });
|
if (!(await this.isConfigured())) {
|
||||||
const response = await this.fireDcRouterRequest<{ domains: IWorkHosterDomain[] }>(
|
return this.database.getDomainsByProvider('dcrouter');
|
||||||
'getWorkHosterDomains',
|
}
|
||||||
{},
|
const response = { domains: await this.getGatewayDomains() };
|
||||||
config,
|
|
||||||
);
|
|
||||||
|
|
||||||
const activeDomainNames = new Set<string>();
|
const activeDomainNames = new Set<string>();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -143,46 +267,146 @@ export class ExternalGatewayManager {
|
|||||||
return this.database.getDomainsByProvider('dcrouter');
|
return this.database.getDomainsByProvider('dcrouter');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async getGatewayDomains(): Promise<IWorkHosterDomain[]> {
|
||||||
|
const config = await this.getConfig({ requireTarget: false });
|
||||||
|
if (!config) return [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.fireDcRouterRequest<{ domains: IWorkHosterDomain[] }>(
|
||||||
|
'getGatewayClientDomains',
|
||||||
|
config.gatewayClientId ? { gatewayClientId: config.gatewayClientId } : {},
|
||||||
|
config,
|
||||||
|
);
|
||||||
|
return response.domains.map((domain) => ({
|
||||||
|
...domain,
|
||||||
|
manageUrl: this.buildManageUrl(config, domain.managePath),
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
logger.debug(`Falling back to legacy gateway domain API: ${getErrorMessage(error)}`);
|
||||||
|
const response = await this.fireDcRouterRequest<{ domains: IWorkHosterDomain[] }>(
|
||||||
|
'getWorkHosterDomains',
|
||||||
|
{},
|
||||||
|
config,
|
||||||
|
);
|
||||||
|
return response.domains.map((domain) => ({
|
||||||
|
...domain,
|
||||||
|
manageUrl: this.buildManageUrl(config, domain.managePath),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getGatewayDnsRecords(): Promise<IGatewayDnsRecord[]> {
|
||||||
|
const config = await this.getConfig({ requireTarget: false });
|
||||||
|
if (!config) return [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.fireDcRouterRequest<{ records: IGatewayDnsRecord[] }>(
|
||||||
|
'getGatewayClientDnsRecords',
|
||||||
|
config.gatewayClientId ? { gatewayClientId: config.gatewayClientId } : {},
|
||||||
|
config,
|
||||||
|
);
|
||||||
|
return response.records.map((record) => ({
|
||||||
|
...record,
|
||||||
|
serviceName: record.serviceName || record.appId,
|
||||||
|
manageUrl: this.buildManageUrl(config, record.managePath),
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(`Failed to fetch gateway DNS records: ${getErrorMessage(error)}`);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public async syncServiceRoute(service: IService): Promise<void> {
|
public async syncServiceRoute(service: IService): Promise<void> {
|
||||||
if (!service.domain) return;
|
if (!service.domain) return;
|
||||||
|
|
||||||
|
await this.syncGatewayRoute({
|
||||||
|
id: service.id,
|
||||||
|
name: service.name,
|
||||||
|
domain: service.domain,
|
||||||
|
status: service.status,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public async syncAdminUiRoute(): Promise<void> {
|
||||||
|
const route = this.getAdminUiRoute();
|
||||||
|
if (!route) return;
|
||||||
|
await this.syncGatewayRoute(route);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async deleteAdminUiRoute(domain: string): Promise<void> {
|
||||||
|
const normalizedDomain = normalizeHostname(domain);
|
||||||
|
if (!normalizedDomain) return;
|
||||||
|
await this.deleteServiceRoute({
|
||||||
|
name: adminUiRouteName,
|
||||||
|
domain: normalizedDomain,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async syncGatewayRoute(route: TExternalGatewayRoute): Promise<void> {
|
||||||
|
if (!route.domain) return;
|
||||||
|
|
||||||
const config = await this.getConfig({ requireTarget: true });
|
const config = await this.getConfig({ requireTarget: true });
|
||||||
if (!config) return;
|
if (!config) return;
|
||||||
|
|
||||||
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||||
|
'syncGatewayClientRoute',
|
||||||
|
{
|
||||||
|
ownership: this.buildGatewayClientOwnership(route, route.domain, config),
|
||||||
|
route: this.buildRoute(route, config),
|
||||||
|
enabled: route.status === 'running',
|
||||||
|
},
|
||||||
|
config,
|
||||||
|
).catch(async () => {
|
||||||
|
return await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||||
'syncWorkAppRoute',
|
'syncWorkAppRoute',
|
||||||
{
|
{
|
||||||
ownership: this.buildOwnership(service, service.domain, config),
|
ownership: this.buildOwnership(route, route.domain, config),
|
||||||
route: this.buildRoute(service, config),
|
route: this.buildRoute(route, config),
|
||||||
enabled: service.status === 'running',
|
enabled: route.status === 'running',
|
||||||
},
|
},
|
||||||
config,
|
config,
|
||||||
);
|
);
|
||||||
|
});
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
throw new Error(result.message || `dcrouter route sync failed for ${service.domain}`);
|
throw new Error(result.message || `dcrouter route sync failed for ${route.domain}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.success(`External gateway route ${result.action || 'synced'} for ${service.domain}`);
|
logger.success(`External gateway route ${result.action || 'synced'} for ${route.domain}`);
|
||||||
await this.importCertificateForDomain(service.domain).catch((error) => {
|
await this.importCertificateForDomain(route.domain).catch((error) => {
|
||||||
logger.debug(`External gateway certificate import skipped for ${service.domain}: ${getErrorMessage(error)}`);
|
logger.debug(
|
||||||
|
`External gateway certificate import skipped for ${route.domain}: ${
|
||||||
|
getErrorMessage(error)
|
||||||
|
}`,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
public async deleteServiceRoute(service: Pick<IService, 'id' | 'name' | 'domain'>): Promise<void> {
|
public async deleteServiceRoute(
|
||||||
|
service: Pick<IService, 'id' | 'name' | 'domain'>,
|
||||||
|
): Promise<void> {
|
||||||
if (!service.domain) return;
|
if (!service.domain) return;
|
||||||
|
|
||||||
const config = await this.getConfig({ requireTarget: false });
|
const config = await this.getConfig({ requireTarget: false });
|
||||||
if (!config) return;
|
if (!config) return;
|
||||||
|
|
||||||
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
const result = await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||||
|
'syncGatewayClientRoute',
|
||||||
|
{
|
||||||
|
ownership: this.buildGatewayClientOwnership(service, service.domain, config),
|
||||||
|
delete: true,
|
||||||
|
},
|
||||||
|
config,
|
||||||
|
).catch(async () => {
|
||||||
|
return await this.fireDcRouterRequest<IWorkAppRouteSyncResult>(
|
||||||
'syncWorkAppRoute',
|
'syncWorkAppRoute',
|
||||||
{
|
{
|
||||||
ownership: this.buildOwnership(service, service.domain, config),
|
ownership: this.buildOwnership(service, service.domain!, config),
|
||||||
delete: true,
|
delete: true,
|
||||||
},
|
},
|
||||||
config,
|
config,
|
||||||
);
|
);
|
||||||
|
});
|
||||||
|
|
||||||
if (!result.success) {
|
if (!result.success) {
|
||||||
throw new Error(result.message || `dcrouter route delete failed for ${service.domain}`);
|
throw new Error(result.message || `dcrouter route delete failed for ${service.domain}`);
|
||||||
@@ -234,8 +458,17 @@ export class ExternalGatewayManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async getConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig | null> {
|
private async getConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig | null> {
|
||||||
const url = this.normalizeUrl(this.database.getSetting('dcrouterGatewayUrl') || '');
|
const mode = this.getMode();
|
||||||
const apiToken = await this.database.getSecretSetting('dcrouterGatewayApiToken');
|
if (mode === 'disabled') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const url = mode === 'managed'
|
||||||
|
? this.oneboxRef.managedDcRouter.getGatewayUrl()
|
||||||
|
: this.normalizeUrl(this.database.getSetting('dcrouterGatewayUrl') || '');
|
||||||
|
const apiToken = mode === 'managed'
|
||||||
|
? await this.oneboxRef.managedDcRouter.getAdminToken()
|
||||||
|
: await this.database.getSecretSetting('dcrouterGatewayApiToken');
|
||||||
if (!url || !apiToken) {
|
if (!url || !apiToken) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -243,10 +476,30 @@ export class ExternalGatewayManager {
|
|||||||
const config: IExternalGatewayConfig = {
|
const config: IExternalGatewayConfig = {
|
||||||
url,
|
url,
|
||||||
apiToken,
|
apiToken,
|
||||||
workHosterId: this.ensureWorkHosterId(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const contextClient = await this.getGatewayClientFromToken(config);
|
||||||
|
if (contextClient) {
|
||||||
|
config.gatewayClientType = contextClient.type;
|
||||||
|
config.gatewayClientId = contextClient.id;
|
||||||
|
config.workHosterId = contextClient.id;
|
||||||
|
} else {
|
||||||
|
const fallbackGatewayClientId = mode === 'managed'
|
||||||
|
? this.oneboxRef.managedDcRouter.ensureGatewayClientId()
|
||||||
|
: this.getStoredGatewayClientId();
|
||||||
|
if (fallbackGatewayClientId) {
|
||||||
|
config.gatewayClientType = 'onebox';
|
||||||
|
config.gatewayClientId = fallbackGatewayClientId;
|
||||||
|
config.workHosterId = fallbackGatewayClientId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if (options.requireTarget !== false) {
|
if (options.requireTarget !== false) {
|
||||||
|
if (mode === 'managed') {
|
||||||
|
const target = this.oneboxRef.managedDcRouter.getRouteTarget();
|
||||||
|
config.targetHost = target.host;
|
||||||
|
config.targetPort = target.port;
|
||||||
|
} else {
|
||||||
config.targetHost = this.database.getSetting('dcrouterTargetHost')
|
config.targetHost = this.database.getSetting('dcrouterTargetHost')
|
||||||
|| this.database.getSetting('serverIP')
|
|| this.database.getSetting('serverIP')
|
||||||
|| undefined;
|
|| undefined;
|
||||||
@@ -256,6 +509,7 @@ export class ExternalGatewayManager {
|
|||||||
|| '80',
|
|| '80',
|
||||||
);
|
);
|
||||||
config.targetPort = targetPort;
|
config.targetPort = targetPort;
|
||||||
|
}
|
||||||
|
|
||||||
if (!config.targetHost) {
|
if (!config.targetHost) {
|
||||||
throw new Error('dcrouterTargetHost or serverIP must be configured for external gateway route sync');
|
throw new Error('dcrouterTargetHost or serverIP must be configured for external gateway route sync');
|
||||||
@@ -265,6 +519,10 @@ export class ExternalGatewayManager {
|
|||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getMode(): TDcRouterMode {
|
||||||
|
return this.oneboxRef.managedDcRouter?.getMode?.() || 'external';
|
||||||
|
}
|
||||||
|
|
||||||
private async requireConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig> {
|
private async requireConfig(options: { requireTarget?: boolean } = {}): Promise<IExternalGatewayConfig> {
|
||||||
const config = await this.getConfig(options);
|
const config = await this.getConfig(options);
|
||||||
if (!config) {
|
if (!config) {
|
||||||
@@ -288,13 +546,27 @@ export class ExternalGatewayManager {
|
|||||||
return port;
|
return port;
|
||||||
}
|
}
|
||||||
|
|
||||||
private ensureWorkHosterId(): string {
|
private getStoredGatewayClientId(): string {
|
||||||
let workHosterId = this.database.getSetting('dcrouterWorkHosterId');
|
return this.database.getSetting('dcrouterGatewayClientId') || this.database.getSetting('dcrouterWorkHosterId') || '';
|
||||||
if (!workHosterId) {
|
}
|
||||||
workHosterId = crypto.randomUUID();
|
|
||||||
this.database.setSetting('dcrouterWorkHosterId', workHosterId);
|
private async getGatewayClientFromToken(config: IExternalGatewayConfig): Promise<{ type: TWorkHosterType; id: string } | null> {
|
||||||
|
try {
|
||||||
|
const response = await this.fireDcRouterRequest<IGatewayClientContextResponse>(
|
||||||
|
'getGatewayClientContext',
|
||||||
|
{},
|
||||||
|
config,
|
||||||
|
);
|
||||||
|
const gatewayClient = response.context.gatewayClient;
|
||||||
|
if (!gatewayClient) return null;
|
||||||
|
if (gatewayClient.type !== 'onebox') {
|
||||||
|
throw new Error(`dcrouter token is bound to unsupported gateway client type: ${gatewayClient.type}`);
|
||||||
|
}
|
||||||
|
return { type: gatewayClient.type, id: gatewayClient.id };
|
||||||
|
} catch (error) {
|
||||||
|
logger.debug(`dcrouter gateway client context unavailable: ${getErrorMessage(error)}`);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
return workHosterId;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildOwnership(
|
private buildOwnership(
|
||||||
@@ -304,18 +576,57 @@ export class ExternalGatewayManager {
|
|||||||
): IWorkAppRouteOwnership {
|
): IWorkAppRouteOwnership {
|
||||||
return {
|
return {
|
||||||
workHosterType: 'onebox',
|
workHosterType: 'onebox',
|
||||||
workHosterId: config.workHosterId,
|
workHosterId: config.gatewayClientId || '',
|
||||||
workAppId: service.name || `service-${service.id}`,
|
workAppId: service.name || `service-${service.id}`,
|
||||||
hostname,
|
hostname,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private buildRoute(service: IService, config: IExternalGatewayConfig): IDcRouterRouteConfig {
|
private buildGatewayClientOwnership(
|
||||||
|
service: Pick<IService, 'id' | 'name'>,
|
||||||
|
hostname: string,
|
||||||
|
config: IExternalGatewayConfig,
|
||||||
|
): IGatewayClientOwnership {
|
||||||
|
const ownership: IGatewayClientOwnership = {
|
||||||
|
gatewayClientType: config.gatewayClientType || 'onebox',
|
||||||
|
appId: service.name || `service-${service.id}`,
|
||||||
|
hostname,
|
||||||
|
};
|
||||||
|
if (config.gatewayClientId) {
|
||||||
|
ownership.gatewayClientId = config.gatewayClientId;
|
||||||
|
}
|
||||||
|
return ownership;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getAdminUiRoute(): TExternalGatewayRoute | null {
|
||||||
|
const domain = normalizeHostname(this.database.getSetting('adminUiDomain') || '');
|
||||||
|
if (!domain) return null;
|
||||||
return {
|
return {
|
||||||
name: this.routeName(service.domain!),
|
id: 0,
|
||||||
|
name: adminUiRouteName,
|
||||||
|
domain,
|
||||||
|
status: 'running',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private isAdminUiRecord(record: IGatewayDnsRecord): boolean {
|
||||||
|
const ownerName = record.serviceName || record.appId;
|
||||||
|
return ownerName === adminUiRouteName || ownerName === 'onebox';
|
||||||
|
}
|
||||||
|
|
||||||
|
private shouldPreserveUnconfiguredAdminUiRecord(record: IGatewayDnsRecord): boolean {
|
||||||
|
return this.database.getSetting('adminUiDomain') === null && this.isAdminUiRecord(record);
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildRoute(
|
||||||
|
route: TExternalGatewayRoute,
|
||||||
|
config: IExternalGatewayConfig,
|
||||||
|
): IDcRouterRouteConfig {
|
||||||
|
return {
|
||||||
|
name: this.routeName(route.domain),
|
||||||
match: {
|
match: {
|
||||||
ports: [443],
|
ports: [443],
|
||||||
domains: [service.domain!],
|
domains: [route.domain],
|
||||||
},
|
},
|
||||||
action: {
|
action: {
|
||||||
type: 'forward',
|
type: 'forward',
|
||||||
@@ -335,6 +646,11 @@ export class ExternalGatewayManager {
|
|||||||
return `onebox-${domain.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '')}`;
|
return `onebox-${domain.replace(/[^a-zA-Z0-9]+/g, '-').replace(/^-|-$/g, '')}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private buildManageUrl(config: IExternalGatewayConfig, managePath?: string): string {
|
||||||
|
const normalizedPath = managePath?.startsWith('/') ? managePath : managePath ? `/${managePath}` : '';
|
||||||
|
return `${config.url}${normalizedPath}`;
|
||||||
|
}
|
||||||
|
|
||||||
private async fireDcRouterRequest<TResponse>(
|
private async fireDcRouterRequest<TResponse>(
|
||||||
method: string,
|
method: string,
|
||||||
requestData: Record<string, unknown>,
|
requestData: Record<string, unknown>,
|
||||||
|
|||||||
@@ -0,0 +1,354 @@
|
|||||||
|
import * as plugins from '../plugins.ts';
|
||||||
|
import { logger } from '../logging.ts';
|
||||||
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
|
import { OneboxDatabase } from './database.ts';
|
||||||
|
|
||||||
|
export type TDcRouterMode = 'managed' | 'external' | 'disabled';
|
||||||
|
|
||||||
|
export interface IManagedDcRouterStatus {
|
||||||
|
mode: TDcRouterMode;
|
||||||
|
configured: boolean;
|
||||||
|
running: boolean;
|
||||||
|
healthy: boolean;
|
||||||
|
containerId?: string;
|
||||||
|
image: string;
|
||||||
|
gatewayUrl: string;
|
||||||
|
opsPort: number;
|
||||||
|
httpPort: number;
|
||||||
|
httpsPort: number;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const containerName = 'onebox-dcrouter';
|
||||||
|
const defaultImage = 'code.foss.global/serve.zone/dcrouter:latest';
|
||||||
|
const defaultDataDir = './.nogit/dcrouter-data';
|
||||||
|
const defaultOpsPort = 3300;
|
||||||
|
const defaultHttpPort = 80;
|
||||||
|
const defaultHttpsPort = 443;
|
||||||
|
const internalBaseDir = '/data';
|
||||||
|
|
||||||
|
export class ManagedDcRouterManager {
|
||||||
|
private database: OneboxDatabase;
|
||||||
|
private dockerClient: InstanceType<typeof plugins.docker.Docker> | null = null;
|
||||||
|
|
||||||
|
constructor(private oneboxRef: any) {
|
||||||
|
this.database = oneboxRef.database;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getMode(): TDcRouterMode {
|
||||||
|
const storedMode = this.database.getSetting('dcrouterMode');
|
||||||
|
if (storedMode === 'managed' || storedMode === 'external' || storedMode === 'disabled') {
|
||||||
|
return storedMode;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasExternalGateway = Boolean(this.database.getSetting('dcrouterGatewayUrl'));
|
||||||
|
return hasExternalGateway ? 'external' : 'managed';
|
||||||
|
}
|
||||||
|
|
||||||
|
public getImage(): string {
|
||||||
|
return this.database.getSetting('dcrouterManagedImage') || defaultImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getOpsPort(): number {
|
||||||
|
return this.parsePort(this.database.getSetting('dcrouterManagedOpsPort'), defaultOpsPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getHttpPort(): number {
|
||||||
|
return this.parsePort(this.database.getSetting('dcrouterManagedHttpPort'), defaultHttpPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getHttpsPort(): number {
|
||||||
|
return this.parsePort(this.database.getSetting('dcrouterManagedHttpsPort'), defaultHttpsPort);
|
||||||
|
}
|
||||||
|
|
||||||
|
public getDataDir(): string {
|
||||||
|
return this.database.getSetting('dcrouterManagedDataDir') || defaultDataDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getGatewayUrl(): string {
|
||||||
|
return `http://127.0.0.1:${this.getOpsPort()}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
public getRouteTarget(): { host: string; port: number } {
|
||||||
|
return {
|
||||||
|
host: 'onebox-smartproxy',
|
||||||
|
port: 80,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public ensureGatewayClientId(): string {
|
||||||
|
let gatewayClientId = this.database.getSetting('dcrouterGatewayClientId')
|
||||||
|
|| this.database.getSetting('dcrouterWorkHosterId');
|
||||||
|
if (!gatewayClientId) {
|
||||||
|
gatewayClientId = `onebox-${crypto.randomUUID()}`;
|
||||||
|
this.database.setSetting('dcrouterGatewayClientId', gatewayClientId);
|
||||||
|
}
|
||||||
|
return gatewayClientId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getAdminToken(): Promise<string> {
|
||||||
|
const existingToken = await this.database.getSecretSetting('dcrouterManagedAdminApiToken');
|
||||||
|
if (existingToken) {
|
||||||
|
return existingToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = `dcr_${crypto.randomUUID().replaceAll('-', '')}${crypto.randomUUID().replaceAll('-', '')}`;
|
||||||
|
await this.database.setSecretSetting('dcrouterManagedAdminApiToken', token);
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async prepareGatewaySettings(): Promise<void> {
|
||||||
|
if (this.getMode() !== 'managed') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const target = this.getRouteTarget();
|
||||||
|
this.database.setSetting('dcrouterMode', 'managed');
|
||||||
|
this.database.setSetting('dcrouterGatewayUrl', this.getGatewayUrl());
|
||||||
|
this.database.setSetting('dcrouterTargetHost', target.host);
|
||||||
|
this.database.setSetting('dcrouterTargetPort', String(target.port));
|
||||||
|
this.ensureGatewayClientId();
|
||||||
|
await this.getAdminToken();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async init(): Promise<void> {
|
||||||
|
if (this.getMode() === 'managed') {
|
||||||
|
await this.start();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.stop();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async start(options: { recreate?: boolean } = {}): Promise<IManagedDcRouterStatus> {
|
||||||
|
if (this.getMode() !== 'managed') {
|
||||||
|
throw new Error('Managed dcrouter mode is not enabled');
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.prepareGatewaySettings();
|
||||||
|
await this.ensureDockerClient();
|
||||||
|
|
||||||
|
if (options.recreate) {
|
||||||
|
await this.removeExistingContainer();
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingContainer = await this.getExistingContainer();
|
||||||
|
if (existingContainer) {
|
||||||
|
if (this.isContainerRunning(existingContainer)) {
|
||||||
|
await this.waitForReady().catch((error) => {
|
||||||
|
logger.warn(`Managed dcrouter readiness check failed: ${getErrorMessage(error)}`);
|
||||||
|
});
|
||||||
|
return await this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.startContainer(existingContainer.Id);
|
||||||
|
await this.waitForReady();
|
||||||
|
return await this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.createContainer();
|
||||||
|
await this.waitForReady();
|
||||||
|
return await this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async stop(): Promise<IManagedDcRouterStatus> {
|
||||||
|
await this.ensureDockerClient();
|
||||||
|
const existingContainer = await this.getExistingContainer();
|
||||||
|
if (existingContainer && this.isContainerRunning(existingContainer)) {
|
||||||
|
await this.stopContainer(existingContainer.Id);
|
||||||
|
}
|
||||||
|
return await this.getStatus();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async restart(): Promise<IManagedDcRouterStatus> {
|
||||||
|
return await this.start({ recreate: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getStatus(): Promise<IManagedDcRouterStatus> {
|
||||||
|
const baseStatus: IManagedDcRouterStatus = {
|
||||||
|
mode: this.getMode(),
|
||||||
|
configured: this.getMode() === 'managed',
|
||||||
|
running: false,
|
||||||
|
healthy: false,
|
||||||
|
image: this.getImage(),
|
||||||
|
gatewayUrl: this.getGatewayUrl(),
|
||||||
|
opsPort: this.getOpsPort(),
|
||||||
|
httpPort: this.getHttpPort(),
|
||||||
|
httpsPort: this.getHttpsPort(),
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.ensureDockerClient();
|
||||||
|
const existingContainer = await this.getExistingContainer();
|
||||||
|
if (!existingContainer) {
|
||||||
|
return baseStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
const running = this.isContainerRunning(existingContainer);
|
||||||
|
return {
|
||||||
|
...baseStatus,
|
||||||
|
running,
|
||||||
|
healthy: running ? await this.checkHealthy() : false,
|
||||||
|
containerId: existingContainer.Id,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
...baseStatus,
|
||||||
|
message: getErrorMessage(error),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensureDockerClient(): Promise<void> {
|
||||||
|
if (!this.dockerClient) {
|
||||||
|
this.dockerClient = new plugins.docker.Docker({
|
||||||
|
socketPath: 'unix:///var/run/docker.sock',
|
||||||
|
});
|
||||||
|
await this.dockerClient.start();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parsePort(value: string | null, fallback: number): number {
|
||||||
|
if (!value) return fallback;
|
||||||
|
const port = Number(value);
|
||||||
|
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
return port;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getAbsoluteDataDir(): Promise<string> {
|
||||||
|
const dataDir = plugins.path.resolve(this.getDataDir());
|
||||||
|
await Deno.mkdir(dataDir, { recursive: true });
|
||||||
|
return dataDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async createContainer(): Promise<void> {
|
||||||
|
const image = this.getImage();
|
||||||
|
const token = await this.getAdminToken();
|
||||||
|
const dataDir = await this.getAbsoluteDataDir();
|
||||||
|
await this.writeManagedConfig(dataDir);
|
||||||
|
|
||||||
|
await this.oneboxRef.docker.pullImage(image);
|
||||||
|
|
||||||
|
const response = await this.dockerClient!.request('POST', `/containers/create?name=${containerName}`, {
|
||||||
|
Image: image,
|
||||||
|
Env: [
|
||||||
|
`DCROUTER_BASE_DIR=${internalBaseDir}`,
|
||||||
|
`DCROUTER_CONFIG_PATH=${internalBaseDir}/managed-config.json`,
|
||||||
|
`DCROUTER_ADMIN_API_TOKEN=${token}`,
|
||||||
|
'DCROUTER_ADMIN_API_TOKEN_NAME=Onebox Managed Admin Token',
|
||||||
|
],
|
||||||
|
Labels: {
|
||||||
|
'managed-by': 'onebox',
|
||||||
|
'onebox-type': 'dcrouter',
|
||||||
|
},
|
||||||
|
ExposedPorts: {
|
||||||
|
'80/tcp': {},
|
||||||
|
'443/tcp': {},
|
||||||
|
'3000/tcp': {},
|
||||||
|
},
|
||||||
|
HostConfig: {
|
||||||
|
NetworkMode: 'onebox-network',
|
||||||
|
RestartPolicy: {
|
||||||
|
Name: 'unless-stopped',
|
||||||
|
},
|
||||||
|
Binds: [`${dataDir}:${internalBaseDir}`],
|
||||||
|
PortBindings: {
|
||||||
|
'80/tcp': [{ HostIp: '0.0.0.0', HostPort: String(this.getHttpPort()) }],
|
||||||
|
'443/tcp': [{ HostIp: '0.0.0.0', HostPort: String(this.getHttpsPort()) }],
|
||||||
|
'3000/tcp': [{ HostIp: '127.0.0.1', HostPort: String(this.getOpsPort()) }],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.statusCode >= 300) {
|
||||||
|
throw new Error(`Failed to create managed dcrouter container: HTTP ${response.statusCode} - ${JSON.stringify(response.body)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.startContainer(response.body.Id);
|
||||||
|
logger.success(`Managed dcrouter container started: ${response.body.Id}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async writeManagedConfig(dataDirArg: string): Promise<void> {
|
||||||
|
const configPath = plugins.path.join(dataDirArg, 'managed-config.json');
|
||||||
|
try {
|
||||||
|
const existingConfig = await Deno.readTextFile(configPath);
|
||||||
|
JSON.parse(existingConfig);
|
||||||
|
return;
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof Deno.errors.NotFound)) {
|
||||||
|
throw new Error(`Managed dcrouter config exists but is not valid JSON: ${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = {
|
||||||
|
smartProxyConfig: {
|
||||||
|
routes: [],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
await Deno.writeTextFile(configPath, JSON.stringify(config, null, 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getExistingContainer(): Promise<any | null> {
|
||||||
|
const filters = encodeURIComponent(JSON.stringify({ name: [containerName] }));
|
||||||
|
const response = await this.dockerClient!.request('GET', `/containers/json?all=true&filters=${filters}`, {});
|
||||||
|
if (response.statusCode >= 300 || !Array.isArray(response.body)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.body.find((container: any) => {
|
||||||
|
return container.Names?.some((name: string) => name === `/${containerName}` || name === containerName);
|
||||||
|
}) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isContainerRunning(container: any): boolean {
|
||||||
|
return container.State === 'running' || Boolean(container.Status?.toLowerCase().startsWith('up '));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async startContainer(containerId: string): Promise<void> {
|
||||||
|
const response = await this.dockerClient!.request('POST', `/containers/${containerId}/start`, {});
|
||||||
|
if (response.statusCode >= 300 && response.statusCode !== 304) {
|
||||||
|
throw new Error(`Failed to start managed dcrouter container: HTTP ${response.statusCode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async stopContainer(containerId: string): Promise<void> {
|
||||||
|
const response = await this.dockerClient!.request('POST', `/containers/${containerId}/stop`, {});
|
||||||
|
if (response.statusCode >= 300 && response.statusCode !== 304) {
|
||||||
|
throw new Error(`Failed to stop managed dcrouter container: HTTP ${response.statusCode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async removeExistingContainer(): Promise<void> {
|
||||||
|
const existingContainer = await this.getExistingContainer();
|
||||||
|
if (!existingContainer) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await this.dockerClient!.request('DELETE', `/containers/${existingContainer.Id}?force=true`, {});
|
||||||
|
if (response.statusCode >= 300) {
|
||||||
|
throw new Error(`Failed to remove managed dcrouter container: HTTP ${response.statusCode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async checkHealthy(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(this.getGatewayUrl());
|
||||||
|
return response.ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async waitForReady(maxAttempts = 30, intervalMs = 1000): Promise<void> {
|
||||||
|
for (let i = 0; i < maxAttempts; i++) {
|
||||||
|
if (await this.checkHealthy()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error('Managed dcrouter did not become ready in time');
|
||||||
|
}
|
||||||
|
}
|
||||||
+38
-3
@@ -5,6 +5,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { logger } from '../logging.ts';
|
import { logger } from '../logging.ts';
|
||||||
|
import { projectInfo } from '../info.ts';
|
||||||
import { getErrorMessage } from '../utils/error.ts';
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
import { hashPassword } from '../utils/auth.ts';
|
import { hashPassword } from '../utils/auth.ts';
|
||||||
import { OneboxDatabase } from './database.ts';
|
import { OneboxDatabase } from './database.ts';
|
||||||
@@ -25,6 +26,8 @@ import { ProxyLogReceiver } from './proxy-log-receiver.ts';
|
|||||||
import { BackupManager } from './backup-manager.ts';
|
import { BackupManager } from './backup-manager.ts';
|
||||||
import { BackupScheduler } from './backup-scheduler.ts';
|
import { BackupScheduler } from './backup-scheduler.ts';
|
||||||
import { ExternalGatewayManager } from './external-gateway.ts';
|
import { ExternalGatewayManager } from './external-gateway.ts';
|
||||||
|
import { ManagedDcRouterManager } from './managed-dcrouter.ts';
|
||||||
|
import { OneboxUpdateManager } from './update-manager.ts';
|
||||||
import { OpsServer } from '../opsserver/index.ts';
|
import { OpsServer } from '../opsserver/index.ts';
|
||||||
|
|
||||||
export class Onebox {
|
export class Onebox {
|
||||||
@@ -45,7 +48,9 @@ export class Onebox {
|
|||||||
public proxyLogReceiver: ProxyLogReceiver;
|
public proxyLogReceiver: ProxyLogReceiver;
|
||||||
public backupManager: BackupManager;
|
public backupManager: BackupManager;
|
||||||
public backupScheduler: BackupScheduler;
|
public backupScheduler: BackupScheduler;
|
||||||
|
public managedDcRouter: ManagedDcRouterManager;
|
||||||
public externalGateway: ExternalGatewayManager;
|
public externalGateway: ExternalGatewayManager;
|
||||||
|
public updateManager: OneboxUpdateManager;
|
||||||
public opsServer: OpsServer;
|
public opsServer: OpsServer;
|
||||||
|
|
||||||
private initialized = false;
|
private initialized = false;
|
||||||
@@ -88,8 +93,10 @@ export class Onebox {
|
|||||||
// Initialize Backup scheduler
|
// Initialize Backup scheduler
|
||||||
this.backupScheduler = new BackupScheduler(this);
|
this.backupScheduler = new BackupScheduler(this);
|
||||||
|
|
||||||
// Initialize optional dcrouter edge gateway integration
|
// Initialize optional dcrouter gateway integration
|
||||||
|
this.managedDcRouter = new ManagedDcRouterManager(this);
|
||||||
this.externalGateway = new ExternalGatewayManager(this);
|
this.externalGateway = new ExternalGatewayManager(this);
|
||||||
|
this.updateManager = new OneboxUpdateManager();
|
||||||
|
|
||||||
// Initialize OpsServer (TypedRequest-based server)
|
// Initialize OpsServer (TypedRequest-based server)
|
||||||
this.opsServer = new OpsServer(this);
|
this.opsServer = new OpsServer(this);
|
||||||
@@ -111,6 +118,20 @@ export class Onebox {
|
|||||||
// Initialize Docker
|
// Initialize Docker
|
||||||
await this.docker.init();
|
await this.docker.init();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.managedDcRouter.prepareGatewaySettings();
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(`Managed dcrouter settings preparation failed: ${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.managedDcRouter.getMode() !== 'managed') {
|
||||||
|
try {
|
||||||
|
await this.managedDcRouter.stop();
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(`Failed to stop inactive managed dcrouter: ${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Start proxy log receiver before reverse proxy startup.
|
// Start proxy log receiver before reverse proxy startup.
|
||||||
try {
|
try {
|
||||||
await this.proxyLogReceiver.start();
|
await this.proxyLogReceiver.start();
|
||||||
@@ -128,8 +149,9 @@ export class Onebox {
|
|||||||
// Start HTTP reverse proxy (non-critical - don't fail init if ports are busy)
|
// Start HTTP reverse proxy (non-critical - don't fail init if ports are busy)
|
||||||
// Use 8080/8443 in dev mode to avoid permission issues
|
// Use 8080/8443 in dev mode to avoid permission issues
|
||||||
const isDev = Deno.env.get('ONEBOX_DEV') === 'true' || Deno.args.includes('--ephemeral');
|
const isDev = Deno.env.get('ONEBOX_DEV') === 'true' || Deno.args.includes('--ephemeral');
|
||||||
const httpPort = isDev ? 8080 : 80;
|
const isManagedDcRouter = this.managedDcRouter.getMode() === 'managed';
|
||||||
const httpsPort = isDev ? 8443 : 443;
|
const httpPort = isDev || isManagedDcRouter ? 8080 : 80;
|
||||||
|
const httpsPort = isDev || isManagedDcRouter ? 8443 : 443;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await this.reverseProxy.startHttp(httpPort);
|
await this.reverseProxy.startHttp(httpPort);
|
||||||
@@ -165,6 +187,14 @@ export class Onebox {
|
|||||||
logger.warn('Cloudflare domain sync initialization failed - domain sync will be limited');
|
logger.warn('Cloudflare domain sync initialization failed - domain sync will be limited');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Initialize managed local dcrouter before syncing delegated routes.
|
||||||
|
try {
|
||||||
|
await this.managedDcRouter.init();
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('Managed dcrouter initialization failed - local gateway sync will be disabled');
|
||||||
|
logger.warn(`Error: ${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
|
||||||
// Initialize external dcrouter gateway (non-critical)
|
// Initialize external dcrouter gateway (non-critical)
|
||||||
try {
|
try {
|
||||||
await this.externalGateway.init();
|
await this.externalGateway.init();
|
||||||
@@ -279,6 +309,7 @@ export class Onebox {
|
|||||||
const proxyStatus = this.reverseProxy.getStatus();
|
const proxyStatus = this.reverseProxy.getStatus();
|
||||||
const dnsConfigured = this.dns.isConfigured();
|
const dnsConfigured = this.dns.isConfigured();
|
||||||
const sslConfigured = this.ssl.isConfigured();
|
const sslConfigured = this.ssl.isConfigured();
|
||||||
|
const oneboxUpdate = await this.updateManager.getUpdateStatus();
|
||||||
|
|
||||||
const services = this.services.listServices();
|
const services = this.services.listServices();
|
||||||
const runningServices = services.filter((s) => s.status === 'running').length;
|
const runningServices = services.filter((s) => s.status === 'running').length;
|
||||||
@@ -381,6 +412,10 @@ export class Onebox {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
onebox: {
|
||||||
|
version: projectInfo.version,
|
||||||
|
update: oneboxUpdate,
|
||||||
|
},
|
||||||
docker: {
|
docker: {
|
||||||
running: dockerRunning,
|
running: dockerRunning,
|
||||||
version: dockerRunning ? await this.docker.getDockerVersion() : null,
|
version: dockerRunning ? await this.docker.getDockerVersion() : null,
|
||||||
|
|||||||
@@ -10,15 +10,20 @@
|
|||||||
|
|
||||||
import { logger } from '../logging.ts';
|
import { logger } from '../logging.ts';
|
||||||
import { getErrorMessage } from '../utils/error.ts';
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
|
import { normalizeHostname } from '../utils/domain.ts';
|
||||||
import { OneboxDatabase } from './database.ts';
|
import { OneboxDatabase } from './database.ts';
|
||||||
import { SmartProxyManager } from './smartproxy.ts';
|
import { SmartProxyManager } from './smartproxy.ts';
|
||||||
|
|
||||||
|
const adminUiRouteName = 'onebox-admin-ui';
|
||||||
|
const adminUiPort = 3000;
|
||||||
|
|
||||||
interface IProxyRoute {
|
interface IProxyRoute {
|
||||||
domain: string;
|
domain: string;
|
||||||
targetHost: string;
|
targetHost: string;
|
||||||
targetPort: number;
|
targetPort: number;
|
||||||
serviceId: number;
|
serviceId?: number;
|
||||||
serviceName?: string;
|
serviceName?: string;
|
||||||
|
routeType: 'service' | 'admin-ui';
|
||||||
}
|
}
|
||||||
|
|
||||||
export class OneboxReverseProxy {
|
export class OneboxReverseProxy {
|
||||||
@@ -112,6 +117,7 @@ export class OneboxReverseProxy {
|
|||||||
targetPort,
|
targetPort,
|
||||||
serviceId,
|
serviceId,
|
||||||
serviceName,
|
serviceName,
|
||||||
|
routeType: 'service',
|
||||||
};
|
};
|
||||||
|
|
||||||
this.routes.set(domain, route);
|
this.routes.set(domain, route);
|
||||||
@@ -127,6 +133,25 @@ export class OneboxReverseProxy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async addAdminUiRoute(domain: string): Promise<void> {
|
||||||
|
const normalizedDomain = normalizeHostname(domain);
|
||||||
|
if (!normalizedDomain) return;
|
||||||
|
|
||||||
|
const targetHost = this.getAdminUiTargetHost();
|
||||||
|
const route: IProxyRoute = {
|
||||||
|
domain: normalizedDomain,
|
||||||
|
targetHost,
|
||||||
|
targetPort: adminUiPort,
|
||||||
|
serviceName: adminUiRouteName,
|
||||||
|
routeType: 'admin-ui',
|
||||||
|
};
|
||||||
|
|
||||||
|
this.routes.set(normalizedDomain, route);
|
||||||
|
const upstream = `${targetHost}:${adminUiPort}`;
|
||||||
|
await this.smartProxy.addRoute(normalizedDomain, upstream);
|
||||||
|
logger.success(`Added Admin UI proxy route: ${normalizedDomain} -> ${upstream}`);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Remove a route
|
* Remove a route
|
||||||
*/
|
*/
|
||||||
@@ -166,6 +191,11 @@ export class OneboxReverseProxy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const adminUiDomain = this.getAdminUiDomain();
|
||||||
|
if (adminUiDomain) {
|
||||||
|
await this.addAdminUiRoute(adminUiDomain);
|
||||||
|
}
|
||||||
|
|
||||||
logger.success(`Loaded ${this.routes.size} proxy routes`);
|
logger.success(`Loaded ${this.routes.size} proxy routes`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Failed to reload routes: ${getErrorMessage(error)}`);
|
logger.error(`Failed to reload routes: ${getErrorMessage(error)}`);
|
||||||
@@ -173,6 +203,18 @@ export class OneboxReverseProxy {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getAdminUiDomain(): string {
|
||||||
|
return normalizeHostname(this.database.getSetting('adminUiDomain') || '');
|
||||||
|
}
|
||||||
|
|
||||||
|
private getAdminUiTargetHost(): string {
|
||||||
|
const serverIP = this.database.getSetting('serverIP');
|
||||||
|
if (!serverIP) {
|
||||||
|
logger.warn('serverIP is not configured; Admin UI proxy route will use host.docker.internal');
|
||||||
|
}
|
||||||
|
return serverIP || 'host.docker.internal';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Add TLS certificate for a domain
|
* Add TLS certificate for a domain
|
||||||
* Sends PEM content to SmartProxy via Admin API
|
* Sends PEM content to SmartProxy via Admin API
|
||||||
|
|||||||
+55
-1
@@ -11,6 +11,26 @@ import { OneboxDatabase } from './database.ts';
|
|||||||
import { OneboxDockerManager } from './docker.ts';
|
import { OneboxDockerManager } from './docker.ts';
|
||||||
import type { PlatformServicesManager } from './platform-services/index.ts';
|
import type { PlatformServicesManager } from './platform-services/index.ts';
|
||||||
|
|
||||||
|
export type TServiceUpdateProgressStep =
|
||||||
|
| 'stopping'
|
||||||
|
| 'pulling-image'
|
||||||
|
| 'updating-record'
|
||||||
|
| 'removing-container'
|
||||||
|
| 'creating-container'
|
||||||
|
| 'starting'
|
||||||
|
| 'restoring-route'
|
||||||
|
| 'syncing-gateway'
|
||||||
|
| 'complete';
|
||||||
|
|
||||||
|
export interface IServiceUpdateProgress {
|
||||||
|
step: TServiceUpdateProgressStep;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IServiceUpdateOptions {
|
||||||
|
onProgress?: (progressArg: IServiceUpdateProgress) => void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
export class OneboxServicesManager {
|
export class OneboxServicesManager {
|
||||||
private oneboxRef: any; // Will be Onebox instance
|
private oneboxRef: any; // Will be Onebox instance
|
||||||
private database: OneboxDatabase;
|
private database: OneboxDatabase;
|
||||||
@@ -95,6 +115,8 @@ export class OneboxServicesManager {
|
|||||||
image: options.useOneboxRegistry ? imageToPull : options.image,
|
image: options.useOneboxRegistry ? imageToPull : options.image,
|
||||||
registry: options.registry,
|
registry: options.registry,
|
||||||
envVars: options.envVars || {},
|
envVars: options.envVars || {},
|
||||||
|
volumes: options.volumes || [],
|
||||||
|
publishedPorts: options.publishedPorts || [],
|
||||||
port: options.port,
|
port: options.port,
|
||||||
domain: options.domain,
|
domain: options.domain,
|
||||||
status: 'stopped',
|
status: 'stopped',
|
||||||
@@ -105,6 +127,7 @@ export class OneboxServicesManager {
|
|||||||
registryRepository: options.useOneboxRegistry ? options.name : undefined,
|
registryRepository: options.useOneboxRegistry ? options.name : undefined,
|
||||||
registryImageTag: options.registryImageTag || 'latest',
|
registryImageTag: options.registryImageTag || 'latest',
|
||||||
autoUpdateOnPush: options.autoUpdateOnPush,
|
autoUpdateOnPush: options.autoUpdateOnPush,
|
||||||
|
imageDigest: options.imageDigest,
|
||||||
// Platform requirements
|
// Platform requirements
|
||||||
platformRequirements,
|
platformRequirements,
|
||||||
// App Store template tracking
|
// App Store template tracking
|
||||||
@@ -578,9 +601,17 @@ export class OneboxServicesManager {
|
|||||||
port?: number;
|
port?: number;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
envVars?: Record<string, string>;
|
envVars?: Record<string, string>;
|
||||||
}
|
volumes?: IService['volumes'];
|
||||||
|
publishedPorts?: IService['publishedPorts'];
|
||||||
|
imageDigest?: string;
|
||||||
|
appTemplateVersion?: string;
|
||||||
|
},
|
||||||
|
optionsArg: IServiceUpdateOptions = {},
|
||||||
): Promise<IService> {
|
): Promise<IService> {
|
||||||
try {
|
try {
|
||||||
|
const emitProgress = async (step: TServiceUpdateProgressStep, message: string) => {
|
||||||
|
await optionsArg.onProgress?.({ step, message });
|
||||||
|
};
|
||||||
const service = this.database.getServiceByName(name);
|
const service = this.database.getServiceByName(name);
|
||||||
if (!service) {
|
if (!service) {
|
||||||
throw new Error(`Service not found: ${name}`);
|
throw new Error(`Service not found: ${name}`);
|
||||||
@@ -594,6 +625,7 @@ export class OneboxServicesManager {
|
|||||||
// Stop the container if running
|
// Stop the container if running
|
||||||
if (wasRunning && oldContainerID) {
|
if (wasRunning && oldContainerID) {
|
||||||
logger.info(`Stopping service ${name} for updates...`);
|
logger.info(`Stopping service ${name} for updates...`);
|
||||||
|
await emitProgress('stopping', `Stopping ${name} before updating its container`);
|
||||||
try {
|
try {
|
||||||
await this.docker.stopContainer(oldContainerID);
|
await this.docker.stopContainer(oldContainerID);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -604,10 +636,12 @@ export class OneboxServicesManager {
|
|||||||
// Pull new image if changed
|
// Pull new image if changed
|
||||||
if (updates.image && updates.image !== service.image) {
|
if (updates.image && updates.image !== service.image) {
|
||||||
logger.info(`Pulling new image: ${updates.image}`);
|
logger.info(`Pulling new image: ${updates.image}`);
|
||||||
|
await emitProgress('pulling-image', `Pulling image ${updates.image}`);
|
||||||
await this.docker.pullImage(updates.image, updates.registry || service.registry);
|
await this.docker.pullImage(updates.image, updates.registry || service.registry);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update service in database
|
// Update service in database
|
||||||
|
await emitProgress('updating-record', `Updating service record for ${name}`);
|
||||||
const updateData: any = {
|
const updateData: any = {
|
||||||
updatedAt: Date.now(),
|
updatedAt: Date.now(),
|
||||||
};
|
};
|
||||||
@@ -616,6 +650,10 @@ export class OneboxServicesManager {
|
|||||||
if (updates.port !== undefined) updateData.port = updates.port;
|
if (updates.port !== undefined) updateData.port = updates.port;
|
||||||
if (updates.domain !== undefined) updateData.domain = updates.domain;
|
if (updates.domain !== undefined) updateData.domain = updates.domain;
|
||||||
if (updates.envVars !== undefined) updateData.envVars = updates.envVars;
|
if (updates.envVars !== undefined) updateData.envVars = updates.envVars;
|
||||||
|
if (updates.volumes !== undefined) updateData.volumes = updates.volumes;
|
||||||
|
if (updates.publishedPorts !== undefined) updateData.publishedPorts = updates.publishedPorts;
|
||||||
|
if (updates.imageDigest !== undefined) updateData.imageDigest = updates.imageDigest;
|
||||||
|
if (updates.appTemplateVersion !== undefined) updateData.appTemplateVersion = updates.appTemplateVersion;
|
||||||
|
|
||||||
this.database.updateService(service.id!, updateData);
|
this.database.updateService(service.id!, updateData);
|
||||||
|
|
||||||
@@ -624,6 +662,7 @@ export class OneboxServicesManager {
|
|||||||
|
|
||||||
// Remove old container
|
// Remove old container
|
||||||
if (oldContainerID) {
|
if (oldContainerID) {
|
||||||
|
await emitProgress('removing-container', `Removing old container for ${name}`);
|
||||||
try {
|
try {
|
||||||
await this.docker.removeContainer(oldContainerID, true);
|
await this.docker.removeContainer(oldContainerID, true);
|
||||||
logger.info(`Removed old container for ${name}`);
|
logger.info(`Removed old container for ${name}`);
|
||||||
@@ -634,6 +673,7 @@ export class OneboxServicesManager {
|
|||||||
|
|
||||||
// Create new container with updated config
|
// Create new container with updated config
|
||||||
logger.info(`Creating new container for ${name}...`);
|
logger.info(`Creating new container for ${name}...`);
|
||||||
|
await emitProgress('creating-container', `Creating replacement container for ${name}`);
|
||||||
const containerID = await this.docker.createContainer(updatedService);
|
const containerID = await this.docker.createContainer(updatedService);
|
||||||
this.database.updateService(service.id!, { containerID });
|
this.database.updateService(service.id!, { containerID });
|
||||||
|
|
||||||
@@ -667,6 +707,7 @@ export class OneboxServicesManager {
|
|||||||
// Restart the container if it was running
|
// Restart the container if it was running
|
||||||
if (wasRunning) {
|
if (wasRunning) {
|
||||||
logger.info(`Starting updated service ${name}...`);
|
logger.info(`Starting updated service ${name}...`);
|
||||||
|
await emitProgress('starting', `Starting updated service ${name}`);
|
||||||
this.database.updateService(service.id!, { status: 'starting' });
|
this.database.updateService(service.id!, { status: 'starting' });
|
||||||
await this.docker.startContainer(containerID);
|
await this.docker.startContainer(containerID);
|
||||||
this.database.updateService(service.id!, { status: 'running' });
|
this.database.updateService(service.id!, { status: 'running' });
|
||||||
@@ -678,8 +719,21 @@ export class OneboxServicesManager {
|
|||||||
|
|
||||||
const refreshedService = this.database.getServiceByName(name)!;
|
const refreshedService = this.database.getServiceByName(name)!;
|
||||||
if (refreshedService.domain && refreshedService.status === 'running') {
|
if (refreshedService.domain && refreshedService.status === 'running') {
|
||||||
|
await emitProgress('restoring-route', `Restoring route ${refreshedService.domain} -> ${refreshedService.port}`);
|
||||||
|
try {
|
||||||
|
await this.oneboxRef.reverseProxy.addRoute(
|
||||||
|
refreshedService.id!,
|
||||||
|
refreshedService.domain,
|
||||||
|
refreshedService.port,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn(`Failed to restore reverse proxy route for ${refreshedService.domain}: ${getErrorMessage(error)}`);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
await emitProgress('syncing-gateway', `Syncing external gateway route for ${refreshedService.domain}`);
|
||||||
await this.syncExternalGatewayRoute(refreshedService);
|
await this.syncExternalGatewayRoute(refreshedService);
|
||||||
}
|
}
|
||||||
|
await emitProgress('complete', `Service ${name} update completed`);
|
||||||
await this.broadcastServiceUpdate(name, 'updated');
|
await this.broadcastServiceUpdate(name, 'updated');
|
||||||
return refreshedService;
|
return refreshedService;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ import { logger } from '../logging.ts';
|
|||||||
import { getErrorMessage } from '../utils/error.ts';
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
|
|
||||||
const SMARTPROXY_SERVICE_NAME = 'onebox-smartproxy';
|
const SMARTPROXY_SERVICE_NAME = 'onebox-smartproxy';
|
||||||
const LEGACY_CADDY_SERVICE_NAME = 'onebox-caddy';
|
const LEGACY_REVERSE_PROXY_SERVICE_NAME = 'onebox-caddy';
|
||||||
const SMARTPROXY_IMAGE = 'code.foss.global/host.today/ht-docker-smartproxy:latest';
|
const SMARTPROXY_IMAGE = 'code.foss.global/host.today/ht-docker-smartproxy:latest';
|
||||||
const SMARTPROXY_ADMIN_CONTAINER_PORT = 3000;
|
const SMARTPROXY_ADMIN_CONTAINER_PORT = 3000;
|
||||||
const SMARTPROXY_HTTP_CONTAINER_PORT = 80;
|
const SMARTPROXY_HTTP_CONTAINER_PORT = 80;
|
||||||
@@ -102,10 +102,12 @@ export class SmartProxyManager {
|
|||||||
|
|
||||||
logger.info('Starting SmartProxy Docker service...');
|
logger.info('Starting SmartProxy Docker service...');
|
||||||
|
|
||||||
const legacyService = await this.getExistingService(LEGACY_CADDY_SERVICE_NAME);
|
const legacyService = await this.getExistingService(LEGACY_REVERSE_PROXY_SERVICE_NAME);
|
||||||
if (legacyService) {
|
if (legacyService) {
|
||||||
logger.info('Legacy Caddy service exists, removing it before SmartProxy startup...');
|
logger.info(
|
||||||
await this.removeService(LEGACY_CADDY_SERVICE_NAME);
|
`Legacy reverse proxy service ${LEGACY_REVERSE_PROXY_SERVICE_NAME} exists, removing it before SmartProxy startup...`,
|
||||||
|
);
|
||||||
|
await this.removeService(LEGACY_REVERSE_PROXY_SERVICE_NAME);
|
||||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,11 +177,13 @@ export class SmartProxyManager {
|
|||||||
throw new Error(`Failed to create SmartProxy service: HTTP ${response.statusCode} - ${JSON.stringify(response.body)}`);
|
throw new Error(`Failed to create SmartProxy service: HTTP ${response.statusCode} - ${JSON.stringify(response.body)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(`SmartProxy service created: ${response.body.ID}`);
|
const serviceId = response.body.ID;
|
||||||
|
logger.info(`SmartProxy service created: ${serviceId}`);
|
||||||
|
|
||||||
|
await this.waitForServiceTaskRunning(serviceId);
|
||||||
await this.waitForReady();
|
await this.waitForReady();
|
||||||
this.serviceRunning = true;
|
this.serviceRunning = true;
|
||||||
await this.reloadConfig();
|
await this.reloadConfig({ skipRunningCheck: true });
|
||||||
|
|
||||||
logger.success(`SmartProxy started (HTTP: ${this.httpPort}, HTTPS: ${this.httpsPort}, Admin: ${this.adminUrl})`);
|
logger.success(`SmartProxy started (HTTP: ${this.httpPort}, HTTPS: ${this.httpsPort}, Admin: ${this.adminUrl})`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -232,6 +236,37 @@ export class SmartProxyManager {
|
|||||||
throw new Error('SmartProxy service failed to start within timeout');
|
throw new Error('SmartProxy service failed to start within timeout');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async waitForServiceTaskRunning(
|
||||||
|
serviceIdArg: string,
|
||||||
|
maxAttempts = 30,
|
||||||
|
intervalMs = 1000,
|
||||||
|
): Promise<void> {
|
||||||
|
let lastState = 'unknown';
|
||||||
|
|
||||||
|
for (let i = 0; i < maxAttempts; i++) {
|
||||||
|
const tasksResponse = await this.dockerClient!.request(
|
||||||
|
'GET',
|
||||||
|
`/tasks?filters=${encodeURIComponent(JSON.stringify({ service: [serviceIdArg] }))}`,
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
|
||||||
|
if (tasksResponse.statusCode === 200 && Array.isArray(tasksResponse.body)) {
|
||||||
|
const tasks = tasksResponse.body;
|
||||||
|
const runningTask = tasks.find((task: any) => task.Status?.State === 'running');
|
||||||
|
if (runningTask) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const latestTask = tasks[0];
|
||||||
|
lastState = latestTask?.Status?.State || lastState;
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, intervalMs));
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`SmartProxy service task did not reach running state (last state: ${lastState})`);
|
||||||
|
}
|
||||||
|
|
||||||
async stop(): Promise<void> {
|
async stop(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
await this.ensureDockerClient();
|
await this.ensureDockerClient();
|
||||||
@@ -360,12 +395,14 @@ export class SmartProxyManager {
|
|||||||
return routeConfigs;
|
return routeConfigs;
|
||||||
}
|
}
|
||||||
|
|
||||||
async reloadConfig(): Promise<void> {
|
async reloadConfig(options: { skipRunningCheck?: boolean } = {}): Promise<void> {
|
||||||
|
if (!options.skipRunningCheck) {
|
||||||
const isRunning = await this.isRunning();
|
const isRunning = await this.isRunning();
|
||||||
if (!isRunning) {
|
if (!isRunning) {
|
||||||
logger.warn('SmartProxy not running, cannot reload config');
|
logger.warn('SmartProxy not running, cannot reload config');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const routes = this.buildRoutes();
|
const routes = this.buildRoutes();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,234 @@
|
|||||||
|
import { logger } from '../logging.ts';
|
||||||
|
import { projectInfo } from '../info.ts';
|
||||||
|
import { getErrorMessage } from '../utils/error.ts';
|
||||||
|
import * as interfaces from '../../ts_interfaces/index.ts';
|
||||||
|
|
||||||
|
const ONEBOX_REPOSITORY_URL = 'https://code.foss.global/serve.zone/onebox';
|
||||||
|
const ONEBOX_LATEST_RELEASE_API_URL =
|
||||||
|
'https://code.foss.global/api/v1/repos/serve.zone/onebox/releases/latest';
|
||||||
|
const ONEBOX_INSTALL_SCRIPT_URL = `${ONEBOX_REPOSITORY_URL}/raw/branch/main/install.sh`;
|
||||||
|
const ONEBOX_CHANGELOG_URL = `${ONEBOX_REPOSITORY_URL}/src/branch/main/changelog.md`;
|
||||||
|
const UPGRADE_LOG_PATH = '/var/log/onebox-upgrade.log';
|
||||||
|
|
||||||
|
interface IGiteaReleaseResponse {
|
||||||
|
tag_name?: unknown;
|
||||||
|
html_url?: unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IParsedRelease {
|
||||||
|
tagName: string;
|
||||||
|
releaseUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class OneboxUpdateManager {
|
||||||
|
private cachedStatus: interfaces.data.IOneboxUpdateStatus | null = null;
|
||||||
|
private cachedStatusExpiresAt = 0;
|
||||||
|
private upgradeStartedAt = 0;
|
||||||
|
private readonly statusCacheTtlMs = 5 * 60 * 1000;
|
||||||
|
|
||||||
|
public async getUpdateStatus(
|
||||||
|
optionsArg: { force?: boolean } = {},
|
||||||
|
): Promise<interfaces.data.IOneboxUpdateStatus> {
|
||||||
|
const now = Date.now();
|
||||||
|
if (!optionsArg.force && this.cachedStatus && this.cachedStatusExpiresAt > now) {
|
||||||
|
return this.cachedStatus;
|
||||||
|
}
|
||||||
|
|
||||||
|
const status = await this.fetchUpdateStatus();
|
||||||
|
this.cachedStatus = status;
|
||||||
|
this.cachedStatusExpiresAt = now + this.statusCacheTtlMs;
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async startDetachedUpgrade(): Promise<interfaces.data.IOneboxUpgradeStartResult> {
|
||||||
|
this.assertRoot();
|
||||||
|
|
||||||
|
const status = await this.getUpdateStatus({ force: true });
|
||||||
|
this.assertUpdateCheckSucceeded(status);
|
||||||
|
|
||||||
|
const targetVersion = status.latestVersion || status.currentVersion;
|
||||||
|
if (!status.updateAvailable) {
|
||||||
|
return {
|
||||||
|
accepted: false,
|
||||||
|
currentVersion: status.currentVersion,
|
||||||
|
targetVersion,
|
||||||
|
message: 'Onebox is already up to date.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.upgradeStartedAt && Date.now() - this.upgradeStartedAt < 10 * 60 * 1000) {
|
||||||
|
return {
|
||||||
|
accepted: false,
|
||||||
|
currentVersion: status.currentVersion,
|
||||||
|
targetVersion,
|
||||||
|
message: 'A Onebox upgrade has already been started.',
|
||||||
|
logPath: UPGRADE_LOG_PATH,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const unitName = `onebox-upgrade-${Date.now()}`;
|
||||||
|
const command = new Deno.Command('systemd-run', {
|
||||||
|
args: [
|
||||||
|
'--unit',
|
||||||
|
unitName,
|
||||||
|
'--description',
|
||||||
|
`Onebox upgrade to ${targetVersion}`,
|
||||||
|
'--collect',
|
||||||
|
'--property=Type=oneshot',
|
||||||
|
'--setenv=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
|
||||||
|
'bash',
|
||||||
|
'-lc',
|
||||||
|
this.createDetachedUpgradeScript(),
|
||||||
|
],
|
||||||
|
stdin: 'null',
|
||||||
|
stdout: 'piped',
|
||||||
|
stderr: 'piped',
|
||||||
|
});
|
||||||
|
const result = await command.output();
|
||||||
|
if (!result.success) {
|
||||||
|
const stderr = new TextDecoder().decode(result.stderr).trim();
|
||||||
|
const stdout = new TextDecoder().decode(result.stdout).trim();
|
||||||
|
throw new Error(
|
||||||
|
`Failed to start Onebox upgrade systemd unit: ${
|
||||||
|
stderr || stdout || `exit code ${result.code}`
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.upgradeStartedAt = Date.now();
|
||||||
|
|
||||||
|
logger.info(`Started Onebox upgrade systemd unit ${unitName}`);
|
||||||
|
return {
|
||||||
|
accepted: true,
|
||||||
|
currentVersion: status.currentVersion,
|
||||||
|
targetVersion,
|
||||||
|
message: 'Onebox upgrade started. The service will restart automatically.',
|
||||||
|
unitName,
|
||||||
|
logPath: UPGRADE_LOG_PATH,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async runUpgradeForeground(
|
||||||
|
statusArg?: interfaces.data.IOneboxUpdateStatus,
|
||||||
|
): Promise<interfaces.data.IOneboxUpgradeStartResult> {
|
||||||
|
this.assertRoot();
|
||||||
|
|
||||||
|
const status = statusArg || (await this.getUpdateStatus({ force: true }));
|
||||||
|
this.assertUpdateCheckSucceeded(status);
|
||||||
|
|
||||||
|
const targetVersion = status.latestVersion || status.currentVersion;
|
||||||
|
if (!status.updateAvailable) {
|
||||||
|
return {
|
||||||
|
accepted: false,
|
||||||
|
currentVersion: status.currentVersion,
|
||||||
|
targetVersion,
|
||||||
|
message: 'Onebox is already up to date.',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const installCommand = new Deno.Command('bash', {
|
||||||
|
args: ['-c', `set -o pipefail; curl -fsSL ${ONEBOX_INSTALL_SCRIPT_URL} | bash`],
|
||||||
|
stdin: 'inherit',
|
||||||
|
stdout: 'inherit',
|
||||||
|
stderr: 'inherit',
|
||||||
|
});
|
||||||
|
const installResult = await installCommand.output();
|
||||||
|
if (!installResult.success) {
|
||||||
|
throw new Error('Upgrade failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
accepted: true,
|
||||||
|
currentVersion: status.currentVersion,
|
||||||
|
targetVersion,
|
||||||
|
message: `Upgraded to ${targetVersion}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchUpdateStatus(): Promise<interfaces.data.IOneboxUpdateStatus> {
|
||||||
|
const currentVersion = this.normalizeVersion(projectInfo.version);
|
||||||
|
const checkedAt = Date.now();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const release = await this.fetchLatestRelease();
|
||||||
|
const latestVersion = this.normalizeVersion(release.tagName);
|
||||||
|
return {
|
||||||
|
currentVersion,
|
||||||
|
latestVersion,
|
||||||
|
updateAvailable: currentVersion !== latestVersion,
|
||||||
|
checkedAt,
|
||||||
|
releaseUrl: release.releaseUrl,
|
||||||
|
changelogUrl: ONEBOX_CHANGELOG_URL,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
currentVersion,
|
||||||
|
latestVersion: null,
|
||||||
|
updateAvailable: false,
|
||||||
|
checkedAt,
|
||||||
|
releaseUrl: `${ONEBOX_REPOSITORY_URL}/releases`,
|
||||||
|
changelogUrl: ONEBOX_CHANGELOG_URL,
|
||||||
|
error: getErrorMessage(error),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchLatestRelease(): Promise<IParsedRelease> {
|
||||||
|
const abortController = new AbortController();
|
||||||
|
const timeoutId = setTimeout(() => abortController.abort(), 5000);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(ONEBOX_LATEST_RELEASE_API_URL, {
|
||||||
|
headers: { accept: 'application/json' },
|
||||||
|
signal: abortController.signal,
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Failed to fetch latest release: HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const release = await response.json() as IGiteaReleaseResponse;
|
||||||
|
if (typeof release.tag_name !== 'string' || !release.tag_name) {
|
||||||
|
throw new Error('Latest release response does not include a tag name');
|
||||||
|
}
|
||||||
|
|
||||||
|
const tagName = release.tag_name;
|
||||||
|
const releaseUrl = typeof release.html_url === 'string' && release.html_url
|
||||||
|
? release.html_url
|
||||||
|
: `${ONEBOX_REPOSITORY_URL}/releases/tag/${this.normalizeVersion(tagName)}`;
|
||||||
|
|
||||||
|
return { tagName, releaseUrl };
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertRoot(): void {
|
||||||
|
if (Deno.uid() !== 0) {
|
||||||
|
throw new Error('Onebox upgrades must be started as root. Try: sudo onebox upgrade');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private assertUpdateCheckSucceeded(statusArg: interfaces.data.IOneboxUpdateStatus): void {
|
||||||
|
if (statusArg.error) {
|
||||||
|
throw new Error(`Cannot determine latest Onebox release: ${statusArg.error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeVersion(versionArg: string): string {
|
||||||
|
const trimmedVersion = versionArg.trim();
|
||||||
|
return trimmedVersion.startsWith('v') ? trimmedVersion : `v${trimmedVersion}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private createDetachedUpgradeScript(): string {
|
||||||
|
return `
|
||||||
|
set -e
|
||||||
|
set -o pipefail
|
||||||
|
mkdir -p /var/log
|
||||||
|
{
|
||||||
|
echo "==== Onebox upgrade started $(date -Is) ===="
|
||||||
|
sleep 2
|
||||||
|
curl -fsSL ${ONEBOX_INSTALL_SCRIPT_URL} | bash
|
||||||
|
echo "==== Onebox upgrade finished $(date -Is) ===="
|
||||||
|
} >> ${UPGRADE_LOG_PATH} 2>&1
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,7 +8,10 @@ import { getErrorMessage } from './utils/error.ts';
|
|||||||
import { Onebox } from './classes/onebox.ts';
|
import { Onebox } from './classes/onebox.ts';
|
||||||
import { OneboxDaemon } from './classes/daemon.ts';
|
import { OneboxDaemon } from './classes/daemon.ts';
|
||||||
import { OneboxSystemd } from './classes/systemd.ts';
|
import { OneboxSystemd } from './classes/systemd.ts';
|
||||||
import type { IAppVersionConfig } from './classes/appstore-types.ts';
|
import { OneboxUpdateManager } from './classes/update-manager.ts';
|
||||||
|
import type * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||||
|
|
||||||
|
type IAppStoreVersionConfig = servezoneInterfaces.appstore.IAppStoreVersionConfig;
|
||||||
|
|
||||||
export async function runCli(): Promise<void> {
|
export async function runCli(): Promise<void> {
|
||||||
const args = Deno.args;
|
const args = Deno.args;
|
||||||
@@ -214,33 +217,25 @@ async function handleAppStoreCommand(onebox: Onebox, subcommand: string, args: s
|
|||||||
|
|
||||||
const appMeta = await onebox.appStore.getAppMeta(appId);
|
const appMeta = await onebox.appStore.getAppMeta(appId);
|
||||||
const version = getArg(args, '--version') || appMeta.latestVersion;
|
const version = getArg(args, '--version') || appMeta.latestVersion;
|
||||||
const config = await onebox.appStore.getAppVersionConfig(appId, version);
|
|
||||||
const serviceName = getArg(args, '--name') || appId;
|
const serviceName = getArg(args, '--name') || appId;
|
||||||
const domain = getArg(args, '--domain');
|
const domain = getArg(args, '--domain');
|
||||||
const port = parseInt(getArg(args, '--port') || String(config.port), 10);
|
const portArg = getArg(args, '--port');
|
||||||
const envVars = getAppStoreEnvVars(config, parseEnvArgs(args));
|
const port = portArg ? parseInt(portArg, 10) : undefined;
|
||||||
const autoDNS = getBooleanArg(args, '--auto-dns', true);
|
const autoDNS = getBooleanArg(args, '--auto-dns', true);
|
||||||
|
|
||||||
requireValue(serviceName, '--name');
|
requireValue(serviceName, '--name');
|
||||||
|
if (port !== undefined) {
|
||||||
assertValidPort(port, '--port');
|
assertValidPort(port, '--port');
|
||||||
if (requiresTemplateValue(envVars, 'SERVICE_DOMAIN')) {
|
|
||||||
requireValue(domain, '--domain');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const service = await onebox.services.deployService({
|
const service = await onebox.appStore.installApp({
|
||||||
name: serviceName,
|
appId,
|
||||||
image: config.image,
|
version,
|
||||||
port,
|
serviceName,
|
||||||
domain,
|
domain,
|
||||||
|
port,
|
||||||
autoDNS,
|
autoDNS,
|
||||||
envVars,
|
envVars: parseEnvArgs(args),
|
||||||
enableMongoDB: Boolean(config.platformRequirements?.mongodb),
|
|
||||||
enableS3: Boolean(config.platformRequirements?.s3),
|
|
||||||
enableClickHouse: Boolean(config.platformRequirements?.clickhouse),
|
|
||||||
enableRedis: Boolean(config.platformRequirements?.redis),
|
|
||||||
enableMariaDB: Boolean(config.platformRequirements?.mariadb),
|
|
||||||
appTemplateId: appId,
|
|
||||||
appTemplateVersion: version,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.success(`Installed ${appMeta.name} ${version} as ${service.name}`);
|
logger.success(`Installed ${appMeta.name} ${version} as ${service.name}`);
|
||||||
@@ -508,60 +503,29 @@ async function handleUpgradeCommand(): Promise<void> {
|
|||||||
logger.info('Checking for updates...');
|
logger.info('Checking for updates...');
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Get current version
|
const updateManager = new OneboxUpdateManager();
|
||||||
const currentVersion = projectInfo.version;
|
const status = await updateManager.getUpdateStatus({ force: true });
|
||||||
|
if (status.error) {
|
||||||
|
throw new Error(status.error);
|
||||||
|
}
|
||||||
|
|
||||||
// Fetch latest version from Gitea API
|
console.log(` Current version: ${status.currentVersion}`);
|
||||||
const apiUrl = 'https://code.foss.global/api/v1/repos/serve.zone/onebox/releases/latest';
|
console.log(` Latest version: ${status.latestVersion}`);
|
||||||
const curlCmd = new Deno.Command('curl', {
|
|
||||||
args: ['-sSL', apiUrl],
|
|
||||||
stdout: 'piped',
|
|
||||||
stderr: 'piped',
|
|
||||||
});
|
|
||||||
const curlResult = await curlCmd.output();
|
|
||||||
const response = new TextDecoder().decode(curlResult.stdout);
|
|
||||||
const release = JSON.parse(response);
|
|
||||||
const latestVersion = release.tag_name as string; // e.g., "v1.11.0"
|
|
||||||
|
|
||||||
// Normalize versions for comparison (ensure both have "v" prefix)
|
|
||||||
const normalizedCurrent = currentVersion.startsWith('v')
|
|
||||||
? currentVersion
|
|
||||||
: `v${currentVersion}`;
|
|
||||||
const normalizedLatest = latestVersion.startsWith('v')
|
|
||||||
? latestVersion
|
|
||||||
: `v${latestVersion}`;
|
|
||||||
|
|
||||||
console.log(` Current version: ${normalizedCurrent}`);
|
|
||||||
console.log(` Latest version: ${normalizedLatest}`);
|
|
||||||
console.log('');
|
console.log('');
|
||||||
|
|
||||||
// Compare normalized versions
|
if (!status.updateAvailable) {
|
||||||
if (normalizedCurrent === normalizedLatest) {
|
|
||||||
logger.success('Already up to date!');
|
logger.success('Already up to date!');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.info(`New version available: ${latestVersion}`);
|
logger.info(`New version available: ${status.latestVersion}`);
|
||||||
logger.info('Downloading and installing...');
|
logger.info('Downloading and installing...');
|
||||||
console.log('');
|
console.log('');
|
||||||
|
|
||||||
// Download and run the install script
|
const upgrade = await updateManager.runUpgradeForeground(status);
|
||||||
const installUrl = 'https://code.foss.global/serve.zone/onebox/raw/branch/main/install.sh';
|
|
||||||
const installCmd = new Deno.Command('bash', {
|
|
||||||
args: ['-c', `curl -sSL ${installUrl} | bash`],
|
|
||||||
stdin: 'inherit',
|
|
||||||
stdout: 'inherit',
|
|
||||||
stderr: 'inherit',
|
|
||||||
});
|
|
||||||
const installResult = await installCmd.output();
|
|
||||||
|
|
||||||
if (!installResult.success) {
|
|
||||||
logger.error('Upgrade failed');
|
|
||||||
Deno.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('');
|
console.log('');
|
||||||
logger.success(`Upgraded to ${latestVersion}`);
|
logger.success(upgrade.message);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error(`Upgrade failed: ${getErrorMessage(error)}`);
|
logger.error(`Upgrade failed: ${getErrorMessage(error)}`);
|
||||||
Deno.exit(1);
|
Deno.exit(1);
|
||||||
@@ -629,7 +593,7 @@ function parseEnvArgs(args: string[]): Record<string, string> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function getAppStoreEnvVars(
|
function getAppStoreEnvVars(
|
||||||
configArg: IAppVersionConfig,
|
configArg: IAppStoreVersionConfig,
|
||||||
overridesArg: Record<string, string>,
|
overridesArg: Record<string, string>,
|
||||||
): Record<string, string> {
|
): Record<string, string> {
|
||||||
const envVars: Record<string, string> = {};
|
const envVars: Record<string, string> = {};
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import type { TQueryFunction } from '../types.ts';
|
|||||||
|
|
||||||
export class Migration015SmartProxyPlatformService extends BaseMigration {
|
export class Migration015SmartProxyPlatformService extends BaseMigration {
|
||||||
readonly version = 15;
|
readonly version = 15;
|
||||||
readonly description = 'Rename Caddy platform service to SmartProxy';
|
readonly description = 'Rename legacy reverse proxy platform service to SmartProxy';
|
||||||
|
|
||||||
up(query: TQueryFunction): void {
|
up(query: TQueryFunction): void {
|
||||||
query(
|
query(
|
||||||
|
|||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { BaseMigration } from './base-migration.ts';
|
||||||
|
import type { TQueryFunction } from '../types.ts';
|
||||||
|
|
||||||
|
export class Migration016ServiceVolumes extends BaseMigration {
|
||||||
|
readonly version = 16;
|
||||||
|
readonly description = 'Add persistent volume declarations to services';
|
||||||
|
|
||||||
|
up(query: TQueryFunction): void {
|
||||||
|
query(`ALTER TABLE services ADD COLUMN volumes TEXT DEFAULT '[]'`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { BaseMigration } from './base-migration.ts';
|
||||||
|
import type { TQueryFunction } from '../types.ts';
|
||||||
|
|
||||||
|
export class Migration017ServicePublishedPorts extends BaseMigration {
|
||||||
|
readonly version = 17;
|
||||||
|
readonly description = 'Add raw published port declarations to services';
|
||||||
|
|
||||||
|
up(query: TQueryFunction): void {
|
||||||
|
query(`ALTER TABLE services ADD COLUMN published_ports TEXT DEFAULT '[]'`);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -22,6 +22,8 @@ import { Migration012GfsRetention } from './migration-012-gfs-retention.ts';
|
|||||||
import { Migration013AppTemplateVersion } from './migration-013-app-template-version.ts';
|
import { Migration013AppTemplateVersion } from './migration-013-app-template-version.ts';
|
||||||
import { Migration014ContainerArchive } from './migration-014-containerarchive.ts';
|
import { Migration014ContainerArchive } from './migration-014-containerarchive.ts';
|
||||||
import { Migration015SmartProxyPlatformService } from './migration-015-smartproxy-platform-service.ts';
|
import { Migration015SmartProxyPlatformService } from './migration-015-smartproxy-platform-service.ts';
|
||||||
|
import { Migration016ServiceVolumes } from './migration-016-service-volumes.ts';
|
||||||
|
import { Migration017ServicePublishedPorts } from './migration-017-service-published-ports.ts';
|
||||||
import type { BaseMigration } from './base-migration.ts';
|
import type { BaseMigration } from './base-migration.ts';
|
||||||
|
|
||||||
export class MigrationRunner {
|
export class MigrationRunner {
|
||||||
@@ -48,6 +50,8 @@ export class MigrationRunner {
|
|||||||
new Migration013AppTemplateVersion(),
|
new Migration013AppTemplateVersion(),
|
||||||
new Migration014ContainerArchive(),
|
new Migration014ContainerArchive(),
|
||||||
new Migration015SmartProxyPlatformService(),
|
new Migration015SmartProxyPlatformService(),
|
||||||
|
new Migration016ServiceVolumes(),
|
||||||
|
new Migration017ServicePublishedPorts(),
|
||||||
].sort((a, b) => a.version - b.version);
|
].sort((a, b) => a.version - b.version);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,17 +14,19 @@ export class ServiceRepository extends BaseRepository {
|
|||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
this.query(
|
this.query(
|
||||||
`INSERT INTO services (
|
`INSERT INTO services (
|
||||||
name, image, registry, env_vars, port, domain, container_id, status,
|
name, image, registry, env_vars, volumes, published_ports, port, domain, container_id, status,
|
||||||
created_at, updated_at,
|
created_at, updated_at,
|
||||||
use_onebox_registry, registry_repository, registry_image_tag,
|
use_onebox_registry, registry_repository, registry_image_tag,
|
||||||
auto_update_on_push, image_digest, platform_requirements,
|
auto_update_on_push, image_digest, platform_requirements,
|
||||||
app_template_id, app_template_version
|
app_template_id, app_template_version
|
||||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||||
[
|
[
|
||||||
service.name,
|
service.name,
|
||||||
service.image,
|
service.image,
|
||||||
service.registry || null,
|
service.registry || null,
|
||||||
JSON.stringify(service.envVars),
|
JSON.stringify(service.envVars),
|
||||||
|
JSON.stringify(service.volumes || []),
|
||||||
|
JSON.stringify(service.publishedPorts || []),
|
||||||
service.port,
|
service.port,
|
||||||
service.domain || null,
|
service.domain || null,
|
||||||
service.containerID || null,
|
service.containerID || null,
|
||||||
@@ -82,6 +84,14 @@ export class ServiceRepository extends BaseRepository {
|
|||||||
fields.push('env_vars = ?');
|
fields.push('env_vars = ?');
|
||||||
values.push(JSON.stringify(updates.envVars));
|
values.push(JSON.stringify(updates.envVars));
|
||||||
}
|
}
|
||||||
|
if (updates.volumes !== undefined) {
|
||||||
|
fields.push('volumes = ?');
|
||||||
|
values.push(JSON.stringify(updates.volumes));
|
||||||
|
}
|
||||||
|
if (updates.publishedPorts !== undefined) {
|
||||||
|
fields.push('published_ports = ?');
|
||||||
|
values.push(JSON.stringify(updates.publishedPorts));
|
||||||
|
}
|
||||||
if (updates.port !== undefined) {
|
if (updates.port !== undefined) {
|
||||||
fields.push('port = ?');
|
fields.push('port = ?');
|
||||||
values.push(updates.port);
|
values.push(updates.port);
|
||||||
@@ -169,18 +179,42 @@ export class ServiceRepository extends BaseRepository {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let volumes = [];
|
||||||
|
const volumesRaw = row.volumes ?? row[20];
|
||||||
|
if (volumesRaw && volumesRaw !== 'undefined' && volumesRaw !== 'null') {
|
||||||
|
try {
|
||||||
|
volumes = JSON.parse(String(volumesRaw));
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn(`Failed to parse volumes for service: ${getErrorMessage(e)}`);
|
||||||
|
volumes = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let publishedPorts = [];
|
||||||
|
const publishedPortsRaw = row.published_ports;
|
||||||
|
if (publishedPortsRaw && publishedPortsRaw !== 'undefined' && publishedPortsRaw !== 'null') {
|
||||||
|
try {
|
||||||
|
publishedPorts = JSON.parse(String(publishedPortsRaw));
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn(`Failed to parse published_ports for service: ${getErrorMessage(e)}`);
|
||||||
|
publishedPorts = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: Number(row.id || row[0]),
|
id: Number(row.id || row[0]),
|
||||||
name: String(row.name || row[1]),
|
name: String(row.name || row[1]),
|
||||||
image: String(row.image || row[2]),
|
image: String(row.image || row[2]),
|
||||||
registry: (row.registry || row[3]) ? String(row.registry || row[3]) : undefined,
|
registry: (row.registry || row[3]) ? String(row.registry || row[3]) : undefined,
|
||||||
envVars,
|
envVars,
|
||||||
port: Number(row.port || row[5]),
|
volumes,
|
||||||
domain: (row.domain || row[6]) ? String(row.domain || row[6]) : undefined,
|
publishedPorts,
|
||||||
containerID: (row.container_id || row[7]) ? String(row.container_id || row[7]) : undefined,
|
port: Number(row.port ?? row[6] ?? row[5]),
|
||||||
status: String(row.status || row[8]) as IService['status'],
|
domain: (row.domain ?? row[7] ?? row[6]) ? String(row.domain ?? row[7] ?? row[6]) : undefined,
|
||||||
createdAt: Number(row.created_at || row[9]),
|
containerID: (row.container_id ?? row[8] ?? row[7]) ? String(row.container_id ?? row[8] ?? row[7]) : undefined,
|
||||||
updatedAt: Number(row.updated_at || row[10]),
|
status: String(row.status ?? row[9] ?? row[8]) as IService['status'],
|
||||||
|
createdAt: Number(row.created_at ?? row[10] ?? row[9]),
|
||||||
|
updatedAt: Number(row.updated_at ?? row[11] ?? row[10]),
|
||||||
useOneboxRegistry: row.use_onebox_registry ? Boolean(row.use_onebox_registry) : undefined,
|
useOneboxRegistry: row.use_onebox_registry ? Boolean(row.use_onebox_registry) : undefined,
|
||||||
registryRepository: row.registry_repository ? String(row.registry_repository) : undefined,
|
registryRepository: row.registry_repository ? String(row.registry_repository) : undefined,
|
||||||
registryImageTag: row.registry_image_tag ? String(row.registry_image_tag) : undefined,
|
registryImageTag: row.registry_image_tag ? String(row.registry_image_tag) : undefined,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ const secretSettingAliases = {
|
|||||||
backupPassword: ['backup_encryption_password'],
|
backupPassword: ['backup_encryption_password'],
|
||||||
cloudflareToken: ['cloudflareAPIKey'],
|
cloudflareToken: ['cloudflareAPIKey'],
|
||||||
dcrouterGatewayApiToken: ['externalGatewayApiToken'],
|
dcrouterGatewayApiToken: ['externalGatewayApiToken'],
|
||||||
|
dcrouterManagedAdminApiToken: [],
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
type TCanonicalSecretSettingKey = keyof typeof secretSettingAliases;
|
type TCanonicalSecretSettingKey = keyof typeof secretSettingAliases;
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ export class OpsServer {
|
|||||||
public backupsHandler!: handlers.BackupsHandler;
|
public backupsHandler!: handlers.BackupsHandler;
|
||||||
public schedulesHandler!: handlers.SchedulesHandler;
|
public schedulesHandler!: handlers.SchedulesHandler;
|
||||||
public settingsHandler!: handlers.SettingsHandler;
|
public settingsHandler!: handlers.SettingsHandler;
|
||||||
|
public managedDcRouterHandler!: handlers.ManagedDcRouterHandler;
|
||||||
public logsHandler!: handlers.LogsHandler;
|
public logsHandler!: handlers.LogsHandler;
|
||||||
public workspaceHandler!: handlers.WorkspaceHandler;
|
public workspaceHandler!: handlers.WorkspaceHandler;
|
||||||
public appStoreHandler!: handlers.AppStoreHandler;
|
public appStoreHandler!: handlers.AppStoreHandler;
|
||||||
@@ -66,6 +67,7 @@ export class OpsServer {
|
|||||||
this.backupsHandler = new handlers.BackupsHandler(this);
|
this.backupsHandler = new handlers.BackupsHandler(this);
|
||||||
this.schedulesHandler = new handlers.SchedulesHandler(this);
|
this.schedulesHandler = new handlers.SchedulesHandler(this);
|
||||||
this.settingsHandler = new handlers.SettingsHandler(this);
|
this.settingsHandler = new handlers.SettingsHandler(this);
|
||||||
|
this.managedDcRouterHandler = new handlers.ManagedDcRouterHandler(this);
|
||||||
this.logsHandler = new handlers.LogsHandler(this);
|
this.logsHandler = new handlers.LogsHandler(this);
|
||||||
this.workspaceHandler = new handlers.WorkspaceHandler(this);
|
this.workspaceHandler = new handlers.WorkspaceHandler(this);
|
||||||
this.appStoreHandler = new handlers.AppStoreHandler(this);
|
this.appStoreHandler = new handlers.AppStoreHandler(this);
|
||||||
|
|||||||
@@ -3,20 +3,209 @@ import { logger } from '../../logging.ts';
|
|||||||
import type { OpsServer } from '../classes.opsserver.ts';
|
import type { OpsServer } from '../classes.opsserver.ts';
|
||||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||||
|
import { getErrorMessage } from '../../utils/error.ts';
|
||||||
|
|
||||||
|
type IAppStoreUpgradeOperation = interfaces.requests.IAppStoreUpgradeOperation;
|
||||||
|
type TAppStoreUpgradeStep = interfaces.requests.TAppStoreUpgradeStep;
|
||||||
|
|
||||||
export class AppStoreHandler {
|
export class AppStoreHandler {
|
||||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||||
|
private upgradeOperations = new Map<string, IAppStoreUpgradeOperation>();
|
||||||
|
|
||||||
constructor(private opsServerRef: OpsServer) {
|
constructor(private opsServerRef: OpsServer) {
|
||||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||||
this.registerHandlers();
|
this.registerHandlers();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private getUpgradeOperations(): IAppStoreUpgradeOperation[] {
|
||||||
|
return Array.from(this.upgradeOperations.values())
|
||||||
|
.sort((a, b) => b.startedAt - a.startedAt)
|
||||||
|
.slice(0, 25);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getRunningUpgrade(serviceNameArg: string): IAppStoreUpgradeOperation | null {
|
||||||
|
for (const operation of this.upgradeOperations.values()) {
|
||||||
|
if (operation.serviceName === serviceNameArg && operation.status === 'running') {
|
||||||
|
return operation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async createUpgradeOperation(
|
||||||
|
serviceNameArg: string,
|
||||||
|
targetVersionArg: string,
|
||||||
|
): Promise<IAppStoreUpgradeOperation> {
|
||||||
|
const existingRunning = this.getRunningUpgrade(serviceNameArg);
|
||||||
|
if (existingRunning) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError(
|
||||||
|
`An upgrade is already running for ${serviceNameArg}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(serviceNameArg);
|
||||||
|
if (!existingService) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError(`Service not found: ${serviceNameArg}`);
|
||||||
|
}
|
||||||
|
if (!existingService.appTemplateId) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError('Service was not deployed from an app template');
|
||||||
|
}
|
||||||
|
if (!existingService.appTemplateVersion) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError('Service has no tracked template version');
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const operation: IAppStoreUpgradeOperation = {
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
serviceName: existingService.name,
|
||||||
|
appTemplateId: existingService.appTemplateId,
|
||||||
|
fromVersion: existingService.appTemplateVersion,
|
||||||
|
targetVersion: targetVersionArg,
|
||||||
|
status: 'running',
|
||||||
|
step: 'queued',
|
||||||
|
progressLines: [`Queued upgrade ${existingService.appTemplateVersion} -> ${targetVersionArg}`],
|
||||||
|
warnings: [],
|
||||||
|
startedAt: now,
|
||||||
|
updatedAt: now,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.upgradeOperations.set(operation.id, operation);
|
||||||
|
await this.pushUpgradeProgress(operation);
|
||||||
|
return operation;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updateUpgradeOperation(
|
||||||
|
operationIdArg: string,
|
||||||
|
stepArg: TAppStoreUpgradeStep,
|
||||||
|
messageArg: string,
|
||||||
|
updatesArg: Partial<IAppStoreUpgradeOperation> = {},
|
||||||
|
): Promise<IAppStoreUpgradeOperation> {
|
||||||
|
const existing = this.upgradeOperations.get(operationIdArg);
|
||||||
|
if (!existing) {
|
||||||
|
throw new Error(`Upgrade operation not found: ${operationIdArg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextOperation: IAppStoreUpgradeOperation = {
|
||||||
|
...existing,
|
||||||
|
...updatesArg,
|
||||||
|
step: stepArg,
|
||||||
|
updatedAt: Date.now(),
|
||||||
|
progressLines: [...existing.progressLines, messageArg].slice(-200),
|
||||||
|
};
|
||||||
|
this.upgradeOperations.set(operationIdArg, nextOperation);
|
||||||
|
await this.pushUpgradeProgress(nextOperation);
|
||||||
|
return nextOperation;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pushUpgradeProgress(operationArg: IAppStoreUpgradeOperation): Promise<void> {
|
||||||
|
await this.opsServerRef.pushDashboardEvent('pushAppStoreUpgradeProgress', {
|
||||||
|
operation: operationArg,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async performUpgrade(operationIdArg: string): Promise<interfaces.data.IService> {
|
||||||
|
let operation = this.upgradeOperations.get(operationIdArg);
|
||||||
|
if (!operation) {
|
||||||
|
throw new Error(`Upgrade operation not found: ${operationIdArg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
operation = await this.updateUpgradeOperation(
|
||||||
|
operation.id,
|
||||||
|
'validating',
|
||||||
|
`Validating ${operation.serviceName} for App Store upgrade`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(operation.serviceName);
|
||||||
|
if (!existingService) {
|
||||||
|
throw new Error(`Service not found: ${operation.serviceName}`);
|
||||||
|
}
|
||||||
|
if (!existingService.appTemplateId || !existingService.appTemplateVersion) {
|
||||||
|
throw new Error('Service is missing App Store template metadata');
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(
|
||||||
|
`Upgrading service '${operation.serviceName}' from v${operation.fromVersion} to v${operation.targetVersion}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.updateUpgradeOperation(
|
||||||
|
operation.id,
|
||||||
|
'migration',
|
||||||
|
`Resolving migration for ${operation.appTemplateId} ${operation.fromVersion} -> ${operation.targetVersion}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const migrationResult = await this.opsServerRef.oneboxRef.appStore.executeMigration(
|
||||||
|
existingService,
|
||||||
|
operation.fromVersion,
|
||||||
|
operation.targetVersion,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!migrationResult.success) {
|
||||||
|
throw new Error(`Migration failed: ${migrationResult.warnings.join('; ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (migrationResult.warnings.length > 0) {
|
||||||
|
operation = await this.updateUpgradeOperation(
|
||||||
|
operation.id,
|
||||||
|
'migration',
|
||||||
|
`Migration completed with ${migrationResult.warnings.length} warning(s)`,
|
||||||
|
{ warnings: migrationResult.warnings },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.updateUpgradeOperation(
|
||||||
|
operation.id,
|
||||||
|
'applying',
|
||||||
|
`Applying upgrade to ${operation.serviceName}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const updatedService = await this.opsServerRef.oneboxRef.appStore.applyUpgrade(
|
||||||
|
operation.serviceName,
|
||||||
|
migrationResult,
|
||||||
|
operation.targetVersion,
|
||||||
|
{
|
||||||
|
onProgress: async (progressArg) => {
|
||||||
|
await this.updateUpgradeOperation(
|
||||||
|
operation!.id,
|
||||||
|
progressArg.step as TAppStoreUpgradeStep,
|
||||||
|
progressArg.message,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
await this.updateUpgradeOperation(
|
||||||
|
operation.id,
|
||||||
|
'complete',
|
||||||
|
`Upgrade completed for ${operation.serviceName}`,
|
||||||
|
{
|
||||||
|
status: 'success',
|
||||||
|
completedAt: Date.now(),
|
||||||
|
service: updatedService,
|
||||||
|
warnings: migrationResult.warnings,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
return updatedService;
|
||||||
|
} catch (error) {
|
||||||
|
await this.updateUpgradeOperation(
|
||||||
|
operation.id,
|
||||||
|
'failed',
|
||||||
|
`Upgrade failed: ${getErrorMessage(error)}`,
|
||||||
|
{
|
||||||
|
status: 'failed',
|
||||||
|
completedAt: Date.now(),
|
||||||
|
error: getErrorMessage(error),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private registerHandlers(): void {
|
private registerHandlers(): void {
|
||||||
// Get app templates (catalog)
|
|
||||||
this.typedrouter.addTypedHandler(
|
this.typedrouter.addTypedHandler(
|
||||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppTemplates>(
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreTemplates>(
|
||||||
'getAppTemplates',
|
'getAppStoreTemplates',
|
||||||
async (dataArg) => {
|
async (dataArg) => {
|
||||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
const apps = await this.opsServerRef.oneboxRef.appStore.getApps();
|
const apps = await this.opsServerRef.oneboxRef.appStore.getApps();
|
||||||
@@ -25,10 +214,9 @@ export class AppStoreHandler {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Get app config for a specific version
|
|
||||||
this.typedrouter.addTypedHandler(
|
this.typedrouter.addTypedHandler(
|
||||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppConfig>(
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreConfig>(
|
||||||
'getAppConfig',
|
'getAppStoreConfig',
|
||||||
async (dataArg) => {
|
async (dataArg) => {
|
||||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
const config = await this.opsServerRef.oneboxRef.appStore.getAppVersionConfig(
|
const config = await this.opsServerRef.oneboxRef.appStore.getAppVersionConfig(
|
||||||
@@ -41,64 +229,65 @@ export class AppStoreHandler {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Get services with available upgrades
|
|
||||||
this.typedrouter.addTypedHandler(
|
this.typedrouter.addTypedHandler(
|
||||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetUpgradeableServices>(
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_InstallAppStoreApp>(
|
||||||
'getUpgradeableServices',
|
'installAppStoreApp',
|
||||||
async (dataArg) => {
|
async (dataArg) => {
|
||||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
const services = await this.opsServerRef.oneboxRef.appStore.getUpgradeableServices();
|
const service = await this.opsServerRef.oneboxRef.appStore.installApp(dataArg.install);
|
||||||
|
return { service };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetUpgradeableAppStoreServices>(
|
||||||
|
'getUpgradeableAppStoreServices',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const services = await this.opsServerRef.oneboxRef.appStore.getUpgradeableAppStoreServices();
|
||||||
return { services };
|
return { services };
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
// Upgrade a service to a new template version
|
|
||||||
this.typedrouter.addTypedHandler(
|
this.typedrouter.addTypedHandler(
|
||||||
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpgradeService>(
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_UpgradeAppStoreService>(
|
||||||
'upgradeService',
|
'upgradeAppStoreService',
|
||||||
async (dataArg) => {
|
async (dataArg) => {
|
||||||
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const operation = await this.createUpgradeOperation(dataArg.serviceName, dataArg.targetVersion);
|
||||||
const existingService = this.opsServerRef.oneboxRef.database.getServiceByName(dataArg.serviceName);
|
const updatedService = await this.performUpgrade(operation.id);
|
||||||
if (!existingService) {
|
const completedOperation = this.upgradeOperations.get(operation.id)!;
|
||||||
throw new plugins.typedrequest.TypedResponseError(`Service not found: ${dataArg.serviceName}`);
|
|
||||||
}
|
|
||||||
if (!existingService.appTemplateId) {
|
|
||||||
throw new plugins.typedrequest.TypedResponseError('Service was not deployed from an app template');
|
|
||||||
}
|
|
||||||
if (!existingService.appTemplateVersion) {
|
|
||||||
throw new plugins.typedrequest.TypedResponseError('Service has no tracked template version');
|
|
||||||
}
|
|
||||||
|
|
||||||
logger.info(`Upgrading service '${dataArg.serviceName}' from v${existingService.appTemplateVersion} to v${dataArg.targetVersion}`);
|
|
||||||
|
|
||||||
// Execute migration
|
|
||||||
const migrationResult = await this.opsServerRef.oneboxRef.appStore.executeMigration(
|
|
||||||
existingService,
|
|
||||||
existingService.appTemplateVersion,
|
|
||||||
dataArg.targetVersion,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!migrationResult.success) {
|
|
||||||
throw new plugins.typedrequest.TypedResponseError(
|
|
||||||
`Migration failed: ${migrationResult.warnings.join('; ')}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Apply the upgrade
|
|
||||||
const updatedService = await this.opsServerRef.oneboxRef.appStore.applyUpgrade(
|
|
||||||
dataArg.serviceName,
|
|
||||||
migrationResult,
|
|
||||||
dataArg.targetVersion,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
service: updatedService,
|
service: updatedService,
|
||||||
warnings: migrationResult.warnings,
|
warnings: completedOperation.warnings,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StartAppStoreServiceUpgrade>(
|
||||||
|
'startAppStoreServiceUpgrade',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const operation = await this.createUpgradeOperation(dataArg.serviceName, dataArg.targetVersion);
|
||||||
|
void this.performUpgrade(operation.id).catch(() => {});
|
||||||
|
return { operation };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetAppStoreUpgradeOperations>(
|
||||||
|
'getAppStoreUpgradeOperations',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
return { operations: this.getUpgradeOperations() };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -61,5 +61,16 @@ export class DnsHandler {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetGatewayDnsRecords>(
|
||||||
|
'getGatewayDnsRecords',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const records = await this.opsServerRef.oneboxRef.externalGateway.getGatewayDnsRecords();
|
||||||
|
return { records };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -97,5 +97,16 @@ export class DomainsHandler {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetGatewayDomains>(
|
||||||
|
'getGatewayDomains',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const domains = await this.opsServerRef.oneboxRef.externalGateway.getGatewayDomains();
|
||||||
|
return { domains };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export * from './network.handler.ts';
|
|||||||
export * from './backups.handler.ts';
|
export * from './backups.handler.ts';
|
||||||
export * from './schedules.handler.ts';
|
export * from './schedules.handler.ts';
|
||||||
export * from './settings.handler.ts';
|
export * from './settings.handler.ts';
|
||||||
|
export * from './managed-dcrouter.handler.ts';
|
||||||
export * from './logs.handler.ts';
|
export * from './logs.handler.ts';
|
||||||
export * from './workspace.handler.ts';
|
export * from './workspace.handler.ts';
|
||||||
export * from './appstore.handler.ts';
|
export * from './appstore.handler.ts';
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import * as plugins from '../../plugins.ts';
|
||||||
|
import type { OpsServer } from '../classes.opsserver.ts';
|
||||||
|
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||||
|
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||||
|
|
||||||
|
export class ManagedDcRouterHandler {
|
||||||
|
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||||
|
|
||||||
|
constructor(private opsServerRef: OpsServer) {
|
||||||
|
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||||
|
this.registerHandlers();
|
||||||
|
}
|
||||||
|
|
||||||
|
private registerHandlers(): void {
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_GetManagedDcRouterStatus>(
|
||||||
|
'getManagedDcRouterStatus',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const status = await this.opsServerRef.oneboxRef.managedDcRouter.getStatus();
|
||||||
|
return { status };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StartManagedDcRouter>(
|
||||||
|
'startManagedDcRouter',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const status = await this.opsServerRef.oneboxRef.managedDcRouter.start();
|
||||||
|
return { status };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StopManagedDcRouter>(
|
||||||
|
'stopManagedDcRouter',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const status = await this.opsServerRef.oneboxRef.managedDcRouter.stop();
|
||||||
|
return { status };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_RestartManagedDcRouter>(
|
||||||
|
'restartManagedDcRouter',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const status = await this.opsServerRef.oneboxRef.managedDcRouter.restart();
|
||||||
|
return { status };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import * as interfaces from '../../../ts_interfaces/index.ts';
|
|||||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||||
import { logger } from '../../logging.ts';
|
import { logger } from '../../logging.ts';
|
||||||
import { getErrorMessage } from '../../utils/error.ts';
|
import { getErrorMessage } from '../../utils/error.ts';
|
||||||
|
import { isValidHostname, normalizeHostname } from '../../utils/domain.ts';
|
||||||
|
|
||||||
export class SettingsHandler {
|
export class SettingsHandler {
|
||||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||||
@@ -18,13 +19,22 @@ export class SettingsHandler {
|
|||||||
const cloudflareToken = await db.getSecretSetting('cloudflareToken');
|
const cloudflareToken = await db.getSecretSetting('cloudflareToken');
|
||||||
const dcrouterGatewayApiToken = await db.getSecretSetting('dcrouterGatewayApiToken');
|
const dcrouterGatewayApiToken = await db.getSecretSetting('dcrouterGatewayApiToken');
|
||||||
const settingsMap = db.getAllSettings();
|
const settingsMap = db.getAllSettings();
|
||||||
|
const managedDcRouter = this.opsServerRef.oneboxRef.managedDcRouter;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
cloudflareToken: cloudflareToken || '',
|
cloudflareToken: cloudflareToken || '',
|
||||||
cloudflareZoneId: settingsMap['cloudflareZoneId'] || '',
|
cloudflareZoneId: settingsMap['cloudflareZoneId'] || '',
|
||||||
|
adminUiDomain: settingsMap['adminUiDomain'] || '',
|
||||||
|
dcrouterMode: managedDcRouter.getMode(),
|
||||||
|
dcrouterManagedImage: managedDcRouter.getImage(),
|
||||||
|
dcrouterManagedOpsPort: managedDcRouter.getOpsPort(),
|
||||||
|
dcrouterManagedHttpPort: managedDcRouter.getHttpPort(),
|
||||||
|
dcrouterManagedHttpsPort: managedDcRouter.getHttpsPort(),
|
||||||
|
dcrouterManagedDataDir: managedDcRouter.getDataDir(),
|
||||||
dcrouterGatewayUrl: settingsMap['dcrouterGatewayUrl'] || '',
|
dcrouterGatewayUrl: settingsMap['dcrouterGatewayUrl'] || '',
|
||||||
dcrouterGatewayApiToken: dcrouterGatewayApiToken || '',
|
dcrouterGatewayApiToken: dcrouterGatewayApiToken || '',
|
||||||
dcrouterWorkHosterId: settingsMap['dcrouterWorkHosterId'] || '',
|
dcrouterGatewayClientId: settingsMap['dcrouterGatewayClientId'] || settingsMap['dcrouterWorkHosterId'] || '',
|
||||||
|
dcrouterWorkHosterId: settingsMap['dcrouterWorkHosterId'] || settingsMap['dcrouterGatewayClientId'] || '',
|
||||||
dcrouterTargetHost: settingsMap['dcrouterTargetHost'] || '',
|
dcrouterTargetHost: settingsMap['dcrouterTargetHost'] || '',
|
||||||
dcrouterTargetPort: parseInt(settingsMap['dcrouterTargetPort'] || '0', 10),
|
dcrouterTargetPort: parseInt(settingsMap['dcrouterTargetPort'] || '0', 10),
|
||||||
autoRenewCerts: settingsMap['autoRenewCerts'] === 'true',
|
autoRenewCerts: settingsMap['autoRenewCerts'] === 'true',
|
||||||
@@ -56,8 +66,10 @@ export class SettingsHandler {
|
|||||||
const db = this.opsServerRef.oneboxRef.database;
|
const db = this.opsServerRef.oneboxRef.database;
|
||||||
const updates = dataArg.settings;
|
const updates = dataArg.settings;
|
||||||
|
|
||||||
|
const normalizedUpdates = this.normalizeUpdates(updates);
|
||||||
|
|
||||||
// Store each setting as key-value pair
|
// Store each setting as key-value pair
|
||||||
for (const [key, value] of Object.entries(updates)) {
|
for (const [key, value] of Object.entries(normalizedUpdates)) {
|
||||||
if (value !== undefined) {
|
if (value !== undefined) {
|
||||||
if (db.isSecretSettingKey(key)) {
|
if (db.isSecretSettingKey(key)) {
|
||||||
await db.setSecretSetting(key, String(value));
|
await db.setSecretSetting(key, String(value));
|
||||||
@@ -67,9 +79,9 @@ export class SettingsHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.hasExternalGatewaySetting(updates)) {
|
if (this.hasRouteSyncSetting(normalizedUpdates)) {
|
||||||
this.refreshExternalGateway().catch((error) => {
|
this.refreshGatewayRoutes(normalizedUpdates).catch((error) => {
|
||||||
logger.warn(`External gateway settings refresh failed: ${getErrorMessage(error)}`);
|
logger.warn(`dcrouter gateway settings refresh failed: ${getErrorMessage(error)}`);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -102,27 +114,61 @@ export class SettingsHandler {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
private hasExternalGatewaySetting(settings: Partial<interfaces.data.ISettings>): boolean {
|
private normalizeUpdates(
|
||||||
|
settings: Partial<interfaces.data.ISettings>,
|
||||||
|
): Partial<interfaces.data.ISettings> {
|
||||||
|
const normalizedUpdates = { ...settings };
|
||||||
|
if (Object.prototype.hasOwnProperty.call(normalizedUpdates, 'adminUiDomain')) {
|
||||||
|
const normalizedDomain = normalizeHostname(String(normalizedUpdates.adminUiDomain || ''));
|
||||||
|
if (!isValidHostname(normalizedDomain)) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError('Invalid Admin UI domain');
|
||||||
|
}
|
||||||
|
normalizedUpdates.adminUiDomain = normalizedDomain;
|
||||||
|
}
|
||||||
|
return normalizedUpdates;
|
||||||
|
}
|
||||||
|
|
||||||
|
private hasRouteSyncSetting(settings: Partial<interfaces.data.ISettings>): boolean {
|
||||||
return [
|
return [
|
||||||
|
'adminUiDomain',
|
||||||
|
'dcrouterMode',
|
||||||
|
'dcrouterManagedImage',
|
||||||
|
'dcrouterManagedOpsPort',
|
||||||
|
'dcrouterManagedHttpPort',
|
||||||
|
'dcrouterManagedHttpsPort',
|
||||||
|
'dcrouterManagedDataDir',
|
||||||
'dcrouterGatewayUrl',
|
'dcrouterGatewayUrl',
|
||||||
'dcrouterGatewayApiToken',
|
'dcrouterGatewayApiToken',
|
||||||
|
'dcrouterGatewayClientId',
|
||||||
'dcrouterWorkHosterId',
|
'dcrouterWorkHosterId',
|
||||||
'dcrouterTargetHost',
|
'dcrouterTargetHost',
|
||||||
'dcrouterTargetPort',
|
'dcrouterTargetPort',
|
||||||
].some((key) => Object.prototype.hasOwnProperty.call(settings, key));
|
].some((key) => Object.prototype.hasOwnProperty.call(settings, key));
|
||||||
}
|
}
|
||||||
|
|
||||||
private async refreshExternalGateway(): Promise<void> {
|
private hasManagedDcRouterRuntimeSetting(settings: Partial<interfaces.data.ISettings>): boolean {
|
||||||
const onebox = this.opsServerRef.oneboxRef;
|
return [
|
||||||
await onebox.externalGateway.syncDomains();
|
'dcrouterMode',
|
||||||
|
'dcrouterManagedImage',
|
||||||
|
'dcrouterManagedOpsPort',
|
||||||
|
'dcrouterManagedHttpPort',
|
||||||
|
'dcrouterManagedHttpsPort',
|
||||||
|
'dcrouterManagedDataDir',
|
||||||
|
].some((key) => Object.prototype.hasOwnProperty.call(settings, key));
|
||||||
|
}
|
||||||
|
|
||||||
const services = onebox.database.getAllServices().filter((service) => service.domain);
|
private async refreshGatewayRoutes(settings: Partial<interfaces.data.ISettings>): Promise<void> {
|
||||||
await Promise.all(services.map(async (service) => {
|
const onebox = this.opsServerRef.oneboxRef;
|
||||||
try {
|
if (this.hasManagedDcRouterRuntimeSetting(settings)) {
|
||||||
await onebox.externalGateway.syncServiceRoute(service);
|
if (onebox.managedDcRouter.getMode() === 'managed') {
|
||||||
} catch (error) {
|
await onebox.managedDcRouter.restart();
|
||||||
logger.warn(`Failed to sync external gateway route for ${service.domain}: ${getErrorMessage(error)}`);
|
} else {
|
||||||
}
|
await onebox.managedDcRouter.stop();
|
||||||
}));
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await onebox.reverseProxy.reloadRoutes();
|
||||||
|
await onebox.externalGateway.syncDomains();
|
||||||
|
await onebox.externalGateway.syncServiceRoutes();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import * as plugins from '../../plugins.ts';
|
|||||||
import type { OpsServer } from '../classes.opsserver.ts';
|
import type { OpsServer } from '../classes.opsserver.ts';
|
||||||
import * as interfaces from '../../../ts_interfaces/index.ts';
|
import * as interfaces from '../../../ts_interfaces/index.ts';
|
||||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||||
|
import { getErrorMessage } from '../../utils/error.ts';
|
||||||
|
|
||||||
export class StatusHandler {
|
export class StatusHandler {
|
||||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||||
@@ -22,5 +23,20 @@ export class StatusHandler {
|
|||||||
},
|
},
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_StartOneboxUpgrade>(
|
||||||
|
'startOneboxUpgrade',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
try {
|
||||||
|
const upgrade = await this.opsServerRef.oneboxRef.updateManager.startDetachedUpgrade();
|
||||||
|
return { upgrade };
|
||||||
|
} catch (error) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError(getErrorMessage(error));
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,21 @@ import * as interfaces from '../../../ts_interfaces/index.ts';
|
|||||||
import { requireAdminIdentity } from '../helpers/guards.ts';
|
import { requireAdminIdentity } from '../helpers/guards.ts';
|
||||||
import { getErrorMessage } from '../../utils/error.ts';
|
import { getErrorMessage } from '../../utils/error.ts';
|
||||||
|
|
||||||
|
interface IWorkspaceProcessSession {
|
||||||
|
processId: string;
|
||||||
|
serviceName: string;
|
||||||
|
userId: string;
|
||||||
|
stream: plugins.nodeStream.Duplex;
|
||||||
|
close: () => Promise<void>;
|
||||||
|
inspect: () => Promise<{ ExitCode?: number | null; Running?: boolean }>;
|
||||||
|
finalized: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const getWorkspaceProcessTag = (processIdArg: string) => `workspaceProcess:${processIdArg}`;
|
||||||
|
|
||||||
export class WorkspaceHandler {
|
export class WorkspaceHandler {
|
||||||
public typedrouter = new plugins.typedrequest.TypedRouter();
|
public typedrouter = new plugins.typedrequest.TypedRouter();
|
||||||
|
private workspaceProcesses = new Map<string, IWorkspaceProcessSession>();
|
||||||
|
|
||||||
constructor(private opsServerRef: OpsServer) {
|
constructor(private opsServerRef: OpsServer) {
|
||||||
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
this.opsServerRef.typedrouter.addTypedRouter(this.typedrouter);
|
||||||
@@ -24,6 +37,111 @@ export class WorkspaceHandler {
|
|||||||
return service.containerID;
|
return service.containerID;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private validateProcessId(processIdArg: string): void {
|
||||||
|
if (!/^[a-zA-Z0-9_-]{8,80}$/.test(processIdArg)) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError('Invalid workspace process id');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getShellCommandForContainer(
|
||||||
|
containerIdArg: string,
|
||||||
|
): Promise<interfaces.requests.IWorkspaceShellCommand> {
|
||||||
|
const candidates: interfaces.requests.IWorkspaceShellCommand[] = [
|
||||||
|
{ command: '/bin/bash', args: ['-il'], label: 'bash', prompt: '# ' },
|
||||||
|
{ command: 'bash', args: ['-il'], label: 'bash', prompt: '# ' },
|
||||||
|
{ command: '/bin/sh', args: ['-i'], label: 'sh', prompt: '# ' },
|
||||||
|
{ command: 'sh', args: ['-i'], label: 'sh', prompt: '# ' },
|
||||||
|
{ command: '/bin/ash', args: ['-i'], label: 'ash', prompt: '# ' },
|
||||||
|
{ command: 'ash', args: ['-i'], label: 'ash', prompt: '# ' },
|
||||||
|
{ command: '/usr/bin/zsh', args: ['-il'], label: 'zsh', prompt: '# ' },
|
||||||
|
{ command: 'zsh', args: ['-il'], label: 'zsh', prompt: '# ' },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const candidate of candidates) {
|
||||||
|
const result = await this.opsServerRef.oneboxRef.docker.execInContainer(
|
||||||
|
containerIdArg,
|
||||||
|
[candidate.command, '-c', 'printf onebox-shell'],
|
||||||
|
);
|
||||||
|
if (result.exitCode === 0 && result.stdout.includes('onebox-shell')) {
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new plugins.typedrequest.TypedResponseError(
|
||||||
|
'No supported interactive shell found in the target container',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getProcessSession(
|
||||||
|
dataArg: { identity: interfaces.data.IIdentity; processId: string },
|
||||||
|
): Promise<IWorkspaceProcessSession> {
|
||||||
|
const identity = await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
this.validateProcessId(dataArg.processId);
|
||||||
|
const session = this.workspaceProcesses.get(dataArg.processId);
|
||||||
|
if (!session) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError(`Workspace process not found: ${dataArg.processId}`);
|
||||||
|
}
|
||||||
|
if (session.userId !== identity.userId) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError('Workspace process belongs to another session');
|
||||||
|
}
|
||||||
|
return session;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pushWorkspaceProcessOutput(processIdArg: string, outputArg: string): Promise<void> {
|
||||||
|
const typedsocket = (this.opsServerRef.server as any)?.typedserver?.typedsocket;
|
||||||
|
if (!typedsocket) return;
|
||||||
|
|
||||||
|
const connections = await typedsocket.findAllTargetConnectionsByTag(getWorkspaceProcessTag(processIdArg));
|
||||||
|
await Promise.allSettled(
|
||||||
|
connections.map((connection: any) => typedsocket
|
||||||
|
.createTypedRequest(
|
||||||
|
'pushWorkspaceProcessOutput',
|
||||||
|
connection,
|
||||||
|
)
|
||||||
|
.fire({ processId: processIdArg, output: outputArg })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async pushWorkspaceProcessExit(processIdArg: string, exitCodeArg: number): Promise<void> {
|
||||||
|
const typedsocket = (this.opsServerRef.server as any)?.typedserver?.typedsocket;
|
||||||
|
if (!typedsocket) return;
|
||||||
|
|
||||||
|
const connections = await typedsocket.findAllTargetConnectionsByTag(getWorkspaceProcessTag(processIdArg));
|
||||||
|
await Promise.allSettled(
|
||||||
|
connections.map((connection: any) => typedsocket
|
||||||
|
.createTypedRequest(
|
||||||
|
'pushWorkspaceProcessExit',
|
||||||
|
connection,
|
||||||
|
)
|
||||||
|
.fire({ processId: processIdArg, exitCode: exitCodeArg })),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async finalizeWorkspaceProcess(processIdArg: string, fallbackExitCodeArg = -1): Promise<void> {
|
||||||
|
const session = this.workspaceProcesses.get(processIdArg);
|
||||||
|
if (!session || session.finalized) return;
|
||||||
|
session.finalized = true;
|
||||||
|
|
||||||
|
let exitCode = fallbackExitCodeArg;
|
||||||
|
try {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||||
|
const inspectResult = await session.inspect();
|
||||||
|
if (typeof inspectResult.ExitCode === 'number') {
|
||||||
|
exitCode = inspectResult.ExitCode;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.debug(`Failed to inspect workspace process ${processIdArg}: ${getErrorMessage(error)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.workspaceProcesses.delete(processIdArg);
|
||||||
|
await this.pushWorkspaceProcessExit(processIdArg, exitCode);
|
||||||
|
try {
|
||||||
|
await session.close();
|
||||||
|
} catch {
|
||||||
|
// The hijacked connection may already be closed by Docker.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private registerHandlers(): void {
|
private registerHandlers(): void {
|
||||||
// Read file from container
|
// Read file from container
|
||||||
this.typedrouter.addTypedHandler(
|
this.typedrouter.addTypedHandler(
|
||||||
@@ -176,6 +294,108 @@ export class WorkspaceHandler {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceGetShellCommand>(
|
||||||
|
'workspaceGetShellCommand',
|
||||||
|
async (dataArg) => {
|
||||||
|
await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
const containerId = await this.resolveContainerId(dataArg.serviceName);
|
||||||
|
const shellCommand = await this.getShellCommandForContainer(containerId);
|
||||||
|
return { shellCommand };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceStartProcess>(
|
||||||
|
'workspaceStartProcess',
|
||||||
|
async (dataArg) => {
|
||||||
|
const identity = await requireAdminIdentity(this.opsServerRef.adminHandler, dataArg);
|
||||||
|
this.validateProcessId(dataArg.processId);
|
||||||
|
if (this.workspaceProcesses.has(dataArg.processId)) {
|
||||||
|
throw new plugins.typedrequest.TypedResponseError(`Workspace process already exists: ${dataArg.processId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const containerId = await this.resolveContainerId(dataArg.serviceName);
|
||||||
|
const command = dataArg.args ? [dataArg.command, ...dataArg.args] : [dataArg.command];
|
||||||
|
const interactiveExec = await this.opsServerRef.oneboxRef.docker.startInteractiveExecInContainer(
|
||||||
|
containerId,
|
||||||
|
command,
|
||||||
|
);
|
||||||
|
|
||||||
|
const session: IWorkspaceProcessSession = {
|
||||||
|
processId: dataArg.processId,
|
||||||
|
serviceName: dataArg.serviceName,
|
||||||
|
userId: identity.userId,
|
||||||
|
stream: interactiveExec.stream,
|
||||||
|
close: interactiveExec.close,
|
||||||
|
inspect: interactiveExec.inspect,
|
||||||
|
finalized: false,
|
||||||
|
};
|
||||||
|
this.workspaceProcesses.set(dataArg.processId, session);
|
||||||
|
|
||||||
|
interactiveExec.stream.on('data', (chunk: Uint8Array | string) => {
|
||||||
|
const output = typeof chunk === 'string' ? chunk : new TextDecoder().decode(chunk);
|
||||||
|
void this.pushWorkspaceProcessOutput(dataArg.processId, output);
|
||||||
|
});
|
||||||
|
interactiveExec.stream.on('error', (error: Error) => {
|
||||||
|
void this.pushWorkspaceProcessOutput(
|
||||||
|
dataArg.processId,
|
||||||
|
`\r\n[workspace process error: ${getErrorMessage(error)}]\r\n`,
|
||||||
|
);
|
||||||
|
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||||
|
});
|
||||||
|
interactiveExec.stream.on('end', () => {
|
||||||
|
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||||
|
});
|
||||||
|
interactiveExec.stream.on('close', () => {
|
||||||
|
void this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||||
|
});
|
||||||
|
|
||||||
|
return { processId: dataArg.processId };
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceProcessInput>(
|
||||||
|
'workspaceProcessInput',
|
||||||
|
async (dataArg) => {
|
||||||
|
const session = await this.getProcessSession(dataArg);
|
||||||
|
if (session.finalized || session.stream.writableEnded) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
session.stream.write(dataArg.input, (error?: Error | null) => {
|
||||||
|
if (error) {
|
||||||
|
reject(error);
|
||||||
|
} else {
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
return {};
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.typedrouter.addTypedHandler(
|
||||||
|
new plugins.typedrequest.TypedHandler<interfaces.requests.IReq_WorkspaceKillProcess>(
|
||||||
|
'workspaceKillProcess',
|
||||||
|
async (dataArg) => {
|
||||||
|
const session = await this.getProcessSession(dataArg);
|
||||||
|
session.stream.destroy();
|
||||||
|
try {
|
||||||
|
await session.close();
|
||||||
|
} catch {
|
||||||
|
// The stream may already be closed.
|
||||||
|
}
|
||||||
|
await this.finalizeWorkspaceProcess(dataArg.processId, -1);
|
||||||
|
return {};
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
logger.info('Workspace handler registered');
|
logger.info('Workspace handler registered');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -82,6 +82,11 @@ export { smartguard, smartjwt };
|
|||||||
import { ContainerArchive } from '@serve.zone/containerarchive';
|
import { ContainerArchive } from '@serve.zone/containerarchive';
|
||||||
export { ContainerArchive };
|
export { ContainerArchive };
|
||||||
|
|
||||||
|
// serve.zone App Store contracts and resolver
|
||||||
|
import * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||||
|
import * as servezoneAppstore from '@serve.zone/appstore';
|
||||||
|
export { servezoneInterfaces, servezoneAppstore };
|
||||||
|
|
||||||
// Node.js compat for streaming
|
// Node.js compat for streaming
|
||||||
import * as nodeFs from 'node:fs';
|
import * as nodeFs from 'node:fs';
|
||||||
import * as nodeStream from 'node:stream';
|
import * as nodeStream from 'node:stream';
|
||||||
|
|||||||
+37
@@ -9,6 +9,8 @@ export interface IService {
|
|||||||
image: string;
|
image: string;
|
||||||
registry?: string;
|
registry?: string;
|
||||||
envVars: Record<string, string>;
|
envVars: Record<string, string>;
|
||||||
|
volumes?: IServiceVolume[];
|
||||||
|
publishedPorts?: IServicePublishedPort[];
|
||||||
port: number;
|
port: number;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
containerID?: string;
|
containerID?: string;
|
||||||
@@ -30,6 +32,27 @@ export interface IService {
|
|||||||
appTemplateVersion?: string;
|
appTemplateVersion?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IServiceVolume {
|
||||||
|
name?: string;
|
||||||
|
source?: string;
|
||||||
|
mountPath: string;
|
||||||
|
driver?: string;
|
||||||
|
readOnly?: boolean;
|
||||||
|
backup?: boolean;
|
||||||
|
options?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TServicePortProtocol = 'tcp' | 'udp';
|
||||||
|
|
||||||
|
export interface IServicePublishedPort {
|
||||||
|
targetPort: number;
|
||||||
|
targetPortEnd?: number;
|
||||||
|
publishedPort?: number;
|
||||||
|
publishedPortEnd?: number;
|
||||||
|
protocol?: TServicePortProtocol;
|
||||||
|
hostIp?: string;
|
||||||
|
}
|
||||||
|
|
||||||
// Registry types
|
// Registry types
|
||||||
export interface IRegistry {
|
export interface IRegistry {
|
||||||
id?: number;
|
id?: number;
|
||||||
@@ -257,10 +280,19 @@ export interface ISetting {
|
|||||||
// Application settings
|
// Application settings
|
||||||
export interface IAppSettings {
|
export interface IAppSettings {
|
||||||
serverIP?: string;
|
serverIP?: string;
|
||||||
|
adminUiDomain?: string;
|
||||||
cloudflareToken?: string;
|
cloudflareToken?: string;
|
||||||
cloudflareZoneId?: string;
|
cloudflareZoneId?: string;
|
||||||
|
dcrouterMode?: 'managed' | 'external' | 'disabled';
|
||||||
|
dcrouterManagedImage?: string;
|
||||||
|
dcrouterManagedOpsPort?: number;
|
||||||
|
dcrouterManagedHttpPort?: number;
|
||||||
|
dcrouterManagedHttpsPort?: number;
|
||||||
|
dcrouterManagedDataDir?: string;
|
||||||
dcrouterGatewayUrl?: string;
|
dcrouterGatewayUrl?: string;
|
||||||
dcrouterGatewayApiToken?: string;
|
dcrouterGatewayApiToken?: string;
|
||||||
|
dcrouterGatewayClientId?: string;
|
||||||
|
/** @deprecated Use dcrouterGatewayClientId. */
|
||||||
dcrouterWorkHosterId?: string;
|
dcrouterWorkHosterId?: string;
|
||||||
dcrouterTargetHost?: string;
|
dcrouterTargetHost?: string;
|
||||||
dcrouterTargetPort?: number;
|
dcrouterTargetPort?: number;
|
||||||
@@ -291,6 +323,8 @@ export interface IServiceDeployOptions {
|
|||||||
image: string;
|
image: string;
|
||||||
registry?: string;
|
registry?: string;
|
||||||
envVars?: Record<string, string>;
|
envVars?: Record<string, string>;
|
||||||
|
volumes?: IServiceVolume[];
|
||||||
|
publishedPorts?: IServicePublishedPort[];
|
||||||
port: number;
|
port: number;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
autoSSL?: boolean;
|
autoSSL?: boolean;
|
||||||
@@ -299,6 +333,7 @@ export interface IServiceDeployOptions {
|
|||||||
useOneboxRegistry?: boolean;
|
useOneboxRegistry?: boolean;
|
||||||
registryImageTag?: string;
|
registryImageTag?: string;
|
||||||
autoUpdateOnPush?: boolean;
|
autoUpdateOnPush?: boolean;
|
||||||
|
imageDigest?: string;
|
||||||
// Platform service requirements
|
// Platform service requirements
|
||||||
enableMongoDB?: boolean;
|
enableMongoDB?: boolean;
|
||||||
enableS3?: boolean;
|
enableS3?: boolean;
|
||||||
@@ -389,6 +424,8 @@ export interface IBackupServiceConfig {
|
|||||||
image: string;
|
image: string;
|
||||||
registry?: string;
|
registry?: string;
|
||||||
envVars: Record<string, string>;
|
envVars: Record<string, string>;
|
||||||
|
volumes?: IServiceVolume[];
|
||||||
|
publishedPorts?: IServicePublishedPort[];
|
||||||
port: number;
|
port: number;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
useOneboxRegistry?: boolean;
|
useOneboxRegistry?: boolean;
|
||||||
|
|||||||
@@ -0,0 +1,17 @@
|
|||||||
|
export function normalizeHostname(valueArg: string): string {
|
||||||
|
const trimmedValue = valueArg.trim().toLowerCase();
|
||||||
|
if (!trimmedValue) return '';
|
||||||
|
|
||||||
|
const withoutProtocol = trimmedValue.replace(/^[a-z][a-z0-9+.-]*:\/\//, '');
|
||||||
|
const withoutPath = withoutProtocol.split('/')[0].split('?')[0].split('#')[0];
|
||||||
|
return withoutPath.replace(/:\d+$/, '').replace(/\.$/, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidHostname(hostnameArg: string): boolean {
|
||||||
|
if (!hostnameArg) return true;
|
||||||
|
if (hostnameArg.length > 253) return false;
|
||||||
|
return hostnameArg.split('.').every((label) => {
|
||||||
|
if (!label || label.length > 63) return false;
|
||||||
|
return /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(label);
|
||||||
|
});
|
||||||
|
}
|
||||||
File diff suppressed because one or more lines are too long
@@ -57,3 +57,40 @@ export interface IDnsRecord {
|
|||||||
createdAt: number;
|
createdAt: number;
|
||||||
updatedAt: number;
|
updatedAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IGatewayDomain {
|
||||||
|
id?: string;
|
||||||
|
name: string;
|
||||||
|
source?: 'dcrouter' | 'provider';
|
||||||
|
authoritative?: boolean;
|
||||||
|
providerId?: string;
|
||||||
|
serviceCount?: number;
|
||||||
|
managePath?: string;
|
||||||
|
manageUrl?: string;
|
||||||
|
capabilities?: {
|
||||||
|
canCreateSubdomains: boolean;
|
||||||
|
canManageDnsRecords: boolean;
|
||||||
|
canIssueCertificates: boolean;
|
||||||
|
canHostEmail: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IGatewayDnsRecord {
|
||||||
|
id: string;
|
||||||
|
domainId: string;
|
||||||
|
domainName?: string;
|
||||||
|
name: string;
|
||||||
|
type: string;
|
||||||
|
value: string;
|
||||||
|
ttl: number;
|
||||||
|
source: string;
|
||||||
|
status: 'active' | 'missing';
|
||||||
|
gatewayClientType: 'onebox' | 'cloudly' | 'custom';
|
||||||
|
gatewayClientId: string;
|
||||||
|
appId: string;
|
||||||
|
hostname: string;
|
||||||
|
routeId?: string;
|
||||||
|
serviceName?: string;
|
||||||
|
managePath?: string;
|
||||||
|
manageUrl?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ export interface IService {
|
|||||||
image: string;
|
image: string;
|
||||||
registry?: string;
|
registry?: string;
|
||||||
envVars: Record<string, string>;
|
envVars: Record<string, string>;
|
||||||
|
volumes?: IServiceVolume[];
|
||||||
|
publishedPorts?: IServicePublishedPort[];
|
||||||
port: number;
|
port: number;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
containerID?: string;
|
containerID?: string;
|
||||||
@@ -33,12 +35,35 @@ export interface IService {
|
|||||||
appTemplateVersion?: string;
|
appTemplateVersion?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IServiceVolume {
|
||||||
|
name?: string;
|
||||||
|
source?: string;
|
||||||
|
mountPath: string;
|
||||||
|
driver?: string;
|
||||||
|
readOnly?: boolean;
|
||||||
|
backup?: boolean;
|
||||||
|
options?: Record<string, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TServicePortProtocol = 'tcp' | 'udp';
|
||||||
|
|
||||||
|
export interface IServicePublishedPort {
|
||||||
|
targetPort: number;
|
||||||
|
targetPortEnd?: number;
|
||||||
|
publishedPort?: number;
|
||||||
|
publishedPortEnd?: number;
|
||||||
|
protocol?: TServicePortProtocol;
|
||||||
|
hostIp?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface IServiceCreate {
|
export interface IServiceCreate {
|
||||||
name: string;
|
name: string;
|
||||||
image: string;
|
image: string;
|
||||||
port: number;
|
port: number;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
envVars?: Record<string, string>;
|
envVars?: Record<string, string>;
|
||||||
|
volumes?: IServiceVolume[];
|
||||||
|
publishedPorts?: IServicePublishedPort[];
|
||||||
useOneboxRegistry?: boolean;
|
useOneboxRegistry?: boolean;
|
||||||
registryImageTag?: string;
|
registryImageTag?: string;
|
||||||
autoUpdateOnPush?: boolean;
|
autoUpdateOnPush?: boolean;
|
||||||
@@ -57,6 +82,8 @@ export interface IServiceUpdate {
|
|||||||
port?: number;
|
port?: number;
|
||||||
domain?: string;
|
domain?: string;
|
||||||
envVars?: Record<string, string>;
|
envVars?: Record<string, string>;
|
||||||
|
volumes?: IServiceVolume[];
|
||||||
|
publishedPorts?: IServicePublishedPort[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IContainerStats {
|
export interface IContainerStats {
|
||||||
|
|||||||
@@ -2,11 +2,36 @@
|
|||||||
* Settings data shapes for Onebox
|
* Settings data shapes for Onebox
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
export type TDcRouterMode = 'managed' | 'external' | 'disabled';
|
||||||
|
|
||||||
|
export interface IManagedDcRouterStatus {
|
||||||
|
mode: TDcRouterMode;
|
||||||
|
configured: boolean;
|
||||||
|
running: boolean;
|
||||||
|
healthy: boolean;
|
||||||
|
containerId?: string;
|
||||||
|
image: string;
|
||||||
|
gatewayUrl: string;
|
||||||
|
opsPort: number;
|
||||||
|
httpPort: number;
|
||||||
|
httpsPort: number;
|
||||||
|
message?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ISettings {
|
export interface ISettings {
|
||||||
cloudflareToken: string;
|
cloudflareToken: string;
|
||||||
cloudflareZoneId: string;
|
cloudflareZoneId: string;
|
||||||
|
adminUiDomain: string;
|
||||||
|
dcrouterMode: TDcRouterMode;
|
||||||
|
dcrouterManagedImage: string;
|
||||||
|
dcrouterManagedOpsPort: number;
|
||||||
|
dcrouterManagedHttpPort: number;
|
||||||
|
dcrouterManagedHttpsPort: number;
|
||||||
|
dcrouterManagedDataDir: string;
|
||||||
dcrouterGatewayUrl: string;
|
dcrouterGatewayUrl: string;
|
||||||
dcrouterGatewayApiToken: string;
|
dcrouterGatewayApiToken: string;
|
||||||
|
dcrouterGatewayClientId: string;
|
||||||
|
/** @deprecated Use dcrouterGatewayClientId. */
|
||||||
dcrouterWorkHosterId: string;
|
dcrouterWorkHosterId: string;
|
||||||
dcrouterTargetHost: string;
|
dcrouterTargetHost: string;
|
||||||
dcrouterTargetPort: number;
|
dcrouterTargetPort: number;
|
||||||
|
|||||||
@@ -2,9 +2,33 @@
|
|||||||
* System status data shapes for Onebox
|
* System status data shapes for Onebox
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import type { TPlatformServiceType, TPlatformServiceStatus } from './platform.ts';
|
import type { TPlatformServiceStatus, TPlatformServiceType } from './platform.ts';
|
||||||
|
|
||||||
|
export interface IOneboxUpdateStatus {
|
||||||
|
currentVersion: string;
|
||||||
|
latestVersion: string | null;
|
||||||
|
updateAvailable: boolean;
|
||||||
|
checkedAt: number;
|
||||||
|
releaseUrl: string;
|
||||||
|
changelogUrl: string;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IOneboxUpgradeStartResult {
|
||||||
|
accepted: boolean;
|
||||||
|
currentVersion: string;
|
||||||
|
targetVersion: string;
|
||||||
|
message: string;
|
||||||
|
pid?: number;
|
||||||
|
unitName?: string;
|
||||||
|
logPath?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ISystemStatus {
|
export interface ISystemStatus {
|
||||||
|
onebox: {
|
||||||
|
version: string;
|
||||||
|
update: IOneboxUpdateStatus;
|
||||||
|
};
|
||||||
docker: {
|
docker: {
|
||||||
running: boolean;
|
running: boolean;
|
||||||
version: unknown;
|
version: unknown;
|
||||||
|
|||||||
@@ -1,99 +1,112 @@
|
|||||||
|
import type * as servezoneInterfaces from '@serve.zone/interfaces';
|
||||||
import * as plugins from '../plugins.ts';
|
import * as plugins from '../plugins.ts';
|
||||||
import * as data from '../data/index.ts';
|
import * as data from '../data/index.ts';
|
||||||
|
|
||||||
export interface ICatalogApp {
|
export type IAppStoreApp = servezoneInterfaces.appstore.IAppStoreApp;
|
||||||
|
export type IAppStoreVersionConfig = servezoneInterfaces.appstore.IAppStoreVersionConfig;
|
||||||
|
export type IAppStoreAppMeta = servezoneInterfaces.appstore.IAppStoreAppMeta;
|
||||||
|
export type IUpgradeableAppStoreService = servezoneInterfaces.appstore.IUpgradeableAppStoreService;
|
||||||
|
|
||||||
|
export interface IAppStoreInstallOptions extends servezoneInterfaces.appstore.IAppStoreInstallRequest {
|
||||||
|
autoDNS?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TAppStoreUpgradeStatus = 'running' | 'success' | 'failed';
|
||||||
|
|
||||||
|
export type TAppStoreUpgradeStep =
|
||||||
|
| 'queued'
|
||||||
|
| 'validating'
|
||||||
|
| 'migration'
|
||||||
|
| 'applying'
|
||||||
|
| 'stopping'
|
||||||
|
| 'pulling-image'
|
||||||
|
| 'updating-record'
|
||||||
|
| 'removing-container'
|
||||||
|
| 'creating-container'
|
||||||
|
| 'starting'
|
||||||
|
| 'restoring-route'
|
||||||
|
| 'syncing-gateway'
|
||||||
|
| 'complete'
|
||||||
|
| 'failed';
|
||||||
|
|
||||||
|
export interface IAppStoreUpgradeOperation {
|
||||||
id: string;
|
id: string;
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
category: string;
|
|
||||||
iconName?: string;
|
|
||||||
iconUrl?: string;
|
|
||||||
latestVersion: string;
|
|
||||||
tags?: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IAppVersionConfig {
|
|
||||||
image: string;
|
|
||||||
port: number;
|
|
||||||
envVars?: Array<{ key: string; value: string; description: string; required?: boolean }>;
|
|
||||||
volumes?: string[];
|
|
||||||
platformRequirements?: {
|
|
||||||
mongodb?: boolean;
|
|
||||||
s3?: boolean;
|
|
||||||
clickhouse?: boolean;
|
|
||||||
redis?: boolean;
|
|
||||||
mariadb?: boolean;
|
|
||||||
};
|
|
||||||
minOneboxVersion?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IAppMeta {
|
|
||||||
id: string;
|
|
||||||
name: string;
|
|
||||||
description: string;
|
|
||||||
category: string;
|
|
||||||
iconName?: string;
|
|
||||||
latestVersion: string;
|
|
||||||
versions: string[];
|
|
||||||
maintainer?: string;
|
|
||||||
links?: Record<string, string>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface IUpgradeableService {
|
|
||||||
serviceName: string;
|
serviceName: string;
|
||||||
appTemplateId: string;
|
appTemplateId: string;
|
||||||
currentVersion: string;
|
fromVersion: string;
|
||||||
latestVersion: string;
|
targetVersion: string;
|
||||||
hasMigration: boolean;
|
status: TAppStoreUpgradeStatus;
|
||||||
|
step: TAppStoreUpgradeStep;
|
||||||
|
progressLines: string[];
|
||||||
|
warnings: string[];
|
||||||
|
error?: string;
|
||||||
|
startedAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
completedAt?: number;
|
||||||
|
service?: data.IService;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IReq_GetAppTemplates extends plugins.typedrequestInterfaces.implementsTR<
|
export interface IReq_GetAppStoreTemplates extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
plugins.typedrequestInterfaces.ITypedRequest,
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
IReq_GetAppTemplates
|
IReq_GetAppStoreTemplates
|
||||||
> {
|
> {
|
||||||
method: 'getAppTemplates';
|
method: 'getAppStoreTemplates';
|
||||||
request: {
|
request: {
|
||||||
identity: data.IIdentity;
|
identity: data.IIdentity;
|
||||||
};
|
};
|
||||||
response: {
|
response: {
|
||||||
apps: ICatalogApp[];
|
apps: IAppStoreApp[];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IReq_GetAppConfig extends plugins.typedrequestInterfaces.implementsTR<
|
export interface IReq_GetAppStoreConfig extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
plugins.typedrequestInterfaces.ITypedRequest,
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
IReq_GetAppConfig
|
IReq_GetAppStoreConfig
|
||||||
> {
|
> {
|
||||||
method: 'getAppConfig';
|
method: 'getAppStoreConfig';
|
||||||
request: {
|
request: {
|
||||||
identity: data.IIdentity;
|
identity: data.IIdentity;
|
||||||
appId: string;
|
appId: string;
|
||||||
version: string;
|
version: string;
|
||||||
};
|
};
|
||||||
response: {
|
response: {
|
||||||
config: IAppVersionConfig;
|
config: IAppStoreVersionConfig;
|
||||||
appMeta: IAppMeta;
|
appMeta: IAppStoreAppMeta;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IReq_GetUpgradeableServices extends plugins.typedrequestInterfaces.implementsTR<
|
export interface IReq_InstallAppStoreApp extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
plugins.typedrequestInterfaces.ITypedRequest,
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
IReq_GetUpgradeableServices
|
IReq_InstallAppStoreApp
|
||||||
> {
|
> {
|
||||||
method: 'getUpgradeableServices';
|
method: 'installAppStoreApp';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
install: IAppStoreInstallOptions;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
service: data.IService;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_GetUpgradeableAppStoreServices extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_GetUpgradeableAppStoreServices
|
||||||
|
> {
|
||||||
|
method: 'getUpgradeableAppStoreServices';
|
||||||
request: {
|
request: {
|
||||||
identity: data.IIdentity;
|
identity: data.IIdentity;
|
||||||
};
|
};
|
||||||
response: {
|
response: {
|
||||||
services: IUpgradeableService[];
|
services: IUpgradeableAppStoreService[];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IReq_UpgradeService extends plugins.typedrequestInterfaces.implementsTR<
|
export interface IReq_UpgradeAppStoreService extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
plugins.typedrequestInterfaces.ITypedRequest,
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
IReq_UpgradeService
|
IReq_UpgradeAppStoreService
|
||||||
> {
|
> {
|
||||||
method: 'upgradeService';
|
method: 'upgradeAppStoreService';
|
||||||
request: {
|
request: {
|
||||||
identity: data.IIdentity;
|
identity: data.IIdentity;
|
||||||
serviceName: string;
|
serviceName: string;
|
||||||
@@ -104,3 +117,42 @@ export interface IReq_UpgradeService extends plugins.typedrequestInterfaces.impl
|
|||||||
warnings: string[];
|
warnings: string[];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IReq_StartAppStoreServiceUpgrade extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_StartAppStoreServiceUpgrade
|
||||||
|
> {
|
||||||
|
method: 'startAppStoreServiceUpgrade';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
serviceName: string;
|
||||||
|
targetVersion: string;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
operation: IAppStoreUpgradeOperation;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_GetAppStoreUpgradeOperations extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_GetAppStoreUpgradeOperations
|
||||||
|
> {
|
||||||
|
method: 'getAppStoreUpgradeOperations';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
operations: IAppStoreUpgradeOperation[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_PushAppStoreUpgradeProgress extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_PushAppStoreUpgradeProgress
|
||||||
|
> {
|
||||||
|
method: 'pushAppStoreUpgradeProgress';
|
||||||
|
request: {
|
||||||
|
operation: IAppStoreUpgradeOperation;
|
||||||
|
};
|
||||||
|
response: {};
|
||||||
|
}
|
||||||
|
|||||||
@@ -56,3 +56,16 @@ export interface IReq_SyncDns extends plugins.typedrequestInterfaces.implementsT
|
|||||||
records: data.IDnsRecord[];
|
records: data.IDnsRecord[];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IReq_GetGatewayDnsRecords extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_GetGatewayDnsRecords
|
||||||
|
> {
|
||||||
|
method: 'getGatewayDnsRecords';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
records: data.IGatewayDnsRecord[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -40,3 +40,16 @@ export interface IReq_SyncDomains extends plugins.typedrequestInterfaces.impleme
|
|||||||
domains: data.IDomainDetail[];
|
domains: data.IDomainDetail[];
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IReq_GetGatewayDomains extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_GetGatewayDomains
|
||||||
|
> {
|
||||||
|
method: 'getGatewayDomains';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
domains: data.IGatewayDomain[];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -54,3 +54,55 @@ export interface IReq_GetBackupPasswordStatus extends plugins.typedrequestInterf
|
|||||||
status: data.IBackupPasswordStatus;
|
status: data.IBackupPasswordStatus;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IReq_GetManagedDcRouterStatus extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_GetManagedDcRouterStatus
|
||||||
|
> {
|
||||||
|
method: 'getManagedDcRouterStatus';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
status: data.IManagedDcRouterStatus;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_StartManagedDcRouter extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_StartManagedDcRouter
|
||||||
|
> {
|
||||||
|
method: 'startManagedDcRouter';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
status: data.IManagedDcRouterStatus;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_StopManagedDcRouter extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_StopManagedDcRouter
|
||||||
|
> {
|
||||||
|
method: 'stopManagedDcRouter';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
status: data.IManagedDcRouterStatus;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_RestartManagedDcRouter extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_RestartManagedDcRouter
|
||||||
|
> {
|
||||||
|
method: 'restartManagedDcRouter';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
status: data.IManagedDcRouterStatus;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -13,3 +13,16 @@ export interface IReq_GetSystemStatus extends plugins.typedrequestInterfaces.imp
|
|||||||
status: data.ISystemStatus;
|
status: data.ISystemStatus;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IReq_StartOneboxUpgrade extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_StartOneboxUpgrade
|
||||||
|
> {
|
||||||
|
method: 'startOneboxUpgrade';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
upgrade: data.IOneboxUpgradeStartResult;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
import * as plugins from '../plugins.ts';
|
import * as plugins from '../plugins.ts';
|
||||||
import * as data from '../data/index.ts';
|
import * as data from '../data/index.ts';
|
||||||
|
|
||||||
|
export interface IWorkspaceShellCommand {
|
||||||
|
command: string;
|
||||||
|
args?: string[];
|
||||||
|
label?: string;
|
||||||
|
prompt?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface IReq_WorkspaceReadFile extends plugins.typedrequestInterfaces.implementsTR<
|
export interface IReq_WorkspaceReadFile extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
plugins.typedrequestInterfaces.ITypedRequest,
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
IReq_WorkspaceReadFile
|
IReq_WorkspaceReadFile
|
||||||
@@ -104,3 +111,83 @@ export interface IReq_WorkspaceExec extends plugins.typedrequestInterfaces.imple
|
|||||||
exitCode: number;
|
exitCode: number;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface IReq_WorkspaceGetShellCommand extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_WorkspaceGetShellCommand
|
||||||
|
> {
|
||||||
|
method: 'workspaceGetShellCommand';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
serviceName: string;
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
shellCommand: IWorkspaceShellCommand;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_WorkspaceStartProcess extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_WorkspaceStartProcess
|
||||||
|
> {
|
||||||
|
method: 'workspaceStartProcess';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
serviceName: string;
|
||||||
|
processId: string;
|
||||||
|
command: string;
|
||||||
|
args?: string[];
|
||||||
|
};
|
||||||
|
response: {
|
||||||
|
processId: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_WorkspaceProcessInput extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_WorkspaceProcessInput
|
||||||
|
> {
|
||||||
|
method: 'workspaceProcessInput';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
processId: string;
|
||||||
|
input: string;
|
||||||
|
};
|
||||||
|
response: {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_WorkspaceKillProcess extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_WorkspaceKillProcess
|
||||||
|
> {
|
||||||
|
method: 'workspaceKillProcess';
|
||||||
|
request: {
|
||||||
|
identity: data.IIdentity;
|
||||||
|
processId: string;
|
||||||
|
};
|
||||||
|
response: {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_PushWorkspaceProcessOutput extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_PushWorkspaceProcessOutput
|
||||||
|
> {
|
||||||
|
method: 'pushWorkspaceProcessOutput';
|
||||||
|
request: {
|
||||||
|
processId: string;
|
||||||
|
output: string;
|
||||||
|
};
|
||||||
|
response: {};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface IReq_PushWorkspaceProcessExit extends plugins.typedrequestInterfaces.implementsTR<
|
||||||
|
plugins.typedrequestInterfaces.ITypedRequest,
|
||||||
|
IReq_PushWorkspaceProcessExit
|
||||||
|
> {
|
||||||
|
method: 'pushWorkspaceProcessExit';
|
||||||
|
request: {
|
||||||
|
processId: string;
|
||||||
|
exitCode: number;
|
||||||
|
};
|
||||||
|
response: {};
|
||||||
|
}
|
||||||
|
|||||||
@@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@serve.zone/onebox',
|
name: '@serve.zone/onebox',
|
||||||
version: '1.24.2',
|
version: '2.1.2',
|
||||||
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
description: 'Self-hosted container platform with automatic SSL and DNS - a mini Heroku for single servers'
|
||||||
}
|
}
|
||||||
|
|||||||
+181
-22
@@ -36,6 +36,8 @@ export interface INetworkState {
|
|||||||
trafficStats: interfaces.data.ITrafficStats | null;
|
trafficStats: interfaces.data.ITrafficStats | null;
|
||||||
dnsRecords: interfaces.data.IDnsRecord[];
|
dnsRecords: interfaces.data.IDnsRecord[];
|
||||||
domains: interfaces.data.IDomainDetail[];
|
domains: interfaces.data.IDomainDetail[];
|
||||||
|
gatewayDomains: interfaces.data.IGatewayDomain[];
|
||||||
|
gatewayDnsRecords: interfaces.data.IGatewayDnsRecord[];
|
||||||
certificates: interfaces.data.ICertificate[];
|
certificates: interfaces.data.ICertificate[];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,15 +54,18 @@ export interface IBackupsState {
|
|||||||
export interface ISettingsState {
|
export interface ISettingsState {
|
||||||
settings: interfaces.data.ISettings | null;
|
settings: interfaces.data.ISettings | null;
|
||||||
backupPasswordConfigured: boolean;
|
backupPasswordConfigured: boolean;
|
||||||
|
managedDcRouterStatus: interfaces.data.IManagedDcRouterStatus | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IAppStoreState {
|
export interface IAppStoreState {
|
||||||
apps: interfaces.requests.ICatalogApp[];
|
apps: interfaces.requests.IAppStoreApp[];
|
||||||
upgradeableServices: interfaces.requests.IUpgradeableService[];
|
upgradeableServices: interfaces.requests.IUpgradeableAppStoreService[];
|
||||||
|
upgradeOperations: interfaces.requests.IAppStoreUpgradeOperation[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface IUiState {
|
export interface IUiState {
|
||||||
activeView: string;
|
activeView: string;
|
||||||
|
activeSubview: string | null;
|
||||||
autoRefresh: boolean;
|
autoRefresh: boolean;
|
||||||
refreshInterval: number;
|
refreshInterval: number;
|
||||||
pendingAppTemplate?: any;
|
pendingAppTemplate?: any;
|
||||||
@@ -110,6 +115,8 @@ export const networkStatePart = await appState.getStatePart<INetworkState>(
|
|||||||
trafficStats: null,
|
trafficStats: null,
|
||||||
dnsRecords: [],
|
dnsRecords: [],
|
||||||
domains: [],
|
domains: [],
|
||||||
|
gatewayDomains: [],
|
||||||
|
gatewayDnsRecords: [],
|
||||||
certificates: [],
|
certificates: [],
|
||||||
},
|
},
|
||||||
'soft',
|
'soft',
|
||||||
@@ -138,6 +145,7 @@ export const settingsStatePart = await appState.getStatePart<ISettingsState>(
|
|||||||
{
|
{
|
||||||
settings: null,
|
settings: null,
|
||||||
backupPasswordConfigured: false,
|
backupPasswordConfigured: false,
|
||||||
|
managedDcRouterStatus: null,
|
||||||
},
|
},
|
||||||
'soft',
|
'soft',
|
||||||
);
|
);
|
||||||
@@ -147,6 +155,7 @@ export const appStoreStatePart = await appState.getStatePart<IAppStoreState>(
|
|||||||
{
|
{
|
||||||
apps: [],
|
apps: [],
|
||||||
upgradeableServices: [],
|
upgradeableServices: [],
|
||||||
|
upgradeOperations: [],
|
||||||
},
|
},
|
||||||
'soft',
|
'soft',
|
||||||
);
|
);
|
||||||
@@ -155,6 +164,7 @@ export const uiStatePart = await appState.getStatePart<IUiState>(
|
|||||||
'ui',
|
'ui',
|
||||||
{
|
{
|
||||||
activeView: 'dashboard',
|
activeView: 'dashboard',
|
||||||
|
activeSubview: null,
|
||||||
autoRefresh: true,
|
autoRefresh: true,
|
||||||
refreshInterval: 30000,
|
refreshInterval: 30000,
|
||||||
},
|
},
|
||||||
@@ -628,6 +638,34 @@ export const fetchDomainsAction = networkStatePart.createAction(async (statePart
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const fetchGatewayDomainsAction = networkStatePart.createAction(async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetGatewayDomains
|
||||||
|
>('/typedrequest', 'getGatewayDomains');
|
||||||
|
const response = await typedRequest.fire({ identity: context.identity! });
|
||||||
|
return { ...statePartArg.getState(), gatewayDomains: response.domains };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch gateway domains:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const fetchGatewayDnsRecordsAction = networkStatePart.createAction(async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetGatewayDnsRecords
|
||||||
|
>('/typedrequest', 'getGatewayDnsRecords');
|
||||||
|
const response = await typedRequest.fire({ identity: context.identity! });
|
||||||
|
return { ...statePartArg.getState(), gatewayDnsRecords: response.records };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch gateway DNS records:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
export const fetchCertificatesAction = networkStatePart.createAction(async (statePartArg) => {
|
export const fetchCertificatesAction = networkStatePart.createAction(async (statePartArg) => {
|
||||||
const context = getActionContext();
|
const context = getActionContext();
|
||||||
try {
|
try {
|
||||||
@@ -866,17 +904,21 @@ export const triggerScheduleAction = backupsStatePart.createAction<{ scheduleId:
|
|||||||
export const fetchSettingsAction = settingsStatePart.createAction(async (statePartArg) => {
|
export const fetchSettingsAction = settingsStatePart.createAction(async (statePartArg) => {
|
||||||
const context = getActionContext();
|
const context = getActionContext();
|
||||||
try {
|
try {
|
||||||
const [settingsResp, passwordResp] = await Promise.all([
|
const [settingsResp, passwordResp, managedDcRouterResp] = await Promise.all([
|
||||||
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
interfaces.requests.IReq_GetSettings
|
interfaces.requests.IReq_GetSettings
|
||||||
>('/typedrequest', 'getSettings').fire({ identity: context.identity! }),
|
>('/typedrequest', 'getSettings').fire({ identity: context.identity! }),
|
||||||
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
interfaces.requests.IReq_GetBackupPasswordStatus
|
interfaces.requests.IReq_GetBackupPasswordStatus
|
||||||
>('/typedrequest', 'getBackupPasswordStatus').fire({ identity: context.identity! }),
|
>('/typedrequest', 'getBackupPasswordStatus').fire({ identity: context.identity! }),
|
||||||
|
new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetManagedDcRouterStatus
|
||||||
|
>('/typedrequest', 'getManagedDcRouterStatus').fire({ identity: context.identity! }),
|
||||||
]);
|
]);
|
||||||
return {
|
return {
|
||||||
settings: settingsResp.settings,
|
settings: settingsResp.settings,
|
||||||
backupPasswordConfigured: passwordResp.status.isConfigured,
|
backupPasswordConfigured: passwordResp.status.isConfigured,
|
||||||
|
managedDcRouterStatus: managedDcRouterResp.status,
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to fetch settings:', err);
|
console.error('Failed to fetch settings:', err);
|
||||||
@@ -903,6 +945,58 @@ export const updateSettingsAction = settingsStatePart.createAction<{
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const fetchManagedDcRouterStatusAction = settingsStatePart.createAction(async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetManagedDcRouterStatus
|
||||||
|
>('/typedrequest', 'getManagedDcRouterStatus').fire({ identity: context.identity! });
|
||||||
|
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch managed dcrouter status:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const startManagedDcRouterAction = settingsStatePart.createAction(async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_StartManagedDcRouter
|
||||||
|
>('/typedrequest', 'startManagedDcRouter').fire({ identity: context.identity! });
|
||||||
|
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to start managed dcrouter:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const stopManagedDcRouterAction = settingsStatePart.createAction(async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_StopManagedDcRouter
|
||||||
|
>('/typedrequest', 'stopManagedDcRouter').fire({ identity: context.identity! });
|
||||||
|
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to stop managed dcrouter:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export const restartManagedDcRouterAction = settingsStatePart.createAction(async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const response = await new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_RestartManagedDcRouter
|
||||||
|
>('/typedrequest', 'restartManagedDcRouter').fire({ identity: context.identity! });
|
||||||
|
return { ...statePartArg.getState(), managedDcRouterStatus: response.status };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to restart managed dcrouter:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
export const setBackupPasswordAction = settingsStatePart.createAction<{ password: string }>(
|
export const setBackupPasswordAction = settingsStatePart.createAction<{ password: string }>(
|
||||||
async (statePartArg, dataArg) => {
|
async (statePartArg, dataArg) => {
|
||||||
const context = getActionContext();
|
const context = getActionContext();
|
||||||
@@ -926,10 +1020,17 @@ export const setBackupPasswordAction = settingsStatePart.createAction<{ password
|
|||||||
// UI Actions
|
// UI Actions
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
export const setActiveViewAction = uiStatePart.createAction<{ view: string }>(
|
export const setActiveViewAction = uiStatePart.createAction<{ view: string; subview?: string | null }>(
|
||||||
async (statePartArg, dataArg) => {
|
async (statePartArg, dataArg) => {
|
||||||
const normalizedView = dataArg.view.toLowerCase().replace(/\s+/g, '-');
|
const normalizedView = dataArg.view.toLowerCase().replace(/\s+/g, '-');
|
||||||
return { ...statePartArg.getState(), activeView: normalizedView };
|
const normalizedSubview = dataArg.subview
|
||||||
|
? dataArg.subview.toLowerCase().replace(/\s+/g, '-')
|
||||||
|
: null;
|
||||||
|
return {
|
||||||
|
...statePartArg.getState(),
|
||||||
|
activeView: normalizedView,
|
||||||
|
activeSubview: normalizedSubview,
|
||||||
|
};
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -949,7 +1050,10 @@ const dispatchCombinedRefreshAction = async () => {
|
|||||||
if (!loginState.isLoggedIn) return;
|
if (!loginState.isLoggedIn) return;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await systemStatePart.dispatchAction(fetchSystemStatusAction, null);
|
await Promise.all([
|
||||||
|
systemStatePart.dispatchAction(fetchSystemStatusAction, null),
|
||||||
|
networkStatePart.dispatchAction(fetchTrafficStatsAction, null),
|
||||||
|
]);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Silently fail on auto-refresh
|
// Silently fail on auto-refresh
|
||||||
}
|
}
|
||||||
@@ -999,6 +1103,19 @@ const upsertService = (
|
|||||||
return updatedServices;
|
return updatedServices;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const upsertUpgradeOperation = (
|
||||||
|
operations: interfaces.requests.IAppStoreUpgradeOperation[],
|
||||||
|
operation: interfaces.requests.IAppStoreUpgradeOperation,
|
||||||
|
): interfaces.requests.IAppStoreUpgradeOperation[] => {
|
||||||
|
const existingIndex = operations.findIndex((item) => item.id === operation.id);
|
||||||
|
const updatedOperations = existingIndex === -1
|
||||||
|
? [operation, ...operations]
|
||||||
|
: operations.map((item) => item.id === operation.id ? operation : item);
|
||||||
|
return updatedOperations
|
||||||
|
.sort((a, b) => b.startedAt - a.startedAt)
|
||||||
|
.slice(0, 25);
|
||||||
|
};
|
||||||
|
|
||||||
socketRouter.addTypedHandler(
|
socketRouter.addTypedHandler(
|
||||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushServiceUpdate>(
|
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushServiceUpdate>(
|
||||||
'pushServiceUpdate',
|
'pushServiceUpdate',
|
||||||
@@ -1035,6 +1152,33 @@ socketRouter.addTypedHandler(
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
socketRouter.addTypedHandler(
|
||||||
|
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushAppStoreUpgradeProgress>(
|
||||||
|
'pushAppStoreUpgradeProgress',
|
||||||
|
async (dataArg) => {
|
||||||
|
const state = appStoreStatePart.getState();
|
||||||
|
appStoreStatePart.setState({
|
||||||
|
...state,
|
||||||
|
upgradeOperations: upsertUpgradeOperation(state.upgradeOperations, dataArg.operation),
|
||||||
|
upgradeableServices: dataArg.operation.status === 'success'
|
||||||
|
? state.upgradeableServices.filter((service) => service.serviceName !== dataArg.operation.serviceName)
|
||||||
|
: state.upgradeableServices,
|
||||||
|
});
|
||||||
|
if (dataArg.operation.service) {
|
||||||
|
const servicesState = servicesStatePart.getState();
|
||||||
|
servicesStatePart.setState({
|
||||||
|
...servicesState,
|
||||||
|
services: upsertService(servicesState.services, dataArg.operation.service),
|
||||||
|
currentService: servicesState.currentService?.name === dataArg.operation.service.name
|
||||||
|
? dataArg.operation.service
|
||||||
|
: servicesState.currentService,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
// Handle server-pushed platform service log entries
|
// Handle server-pushed platform service log entries
|
||||||
socketRouter.addTypedHandler(
|
socketRouter.addTypedHandler(
|
||||||
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushPlatformServiceLog>(
|
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushPlatformServiceLog>(
|
||||||
@@ -1124,13 +1268,13 @@ async function disconnectSocket() {
|
|||||||
// App Store Actions
|
// App Store Actions
|
||||||
// ============================================================================
|
// ============================================================================
|
||||||
|
|
||||||
export const fetchAppTemplatesAction = appStoreStatePart.createAction(
|
export const fetchAppStoreTemplatesAction = appStoreStatePart.createAction(
|
||||||
async (statePartArg) => {
|
async (statePartArg) => {
|
||||||
const context = getActionContext();
|
const context = getActionContext();
|
||||||
try {
|
try {
|
||||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
interfaces.requests.IReq_GetAppTemplates
|
interfaces.requests.IReq_GetAppStoreTemplates
|
||||||
>('/typedrequest', 'getAppTemplates');
|
>('/typedrequest', 'getAppStoreTemplates');
|
||||||
const response = await typedRequest.fire({ identity: context.identity! });
|
const response = await typedRequest.fire({ identity: context.identity! });
|
||||||
return { ...statePartArg.getState(), apps: response.apps };
|
return { ...statePartArg.getState(), apps: response.apps };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -1140,13 +1284,13 @@ export const fetchAppTemplatesAction = appStoreStatePart.createAction(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
export const fetchUpgradeableServicesAction = appStoreStatePart.createAction(
|
export const fetchUpgradeableAppStoreServicesAction = appStoreStatePart.createAction(
|
||||||
async (statePartArg) => {
|
async (statePartArg) => {
|
||||||
const context = getActionContext();
|
const context = getActionContext();
|
||||||
try {
|
try {
|
||||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
interfaces.requests.IReq_GetUpgradeableServices
|
interfaces.requests.IReq_GetUpgradeableAppStoreServices
|
||||||
>('/typedrequest', 'getUpgradeableServices');
|
>('/typedrequest', 'getUpgradeableAppStoreServices');
|
||||||
const response = await typedRequest.fire({ identity: context.identity! });
|
const response = await typedRequest.fire({ identity: context.identity! });
|
||||||
return { ...statePartArg.getState(), upgradeableServices: response.services };
|
return { ...statePartArg.getState(), upgradeableServices: response.services };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -1156,26 +1300,41 @@ export const fetchUpgradeableServicesAction = appStoreStatePart.createAction(
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
export const upgradeServiceAction = appStoreStatePart.createAction<{
|
export const fetchAppStoreUpgradeOperationsAction = appStoreStatePart.createAction(
|
||||||
|
async (statePartArg) => {
|
||||||
|
const context = getActionContext();
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetAppStoreUpgradeOperations
|
||||||
|
>('/typedrequest', 'getAppStoreUpgradeOperations');
|
||||||
|
const response = await typedRequest.fire({ identity: context.identity! });
|
||||||
|
return { ...statePartArg.getState(), upgradeOperations: response.operations };
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Failed to fetch upgrade operations:', err);
|
||||||
|
return statePartArg.getState();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
export const upgradeAppStoreServiceAction = appStoreStatePart.createAction<{
|
||||||
serviceName: string;
|
serviceName: string;
|
||||||
targetVersion: string;
|
targetVersion: string;
|
||||||
}>(async (statePartArg, dataArg) => {
|
}>(async (statePartArg, dataArg) => {
|
||||||
const context = getActionContext();
|
const context = getActionContext();
|
||||||
try {
|
try {
|
||||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
interfaces.requests.IReq_UpgradeService
|
interfaces.requests.IReq_StartAppStoreServiceUpgrade
|
||||||
>('/typedrequest', 'upgradeService');
|
>('/typedrequest', 'startAppStoreServiceUpgrade');
|
||||||
await typedRequest.fire({
|
const response = await typedRequest.fire({
|
||||||
identity: context.identity!,
|
identity: context.identity!,
|
||||||
serviceName: dataArg.serviceName,
|
serviceName: dataArg.serviceName,
|
||||||
targetVersion: dataArg.targetVersion,
|
targetVersion: dataArg.targetVersion,
|
||||||
});
|
});
|
||||||
// Re-fetch upgradeable services and services list
|
const state = statePartArg.getState();
|
||||||
const upgradeReq = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
return {
|
||||||
interfaces.requests.IReq_GetUpgradeableServices
|
...state,
|
||||||
>('/typedrequest', 'getUpgradeableServices');
|
upgradeOperations: upsertUpgradeOperation(state.upgradeOperations, response.operation),
|
||||||
const upgradeResp = await upgradeReq.fire({ identity: context.identity! });
|
};
|
||||||
return { ...statePartArg.getState(), upgradeableServices: upgradeResp.services };
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Failed to upgrade service:', err);
|
console.error('Failed to upgrade service:', err);
|
||||||
return statePartArg.getState();
|
return statePartArg.getState();
|
||||||
|
|||||||
+361
-53
@@ -12,12 +12,21 @@ import {
|
|||||||
type TemplateResult,
|
type TemplateResult,
|
||||||
} from '@design.estate/dees-element';
|
} from '@design.estate/dees-element';
|
||||||
|
|
||||||
import type { ObViewDashboard } from './ob-view-dashboard.js';
|
interface IUnresolvedView {
|
||||||
import type { ObViewServices } from './ob-view-services.js';
|
slug?: string;
|
||||||
import type { ObViewNetwork } from './ob-view-network.js';
|
name: string;
|
||||||
import type { ObViewRegistries } from './ob-view-registries.js';
|
iconName?: string;
|
||||||
import type { ObViewTokens } from './ob-view-tokens.js';
|
element?: Promise<any>;
|
||||||
import type { ObViewSettings } from './ob-view-settings.js';
|
subViews?: IUnresolvedView[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface IResolvedView {
|
||||||
|
slug?: string;
|
||||||
|
name: string;
|
||||||
|
iconName?: string;
|
||||||
|
element?: any;
|
||||||
|
subViews?: IResolvedView[];
|
||||||
|
}
|
||||||
|
|
||||||
@customElement('ob-app-shell')
|
@customElement('ob-app-shell')
|
||||||
export class ObAppShell extends DeesElement {
|
export class ObAppShell extends DeesElement {
|
||||||
@@ -27,52 +36,181 @@ export class ObAppShell extends DeesElement {
|
|||||||
@state()
|
@state()
|
||||||
accessor uiState: appstate.IUiState = {
|
accessor uiState: appstate.IUiState = {
|
||||||
activeView: 'dashboard',
|
activeView: 'dashboard',
|
||||||
|
activeSubview: null,
|
||||||
autoRefresh: true,
|
autoRefresh: true,
|
||||||
refreshInterval: 30000,
|
refreshInterval: 30000,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@state()
|
||||||
|
accessor systemState: appstate.ISystemState = {
|
||||||
|
status: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
@state()
|
||||||
|
accessor globalMessages: plugins.deesCatalog.IGlobalMessage[] = [];
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
accessor loginLoading: boolean = false;
|
accessor loginLoading: boolean = false;
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
accessor loginError: string = '';
|
accessor loginError: string = '';
|
||||||
|
|
||||||
private viewTabs = [
|
private viewTabs: IUnresolvedView[] = [
|
||||||
{ name: 'Dashboard', iconName: 'lucide:layoutDashboard', element: (async () => (await import('./ob-view-dashboard.js')).ObViewDashboard)() },
|
{
|
||||||
{ name: 'App Store', iconName: 'lucide:store', element: (async () => (await import('./ob-view-appstore.js')).ObViewAppStore)() },
|
slug: 'dashboard',
|
||||||
{ name: 'Services', iconName: 'lucide:boxes', element: (async () => (await import('./ob-view-services.js')).ObViewServices)() },
|
name: 'Dashboard',
|
||||||
{ name: 'Network', iconName: 'lucide:network', element: (async () => (await import('./ob-view-network.js')).ObViewNetwork)() },
|
iconName: 'lucide:layoutDashboard',
|
||||||
{ name: 'Registries', iconName: 'lucide:package', element: (async () => (await import('./ob-view-registries.js')).ObViewRegistries)() },
|
element: (async () => (await import('./ob-view-dashboard.js')).ObViewDashboard)(),
|
||||||
{ name: 'Tokens', iconName: 'lucide:key', element: (async () => (await import('./ob-view-tokens.js')).ObViewTokens)() },
|
},
|
||||||
{ name: 'Settings', iconName: 'lucide:settings', element: (async () => (await import('./ob-view-settings.js')).ObViewSettings)() },
|
{
|
||||||
|
slug: 'apps',
|
||||||
|
name: 'Apps',
|
||||||
|
iconName: 'lucide:store',
|
||||||
|
subViews: [
|
||||||
|
{
|
||||||
|
slug: 'app-store',
|
||||||
|
name: 'App Store',
|
||||||
|
iconName: 'lucide:store',
|
||||||
|
element: (async () => (await import('./ob-view-appstore.js')).ObViewAppStore)(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'services',
|
||||||
|
name: 'Services',
|
||||||
|
iconName: 'lucide:boxes',
|
||||||
|
element: (async () => (await import('./ob-view-services.js')).ObViewServices)(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'network',
|
||||||
|
name: 'Network',
|
||||||
|
iconName: 'lucide:network',
|
||||||
|
subViews: [
|
||||||
|
{
|
||||||
|
slug: 'proxy',
|
||||||
|
name: 'Proxy',
|
||||||
|
iconName: 'lucide:route',
|
||||||
|
element: (async () => (await import('./ob-view-network.js')).ObViewNetwork)(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'domains',
|
||||||
|
name: 'Domains',
|
||||||
|
iconName: 'lucide:globe',
|
||||||
|
element: (async () => (await import('./ob-view-domains.js')).ObViewDomains)(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'dns-records',
|
||||||
|
name: 'DNS Records',
|
||||||
|
iconName: 'lucide:listTree',
|
||||||
|
element: (async () => (await import('./ob-view-dns-records.js')).ObViewDnsRecords)(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'registry',
|
||||||
|
name: 'Registry',
|
||||||
|
iconName: 'lucide:package',
|
||||||
|
subViews: [
|
||||||
|
{
|
||||||
|
slug: 'registries',
|
||||||
|
name: 'Registries',
|
||||||
|
iconName: 'lucide:package',
|
||||||
|
element: (async () => (await import('./ob-view-registries.js')).ObViewRegistries)(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'tokens',
|
||||||
|
name: 'Tokens',
|
||||||
|
iconName: 'lucide:key',
|
||||||
|
element: (async () => (await import('./ob-view-tokens.js')).ObViewTokens)(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
slug: 'settings',
|
||||||
|
name: 'Settings',
|
||||||
|
iconName: 'lucide:settings',
|
||||||
|
element: (async () => (await import('./ob-view-settings.js')).ObViewSettings)(),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
private resolvedViewTabs: Array<{ name: string; iconName?: string; element: any }> = [];
|
private resolvedViewTabs: IResolvedView[] = [];
|
||||||
|
private suppressedUpdateVersion = '';
|
||||||
|
private upgradeFlowRunning = false;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
document.title = 'Onebox';
|
document.title = 'Onebox';
|
||||||
|
|
||||||
const loginSubscription = appstate.loginStatePart
|
const loginSubscription = appstate.loginStatePart
|
||||||
.select((stateArg) => stateArg)
|
.select((stateArg: appstate.ILoginState) => stateArg)
|
||||||
.subscribe((loginState) => {
|
.subscribe((loginState: appstate.ILoginState) => {
|
||||||
this.loginState = loginState;
|
this.loginState = loginState;
|
||||||
|
this.updateGlobalMessages();
|
||||||
if (loginState.isLoggedIn) {
|
if (loginState.isLoggedIn) {
|
||||||
appstate.systemStatePart.dispatchAction(appstate.fetchSystemStatusAction, null);
|
appstate.systemStatePart.dispatchAction(appstate.fetchSystemStatusAction, null);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
this.rxSubscriptions.push(loginSubscription);
|
this.rxSubscriptions.push(loginSubscription);
|
||||||
|
|
||||||
|
const systemSubscription = appstate.systemStatePart
|
||||||
|
.select((stateArg: appstate.ISystemState) => stateArg)
|
||||||
|
.subscribe((systemState: appstate.ISystemState) => {
|
||||||
|
this.systemState = systemState;
|
||||||
|
this.updateGlobalMessages();
|
||||||
|
});
|
||||||
|
this.rxSubscriptions.push(systemSubscription);
|
||||||
|
|
||||||
const uiSubscription = appstate.uiStatePart
|
const uiSubscription = appstate.uiStatePart
|
||||||
.select((stateArg) => stateArg)
|
.select((stateArg: appstate.IUiState) => stateArg)
|
||||||
.subscribe((uiState) => {
|
.subscribe((uiState: appstate.IUiState) => {
|
||||||
this.uiState = uiState;
|
this.uiState = uiState;
|
||||||
this.syncAppdashView(uiState.activeView);
|
this.syncAppdashView(uiState.activeView, uiState.activeSubview);
|
||||||
});
|
});
|
||||||
this.rxSubscriptions.push(uiSubscription);
|
this.rxSubscriptions.push(uiSubscription);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static styles = [
|
private async resolveViewTabs(tabs: IUnresolvedView[]): Promise<IResolvedView[]> {
|
||||||
|
return Promise.all(
|
||||||
|
tabs.map(async (tab) => {
|
||||||
|
const resolvedTab: IResolvedView = {
|
||||||
|
slug: tab.slug,
|
||||||
|
name: tab.name,
|
||||||
|
iconName: tab.iconName,
|
||||||
|
};
|
||||||
|
if (tab.element) {
|
||||||
|
resolvedTab.element = await tab.element;
|
||||||
|
}
|
||||||
|
if (tab.subViews) {
|
||||||
|
resolvedTab.subViews = await this.resolveViewTabs(tab.subViews);
|
||||||
|
}
|
||||||
|
return resolvedTab;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private slugFor(view: IResolvedView): string {
|
||||||
|
return view.slug ?? view.name.toLowerCase().replace(/\s+/g, '-');
|
||||||
|
}
|
||||||
|
|
||||||
|
private findParent(view: IResolvedView): IResolvedView | undefined {
|
||||||
|
return this.resolvedViewTabs.find((viewTab) => viewTab.subViews?.includes(view));
|
||||||
|
}
|
||||||
|
|
||||||
|
private findViewBySlug(viewSlug: string, subviewSlug: string | null): IResolvedView | undefined {
|
||||||
|
const topLevelView = this.resolvedViewTabs.find((view) => this.slugFor(view) === viewSlug);
|
||||||
|
if (!topLevelView) return undefined;
|
||||||
|
if (subviewSlug && topLevelView.subViews) {
|
||||||
|
return topLevelView.subViews.find((subview) => this.slugFor(subview) === subviewSlug) ?? topLevelView;
|
||||||
|
}
|
||||||
|
return topLevelView;
|
||||||
|
}
|
||||||
|
|
||||||
|
private get currentViewTab(): IResolvedView | undefined {
|
||||||
|
if (this.resolvedViewTabs.length === 0) return undefined;
|
||||||
|
return this.findViewBySlug(this.uiState.activeView, this.uiState.activeSubview) ?? this.resolvedViewTabs[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static override styles = [
|
||||||
cssManager.defaultStyles,
|
cssManager.defaultStyles,
|
||||||
css`
|
css`
|
||||||
:host {
|
:host {
|
||||||
@@ -87,16 +225,15 @@ export class ObAppShell extends DeesElement {
|
|||||||
`,
|
`,
|
||||||
];
|
];
|
||||||
|
|
||||||
public render(): TemplateResult {
|
public override render(): TemplateResult {
|
||||||
return html`
|
return html`
|
||||||
<div class="maincontainer">
|
<div class="maincontainer">
|
||||||
<dees-simple-login name="Onebox">
|
<dees-simple-login name="Onebox">
|
||||||
<dees-simple-appdash
|
<dees-simple-appdash
|
||||||
name="Onebox"
|
name="Onebox"
|
||||||
.viewTabs=${this.resolvedViewTabs}
|
.viewTabs=${this.resolvedViewTabs}
|
||||||
.selectedView=${this.resolvedViewTabs.find(
|
.selectedView=${this.currentViewTab}
|
||||||
(t) => t.name.toLowerCase().replace(/\s+/g, '-') === this.uiState.activeView
|
.globalMessages=${this.globalMessages}
|
||||||
) || this.resolvedViewTabs[0]}
|
|
||||||
>
|
>
|
||||||
</dees-simple-appdash>
|
</dees-simple-appdash>
|
||||||
</dees-simple-login>
|
</dees-simple-login>
|
||||||
@@ -104,15 +241,8 @@ export class ObAppShell extends DeesElement {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async firstUpdated() {
|
public override async firstUpdated() {
|
||||||
// Resolve async view tab imports
|
this.resolvedViewTabs = await this.resolveViewTabs(this.viewTabs);
|
||||||
this.resolvedViewTabs = await Promise.all(
|
|
||||||
this.viewTabs.map(async (tab) => ({
|
|
||||||
name: tab.name,
|
|
||||||
iconName: tab.iconName,
|
|
||||||
element: await tab.element,
|
|
||||||
})),
|
|
||||||
);
|
|
||||||
this.requestUpdate();
|
this.requestUpdate();
|
||||||
await this.updateComplete;
|
await this.updateComplete;
|
||||||
|
|
||||||
@@ -126,34 +256,44 @@ export class ObAppShell extends DeesElement {
|
|||||||
const appDash = this.shadowRoot!.querySelector('dees-simple-appdash') as any;
|
const appDash = this.shadowRoot!.querySelector('dees-simple-appdash') as any;
|
||||||
if (appDash) {
|
if (appDash) {
|
||||||
appDash.addEventListener('view-select', (e: CustomEvent) => {
|
appDash.addEventListener('view-select', (e: CustomEvent) => {
|
||||||
const viewName = e.detail.view.name.toLowerCase().replace(/\s+/g, '-');
|
const view = e.detail.view as IResolvedView;
|
||||||
appRouter.navigateToView(viewName);
|
const parent = this.findParent(view);
|
||||||
|
const currentState = appstate.uiStatePart.getState();
|
||||||
|
if (parent) {
|
||||||
|
const parentSlug = this.slugFor(parent);
|
||||||
|
const subviewSlug = this.slugFor(view);
|
||||||
|
if (currentState.activeView === parentSlug && currentState.activeSubview === subviewSlug) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
appRouter.navigateToView(parentSlug, subviewSlug);
|
||||||
|
} else {
|
||||||
|
const slug = this.slugFor(view);
|
||||||
|
if (currentState.activeView === slug && !currentState.activeSubview) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
appRouter.navigateToView(slug);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
appDash.addEventListener('logout', async () => {
|
appDash.addEventListener('logout', async () => {
|
||||||
await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null);
|
await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Load the initial view on the appdash now that tabs are resolved
|
|
||||||
// Read activeView directly from state (not this.uiState which may be stale)
|
|
||||||
if (appDash && this.resolvedViewTabs.length > 0) {
|
if (appDash && this.resolvedViewTabs.length > 0) {
|
||||||
const currentActiveView = appstate.uiStatePart.getState().activeView;
|
const currentUiState = appstate.uiStatePart.getState();
|
||||||
const initialView = this.resolvedViewTabs.find(
|
const initialView =
|
||||||
(t) => t.name.toLowerCase().replace(/\s+/g, '-') === currentActiveView,
|
this.findViewBySlug(currentUiState.activeView, currentUiState.activeSubview) ||
|
||||||
) || this.resolvedViewTabs[0];
|
this.resolvedViewTabs[0];
|
||||||
await appDash.loadView(initialView);
|
await appDash.loadView(initialView);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for stored session (persistent login state)
|
|
||||||
const loginState = appstate.loginStatePart.getState();
|
const loginState = appstate.loginStatePart.getState();
|
||||||
if (loginState.identity?.jwt) {
|
if (loginState.identity?.jwt) {
|
||||||
if (loginState.identity.expiresAt > Date.now()) {
|
if (loginState.identity.expiresAt > Date.now()) {
|
||||||
// Switch to dashboard immediately (no flash of login form)
|
|
||||||
this.loginState = loginState;
|
this.loginState = loginState;
|
||||||
if (simpleLogin) {
|
if (simpleLogin) {
|
||||||
await simpleLogin.switchToSlottedContent();
|
await simpleLogin.switchToSlottedContent();
|
||||||
}
|
}
|
||||||
// Validate token with server in the background
|
|
||||||
try {
|
try {
|
||||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
interfaces.requests.IReq_GetSystemStatus
|
interfaces.requests.IReq_GetSystemStatus
|
||||||
@@ -161,11 +301,9 @@ export class ObAppShell extends DeesElement {
|
|||||||
const response = await typedRequest.fire({ identity: loginState.identity });
|
const response = await typedRequest.fire({ identity: loginState.identity });
|
||||||
appstate.systemStatePart.setState({ status: response.status });
|
appstate.systemStatePart.setState({ status: response.status });
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// Token rejected by server - switch back to login
|
|
||||||
console.warn('Stored session invalid, returning to login:', err);
|
console.warn('Stored session invalid, returning to login:', err);
|
||||||
await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null);
|
await appstate.loginStatePart.dispatchAction(appstate.logoutAction, null);
|
||||||
if (simpleLogin) {
|
if (simpleLogin) {
|
||||||
// Force page reload to show login properly
|
|
||||||
window.location.reload();
|
window.location.reload();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -206,14 +344,184 @@ export class ObAppShell extends DeesElement {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private syncAppdashView(viewName: string): void {
|
private updateGlobalMessages(): void {
|
||||||
|
const updateStatus = this.systemState.status?.onebox.update;
|
||||||
|
if (
|
||||||
|
!this.loginState.isLoggedIn ||
|
||||||
|
!updateStatus?.updateAvailable ||
|
||||||
|
!updateStatus.latestVersion ||
|
||||||
|
updateStatus.latestVersion === this.suppressedUpdateVersion
|
||||||
|
) {
|
||||||
|
this.globalMessages = [];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.globalMessages = [
|
||||||
|
{
|
||||||
|
id: `onebox-update-${updateStatus.latestVersion}`,
|
||||||
|
type: 'info',
|
||||||
|
icon: 'lucide:download',
|
||||||
|
message: `Onebox ${updateStatus.latestVersion} is available. Current version: ${updateStatus.currentVersion}.`,
|
||||||
|
dismissible: false,
|
||||||
|
actions: [
|
||||||
|
{
|
||||||
|
name: 'Update Now',
|
||||||
|
iconName: 'lucide:download',
|
||||||
|
action: () => this.startOneboxUpgradeFlow(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Release Notes',
|
||||||
|
iconName: 'lucide:fileText',
|
||||||
|
action: () => this.openUpdateUrl(updateStatus.changelogUrl || updateStatus.releaseUrl),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Later',
|
||||||
|
iconName: 'lucide:clock',
|
||||||
|
action: () => {
|
||||||
|
this.suppressedUpdateVersion = updateStatus.latestVersion || '';
|
||||||
|
this.updateGlobalMessages();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private async startOneboxUpgradeFlow(): Promise<void> {
|
||||||
|
if (this.upgradeFlowRunning) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const identity = appstate.loginStatePart.getState().identity;
|
||||||
|
const updateStatus = this.systemState.status?.onebox.update;
|
||||||
|
if (!identity || !updateStatus?.latestVersion) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.upgradeFlowRunning = true;
|
||||||
|
const updater = await plugins.deesCatalog.DeesUpdater.createAndShow({
|
||||||
|
currentVersion: updateStatus.currentVersion,
|
||||||
|
updatedVersion: updateStatus.latestVersion,
|
||||||
|
moreInfoUrl: updateStatus.releaseUrl,
|
||||||
|
changelogUrl: updateStatus.changelogUrl,
|
||||||
|
successAction: 'reload',
|
||||||
|
successDelayMs: 30000,
|
||||||
|
successActionLabel: 'Reloading Onebox UI',
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
updater.updateProgress({
|
||||||
|
percentage: 10,
|
||||||
|
indeterminate: true,
|
||||||
|
statusText: 'Requesting upgrade...',
|
||||||
|
terminalLines: ['Requesting Onebox upgrade'],
|
||||||
|
});
|
||||||
|
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_StartOneboxUpgrade
|
||||||
|
>('/typedrequest', 'startOneboxUpgrade');
|
||||||
|
const response = await typedRequest.fire({ identity });
|
||||||
|
|
||||||
|
if (!response.upgrade.accepted) {
|
||||||
|
updater.markUpdateError(response.upgrade.message);
|
||||||
|
await this.delay(5000);
|
||||||
|
await updater.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
updater.appendProgressLine(response.upgrade.message);
|
||||||
|
if (response.upgrade.pid) {
|
||||||
|
updater.appendProgressLine(`Upgrade process PID: ${response.upgrade.pid}`);
|
||||||
|
}
|
||||||
|
if (response.upgrade.logPath) {
|
||||||
|
updater.appendProgressLine(`Upgrade log: ${response.upgrade.logPath}`);
|
||||||
|
}
|
||||||
|
updater.updateProgress({
|
||||||
|
percentage: 45,
|
||||||
|
indeterminate: true,
|
||||||
|
statusText: 'Installer started...',
|
||||||
|
});
|
||||||
|
|
||||||
|
await this.waitForOneboxUpgrade(updater, response.upgrade.targetVersion, identity);
|
||||||
|
await updater.markUpdateReady();
|
||||||
|
} catch (error) {
|
||||||
|
updater.markUpdateError(this.getErrorMessage(error));
|
||||||
|
await this.delay(5000);
|
||||||
|
await updater.destroy();
|
||||||
|
} finally {
|
||||||
|
this.upgradeFlowRunning = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async waitForOneboxUpgrade(
|
||||||
|
updaterArg: plugins.deesCatalog.DeesUpdater,
|
||||||
|
targetVersionArg: string,
|
||||||
|
identityArg: interfaces.data.IIdentity,
|
||||||
|
): Promise<void> {
|
||||||
|
const normalizedTargetVersion = this.normalizeVersion(targetVersionArg);
|
||||||
|
const timeoutAt = Date.now() + 90000;
|
||||||
|
let attempt = 0;
|
||||||
|
|
||||||
|
updaterArg.appendProgressLine('Waiting for Onebox to restart with the new version');
|
||||||
|
while (Date.now() < timeoutAt) {
|
||||||
|
await this.delay(5000);
|
||||||
|
attempt++;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
|
interfaces.requests.IReq_GetSystemStatus
|
||||||
|
>('/typedrequest', 'getSystemStatus');
|
||||||
|
const response = await typedRequest.fire({ identity: identityArg });
|
||||||
|
const onlineVersion = this.normalizeVersion(response.status.onebox.version);
|
||||||
|
updaterArg.appendProgressLine(`Onebox API answered with ${onlineVersion}`);
|
||||||
|
|
||||||
|
if (onlineVersion === normalizedTargetVersion) {
|
||||||
|
updaterArg.updateProgress({
|
||||||
|
percentage: 100,
|
||||||
|
indeterminate: false,
|
||||||
|
statusText: `Onebox ${normalizedTargetVersion} is online.`,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
updaterArg.appendProgressLine('Onebox API is restarting...');
|
||||||
|
}
|
||||||
|
|
||||||
|
updaterArg.updateProgress({
|
||||||
|
percentage: Math.min(95, 45 + attempt * 5),
|
||||||
|
indeterminate: true,
|
||||||
|
statusText: `Waiting for Onebox ${normalizedTargetVersion}...`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
updaterArg.appendProgressLine('Timed out waiting for the version check; reloading the UI anyway');
|
||||||
|
}
|
||||||
|
|
||||||
|
private openUpdateUrl(urlArg: string): void {
|
||||||
|
window.open(urlArg, '_blank', 'noopener,noreferrer');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async delay(millisecondsArg: number): Promise<void> {
|
||||||
|
const domtools = await this.domtoolsPromise;
|
||||||
|
await domtools.convenience.smartdelay.delayFor(millisecondsArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
private getErrorMessage(errorArg: unknown): string {
|
||||||
|
return errorArg instanceof Error ? errorArg.message : String(errorArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeVersion(versionArg: string): string {
|
||||||
|
const trimmedVersion = versionArg.trim();
|
||||||
|
return trimmedVersion.startsWith('v') ? trimmedVersion : `v${trimmedVersion}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private syncAppdashView(viewName: string, subviewName: string | null): void {
|
||||||
const appDash = this.shadowRoot?.querySelector('dees-simple-appdash') as any;
|
const appDash = this.shadowRoot?.querySelector('dees-simple-appdash') as any;
|
||||||
if (!appDash || this.resolvedViewTabs.length === 0) return;
|
if (!appDash || this.resolvedViewTabs.length === 0) return;
|
||||||
// Match kebab-case view name (e.g., 'app-store') to tab name (e.g., 'App Store')
|
|
||||||
const targetTab = this.resolvedViewTabs.find(
|
const targetTab = this.findViewBySlug(viewName, subviewName);
|
||||||
(t) => t.name.toLowerCase().replace(/\s+/g, '-') === viewName
|
if (!targetTab || appDash.selectedView === targetTab) return;
|
||||||
);
|
|
||||||
if (!targetTab) return;
|
|
||||||
appDash.loadView(targetTab);
|
appDash.loadView(targetTab);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,19 +19,20 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
accessor appStoreState: appstate.IAppStoreState = {
|
accessor appStoreState: appstate.IAppStoreState = {
|
||||||
apps: [],
|
apps: [],
|
||||||
upgradeableServices: [],
|
upgradeableServices: [],
|
||||||
|
upgradeOperations: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
accessor currentView: 'grid' | 'detail' = 'grid';
|
accessor currentView: 'grid' | 'detail' = 'grid';
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
accessor selectedApp: interfaces.requests.ICatalogApp | null = null;
|
accessor selectedApp: interfaces.requests.IAppStoreApp | null = null;
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
accessor selectedAppMeta: interfaces.requests.IAppMeta | null = null;
|
accessor selectedAppMeta: interfaces.requests.IAppStoreAppMeta | null = null;
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
accessor selectedAppConfig: interfaces.requests.IAppVersionConfig | null = null;
|
accessor selectedAppConfig: interfaces.requests.IAppStoreVersionConfig | null = null;
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
accessor selectedVersion: string = '';
|
accessor selectedVersion: string = '';
|
||||||
@@ -288,6 +289,34 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
color: var(--ci-shade-4, #71717a);
|
color: var(--ci-shade-4, #71717a);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.footprint-list {
|
||||||
|
display: grid;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footprint-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid var(--ci-shade-2, #27272a);
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--ci-shade-6, #d4d4d8);
|
||||||
|
}
|
||||||
|
|
||||||
|
.footprint-meta {
|
||||||
|
color: var(--ci-shade-4, #71717a);
|
||||||
|
font-family: monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
.exposure-warning {
|
||||||
|
margin-top: 10px;
|
||||||
|
color: #fbbf24;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
`,
|
`,
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -303,7 +332,10 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
|
|
||||||
async connectedCallback() {
|
async connectedCallback() {
|
||||||
super.connectedCallback();
|
super.connectedCallback();
|
||||||
await appstate.appStoreStatePart.dispatchAction(appstate.fetchAppTemplatesAction, null);
|
await Promise.all([
|
||||||
|
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreTemplatesAction, null),
|
||||||
|
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreUpgradeOperationsAction, null),
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
public render(): TemplateResult {
|
public render(): TemplateResult {
|
||||||
@@ -329,6 +361,7 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
|
|
||||||
return html`
|
return html`
|
||||||
<ob-sectionheading>App Store</ob-sectionheading>
|
<ob-sectionheading>App Store</ob-sectionheading>
|
||||||
|
${this.renderUpgradeOperations()}
|
||||||
${appTemplates.length === 0
|
${appTemplates.length === 0
|
||||||
? html`<div class="loading-spinner">Loading app templates...</div>`
|
? html`<div class="loading-spinner">Loading app templates...</div>`
|
||||||
: html`
|
: html`
|
||||||
@@ -341,6 +374,27 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private renderUpgradeOperations(): TemplateResult | '' {
|
||||||
|
const visibleOperations = this.appStoreState.upgradeOperations
|
||||||
|
.filter((operation) => operation.status === 'running' || operation.status === 'failed')
|
||||||
|
.slice(0, 3);
|
||||||
|
if (visibleOperations.length === 0) return '';
|
||||||
|
|
||||||
|
return html`
|
||||||
|
<div class="detail-card">
|
||||||
|
<div class="section-label">Recent Upgrade Operations</div>
|
||||||
|
<div class="footprint-list">
|
||||||
|
${visibleOperations.map((operation) => html`
|
||||||
|
<div class="footprint-item">
|
||||||
|
<span>${operation.serviceName}: ${operation.fromVersion} → ${operation.targetVersion}</span>
|
||||||
|
<span class="footprint-meta">${operation.status} / ${operation.step}</span>
|
||||||
|
</div>
|
||||||
|
`)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
private renderDetailView(): TemplateResult {
|
private renderDetailView(): TemplateResult {
|
||||||
if (this.loading) {
|
if (this.loading) {
|
||||||
return html`
|
return html`
|
||||||
@@ -410,6 +464,8 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
</div>
|
</div>
|
||||||
` : ''}
|
` : ''}
|
||||||
|
|
||||||
|
${this.renderDeploymentFootprint(config)}
|
||||||
|
|
||||||
<!-- Version & Image -->
|
<!-- Version & Image -->
|
||||||
<div class="detail-card">
|
<div class="detail-card">
|
||||||
<div class="section-label">Version</div>
|
<div class="section-label">Version</div>
|
||||||
@@ -489,6 +545,8 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
Onebox routes this domain to the deployed app. Required when the app uses SERVICE_DOMAIN.
|
Onebox routes this domain to the deployed app. Required when the app uses SERVICE_DOMAIN.
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
${this.renderDeployConfirmation(config)}
|
||||||
|
|
||||||
<div class="actions-row">
|
<div class="actions-row">
|
||||||
<button class="btn btn-secondary" @click=${() => { this.currentView = 'grid'; }}>Cancel</button>
|
<button class="btn btn-secondary" @click=${() => { this.currentView = 'grid'; }}>Cancel</button>
|
||||||
<button class="btn btn-primary" @click=${() => this.handleDeploy()}>
|
<button class="btn btn-primary" @click=${() => this.handleDeploy()}>
|
||||||
@@ -509,6 +567,73 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private renderDeploymentFootprint(config: interfaces.requests.IAppStoreVersionConfig): TemplateResult | '' {
|
||||||
|
const volumes = this.getConfigVolumes(config);
|
||||||
|
const publishedPorts = config.publishedPorts || [];
|
||||||
|
|
||||||
|
if (volumes.length === 0 && publishedPorts.length === 0) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
return html`
|
||||||
|
<div class="detail-card">
|
||||||
|
<div class="section-label">Deployment Footprint</div>
|
||||||
|
<div class="footprint-list">
|
||||||
|
${volumes.map((volume) => html`
|
||||||
|
<div class="footprint-item">
|
||||||
|
<span>Volume mount</span>
|
||||||
|
<span class="footprint-meta">
|
||||||
|
${volume.source || volume.name || 'managed volume'}:${volume.mountPath}${volume.readOnly ? ':ro' : ''}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
`)}
|
||||||
|
${publishedPorts.map((port) => html`
|
||||||
|
<div class="footprint-item">
|
||||||
|
<span>Published host port</span>
|
||||||
|
<span class="footprint-meta">${this.formatPublishedPort(port)}</span>
|
||||||
|
</div>
|
||||||
|
`)}
|
||||||
|
</div>
|
||||||
|
${publishedPorts.length > 0 ? html`
|
||||||
|
<div class="exposure-warning">
|
||||||
|
This app publishes raw host ports outside the HTTP proxy. Confirm firewall and network policy before deploying.
|
||||||
|
</div>
|
||||||
|
` : ''}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderDeployConfirmation(config: interfaces.requests.IAppStoreVersionConfig): TemplateResult | '' {
|
||||||
|
const volumes = this.getConfigVolumes(config);
|
||||||
|
const publishedPorts = config.publishedPorts || [];
|
||||||
|
if (volumes.length === 0 && publishedPorts.length === 0) return '';
|
||||||
|
|
||||||
|
return html`
|
||||||
|
<div class="exposure-warning">
|
||||||
|
Deploying this app will create ${volumes.length} persistent volume(s)
|
||||||
|
${publishedPorts.length > 0 ? html`and expose ${publishedPorts.length} host port declaration(s)` : ''}.
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private getConfigVolumes(config: interfaces.requests.IAppStoreVersionConfig): interfaces.data.IServiceVolume[] {
|
||||||
|
return (config.volumes || []).map((volume) => {
|
||||||
|
if (typeof volume === 'string') {
|
||||||
|
return { mountPath: volume };
|
||||||
|
}
|
||||||
|
return volume;
|
||||||
|
}).filter((volume) => Boolean(volume.mountPath));
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatPublishedPort(port: interfaces.data.IServicePublishedPort): string {
|
||||||
|
const protocol = port.protocol || 'tcp';
|
||||||
|
const target = port.targetPortEnd ? `${port.targetPort}-${port.targetPortEnd}` : String(port.targetPort);
|
||||||
|
const publishedStart = port.publishedPort || port.targetPort;
|
||||||
|
const publishedEnd = port.publishedPortEnd || (port.targetPortEnd ? publishedStart + (port.targetPortEnd - port.targetPort) : undefined);
|
||||||
|
const published = publishedEnd ? `${publishedStart}-${publishedEnd}` : String(publishedStart);
|
||||||
|
return `${port.hostIp || '0.0.0.0'}:${published}/${protocol} -> ${target}/${protocol}`;
|
||||||
|
}
|
||||||
|
|
||||||
private async handleViewDetails(e: CustomEvent) {
|
private async handleViewDetails(e: CustomEvent) {
|
||||||
const app = e.detail?.app;
|
const app = e.detail?.app;
|
||||||
if (!app) return;
|
if (!app) return;
|
||||||
@@ -559,8 +684,8 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
if (!identity) return;
|
if (!identity) return;
|
||||||
|
|
||||||
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
interfaces.requests.IReq_GetAppConfig
|
interfaces.requests.IReq_GetAppStoreConfig
|
||||||
>('/typedrequest', 'getAppConfig');
|
>('/typedrequest', 'getAppStoreConfig');
|
||||||
|
|
||||||
const response = await typedRequest.fire({ identity, appId, version });
|
const response = await typedRequest.fire({ identity, appId, version });
|
||||||
|
|
||||||
@@ -625,25 +750,21 @@ export class ObViewAppStore extends DeesElement {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const platformReqs = config.platformRequirements || {};
|
try {
|
||||||
const serviceConfig: interfaces.data.IServiceCreate = {
|
const identity = appstate.loginStatePart.getState().identity;
|
||||||
name: this.serviceName || app.id,
|
if (!identity) return;
|
||||||
image: config.image,
|
const typedRequest = new plugins.domtools.plugins.typedrequest.TypedRequest<
|
||||||
port: config.port || 80,
|
interfaces.requests.IReq_InstallAppStoreApp
|
||||||
|
>('/typedrequest', 'installAppStoreApp');
|
||||||
|
await typedRequest.fire({
|
||||||
|
identity,
|
||||||
|
install: {
|
||||||
|
appId: app.id,
|
||||||
|
version: this.selectedVersion,
|
||||||
|
serviceName: this.serviceName || app.id,
|
||||||
domain: this.serviceDomain || undefined,
|
domain: this.serviceDomain || undefined,
|
||||||
envVars,
|
envVars,
|
||||||
enableMongoDB: platformReqs.mongodb || false,
|
},
|
||||||
enableS3: platformReqs.s3 || false,
|
|
||||||
enableClickHouse: platformReqs.clickhouse || false,
|
|
||||||
enableRedis: platformReqs.redis || false,
|
|
||||||
enableMariaDB: platformReqs.mariadb || false,
|
|
||||||
appTemplateId: app.id,
|
|
||||||
appTemplateVersion: this.selectedVersion,
|
|
||||||
};
|
|
||||||
|
|
||||||
try {
|
|
||||||
await appstate.servicesStatePart.dispatchAction(appstate.createServiceAction, {
|
|
||||||
config: serviceConfig,
|
|
||||||
});
|
});
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
appRouter.navigateToView('services');
|
appRouter.navigateToView('services');
|
||||||
|
|||||||
@@ -12,6 +12,20 @@ import {
|
|||||||
type TemplateResult,
|
type TemplateResult,
|
||||||
} from '@design.estate/dees-element';
|
} from '@design.estate/dees-element';
|
||||||
|
|
||||||
|
const byteUnits = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
|
||||||
|
function getByteUnitIndex(bytes: number): number {
|
||||||
|
if (!bytes || bytes === 0) return 0;
|
||||||
|
return Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), byteUnits.length - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number, forcedUnitIndex?: number): string {
|
||||||
|
if ((!bytes || bytes === 0) && forcedUnitIndex === undefined) return '0 B';
|
||||||
|
const unitIndex = forcedUnitIndex ?? getByteUnitIndex(bytes);
|
||||||
|
const value = bytes / Math.pow(1024, unitIndex);
|
||||||
|
return `${value.toFixed(1)} ${byteUnits[unitIndex]}`;
|
||||||
|
}
|
||||||
|
|
||||||
@customElement('ob-view-dashboard')
|
@customElement('ob-view-dashboard')
|
||||||
export class ObViewDashboard extends DeesElement {
|
export class ObViewDashboard extends DeesElement {
|
||||||
@state()
|
@state()
|
||||||
@@ -36,6 +50,8 @@ export class ObViewDashboard extends DeesElement {
|
|||||||
trafficStats: null,
|
trafficStats: null,
|
||||||
dnsRecords: [],
|
dnsRecords: [],
|
||||||
domains: [],
|
domains: [],
|
||||||
|
gatewayDomains: [],
|
||||||
|
gatewayDnsRecords: [],
|
||||||
certificates: [],
|
certificates: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -67,7 +83,42 @@ export class ObViewDashboard extends DeesElement {
|
|||||||
public static styles = [
|
public static styles = [
|
||||||
cssManager.defaultStyles,
|
cssManager.defaultStyles,
|
||||||
shared.viewHostCss,
|
shared.viewHostCss,
|
||||||
css``,
|
css`
|
||||||
|
.dashboard {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: ${cssManager.bdTheme('#18181b', '#fafafa')};
|
||||||
|
margin: 0 0 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.services-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
gap: 16px;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.services-grid > * {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (min-width: 768px) {
|
||||||
|
.services-grid {
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
`,
|
||||||
];
|
];
|
||||||
|
|
||||||
async connectedCallback() {
|
async connectedCallback() {
|
||||||
@@ -77,6 +128,7 @@ export class ObViewDashboard extends DeesElement {
|
|||||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null),
|
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null),
|
||||||
appstate.servicesStatePart.dispatchAction(appstate.fetchPlatformServicesAction, null),
|
appstate.servicesStatePart.dispatchAction(appstate.fetchPlatformServicesAction, null),
|
||||||
appstate.networkStatePart.dispatchAction(appstate.fetchNetworkStatsAction, null),
|
appstate.networkStatePart.dispatchAction(appstate.fetchNetworkStatsAction, null),
|
||||||
|
appstate.networkStatePart.dispatchAction(appstate.fetchTrafficStatsAction, null),
|
||||||
appstate.networkStatePart.dispatchAction(appstate.fetchCertificatesAction, null),
|
appstate.networkStatePart.dispatchAction(appstate.fetchCertificatesAction, null),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
@@ -86,10 +138,15 @@ export class ObViewDashboard extends DeesElement {
|
|||||||
const services = this.servicesState.services;
|
const services = this.servicesState.services;
|
||||||
const platformServices = this.servicesState.platformServices;
|
const platformServices = this.servicesState.platformServices;
|
||||||
const networkStats = this.networkState.stats;
|
const networkStats = this.networkState.stats;
|
||||||
|
const trafficStats = this.networkState.trafficStats;
|
||||||
const certificates = this.networkState.certificates;
|
const certificates = this.networkState.certificates;
|
||||||
|
const statusCounts = trafficStats?.statusCounts || {};
|
||||||
|
|
||||||
const runningServices = services.filter((s) => s.status === 'running').length;
|
const runningServices = services.filter((s) => s.status === 'running').length;
|
||||||
const stoppedServices = services.filter((s) => s.status === 'stopped').length;
|
const stoppedServices = services.filter((s) => s.status === 'stopped').length;
|
||||||
|
const memoryUnitIndex = getByteUnitIndex(
|
||||||
|
status?.docker?.memoryTotal || status?.docker?.memoryUsage || 0,
|
||||||
|
);
|
||||||
|
|
||||||
const validCerts = certificates.filter((c) => c.isValid).length;
|
const validCerts = certificates.filter((c) => c.isValid).length;
|
||||||
const expiringCerts = certificates.filter(
|
const expiringCerts = certificates.filter(
|
||||||
@@ -97,22 +154,19 @@ export class ObViewDashboard extends DeesElement {
|
|||||||
).length;
|
).length;
|
||||||
const expiredCerts = certificates.filter((c) => !c.isValid).length;
|
const expiredCerts = certificates.filter((c) => !c.isValid).length;
|
||||||
|
|
||||||
return html`
|
const dashboardData = {
|
||||||
<ob-sectionheading>Dashboard</ob-sectionheading>
|
|
||||||
<sz-dashboard-view
|
|
||||||
.data=${{
|
|
||||||
cluster: {
|
cluster: {
|
||||||
totalServices: services.length,
|
totalServices: services.length,
|
||||||
running: runningServices,
|
running: runningServices,
|
||||||
stopped: stoppedServices,
|
stopped: stoppedServices,
|
||||||
dockerStatus: status?.docker?.running ? 'running' : 'stopped',
|
dockerStatus: status?.docker?.running ? 'running' as const : 'stopped' as const,
|
||||||
},
|
},
|
||||||
resourceUsage: {
|
resourceUsage: {
|
||||||
cpu: status?.docker?.cpuUsage || 0,
|
cpu: status?.docker?.cpuUsage || 0,
|
||||||
memoryUsed: status?.docker?.memoryUsage || 0,
|
memoryUsed: formatBytes(status?.docker?.memoryUsage || 0, memoryUnitIndex),
|
||||||
memoryTotal: status?.docker?.memoryTotal || 0,
|
memoryTotal: formatBytes(status?.docker?.memoryTotal || 0, memoryUnitIndex),
|
||||||
networkIn: status?.docker?.networkIn || 0,
|
networkIn: formatBytes(status?.docker?.networkIn || 0),
|
||||||
networkOut: status?.docker?.networkOut || 0,
|
networkOut: formatBytes(status?.docker?.networkOut || 0),
|
||||||
topConsumers: [],
|
topConsumers: [],
|
||||||
},
|
},
|
||||||
platformServices: platformServices
|
platformServices: platformServices
|
||||||
@@ -123,39 +177,75 @@ export class ObViewDashboard extends DeesElement {
|
|||||||
running: ps.status === 'running',
|
running: ps.status === 'running',
|
||||||
})),
|
})),
|
||||||
traffic: {
|
traffic: {
|
||||||
requests: 0,
|
requests: trafficStats?.requestCount || 0,
|
||||||
errors: 0,
|
errors: trafficStats?.errorCount || 0,
|
||||||
errorPercent: 0,
|
errorPercent: trafficStats?.errorRate || 0,
|
||||||
avgResponse: 0,
|
avgResponse: trafficStats?.avgResponseTime || 0,
|
||||||
reqPerMin: 0,
|
reqPerMin: trafficStats?.requestsPerMinute || 0,
|
||||||
status2xx: 0,
|
status2xx: statusCounts['2xx'] || 0,
|
||||||
status3xx: 0,
|
status3xx: statusCounts['3xx'] || 0,
|
||||||
status4xx: 0,
|
status4xx: statusCounts['4xx'] || 0,
|
||||||
status5xx: 0,
|
status5xx: statusCounts['5xx'] || 0,
|
||||||
},
|
},
|
||||||
proxy: {
|
proxy: {
|
||||||
httpPort: networkStats?.proxy?.httpPort || 80,
|
httpPort: String(networkStats?.proxy?.httpPort || 80),
|
||||||
httpsPort: networkStats?.proxy?.httpsPort || 443,
|
httpsPort: String(networkStats?.proxy?.httpsPort || 443),
|
||||||
httpActive: networkStats?.proxy?.running || false,
|
httpActive: networkStats?.proxy?.running || false,
|
||||||
httpsActive: networkStats?.proxy?.running || false,
|
httpsActive: networkStats?.proxy?.running || false,
|
||||||
routeCount: networkStats?.proxy?.routes || 0,
|
routeCount: String(networkStats?.proxy?.routes || 0),
|
||||||
},
|
},
|
||||||
certificates: {
|
certificates: {
|
||||||
valid: validCerts,
|
valid: validCerts,
|
||||||
expiring: expiringCerts,
|
expiring: expiringCerts,
|
||||||
expired: expiredCerts,
|
expired: expiredCerts,
|
||||||
},
|
},
|
||||||
dnsConfigured: true,
|
dnsConfigured: status?.dns?.configured || false,
|
||||||
acmeConfigured: true,
|
acmeConfigured: status?.ssl?.configured || false,
|
||||||
quickActions: [
|
quickActions: [
|
||||||
{ label: 'Deploy Service', icon: 'lucide:Plus', primary: true },
|
{ label: 'Deploy Service', icon: 'lucide:Plus', primary: true },
|
||||||
{ label: 'Add Domain', icon: 'lucide:Globe' },
|
{ label: 'Add Domain', icon: 'lucide:Globe' },
|
||||||
{ label: 'View Logs', icon: 'lucide:FileText' },
|
{ label: 'View Logs', icon: 'lucide:FileText' },
|
||||||
],
|
],
|
||||||
}}
|
};
|
||||||
@action-click=${(e: CustomEvent) => this.handleQuickAction(e)}
|
|
||||||
|
return html`
|
||||||
|
<ob-sectionheading>Dashboard</ob-sectionheading>
|
||||||
|
<div class="dashboard">
|
||||||
|
<section class="section">
|
||||||
|
<h2 class="section-title">Cluster Overview</h2>
|
||||||
|
<sz-status-grid-cluster .stats=${dashboardData.cluster}></sz-status-grid-cluster>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="section">
|
||||||
|
<h2 class="section-title">Services & Resources</h2>
|
||||||
|
<div class="services-grid">
|
||||||
|
<sz-resource-usage-card .data=${dashboardData.resourceUsage}></sz-resource-usage-card>
|
||||||
|
<sz-platform-services-card
|
||||||
|
.services=${dashboardData.platformServices}
|
||||||
@service-click=${(e: CustomEvent) => this.handlePlatformServiceClick(e)}
|
@service-click=${(e: CustomEvent) => this.handlePlatformServiceClick(e)}
|
||||||
></sz-dashboard-view>
|
></sz-platform-services-card>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="section">
|
||||||
|
<h2 class="section-title">Network & Traffic</h2>
|
||||||
|
<sz-status-grid-network
|
||||||
|
.traffic=${dashboardData.traffic}
|
||||||
|
.proxy=${dashboardData.proxy}
|
||||||
|
.certificates=${dashboardData.certificates}
|
||||||
|
></sz-status-grid-network>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="section">
|
||||||
|
<h2 class="section-title">Infrastructure</h2>
|
||||||
|
<sz-status-grid-infra
|
||||||
|
?dnsConfigured=${dashboardData.dnsConfigured}
|
||||||
|
?acmeConfigured=${dashboardData.acmeConfigured}
|
||||||
|
.actions=${dashboardData.quickActions}
|
||||||
|
@action-click=${(e: CustomEvent) => this.handleQuickAction(e)}
|
||||||
|
></sz-status-grid-infra>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import * as shared from './shared/index.js';
|
||||||
|
import * as plugins from '../plugins.js';
|
||||||
|
import * as appstate from '../appstate.js';
|
||||||
|
import { appRouter } from '../router.js';
|
||||||
|
import {
|
||||||
|
DeesElement,
|
||||||
|
customElement,
|
||||||
|
html,
|
||||||
|
state,
|
||||||
|
css,
|
||||||
|
cssManager,
|
||||||
|
type TemplateResult,
|
||||||
|
} from '@design.estate/dees-element';
|
||||||
|
|
||||||
|
type TGatewayDnsRecord = appstate.INetworkState['gatewayDnsRecords'][number];
|
||||||
|
|
||||||
|
@customElement('ob-view-dns-records')
|
||||||
|
export class ObViewDnsRecords extends DeesElement {
|
||||||
|
@state()
|
||||||
|
accessor networkState: appstate.INetworkState = {
|
||||||
|
targets: [],
|
||||||
|
stats: null,
|
||||||
|
trafficStats: null,
|
||||||
|
dnsRecords: [],
|
||||||
|
domains: [],
|
||||||
|
gatewayDomains: [],
|
||||||
|
gatewayDnsRecords: [],
|
||||||
|
certificates: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
const networkSub = appstate.networkStatePart.select((s) => s).subscribe((newState) => {
|
||||||
|
this.networkState = newState;
|
||||||
|
});
|
||||||
|
this.rxSubscriptions.push(networkSub);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static styles = [
|
||||||
|
cssManager.defaultStyles,
|
||||||
|
shared.viewHostCss,
|
||||||
|
css`
|
||||||
|
.name { font-weight: 600; }
|
||||||
|
.value { font-family: monospace; color: var(--ci-shade-5, #71717a); overflow-wrap: anywhere; }
|
||||||
|
.muted { color: var(--ci-shade-5, #71717a); font-size: 13px; }
|
||||||
|
.badge { border-radius: 999px; padding: 3px 8px; background: var(--ci-shade-1, #f4f4f5); font-size: 12px; }
|
||||||
|
.missing { color: #dc2626; }
|
||||||
|
.empty { padding: 32px; text-align: center; color: var(--ci-shade-5, #71717a); }
|
||||||
|
`,
|
||||||
|
];
|
||||||
|
|
||||||
|
async connectedCallback() {
|
||||||
|
super.connectedCallback();
|
||||||
|
await appstate.networkStatePart.dispatchAction(appstate.fetchGatewayDnsRecordsAction, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public render(): TemplateResult {
|
||||||
|
const records = this.networkState.gatewayDnsRecords;
|
||||||
|
return html`
|
||||||
|
<ob-sectionheading>DNS Records</ob-sectionheading>
|
||||||
|
${records.length
|
||||||
|
? html`
|
||||||
|
<dees-table
|
||||||
|
.heading1=${'Gateway DNS Records'}
|
||||||
|
.heading2=${'DNS records published through dcrouter for Onebox services'}
|
||||||
|
.data=${records}
|
||||||
|
.showColumnFilters=${true}
|
||||||
|
.displayFunction=${(record: TGatewayDnsRecord) => ({
|
||||||
|
Name: html`
|
||||||
|
<div>
|
||||||
|
<div class="name">${record.name}</div>
|
||||||
|
${record.domainName ? html`<div class="muted">${record.domainName}</div>` : ''}
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
Type: html`<span class="badge">${record.type}</span>`,
|
||||||
|
Value: html`<span class="value">${record.value || '-'}</span>`,
|
||||||
|
Status: html`<span class=${record.status === 'missing' ? 'missing' : ''}>${record.status}</span>`,
|
||||||
|
Service: record.serviceName || record.appId || '-',
|
||||||
|
})}
|
||||||
|
.dataActions=${[
|
||||||
|
{
|
||||||
|
name: 'Refresh',
|
||||||
|
iconName: 'lucide:rotateCw',
|
||||||
|
type: ['header'],
|
||||||
|
actionFunc: async () => {
|
||||||
|
await appstate.networkStatePart.dispatchAction(
|
||||||
|
appstate.fetchGatewayDnsRecordsAction,
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'View service',
|
||||||
|
iconName: 'lucide:boxes',
|
||||||
|
type: ['inRow', 'contextmenu'],
|
||||||
|
actionFunc: async () => {
|
||||||
|
appRouter.navigateToView('services');
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Manage in dcrouter',
|
||||||
|
iconName: 'lucide:externalLink',
|
||||||
|
type: ['inRow', 'contextmenu'],
|
||||||
|
actionRelevancyCheckFunc: (record: TGatewayDnsRecord) => !!record.manageUrl,
|
||||||
|
actionFunc: async (actionData: plugins.deesCatalog.ITableActionDataArg<TGatewayDnsRecord>) => {
|
||||||
|
if (actionData.item.manageUrl) {
|
||||||
|
globalThis.open(actionData.item.manageUrl, '_blank', 'noopener');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
] as plugins.deesCatalog.ITableAction<TGatewayDnsRecord>[]}
|
||||||
|
></dees-table>
|
||||||
|
`
|
||||||
|
: html`<div class="empty">No gateway DNS records found. Configure a dcrouter gateway in Settings.</div>`}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import * as shared from './shared/index.js';
|
||||||
|
import * as plugins from '../plugins.js';
|
||||||
|
import * as appstate from '../appstate.js';
|
||||||
|
import {
|
||||||
|
DeesElement,
|
||||||
|
customElement,
|
||||||
|
html,
|
||||||
|
state,
|
||||||
|
css,
|
||||||
|
cssManager,
|
||||||
|
type TemplateResult,
|
||||||
|
} from '@design.estate/dees-element';
|
||||||
|
|
||||||
|
type TGatewayDomain = appstate.INetworkState['gatewayDomains'][number];
|
||||||
|
|
||||||
|
@customElement('ob-view-domains')
|
||||||
|
export class ObViewDomains extends DeesElement {
|
||||||
|
@state()
|
||||||
|
accessor networkState: appstate.INetworkState = {
|
||||||
|
targets: [],
|
||||||
|
stats: null,
|
||||||
|
trafficStats: null,
|
||||||
|
dnsRecords: [],
|
||||||
|
domains: [],
|
||||||
|
gatewayDomains: [],
|
||||||
|
gatewayDnsRecords: [],
|
||||||
|
certificates: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
super();
|
||||||
|
const networkSub = appstate.networkStatePart.select((s) => s).subscribe((newState) => {
|
||||||
|
this.networkState = newState;
|
||||||
|
});
|
||||||
|
this.rxSubscriptions.push(networkSub);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static styles = [
|
||||||
|
cssManager.defaultStyles,
|
||||||
|
shared.viewHostCss,
|
||||||
|
css`
|
||||||
|
.domain { font-weight: 600; }
|
||||||
|
.muted { color: var(--ci-shade-5, #71717a); font-size: 13px; }
|
||||||
|
.badge { border-radius: 999px; padding: 3px 8px; background: var(--ci-shade-1, #f4f4f5); font-size: 12px; }
|
||||||
|
.empty { padding: 32px; text-align: center; color: var(--ci-shade-5, #71717a); }
|
||||||
|
`,
|
||||||
|
];
|
||||||
|
|
||||||
|
async connectedCallback() {
|
||||||
|
super.connectedCallback();
|
||||||
|
await appstate.networkStatePart.dispatchAction(appstate.fetchGatewayDomainsAction, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
public render(): TemplateResult {
|
||||||
|
const domains = this.networkState.gatewayDomains;
|
||||||
|
return html`
|
||||||
|
<ob-sectionheading>Domains</ob-sectionheading>
|
||||||
|
<div class="muted" style="margin-bottom: 16px;">
|
||||||
|
Domains are managed in dcrouter. Onebox shows gateway visibility for deployed services.
|
||||||
|
</div>
|
||||||
|
${domains.length
|
||||||
|
? html`
|
||||||
|
<dees-table
|
||||||
|
.heading1=${'Gateway Domains'}
|
||||||
|
.heading2=${'Domains imported from dcrouter gateway visibility'}
|
||||||
|
.data=${domains}
|
||||||
|
.showColumnFilters=${true}
|
||||||
|
.displayFunction=${(domain: TGatewayDomain) => ({
|
||||||
|
Domain: html`
|
||||||
|
<div>
|
||||||
|
<div class="domain">${domain.name}</div>
|
||||||
|
${domain.providerId ? html`<div class="muted">Provider: ${domain.providerId}</div>` : ''}
|
||||||
|
</div>
|
||||||
|
`,
|
||||||
|
Source: html`<span class="badge">${domain.source || 'dcrouter'}</span>`,
|
||||||
|
Authoritative: domain.authoritative ? 'Yes' : 'No',
|
||||||
|
Services: domain.serviceCount || 0,
|
||||||
|
})}
|
||||||
|
.dataActions=${[
|
||||||
|
{
|
||||||
|
name: 'Refresh',
|
||||||
|
iconName: 'lucide:rotateCw',
|
||||||
|
type: ['header'],
|
||||||
|
actionFunc: async () => {
|
||||||
|
await appstate.networkStatePart.dispatchAction(
|
||||||
|
appstate.fetchGatewayDomainsAction,
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Manage in dcrouter',
|
||||||
|
iconName: 'lucide:externalLink',
|
||||||
|
type: ['inRow', 'contextmenu'],
|
||||||
|
actionRelevancyCheckFunc: (domain: TGatewayDomain) => !!domain.manageUrl,
|
||||||
|
actionFunc: async (actionData: plugins.deesCatalog.ITableActionDataArg<TGatewayDomain>) => {
|
||||||
|
if (actionData.item.manageUrl) {
|
||||||
|
globalThis.open(actionData.item.manageUrl, '_blank', 'noopener');
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
] as plugins.deesCatalog.ITableAction<TGatewayDomain>[]}
|
||||||
|
></dees-table>
|
||||||
|
`
|
||||||
|
: html`<div class="empty">No gateway domains found. Configure a dcrouter gateway in Settings.</div>`}
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,6 +20,8 @@ export class ObViewNetwork extends DeesElement {
|
|||||||
trafficStats: null,
|
trafficStats: null,
|
||||||
dnsRecords: [],
|
dnsRecords: [],
|
||||||
domains: [],
|
domains: [],
|
||||||
|
gatewayDomains: [],
|
||||||
|
gatewayDnsRecords: [],
|
||||||
certificates: [],
|
certificates: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -146,6 +146,7 @@ export class ObViewServices extends DeesElement {
|
|||||||
accessor appStoreState: appstate.IAppStoreState = {
|
accessor appStoreState: appstate.IAppStoreState = {
|
||||||
apps: [],
|
apps: [],
|
||||||
upgradeableServices: [],
|
upgradeableServices: [],
|
||||||
|
upgradeOperations: [],
|
||||||
};
|
};
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -226,7 +227,8 @@ export class ObViewServices extends DeesElement {
|
|||||||
await Promise.all([
|
await Promise.all([
|
||||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null),
|
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null),
|
||||||
appstate.servicesStatePart.dispatchAction(appstate.fetchPlatformServicesAction, null),
|
appstate.servicesStatePart.dispatchAction(appstate.fetchPlatformServicesAction, null),
|
||||||
appstate.appStoreStatePart.dispatchAction(appstate.fetchUpgradeableServicesAction, null),
|
appstate.appStoreStatePart.dispatchAction(appstate.fetchUpgradeableAppStoreServicesAction, null),
|
||||||
|
appstate.appStoreStatePart.dispatchAction(appstate.fetchAppStoreUpgradeOperationsAction, null),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
// If a platform service was selected from the dashboard, navigate to its detail
|
// If a platform service was selected from the dashboard, navigate to its detail
|
||||||
@@ -471,9 +473,21 @@ export class ObViewServices extends DeesElement {
|
|||||||
const upgradeInfo = service
|
const upgradeInfo = service
|
||||||
? this.appStoreState.upgradeableServices.find((u) => u.serviceName === service.name)
|
? this.appStoreState.upgradeableServices.find((u) => u.serviceName === service.name)
|
||||||
: null;
|
: null;
|
||||||
|
const upgradeOperation = service
|
||||||
|
? this.appStoreState.upgradeOperations.find((operation) => {
|
||||||
|
return operation.serviceName === service.name && operation.status === 'running';
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
const latestUpgradeOperation = service
|
||||||
|
? this.appStoreState.upgradeOperations.find((operation) => operation.serviceName === service.name)
|
||||||
|
: null;
|
||||||
|
|
||||||
return html`
|
return html`
|
||||||
<ob-sectionheading>Service Details</ob-sectionheading>
|
<ob-sectionheading>Service Details</ob-sectionheading>
|
||||||
|
${upgradeOperation ? this.renderUpgradeOperation(upgradeOperation) : ''}
|
||||||
|
${!upgradeOperation && latestUpgradeOperation?.status === 'failed'
|
||||||
|
? this.renderUpgradeOperation(latestUpgradeOperation)
|
||||||
|
: ''}
|
||||||
${upgradeInfo ? html`
|
${upgradeInfo ? html`
|
||||||
<div style="
|
<div style="
|
||||||
background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(139, 92, 246, 0.1));
|
background: linear-gradient(135deg, rgba(59, 130, 246, 0.1), rgba(139, 92, 246, 0.1));
|
||||||
@@ -496,18 +510,14 @@ export class ObViewServices extends DeesElement {
|
|||||||
<button
|
<button
|
||||||
class="deploy-button"
|
class="deploy-button"
|
||||||
style="padding: 8px 16px; font-size: 13px;"
|
style="padding: 8px 16px; font-size: 13px;"
|
||||||
|
?disabled=${Boolean(upgradeOperation)}
|
||||||
@click=${async () => {
|
@click=${async () => {
|
||||||
await appstate.appStoreStatePart.dispatchAction(appstate.upgradeServiceAction, {
|
await appstate.appStoreStatePart.dispatchAction(appstate.upgradeAppStoreServiceAction, {
|
||||||
serviceName: upgradeInfo.serviceName,
|
serviceName: upgradeInfo.serviceName,
|
||||||
targetVersion: upgradeInfo.latestVersion,
|
targetVersion: upgradeInfo.latestVersion,
|
||||||
});
|
});
|
||||||
// Refresh service data
|
|
||||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServiceAction, {
|
|
||||||
name: upgradeInfo.serviceName,
|
|
||||||
});
|
|
||||||
appstate.servicesStatePart.dispatchAction(appstate.fetchServicesAction, null);
|
|
||||||
}}
|
}}
|
||||||
>Upgrade</button>
|
>${upgradeOperation ? 'Upgrading...' : 'Upgrade'}</button>
|
||||||
</div>
|
</div>
|
||||||
` : ''}
|
` : ''}
|
||||||
<sz-service-detail-view
|
<sz-service-detail-view
|
||||||
@@ -544,6 +554,53 @@ export class ObViewServices extends DeesElement {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private renderUpgradeOperation(
|
||||||
|
operationArg: interfaces.requests.IAppStoreUpgradeOperation,
|
||||||
|
): TemplateResult {
|
||||||
|
const color = operationArg.status === 'failed' ? '#f87171' : '#60a5fa';
|
||||||
|
return html`
|
||||||
|
<div style="
|
||||||
|
background: var(--ci-shade-1, #09090b);
|
||||||
|
border: 1px solid ${color};
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 16px;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
">
|
||||||
|
<div style="display: flex; justify-content: space-between; gap: 16px; align-items: flex-start;">
|
||||||
|
<div>
|
||||||
|
<div style="font-size: 14px; font-weight: 600; color: var(--ci-shade-7, #e4e4e7);">
|
||||||
|
Upgrade ${operationArg.fromVersion} → ${operationArg.targetVersion}: ${operationArg.step}
|
||||||
|
</div>
|
||||||
|
<div style="font-size: 12px; color: var(--ci-shade-4, #71717a); margin-top: 4px;">
|
||||||
|
${operationArg.status === 'running' ? 'Operation is running in the background.' : operationArg.error || 'Operation finished.'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<span style="font-size: 12px; color: ${color}; text-transform: uppercase; letter-spacing: 0.04em;">
|
||||||
|
${operationArg.status}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div style="
|
||||||
|
margin-top: 12px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: var(--ci-shade-0, #030305);
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--ci-shade-5, #a1a1aa);
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
line-height: 1.5;
|
||||||
|
max-height: 130px;
|
||||||
|
overflow: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
">${operationArg.progressLines.slice(-8).join('\n')}</div>
|
||||||
|
${operationArg.warnings.length > 0 ? html`
|
||||||
|
<div style="margin-top: 10px; color: #fbbf24; font-size: 12px;">
|
||||||
|
${operationArg.warnings.join(' | ')}
|
||||||
|
</div>
|
||||||
|
` : ''}
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
private renderBackupsView(): TemplateResult {
|
private renderBackupsView(): TemplateResult {
|
||||||
return html`
|
return html`
|
||||||
<ob-sectionheading>Backups</ob-sectionheading>
|
<ob-sectionheading>Backups</ob-sectionheading>
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ export class ObViewSettings extends DeesElement {
|
|||||||
accessor settingsState: appstate.ISettingsState = {
|
accessor settingsState: appstate.ISettingsState = {
|
||||||
settings: null,
|
settings: null,
|
||||||
backupPasswordConfigured: false,
|
backupPasswordConfigured: false,
|
||||||
|
managedDcRouterStatus: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
@state()
|
@state()
|
||||||
@@ -47,29 +48,45 @@ export class ObViewSettings extends DeesElement {
|
|||||||
cssManager.defaultStyles,
|
cssManager.defaultStyles,
|
||||||
shared.viewHostCss,
|
shared.viewHostCss,
|
||||||
css`
|
css`
|
||||||
.gateway-card {
|
dees-tile {
|
||||||
|
display: block;
|
||||||
margin-bottom: 24px;
|
margin-bottom: 24px;
|
||||||
border: 1px solid var(--dees-color-border-subtle);
|
|
||||||
border-radius: 12px;
|
|
||||||
background: var(--dees-color-background, #ffffff);
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.gateway-header {
|
.gateway-header {
|
||||||
padding: 16px 20px;
|
height: 36px;
|
||||||
border-bottom: 1px solid var(--dees-color-border-subtle);
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0 16px;
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-heading {
|
||||||
|
flex: 1;
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
gap: 8px;
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.gateway-title {
|
.gateway-title {
|
||||||
font-size: 15px;
|
font-size: 13px;
|
||||||
font-weight: 600;
|
font-weight: 500;
|
||||||
color: var(--dees-color-text-primary);
|
letter-spacing: -0.01em;
|
||||||
|
color: var(--dees-color-text-secondary);
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
.gateway-subtitle {
|
.gateway-subtitle {
|
||||||
margin-top: 4px;
|
font-size: 12px;
|
||||||
font-size: 13px;
|
|
||||||
color: var(--dees-color-text-muted);
|
color: var(--dees-color-text-muted);
|
||||||
|
letter-spacing: -0.01em;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
}
|
}
|
||||||
|
|
||||||
.gateway-content {
|
.gateway-content {
|
||||||
@@ -79,65 +96,156 @@ export class ObViewSettings extends DeesElement {
|
|||||||
gap: 16px;
|
gap: 16px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.gateway-mode-row,
|
||||||
|
.gateway-status-row {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
padding: 16px 20px;
|
||||||
|
border-bottom: 1px solid ${cssManager.bdTheme('#f4f4f5', '#27272a')};
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-mode-row {
|
||||||
|
justify-content: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-mode-button {
|
||||||
|
border: 1px solid ${cssManager.bdTheme('#d4d4d8', '#3f3f46')};
|
||||||
|
border-radius: 999px;
|
||||||
|
background: ${cssManager.bdTheme('#ffffff', '#18181b')};
|
||||||
|
color: ${cssManager.bdTheme('#3f3f46', '#d4d4d8')};
|
||||||
|
padding: 8px 12px;
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-mode-button.active {
|
||||||
|
border-color: ${cssManager.bdTheme('#2563eb', '#60a5fa')};
|
||||||
|
background: ${cssManager.bdTheme('#eff6ff', '#172554')};
|
||||||
|
color: ${cssManager.bdTheme('#1d4ed8', '#bfdbfe')};
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-status-label {
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
text-transform: uppercase;
|
||||||
|
color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-status-value {
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 14px;
|
||||||
|
color: ${cssManager.bdTheme('#18181b', '#fafafa')};
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-status-error,
|
||||||
|
.gateway-disabled {
|
||||||
|
color: ${cssManager.bdTheme('#b91c1c', '#fca5a5')};
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-disabled {
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
.gateway-field.full {
|
.gateway-field.full {
|
||||||
grid-column: 1 / -1;
|
grid-column: 1 / -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
.field-label {
|
.gateway-readonly {
|
||||||
display: block;
|
|
||||||
margin-bottom: 6px;
|
|
||||||
font-size: 13px;
|
|
||||||
font-weight: 500;
|
|
||||||
color: var(--dees-color-text-secondary);
|
|
||||||
}
|
|
||||||
|
|
||||||
input {
|
|
||||||
width: 100%;
|
|
||||||
box-sizing: border-box;
|
|
||||||
padding: 10px 12px;
|
padding: 10px 12px;
|
||||||
border: 1px solid var(--dees-color-border-subtle);
|
border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#27272a')};
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
background: transparent;
|
background: ${cssManager.bdTheme('#fafafa', '#18181b')};
|
||||||
color: var(--dees-color-text-primary);
|
|
||||||
font-size: 14px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
input:focus {
|
.gateway-readonly-label {
|
||||||
outline: none;
|
|
||||||
border-color: #3b82f6;
|
|
||||||
}
|
|
||||||
|
|
||||||
.field-hint {
|
|
||||||
margin-top: 5px;
|
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
color: var(--dees-color-text-muted);
|
font-weight: 600;
|
||||||
|
color: ${cssManager.bdTheme('#52525b', '#d4d4d8')};
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-readonly-value {
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: ${cssManager.bdTheme('#18181b', '#fafafa')};
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gateway-readonly-hint {
|
||||||
|
margin-top: 4px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
|
||||||
|
}
|
||||||
|
|
||||||
|
dees-input-text {
|
||||||
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
.gateway-footer {
|
.gateway-footer {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
flex-direction: row;
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
padding: 0 20px 20px;
|
align-items: center;
|
||||||
|
gap: 0;
|
||||||
|
height: 36px;
|
||||||
|
width: 100%;
|
||||||
|
box-sizing: border-box;
|
||||||
}
|
}
|
||||||
|
|
||||||
.save-button {
|
.tile-button {
|
||||||
border: none;
|
padding: 0 16px;
|
||||||
border-radius: 8px;
|
height: 100%;
|
||||||
background: #2563eb;
|
text-align: center;
|
||||||
color: white;
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
font-size: 13px;
|
user-select: none;
|
||||||
font-weight: 600;
|
transition: all 0.15s ease;
|
||||||
padding: 9px 14px;
|
background: transparent;
|
||||||
|
border: none;
|
||||||
|
border-left: 1px solid var(--dees-color-border-subtle);
|
||||||
|
color: var(--dees-color-text-muted);
|
||||||
|
white-space: nowrap;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.save-button:hover {
|
.tile-button:first-child {
|
||||||
background: #1d4ed8;
|
border-left: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tile-button:hover {
|
||||||
|
background: var(--dees-color-hover);
|
||||||
|
color: var(--dees-color-text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tile-button.primary {
|
||||||
|
color: ${cssManager.bdTheme('hsl(217.2 91.2% 59.8%)', 'hsl(213.1 93.9% 67.8%)')};
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tile-button.primary:hover {
|
||||||
|
background: ${cssManager.bdTheme('hsl(217.2 91.2% 59.8% / 0.08)', 'hsl(213.1 93.9% 67.8% / 0.08)')};
|
||||||
|
color: ${cssManager.bdTheme('hsl(217.2 91.2% 50%)', 'hsl(213.1 93.9% 75%)')};
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 700px) {
|
@media (max-width: 700px) {
|
||||||
.gateway-content {
|
.gateway-content {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.gateway-status-row {
|
||||||
|
align-items: flex-start;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
`,
|
`,
|
||||||
];
|
];
|
||||||
@@ -150,12 +258,22 @@ export class ObViewSettings extends DeesElement {
|
|||||||
public render(): TemplateResult {
|
public render(): TemplateResult {
|
||||||
return html`
|
return html`
|
||||||
<ob-sectionheading>Settings</ob-sectionheading>
|
<ob-sectionheading>Settings</ob-sectionheading>
|
||||||
|
${this.renderAdminUiSettings()}
|
||||||
${this.renderExternalGatewaySettings()}
|
${this.renderExternalGatewaySettings()}
|
||||||
<sz-settings-view
|
<sz-settings-view
|
||||||
.settings=${this.settingsState.settings || {
|
.settings=${this.settingsState.settings || {
|
||||||
darkMode: true,
|
darkMode: true,
|
||||||
cloudflareToken: '',
|
cloudflareToken: '',
|
||||||
cloudflareZoneId: '',
|
cloudflareZoneId: '',
|
||||||
|
adminUiDomain: '',
|
||||||
|
dcrouterMode: 'managed',
|
||||||
|
dcrouterManagedImage: 'code.foss.global/serve.zone/dcrouter:latest',
|
||||||
|
dcrouterManagedOpsPort: 3300,
|
||||||
|
dcrouterManagedHttpPort: 80,
|
||||||
|
dcrouterManagedHttpsPort: 443,
|
||||||
|
dcrouterManagedDataDir: './.nogit/dcrouter-data',
|
||||||
|
dcrouterGatewayClientId: '',
|
||||||
|
dcrouterWorkHosterId: '',
|
||||||
autoRenewCerts: false,
|
autoRenewCerts: false,
|
||||||
renewalThreshold: 30,
|
renewalThreshold: 30,
|
||||||
acmeEmail: '',
|
acmeEmail: '',
|
||||||
@@ -185,25 +303,102 @@ export class ObViewSettings extends DeesElement {
|
|||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
private renderExternalGatewaySettings(): TemplateResult {
|
private renderAdminUiSettings(): TemplateResult {
|
||||||
const settings = this.settingsState.settings;
|
const settings = this.settingsState.settings;
|
||||||
return html`
|
return html`
|
||||||
<section class="gateway-card">
|
<dees-tile>
|
||||||
<div class="gateway-header">
|
<div slot="header" class="gateway-header">
|
||||||
<div class="gateway-title">External dcrouter Gateway</div>
|
<div class="gateway-heading">
|
||||||
<div class="gateway-subtitle">Delegate public WorkApp routing, DNS, and certificates to a dcrouter edge authority.</div>
|
<span class="gateway-title">Onebox Admin UI</span>
|
||||||
|
<span class="gateway-subtitle">Configure the public hostname for this Onebox dashboard</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="gateway-content">
|
<div class="gateway-content">
|
||||||
${this.renderGatewayInput('dcrouterGatewayUrl', 'Gateway URL', settings?.dcrouterGatewayUrl || '', 'https://edge.example.com', 'Base URL of the dcrouter OpsServer.')}
|
${this.renderGatewayInput('adminUiDomain', 'Admin UI Domain', settings?.adminUiDomain || '', 'Example: onebox.example.com. Leave empty to disable the public Admin UI route.')}
|
||||||
${this.renderGatewayInput('dcrouterGatewayApiToken', 'API Token', settings?.dcrouterGatewayApiToken || '', 'dcrouter API token', 'Requires workhosters and certificates scopes.', 'password')}
|
${this.renderGatewayReadonly('Local Target', 'Onebox OpsServer on port 3000', 'The external gateway forwards to SmartProxy, which forwards this hostname to the Onebox Admin UI.')}
|
||||||
${this.renderGatewayInput('dcrouterWorkHosterId', 'WorkHoster ID', settings?.dcrouterWorkHosterId || '', 'optional stable owner ID', 'Leave empty to let Onebox create a stable ID.')}
|
</div>
|
||||||
${this.renderGatewayInput('dcrouterTargetHost', 'Target Host', settings?.dcrouterTargetHost || '', 'public or private host/IP', 'Defaults to the configured server IP when empty.')}
|
<div slot="footer" class="gateway-footer">
|
||||||
${this.renderGatewayInput('dcrouterTargetPort', 'Target Port', String(settings?.dcrouterTargetPort || 80), '80', 'Internal HTTP port dcrouter forwards to.', 'number')}
|
<button class="tile-button primary" type="button" @click=${() => this.saveAdminUiSettings()}>
|
||||||
|
Save Admin UI Domain
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</dees-tile>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderExternalGatewaySettings(): TemplateResult {
|
||||||
|
const settings = this.settingsState.settings;
|
||||||
|
const mode = settings?.dcrouterMode || 'managed';
|
||||||
|
return html`
|
||||||
|
<dees-tile>
|
||||||
|
<div slot="header" class="gateway-header">
|
||||||
|
<div class="gateway-heading">
|
||||||
|
<span class="gateway-title">dcrouter Gateway</span>
|
||||||
|
<span class="gateway-subtitle">Run a local managed dcrouter or delegate routing to an external dcrouter</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="gateway-mode-row">
|
||||||
|
${this.renderModeButton('managed', 'Managed Local', mode)}
|
||||||
|
${this.renderModeButton('external', 'External dcrouter', mode)}
|
||||||
|
${this.renderModeButton('disabled', 'Disabled', mode)}
|
||||||
|
</div>
|
||||||
|
${mode === 'managed' ? this.renderManagedGatewayStatus() : null}
|
||||||
|
<div class="gateway-content">
|
||||||
|
${mode === 'managed' ? html`
|
||||||
|
${this.renderGatewayInput('dcrouterManagedImage', 'dcrouter Image', settings?.dcrouterManagedImage || 'code.foss.global/serve.zone/dcrouter:latest', 'OCI image used for the managed local gateway.')}
|
||||||
|
${this.renderGatewayInput('dcrouterManagedDataDir', 'Data Directory', settings?.dcrouterManagedDataDir || './.nogit/dcrouter-data', 'Host directory mounted into the dcrouter container.')}
|
||||||
|
${this.renderGatewayInput('dcrouterManagedOpsPort', 'Local Ops Port', String(settings?.dcrouterManagedOpsPort || 3300), 'Bound to 127.0.0.1 for Onebox to call dcrouter APIs.')}
|
||||||
|
${this.renderGatewayInput('dcrouterManagedHttpPort', 'Public HTTP Port', String(settings?.dcrouterManagedHttpPort || 80), 'Host port owned by dcrouter for HTTP ingress.')}
|
||||||
|
${this.renderGatewayInput('dcrouterManagedHttpsPort', 'Public HTTPS Port', String(settings?.dcrouterManagedHttpsPort || 443), 'Host port owned by dcrouter for HTTPS ingress.')}
|
||||||
|
${this.renderGatewayReadonly('Gateway Client ID', settings?.dcrouterGatewayClientId || settings?.dcrouterWorkHosterId || 'Created when managed dcrouter starts', 'Diagnostic only. Onebox manages this local client automatically.')}
|
||||||
|
` : mode === 'external' ? html`
|
||||||
|
${this.renderGatewayInput('dcrouterGatewayUrl', 'Gateway URL', settings?.dcrouterGatewayUrl || '', 'Base URL of the dcrouter OpsServer.')}
|
||||||
|
${this.renderGatewayInput('dcrouterGatewayApiToken', 'API Token', settings?.dcrouterGatewayApiToken || '', 'Requires gateway-client access in dcrouter.', true)}
|
||||||
|
${this.renderGatewayReadonly('Gateway Client ID', settings?.dcrouterGatewayClientId || settings?.dcrouterWorkHosterId || 'Derived from token', 'Configure this in dcrouter Gateway Clients, not in Onebox.')}
|
||||||
|
${this.renderGatewayInput('dcrouterTargetHost', 'Target Host', settings?.dcrouterTargetHost || '', 'Defaults to the configured server IP when empty.')}
|
||||||
|
${this.renderGatewayInput('dcrouterTargetPort', 'Target Port', String(settings?.dcrouterTargetPort || 80), 'Internal HTTP port dcrouter forwards to.')}
|
||||||
|
` : html`
|
||||||
|
<div class="gateway-disabled">dcrouter route delegation is disabled. Onebox will keep using its local SmartProxy directly.</div>
|
||||||
|
`}
|
||||||
|
</div>
|
||||||
|
<div slot="footer" class="gateway-footer">
|
||||||
|
<button class="tile-button primary" type="button" @click=${() => this.saveExternalGatewaySettings()}>
|
||||||
|
Save dcrouter Settings
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</dees-tile>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderModeButton(
|
||||||
|
mode: 'managed' | 'external' | 'disabled',
|
||||||
|
label: string,
|
||||||
|
activeMode: string,
|
||||||
|
): TemplateResult {
|
||||||
|
return html`
|
||||||
|
<button
|
||||||
|
class="gateway-mode-button ${activeMode === mode ? 'active' : ''}"
|
||||||
|
@click=${() => this.updateGatewayDraft('dcrouterMode', mode)}
|
||||||
|
>${label}</button>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderManagedGatewayStatus(): TemplateResult {
|
||||||
|
const status = this.settingsState.managedDcRouterStatus;
|
||||||
|
const stateText = status?.running ? (status.healthy ? 'Running' : 'Starting') : 'Stopped';
|
||||||
|
return html`
|
||||||
|
<div class="gateway-status-row">
|
||||||
|
<div>
|
||||||
|
<div class="gateway-status-label">Managed dcrouter</div>
|
||||||
|
<div class="gateway-status-value">${stateText}${status?.gatewayUrl ? ` at ${status.gatewayUrl}` : ''}</div>
|
||||||
|
${status?.message ? html`<div class="gateway-status-error">${status.message}</div>` : null}
|
||||||
|
</div>
|
||||||
|
<div class="gateway-actions">
|
||||||
|
<dees-button .text=${'Start'} .type=${'default'} @click=${() => appstate.settingsStatePart.dispatchAction(appstate.startManagedDcRouterAction, null)}></dees-button>
|
||||||
|
<dees-button .text=${'Restart'} .type=${'default'} @click=${() => appstate.settingsStatePart.dispatchAction(appstate.restartManagedDcRouterAction, null)}></dees-button>
|
||||||
|
<dees-button .text=${'Stop'} .type=${'default'} @click=${() => appstate.settingsStatePart.dispatchAction(appstate.stopManagedDcRouterAction, null)}></dees-button>
|
||||||
</div>
|
</div>
|
||||||
<div class="gateway-footer">
|
|
||||||
<button class="save-button" @click=${() => this.saveExternalGatewaySettings()}>Save Gateway Settings</button>
|
|
||||||
</div>
|
</div>
|
||||||
</section>
|
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -211,21 +406,30 @@ export class ObViewSettings extends DeesElement {
|
|||||||
key: keyof NonNullable<appstate.ISettingsState['settings']>,
|
key: keyof NonNullable<appstate.ISettingsState['settings']>,
|
||||||
label: string,
|
label: string,
|
||||||
value: string,
|
value: string,
|
||||||
placeholder: string,
|
|
||||||
hint: string,
|
hint: string,
|
||||||
type: 'text' | 'password' | 'number' = 'text',
|
isPassword = false,
|
||||||
): TemplateResult {
|
): TemplateResult {
|
||||||
return html`
|
return html`
|
||||||
<label class="gateway-field ${key === 'dcrouterGatewayUrl' ? 'full' : ''}">
|
<div class="gateway-field ${key === 'dcrouterGatewayUrl' || key === 'adminUiDomain' ? 'full' : ''}">
|
||||||
<span class="field-label">${label}</span>
|
<dees-input-text
|
||||||
<input
|
.key=${key}
|
||||||
type=${type}
|
.label=${label}
|
||||||
.value=${value}
|
.value=${value}
|
||||||
placeholder=${placeholder}
|
.description=${hint}
|
||||||
|
.isPasswordBool=${isPassword}
|
||||||
@input=${(event: Event) => this.updateGatewayDraft(key, (event.target as HTMLInputElement).value)}
|
@input=${(event: Event) => this.updateGatewayDraft(key, (event.target as HTMLInputElement).value)}
|
||||||
/>
|
></dees-input-text>
|
||||||
<span class="field-hint">${hint}</span>
|
</div>
|
||||||
</label>
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private renderGatewayReadonly(label: string, value: string, hint: string): TemplateResult {
|
||||||
|
return html`
|
||||||
|
<div class="gateway-readonly">
|
||||||
|
<div class="gateway-readonly-label">${label}</div>
|
||||||
|
<div class="gateway-readonly-value">${value}</div>
|
||||||
|
<div class="gateway-readonly-hint">${hint}</div>
|
||||||
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -234,7 +438,13 @@ export class ObViewSettings extends DeesElement {
|
|||||||
value: string,
|
value: string,
|
||||||
): void {
|
): void {
|
||||||
const currentSettings = this.settingsState.settings || {} as NonNullable<appstate.ISettingsState['settings']>;
|
const currentSettings = this.settingsState.settings || {} as NonNullable<appstate.ISettingsState['settings']>;
|
||||||
const nextValue = key === 'dcrouterTargetPort' ? Number(value) || 0 : value;
|
const numberKeys = new Set([
|
||||||
|
'dcrouterTargetPort',
|
||||||
|
'dcrouterManagedOpsPort',
|
||||||
|
'dcrouterManagedHttpPort',
|
||||||
|
'dcrouterManagedHttpsPort',
|
||||||
|
]);
|
||||||
|
const nextValue = numberKeys.has(key as string) ? Number(value) || 0 : value;
|
||||||
this.settingsState = {
|
this.settingsState = {
|
||||||
...this.settingsState,
|
...this.settingsState,
|
||||||
settings: {
|
settings: {
|
||||||
@@ -250,12 +460,29 @@ export class ObViewSettings extends DeesElement {
|
|||||||
|
|
||||||
await appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, {
|
await appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, {
|
||||||
settings: {
|
settings: {
|
||||||
|
dcrouterMode: settings.dcrouterMode || 'managed',
|
||||||
|
dcrouterManagedImage: settings.dcrouterManagedImage || 'code.foss.global/serve.zone/dcrouter:latest',
|
||||||
|
dcrouterManagedOpsPort: Number(settings.dcrouterManagedOpsPort) || 3300,
|
||||||
|
dcrouterManagedHttpPort: Number(settings.dcrouterManagedHttpPort) || 80,
|
||||||
|
dcrouterManagedHttpsPort: Number(settings.dcrouterManagedHttpsPort) || 443,
|
||||||
|
dcrouterManagedDataDir: settings.dcrouterManagedDataDir || './.nogit/dcrouter-data',
|
||||||
dcrouterGatewayUrl: settings.dcrouterGatewayUrl || '',
|
dcrouterGatewayUrl: settings.dcrouterGatewayUrl || '',
|
||||||
dcrouterGatewayApiToken: settings.dcrouterGatewayApiToken || '',
|
dcrouterGatewayApiToken: settings.dcrouterGatewayApiToken || '',
|
||||||
dcrouterWorkHosterId: settings.dcrouterWorkHosterId || '',
|
|
||||||
dcrouterTargetHost: settings.dcrouterTargetHost || '',
|
dcrouterTargetHost: settings.dcrouterTargetHost || '',
|
||||||
dcrouterTargetPort: Number(settings.dcrouterTargetPort) || 80,
|
dcrouterTargetPort: Number(settings.dcrouterTargetPort) || 80,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
await appstate.settingsStatePart.dispatchAction(appstate.fetchManagedDcRouterStatusAction, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async saveAdminUiSettings(): Promise<void> {
|
||||||
|
const settings = this.settingsState.settings;
|
||||||
|
if (!settings) return;
|
||||||
|
|
||||||
|
await appstate.settingsStatePart.dispatchAction(appstate.updateSettingsAction, {
|
||||||
|
settings: {
|
||||||
|
adminUiDomain: settings.adminUiDomain || '',
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,19 +12,30 @@ type IExecutionEnvironment = import('@design.estate/dees-catalog').IExecutionEnv
|
|||||||
type IFileEntry = import('@design.estate/dees-catalog').IFileEntry;
|
type IFileEntry = import('@design.estate/dees-catalog').IFileEntry;
|
||||||
type IFileWatcher = import('@design.estate/dees-catalog').IFileWatcher;
|
type IFileWatcher = import('@design.estate/dees-catalog').IFileWatcher;
|
||||||
type IProcessHandle = import('@design.estate/dees-catalog').IProcessHandle;
|
type IProcessHandle = import('@design.estate/dees-catalog').IProcessHandle;
|
||||||
|
type IWorkspaceShellCommand = interfaces.requests.IWorkspaceShellCommand;
|
||||||
|
|
||||||
const domtools = plugins.deesElement.domtools;
|
const domtools = plugins.deesElement.domtools;
|
||||||
|
|
||||||
|
interface IWorkspaceProcessState {
|
||||||
|
outputController: ReadableStreamDefaultController<string>;
|
||||||
|
resolveExit: (exitCodeArg: number) => void;
|
||||||
|
}
|
||||||
|
|
||||||
export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
||||||
readonly type = 'backend' as const;
|
readonly type = 'backend' as const;
|
||||||
private _ready = false;
|
private _ready = false;
|
||||||
private identity: interfaces.data.IIdentity;
|
private identity: interfaces.data.IIdentity;
|
||||||
|
private processRouter = new plugins.domtools.plugins.typedrequest.TypedRouter();
|
||||||
|
private processSocket: InstanceType<typeof plugins.typedsocket.TypedSocket> | null = null;
|
||||||
|
private processSocketPromise: Promise<InstanceType<typeof plugins.typedsocket.TypedSocket>> | null = null;
|
||||||
|
private processStates = new Map<string, IWorkspaceProcessState>();
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private serviceName: string,
|
private serviceName: string,
|
||||||
identity: interfaces.data.IIdentity,
|
identity: interfaces.data.IIdentity,
|
||||||
) {
|
) {
|
||||||
this.identity = identity;
|
this.identity = identity;
|
||||||
|
this.registerProcessSocketHandlers();
|
||||||
}
|
}
|
||||||
|
|
||||||
get ready(): boolean {
|
get ready(): boolean {
|
||||||
@@ -44,6 +55,12 @@ export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async destroy(): Promise<void> {
|
async destroy(): Promise<void> {
|
||||||
|
for (const processId of Array.from(this.processStates.keys())) {
|
||||||
|
await this.killProcess(processId).catch(() => {});
|
||||||
|
}
|
||||||
|
await this.processSocket?.stop().catch(() => {});
|
||||||
|
this.processSocket = null;
|
||||||
|
this.processSocketPromise = null;
|
||||||
this._ready = false;
|
this._ready = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,38 +120,142 @@ export class BackendExecutionEnvironment implements IExecutionEnvironment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async spawn(command: string, args?: string[]): Promise<IProcessHandle> {
|
async spawn(command: string, args?: string[]): Promise<IProcessHandle> {
|
||||||
// For interactive shell: execute the command via the workspace exec API
|
const socket = await this.ensureProcessSocket();
|
||||||
// and return a process handle that bridges stdin/stdout
|
const processId = crypto.randomUUID();
|
||||||
const cmd = args ? [command, ...args] : [command];
|
await socket.setTag(`workspaceProcess:${processId}`, true);
|
||||||
const fullCommand = cmd.join(' ');
|
|
||||||
|
|
||||||
// Use a non-interactive exec for now — full interactive shell would need
|
let resolveExit: (exitCodeArg: number) => void = () => {};
|
||||||
// TypedSocket bidirectional streaming (to be implemented)
|
const exit = new Promise<number>((resolve) => {
|
||||||
const result = await this.fireRequest<interfaces.requests.IReq_WorkspaceExec>(
|
resolveExit = resolve;
|
||||||
'workspaceExec',
|
});
|
||||||
{ command: cmd[0], args: cmd.slice(1) },
|
|
||||||
);
|
|
||||||
|
|
||||||
// Create a ReadableStream from the exec output
|
|
||||||
const output = new ReadableStream<string>({
|
const output = new ReadableStream<string>({
|
||||||
start(controller) {
|
start: (controller) => {
|
||||||
if (result.stdout) controller.enqueue(result.stdout);
|
this.processStates.set(processId, {
|
||||||
if (result.stderr) controller.enqueue(result.stderr);
|
outputController: controller,
|
||||||
controller.close();
|
resolveExit,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
cancel: async () => {
|
||||||
|
await this.killProcess(processId).catch(() => {});
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Create a writable stream (no-op for non-interactive)
|
try {
|
||||||
const inputStream = new WritableStream<string>();
|
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceStartProcess>(
|
||||||
|
'workspaceStartProcess',
|
||||||
|
).fire({
|
||||||
|
identity: this.identity,
|
||||||
|
serviceName: this.serviceName,
|
||||||
|
processId,
|
||||||
|
command,
|
||||||
|
args,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
const processState = this.processStates.get(processId);
|
||||||
|
this.processStates.delete(processId);
|
||||||
|
await socket.removeTag(`workspaceProcess:${processId}`).catch(() => {});
|
||||||
|
try {
|
||||||
|
processState?.outputController.error(error);
|
||||||
|
} catch {
|
||||||
|
// The stream may already have been cancelled by the terminal.
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
const input = new WritableStream<string>({
|
||||||
|
write: async (chunkArg) => {
|
||||||
|
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceProcessInput>(
|
||||||
|
'workspaceProcessInput',
|
||||||
|
).fire({
|
||||||
|
identity: this.identity,
|
||||||
|
processId,
|
||||||
|
input: chunkArg,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
abort: async () => {
|
||||||
|
await this.killProcess(processId).catch(() => {});
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
output,
|
output,
|
||||||
input: inputStream,
|
input,
|
||||||
exit: Promise.resolve(result.exitCode),
|
exit,
|
||||||
kill: () => {},
|
kill: () => {
|
||||||
|
void this.killProcess(processId);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getShellCommand(): Promise<IWorkspaceShellCommand> {
|
||||||
|
const result = await this.fireRequest<interfaces.requests.IReq_WorkspaceGetShellCommand>(
|
||||||
|
'workspaceGetShellCommand',
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
return result.shellCommand;
|
||||||
|
}
|
||||||
|
|
||||||
|
private registerProcessSocketHandlers(): void {
|
||||||
|
this.processRouter.addTypedHandler(
|
||||||
|
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushWorkspaceProcessOutput>(
|
||||||
|
'pushWorkspaceProcessOutput',
|
||||||
|
async (dataArg: interfaces.requests.IReq_PushWorkspaceProcessOutput['request']) => {
|
||||||
|
this.processStates.get(dataArg.processId)?.outputController.enqueue(dataArg.output);
|
||||||
|
return {};
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.processRouter.addTypedHandler(
|
||||||
|
new plugins.domtools.plugins.typedrequest.TypedHandler<interfaces.requests.IReq_PushWorkspaceProcessExit>(
|
||||||
|
'pushWorkspaceProcessExit',
|
||||||
|
async (dataArg: interfaces.requests.IReq_PushWorkspaceProcessExit['request']) => {
|
||||||
|
this.completeProcessState(dataArg.processId, dataArg.exitCode);
|
||||||
|
await this.processSocket?.removeTag(`workspaceProcess:${dataArg.processId}`).catch(() => {});
|
||||||
|
return {};
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensureProcessSocket(): Promise<InstanceType<typeof plugins.typedsocket.TypedSocket>> {
|
||||||
|
if (this.processSocket) return this.processSocket;
|
||||||
|
if (!this.processSocketPromise) {
|
||||||
|
this.processSocketPromise = plugins.typedsocket.TypedSocket.createClient(
|
||||||
|
this.processRouter,
|
||||||
|
plugins.typedsocket.TypedSocket.useWindowLocationOriginUrl(),
|
||||||
|
{ autoReconnect: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.processSocket = await this.processSocketPromise;
|
||||||
|
return this.processSocket;
|
||||||
|
}
|
||||||
|
|
||||||
|
private completeProcessState(processIdArg: string, exitCodeArg: number): void {
|
||||||
|
const processState = this.processStates.get(processIdArg);
|
||||||
|
if (!processState) return;
|
||||||
|
try {
|
||||||
|
processState.outputController.close();
|
||||||
|
} catch {
|
||||||
|
// The terminal may already have cancelled the stream.
|
||||||
|
}
|
||||||
|
processState.resolveExit(exitCodeArg);
|
||||||
|
this.processStates.delete(processIdArg);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async killProcess(processIdArg: string): Promise<void> {
|
||||||
|
const socket = this.processSocket;
|
||||||
|
if (!socket) return;
|
||||||
|
await socket.createTypedRequest<interfaces.requests.IReq_WorkspaceKillProcess>(
|
||||||
|
'workspaceKillProcess',
|
||||||
|
).fire({
|
||||||
|
identity: this.identity,
|
||||||
|
processId: processIdArg,
|
||||||
|
}).catch(() => {});
|
||||||
|
this.completeProcessState(processIdArg, -1);
|
||||||
|
await socket.removeTag(`workspaceProcess:${processIdArg}`).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper to fire TypedRequests to the workspace API
|
* Helper to fire TypedRequests to the workspace API
|
||||||
*/
|
*/
|
||||||
|
|||||||
+92
-22
@@ -3,12 +3,40 @@ import * as appstate from './appstate.js';
|
|||||||
|
|
||||||
const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter;
|
const SmartRouter = plugins.domtools.plugins.smartrouter.SmartRouter;
|
||||||
|
|
||||||
export const validViews = [
|
const flatViews = ['dashboard', 'settings'] as const;
|
||||||
'dashboard', 'app-store', 'services', 'network',
|
|
||||||
'registries', 'tokens', 'settings',
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export type TValidView = typeof validViews[number];
|
const subviewMap: Record<string, readonly string[]> = {
|
||||||
|
apps: ['app-store', 'services'] as const,
|
||||||
|
network: ['proxy', 'domains', 'dns-records'] as const,
|
||||||
|
registry: ['registries', 'tokens'] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultSubview: Record<string, string> = {
|
||||||
|
apps: 'app-store',
|
||||||
|
network: 'proxy',
|
||||||
|
registry: 'registries',
|
||||||
|
};
|
||||||
|
|
||||||
|
const legacySubviewTargetMap: Record<string, { view: string; subview: string }> = {
|
||||||
|
'app-store': { view: 'apps', subview: 'app-store' },
|
||||||
|
services: { view: 'apps', subview: 'services' },
|
||||||
|
proxy: { view: 'network', subview: 'proxy' },
|
||||||
|
domains: { view: 'network', subview: 'domains' },
|
||||||
|
'dns-records': { view: 'network', subview: 'dns-records' },
|
||||||
|
registries: { view: 'registry', subview: 'registries' },
|
||||||
|
tokens: { view: 'registry', subview: 'tokens' },
|
||||||
|
};
|
||||||
|
|
||||||
|
export const validTopLevelViews = [...flatViews, ...Object.keys(subviewMap)] as const;
|
||||||
|
export type TValidView = typeof validTopLevelViews[number];
|
||||||
|
|
||||||
|
export function isValidView(view: string): boolean {
|
||||||
|
return (validTopLevelViews as readonly string[]).includes(view);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isValidSubview(view: string, subview: string): boolean {
|
||||||
|
return subviewMap[view]?.includes(subview) ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
class AppRouter {
|
class AppRouter {
|
||||||
private router: InstanceType<typeof SmartRouter>;
|
private router: InstanceType<typeof SmartRouter>;
|
||||||
@@ -28,24 +56,37 @@ class AppRouter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private setupRoutes(): void {
|
private setupRoutes(): void {
|
||||||
for (const view of validViews) {
|
for (const view of flatViews) {
|
||||||
this.router.on(`/${view}`, async () => {
|
this.router.on(`/${view}`, async () => {
|
||||||
this.updateViewState(view);
|
this.updateViewState(view, null);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// Root redirect
|
for (const view of Object.keys(subviewMap)) {
|
||||||
|
this.router.on(`/${view}`, async () => {
|
||||||
|
this.navigateTo(`/${view}/${defaultSubview[view]}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const subview of subviewMap[view]) {
|
||||||
|
this.router.on(`/${view}/${subview}`, async () => {
|
||||||
|
this.updateViewState(view, subview);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
this.router.on('/', async () => {
|
this.router.on('/', async () => {
|
||||||
this.navigateTo('/dashboard');
|
this.navigateTo('/dashboard');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
private setupStateSync(): void {
|
private setupStateSync(): void {
|
||||||
appstate.uiStatePart.select((s) => s.activeView).subscribe((activeView) => {
|
appstate.uiStatePart.select().subscribe((uiState: appstate.IUiState) => {
|
||||||
if (this.suppressStateUpdate) return;
|
if (this.suppressStateUpdate) return;
|
||||||
|
|
||||||
const currentPath = window.location.pathname;
|
const currentPath = window.location.pathname;
|
||||||
const expectedPath = `/${activeView}`;
|
const expectedPath = uiState.activeSubview
|
||||||
|
? `/${uiState.activeView}/${uiState.activeSubview}`
|
||||||
|
: `/${uiState.activeView}`;
|
||||||
|
|
||||||
if (currentPath !== expectedPath) {
|
if (currentPath !== expectedPath) {
|
||||||
this.suppressStateUpdate = true;
|
this.suppressStateUpdate = true;
|
||||||
@@ -60,25 +101,37 @@ class AppRouter {
|
|||||||
|
|
||||||
if (!path || path === '/') {
|
if (!path || path === '/') {
|
||||||
this.router.pushUrl('/dashboard');
|
this.router.pushUrl('/dashboard');
|
||||||
} else {
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const segments = path.split('/').filter(Boolean);
|
const segments = path.split('/').filter(Boolean);
|
||||||
const view = segments[0];
|
const view = segments[0];
|
||||||
|
const subview = segments[1];
|
||||||
|
|
||||||
if (validViews.includes(view as TValidView)) {
|
if (!isValidView(view)) {
|
||||||
this.updateViewState(view as TValidView);
|
|
||||||
} else {
|
|
||||||
this.router.pushUrl('/dashboard');
|
this.router.pushUrl('/dashboard');
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (subviewMap[view]) {
|
||||||
|
if (subview && isValidSubview(view, subview)) {
|
||||||
|
this.updateViewState(view, subview);
|
||||||
|
} else {
|
||||||
|
this.router.pushUrl(`/${view}/${defaultSubview[view]}`);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.updateViewState(view, null);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private updateViewState(view: string): void {
|
private updateViewState(view: string, subview: string | null): void {
|
||||||
this.suppressStateUpdate = true;
|
this.suppressStateUpdate = true;
|
||||||
const currentState = appstate.uiStatePart.getState();
|
const currentState = appstate.uiStatePart.getState();
|
||||||
if (currentState.activeView !== view) {
|
if (currentState.activeView !== view || currentState.activeSubview !== subview) {
|
||||||
appstate.uiStatePart.setState({
|
appstate.uiStatePart.setState({
|
||||||
...currentState,
|
...currentState,
|
||||||
activeView: view,
|
activeView: view,
|
||||||
|
activeSubview: subview,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
this.suppressStateUpdate = false;
|
this.suppressStateUpdate = false;
|
||||||
@@ -88,17 +141,34 @@ class AppRouter {
|
|||||||
this.router.pushUrl(path);
|
this.router.pushUrl(path);
|
||||||
}
|
}
|
||||||
|
|
||||||
public navigateToView(view: string): void {
|
public navigateToView(view: string, subview?: string): void {
|
||||||
const normalized = view.toLowerCase().replace(/\s+/g, '-');
|
const normalizedView = view.toLowerCase().replace(/\s+/g, '-');
|
||||||
if (validViews.includes(normalized as TValidView)) {
|
const normalizedSubview = subview?.toLowerCase().replace(/\s+/g, '-');
|
||||||
this.navigateTo(`/${normalized}`);
|
|
||||||
} else {
|
if (!isValidView(normalizedView)) {
|
||||||
|
const legacyTarget = legacySubviewTargetMap[normalizedView];
|
||||||
|
if (legacyTarget) {
|
||||||
|
this.navigateToView(legacyTarget.view, legacyTarget.subview);
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.navigateTo('/dashboard');
|
this.navigateTo('/dashboard');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (normalizedSubview && isValidSubview(normalizedView, normalizedSubview)) {
|
||||||
|
this.navigateTo(`/${normalizedView}/${normalizedSubview}`);
|
||||||
|
} else if (subviewMap[normalizedView]) {
|
||||||
|
this.navigateTo(`/${normalizedView}/${defaultSubview[normalizedView]}`);
|
||||||
|
} else {
|
||||||
|
this.navigateTo(`/${normalizedView}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public getCurrentView(): string {
|
public getCurrentView(): string {
|
||||||
return appstate.uiStatePart.getState().activeView;
|
const uiState = appstate.uiStatePart.getState();
|
||||||
|
return uiState.activeSubview
|
||||||
|
? `${uiState.activeView}/${uiState.activeSubview}`
|
||||||
|
: uiState.activeView;
|
||||||
}
|
}
|
||||||
|
|
||||||
public destroy(): void {
|
public destroy(): void {
|
||||||
|
|||||||
Reference in New Issue
Block a user