ВиртМашУправ ВиртМашУправVPS Manager
Home / Project Architecture

Project Architecture

An Expo/React Native mobile app, a NestJS monolith backend, MySQL, Redis/Valkey and VirtualBox — the complete map of modules, protocols and data flows.

1

Overall Diagram

flowchart LR
    subgraph client["Mobile client (Expo / React Native)"]
        UI["Screens (expo-router)"]
        RQ["React Query"]
        CR["Crypto Layer (Argon2id, AES-256-GCM)"]
    end

    subgraph backend["Backend (NestJS)"]
        API["REST API"]
        WS["WebSocket Gateway"]
        MODS["auth / vps / server-connection /
cloud-provider / custom-scripts"]
    end

    DB[("MySQL")]
    CACHE[("Redis / Valkey")]
    VBOX["VirtualBox"]
    SSHSRV["External SSH servers"]
    CLOUD["Timeweb / Yandex Cloud API"]

    UI --> RQ --> API
    UI --> WS
    CR -. credential encryption .-> API
    API --> MODS
    WS --> MODS
    MODS --> DB
    MODS --> CACHE
    MODS -- SSH --> VBOX
    MODS -- SSH --> SSHSRV
    MODS -- REST --> CLOUD

Client, NestJS API, MySQL, Redis/Valkey, SSH servers and VirtualBox

2

Tech Stack

Mobile App
PlatformExpo SDK 54, React Native 0.81.5
Routingexpo-router 6 (file-based routing)
LanguageTypeScript 5.9
Server state@tanstack/react-query v5
Client stateZustand
HTTPAxios (two instances)
Formsreact-hook-form
UIreact-native-paper, lucide-react-native
Cryptographyreact-native-quick-crypto, react-native-argon2
Storageexpo-secure-store (Keychain/Keystore), AsyncStorage
Biometricsexpo-local-authentication
Backend
FrameworkNestJS 11
LanguageTypeScript
ORMPrisma 6 + MySQL
Cache / ephemeral stateioredis → Valkey/Redis
SSHssh2
SFTPssh2-sftp-client
Authentication@nestjs/passport, passport-jwt, passport-google-oauth20, passport-yandex
Password hashingargon2
Mailnodemailer
API documentation@nestjs/swagger (disabled in prod)
WebSocket serverws (no socket.io)
3

Data Model (Prisma + MySQL)

erDiagram
    USER ||--o{ VPS_INSTANCE : "owns"
    USER ||--o{ SERVER_CONNECTION : "owns"
    USER ||--o{ CLOUD_PROVIDER_CONNECTION : "owns"
    USER ||--o{ CUSTOM_SCRIPT : "creates"
    VPS_INSTANCE ||--|| VPS_SETTINGS : "1:1"
    VPS_INSTANCE ||--o{ VPS_STATS : "metrics"
    CLOUD_PROVIDER_CONNECTION ||--o{ PROVIDER_MANAGED_VM : "import"

    USER {
        string username
        string credentialSalt
    }
    VPS_INSTANCE {
        string name
        string status
        string sshEncryptedCreds
    }
    SERVER_CONNECTION {
        string host
        string sshEncryptedCreds
    }
    CUSTOM_SCRIPT {
        json parameters
        boolean isApp
    }
    CLOUD_PROVIDER_CONNECTION {
        string provider
        string encryptedCreds
    }

Key models and relations (Prisma schema)

ModelKey FieldsNotes
Userusername, password (Argon2id), credentialSalt, googleId, yandexId, maxIdcredentialSalt — 32 bytes, rotated on password change
VpsInstancename, nameHash, status, ip, sshUser, sshPort, sshEncryptedCredsnameHash is unique per user; the server never decrypts sshEncryptedCreds
VpsSettingsmemoryMb, cpuCount, isoImage, osType1:1 with VpsInstance
VpsStatscpu, ramUsed/Total, diskUsed/Total, netRxKbps/TxKbps, recordedAtSampled once a minute, compound index [vpsId, recordedAt]
ServerConnectionhost, port, sshUser, sshEncryptedCreds, osType, sudoAvailable, systemdAvailableAn external SSH host; the same encryption model as VpsInstance
CustomScriptscriptUrl / scriptLocalPath, parameters (JSON), targetOs, isPublic, isAppparameters — a typed array of { name, type, required, defaultValue, options }
SystemApplinuxPackageName, windowsWingetId, systemdModules, windowsServicesThe curated app-store catalog
CloudProviderConnectionprovider (TIMEWEB | YANDEX_CLOUD), encryptedCredsThe provider's API credentials are encrypted with the same vault key (vault kdfKey)
ProviderManagedVmproviderResourceId, ip, osType, sshEncryptedCreds?A VM imported from a cloud provider
4

Backend Modules

flowchart TB
    subgraph core["Core"]
        AUTH["auth"]
        REDIS[("redis")]
    end
    subgraph resources["Managed Resources"]
        VPS["vps"]
        SC["server-connection"]
        CP["cloud-provider"]
    end
    subgraph exec["Execution"]
        SSH["ssh"]
        SFTP["sftp"]
        CS["custom-scripts"]
        WS["websocket"]
    end

    WS --> SFTP
    VPS --> WS
    VPS --> SSH
    VPS --> REDIS
    SC --> SSH
    SC --> REDIS
    CP --> REDIS
    CS --> SSH
    CS --> WS
    SFTP --> SSH

Dependencies between the NestJS modules registered in AppModule

auth/
auth.service.ts buildAuthResponse(), token signing, Argon2 verification
auth.controller.ts /auth/login, /register, /refresh, /google, /max/*
strategies/jwt.strategy.ts Bearer token extraction
@Auth() / @CurrentUser() / @SshTokenData() decorators
vps/
vps.service.ts CRUD, VM creation orchestration
vps-stats.service.ts collecting statistics over SSH
ssh-token.service.ts issuing/redeeming ephemeral tokens
app-store.service.ts a wrapper around apt / Chocolatey
service-manager.service.ts systemd / Windows Services
linux-sudo.service.ts sudo without a PTY, via stdin
virtualbox.service.ts VDI cloning, VM creation/deletion
ssh/
ssh.service.ts a serial command queue per host:port, PTY, host-key verification
sftp/
sftp.service.ts list/stat/read/delete via ssh2-sftp-client
websocket/
websocket.gateway.ts JWT handshake, session map, chunked upload, script and terminal streaming
custom-scripts/
custom-scripts.service.ts CRUD, SSRF-protected URL download, shell-injection protection, execution
server-connection/
server-connection.service.ts SSH reachability checks, OS/package-manager detection
server-connection-ssh-token.service.ts sessions and tokens for external hosts
cloud-provider/
cloud-provider.service.ts secure storage of connections (never returns encryptedCreds)
managed-vm.service.ts imported VMs and SSH-credential binding
adapters/* Timeweb and Yandex Cloud
redis/
redis.service.ts an ioredis wrapper (get/set/del/incrByPattern)
5

Frontend Layer

ServiceKey Methods
auth.service.tsmain(type, data), getNewTokensByRefresh(), logout(), pollMaxAuth(), loginGoogle()
sshToken.service.tsestablishSession(), getToken(vpsId, action, encryptedCreds)
vault.service.tsverifyAndUnlockWithPin(pin, salt, vpsList), deriveAuthKey(pin, salt)
vps.service.tsgetVps(), createVps(), startVps(), stopVps(), deleteVps(), getStats()
sftp.service.tslistSftp(), downloadSftp(), uploadSftp(), deleteSftp(), viewSftpFile()
profile.service.tsgetProfile(), updateProfile(), changePassword()
Zustand StoreStateMethods
useVaultStore{ isUnlocked, kdfKey, hasSecureKey }unlockWithBiometrics(), setPinAndKey(), lockVault()
useSocketStore{ socket }connect(), disconnect()
useSftpStore{ history, currentPath }push(), pop(), reset()
useThemePreferenceStore{ preference }setPreference() — persisted to AsyncStorage
useScriptExecutionStorescript run metadata and outputtracks the state of the active execution
useDrawerStore{ isOpen }open(), close()
6

Virtual Machine Lifecycle

sequenceDiagram
    participant C as Client
    participant S as Backend
    participant VB as VirtualBox
    participant VM as VM (installer)

    C->>S: POST /vps { name, cpuCount, memoryMb, osType, sshEncryptedCreds }
    S->>S: name-uniqueness check, INSERT { status: INSTALLING }
    S->>VB: clone golden VDI (~1 min) or install from ISO (~15 min)
    VB->>VM: boot the VM
    VM->>S: PATCH /vps/installed?vpsName=...&installed=true (headers x-vm-ts, x-vm-signature)
    S->>S: verify HMAC(VM_CALLBACK_SECRET, "installed:vpsName:flag:timestamp")
    S-->>C: status = RUNNING (WebSocket event)

    Note over C,S: Start / stop
    C->>S: POST /vps/:id/start
    S->>VB: boot, wait for SSH to become available
    C->>S: POST /vps/:id/stop
    S->>VB: SSH shutdown / ACPI power-off

    Note over S,VB: Background monitoring and statistics — every 30 seconds over SSH
    loop every 30 seconds
        S->>VB: poll status
        S-->>C: WebSocket event on change
    end

Creation, installer HMAC callback, start/stop and background monitoring

7

WebSocket Protocol and SFTP

Upload LimitValue
Max file size2 GiB
Max chunks per file5000
Concurrent uploads per user3
Idle session timeout10 min
Max frame size20 MB
flowchart LR
    A["Client splits the file into 2 MB chunks"] --> B["One SSH token for the whole session → chunks in order → ACK"]
    B --> C["upload-complete"]
    C --> D[("uploadSessions Map
chunks[], vpsId, remotePath, timeout")]
    D --> E["Assemble buffer → ssh2-sftp-client.put()"]
    E --> F["Success event → clean up session"]

Server-side chunk assembly session (uploadSessions)

8

Scripts, App Store and Services

sequenceDiagram
    participant C as Client
    participant S as Backend
    participant SSH as ssh.service

    C->>S: POST /scripts/:id/run/:vpsId { parameterValues, workingDirectory } (headers x-ssh-token, x-ssh-token-ts, x-ssh-sig)
    S->>S: verify SSH token → decrypted credentials
    S->>S: fetch CustomScript, download (file or scriptUrl with SSRF protection)
    S->>S: build the command (name whitelist + value escaping)
    alt script by URL (Linux)
        S->>SSH: curl -fsSL {scriptUrl} | sudo bash (passwordless sudo)
    else local file
        S->>SSH: SFTP upload → chmod +x → bash script.sh
    end
    SSH-->>S: stdout / stderr line by line
    S-->>C: WS script-output:chunk { data: line }
    S-->>C: WS script-output:complete { exitCode }

Running a custom script with streaming output

sequenceDiagram
    participant C as Client
    participant S as Backend
    participant SSH as ssh.service

    C->>S: POST /vps/:id/apps/install { packageId, sudoPassword } (headers x-ssh-token, x-ssh-token-ts, x-ssh-sig)
    S->>S: fetch SystemApp by packageId
    alt Linux
        S->>SSH: apt-get install -y {linuxPackageName}
    else Windows
        S->>SSH: choco install -y {windowsWingetId}
    end
    SSH-->>S: result (300s timeout)
    S->>SSH: systemctl enable + start for each of systemdModules
    S-->>C: { success, stdout, stderr }

Installing an app from the store

flowchart LR
    G["POST /vps/:id/services"] --> L["List of services
(systemctl list-units / Get-CimInstance)"]
    P1["POST /vps/:id/services/:name/control { action }"] --> A["start | stop | restart | enable | disable"]
    P2["POST /vps/:id/services/create { name, command, ... }"] --> V["Validate name and working directory"]
    V --> W["Write unit file, daemon-reload, enable + start"]

Managing systemd / Windows services

9

Cloud Providers

flowchart TB
    A["Unlock vault → kdfKey"] --> B["AES-256-GCM(kdfKey, providerCreds)"]
    B --> C["POST /cloud-providers { provider, name, encryptedCreds }"]
    C --> D[("Server stores encryptedCreds opaquely")]

    E["POST /cloud-providers/auth/session"] --> F["One-time provider token"]
    F --> G["POST /cloud-providers/:id/token"]
    G --> H["POST /cloud-providers/:id/resources"]
    H --> I["POST /cloud-providers/:id/resources/:resourceId/action { start | stop | reboot }"]

    J["GET /cloud-providers/vms"] --> K["POST /:id/vms/import"]
    K --> L["PATCH /vms/:vmId/ssh { sshEncryptedCreds }"]

Main endpoints for working with cloud connections

10

SSH Terminal

flowchart LR
    A["Token (action=ssh-terminal)"] --> B["WS ssh-terminal:start { tokenId, cols, rows }"]
    B --> C["consumeToken → open shell"]
    C --> D["ssh-terminal:ready"]
    D --> E["input / output / resize, while the session is open"]
    E --> F["ssh-terminal:close"]
    G["External connection"] -.-> H["ssh-terminal:start-connection { connectionId }"]

Terminal events and connecting to an external server