# ============================================================================== # ERP Enigma v15 — Production Client Installer (Windows 10 / 11 / Server) # # Installs ONLY the ERP Enigma client stack: # - ERPNext v15 + Official Static ERP Enigma Whitelabel Logo + MariaDB + Redis (Docker WSL2) # - Hardened OpenResty Gatekeeper (ES256 uncrackable offline lease cache) # - Cloudflare Tunnel (native cloudflared.exe) — dual ingress: ERP Web (:8081) + Admin SSH (:22) # - Managed Windows OpenSSH Server with `enigma-admin` Administrator account (reported to Admin Panel) # - Full Hardware Fingerprint (UUID + Physical MAC + ALL HDD/SSD/NVMe M.2 HWIDs) # - Remote Command Executor (11 admin commands delivered inside hourly heartbeat) # # Does NOT install the Central SaaS Admin Panel or any admin secrets. # Quota Design: 1 Cloudflare Worker call per hour (24 calls/day/machine). # ============================================================================== #Requires -Version 5.1 Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" param( [string]$InstallDir = "C:\ERP-Enigma", [string]$WorkerApiUrl = "https://erp.enigmamarketing.pk/api/enigma", [string]$BrandLogoUrl = "https://erp.enigmamarketing.pk/assets/whitelabel/images/erp-enigma-logo.png", [string]$RepoUrl = "https://github.com/ar-enigma/Erp.git", [string]$SiteName = "enigma-site", [int]$GatekeeperPort = 8081, [string]$SshUser = "enigma-admin", [int]$SshPort = 22, [string]$ClientName = "", [string]$CompanyName = "", [string]$LicenseKey = "", [string]$PublicDomain = "" ) Write-Host "============================================================" -ForegroundColor Cyan Write-Host " ERP Enigma v15 - Windows Production Client Installer" -ForegroundColor Cyan Write-Host "============================================================" -ForegroundColor Cyan function New-RandomHex([int]$Bytes) { $buf = New-Object byte[] $Bytes [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($buf) return ([System.BitConverter]::ToString($buf) -replace '-', '').ToLower() } # 1. Verify Git & Docker Desktop (WSL2) Write-Host "`n[1/9] Checking Git and Docker Desktop..." if (-not (Get-Command git -ErrorAction SilentlyContinue)) { Write-Host " Installing Git via winget..." -ForegroundColor Yellow winget install --id Git.Git -e --source winget --accept-package-agreements --accept-source-agreements $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User") } if (-not (Get-Command docker -ErrorAction SilentlyContinue)) { Write-Host "Docker Desktop is required (with WSL2 backend)." -ForegroundColor Red Write-Host "Run: winget install --id Docker.DockerDesktop -e" -ForegroundColor Yellow Write-Host "Start Docker Desktop, wait until it is Running, then re-run this script." -ForegroundColor Yellow exit 1 } try { docker info | Out-Null } catch { Write-Host "Docker Desktop is installed but not running. Start Docker Desktop and re-run." -ForegroundColor Red exit 1 } Write-Host " Docker Desktop is running." -ForegroundColor Green $stateDir = Join-Path $InstallDir "enigma-state" if (-not (Test-Path $stateDir)) { New-Item -ItemType Directory -Path $stateDir -Force | Out-Null } # 2. Enable Windows OpenSSH Server & Provision Managed `enigma-admin` Account Write-Host "`n[2/9] Configuring Windows OpenSSH Server & managed admin user ($SshUser)..." $sshCredPath = Join-Path $stateDir "ssh_credentials.json" $sshPassword = "" if (Test-Path $sshCredPath) { try { $sshPassword = (Get-Content $sshCredPath -Raw | ConvertFrom-Json).ssh_password } catch {} } if ([string]::IsNullOrWhiteSpace($sshPassword)) { $sshPassword = "EnigmaSSH@" + (New-RandomHex 7) } try { $sshCap = Get-WindowsCapability -Online -ErrorAction SilentlyContinue | Where-Object Name -like 'OpenSSH.Server*' | Select-Object -First 1 if ($sshCap -and $sshCap.State -ne 'Installed') { Add-WindowsCapability -Online -Name $sshCap.Name | Out-Null } Set-Service -Name sshd -StartupType Automatic -ErrorAction SilentlyContinue Start-Service sshd -ErrorAction SilentlyContinue if (-not (Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue)) { New-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -DisplayName "OpenSSH Server (sshd)" -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort $SshPort -ErrorAction SilentlyContinue | Out-Null } $secPwd = ConvertTo-SecureString $sshPassword -AsPlainText -Force $existingUser = Get-LocalUser -Name $SshUser -ErrorAction SilentlyContinue if (-not $existingUser) { New-LocalUser -Name $SshUser -Password $secPwd -FullName "Enigma Managed Admin" -Description "ERP Enigma Remote Management Account" -PasswordNeverExpires | Out-Null } else { Set-LocalUser -Name $SshUser -Password $secPwd -PasswordNeverExpires $true } Add-LocalGroupMember -Group "Administrators" -Member $SshUser -ErrorAction SilentlyContinue Write-Host " OpenSSH Server & $SshUser Administrator ready on port $SshPort." -ForegroundColor Green } catch { Write-Host " Note: Run PowerShell as Administrator to auto-enable OpenSSH Server & $SshUser." -ForegroundColor Yellow } $localIp = "" try { $ipObj = Get-NetIPAddress -AddressFamily IPv4 -ErrorAction SilentlyContinue | Where-Object { $_.IPAddress -notmatch '^(127\.|169\.254\.)' -and $_.InterfaceAlias -notmatch 'vEthernet|WSL|Loopback' } | Select-Object -First 1 if ($ipObj) { $localIp = $ipObj.IPAddress } } catch {} $sshCredObj = [ordered]@{ ssh_user = $SshUser ssh_password = $sshPassword ssh_port = $SshPort local_ip = $localIp } [System.IO.File]::WriteAllText($sshCredPath, ($sshCredObj | ConvertTo-Json -Depth 3), (New-Object System.Text.UTF8Encoding $false)) # 3. Install Native Cloudflare Tunnel client (cloudflared.exe) — supports BOTH HTTP :8081 & SSH :22! Write-Host "`n[3/9] Installing native Cloudflare Tunnel (cloudflared.exe)..." $cfExe = Join-Path $InstallDir "cloudflared.exe" if (-not (Get-Command cloudflared -ErrorAction SilentlyContinue) -and -not (Test-Path $cfExe)) { try { Invoke-WebRequest -Uri "https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.exe" -OutFile $cfExe -UseBasicParsing Write-Host " Downloaded native cloudflared.exe to $cfExe" -ForegroundColor Green } catch { Write-Host " Direct download skipped; trying winget..." -ForegroundColor Yellow try { winget install --id Cloudflare.cloudflared -e --source winget --accept-package-agreements --accept-source-agreements } catch {} } } # 4. Collect Full Hardware Fingerprint (UUID + Physical MAC + ALL HDD/SSD/NVMe M.2 HWIDs) Write-Host "`n[4/9] Collecting hardware fingerprint (UUID, MAC, all HDD/SSD/NVMe M.2 drives)..." $sysUuid = (Get-CimInstance -ClassName Win32_ComputerSystemProduct).UUID $boardSerial = (Get-CimInstance -ClassName Win32_BaseBoard).SerialNumber $sha = [System.Security.Cryptography.SHA256]::Create() $hashBytes = $sha.ComputeHash([System.Text.Encoding]::UTF8.GetBytes("$sysUuid|$boardSerial")) $hwUuid = ([System.BitConverter]::ToString($hashBytes) -replace '-', '').ToLower().Substring(0, 36) $primaryMac = "" try { $nic = Get-NetAdapter -Physical -ErrorAction SilentlyContinue | Where-Object { $_.MacAddress -and $_.MacAddress -ne "00-00-00-00-00-00" } | Select-Object -First 1 if ($nic) { $primaryMac = ($nic.MacAddress -replace '-', ':').ToUpper() } } catch {} $diskList = @() try { $physDisks = Get-PhysicalDisk -ErrorAction SilentlyContinue foreach ($pd in $physDisks) { $bus = [string]$pd.BusType $media = if ($bus -match "NVMe") { "NVMe/M.2" } elseif ([string]$pd.MediaType -match "SSD") { "SSD" } else { "HDD" } $sizeGb = if ($pd.Size) { "{0}G" -f [math]::Round($pd.Size / 1GB, 0) } else { "" } $serial = ([string]$pd.SerialNumber).Trim() if (-not $serial) { $serial = ([string]$pd.UniqueId).Trim() } $diskList += [ordered]@{ name = "Disk$($pd.DeviceId)" media_type = $media bus = $bus model = ([string]$pd.FriendlyName).Trim() serial = $serial wwn = ([string]$pd.UniqueId).Trim() size = $sizeGb } } } catch {} if ($diskList.Count -eq 0) { $wmiDisks = Get-CimInstance -ClassName Win32_DiskDrive -ErrorAction SilentlyContinue foreach ($wd in $wmiDisks) { $diskList += [ordered]@{ name = [string]$wd.DeviceID media_type = if ($wd.Model -match "NVMe") { "NVMe/M.2" } elseif ($wd.MediaType -match "SSD|Solid") { "SSD" } else { "HDD" } bus = [string]$wd.InterfaceType model = ([string]$wd.Model).Trim() serial = ([string]$wd.SerialNumber).Trim() wwn = [string]$wd.PNPDeviceID size = if ($wd.Size) { "{0}G" -f [math]::Round($wd.Size / 1GB, 0) } else { "" } } } } $osInfo = Get-CimInstance -ClassName Win32_OperatingSystem $ramGb = [math]::Round(($osInfo.TotalVisibleMemorySize / 1MB), 1) $fingerprint = [ordered]@{ uuid = $hwUuid mac = $primaryMac local_ip = $localIp disk_hwids = $diskList hardware_info = [ordered]@{ hostname = $env:COMPUTERNAME os = $osInfo.Caption arch = $env:PROCESSOR_ARCHITECTURE cpu_cores = [int]$env:NUMBER_OF_PROCESSORS ram_gb = $ramGb cloudflared = $true ssh_enabled = $true } } $fpPath = Join-Path $stateDir "hardware_fingerprint.json" [System.IO.File]::WriteAllText($fpPath, ($fingerprint | ConvertTo-Json -Depth 5), (New-Object System.Text.UTF8Encoding $false)) Write-Host " Hardware UUID : $hwUuid" -ForegroundColor Green Write-Host " Primary MAC : $(if ($primaryMac) { $primaryMac } else { 'N/A' })" -ForegroundColor Green Write-Host " Local IP : $(if ($localIp) { $localIp } else { 'N/A' })" -ForegroundColor Green Write-Host " Storage HWIDs : $($diskList.Count) physical drive(s) detected" -ForegroundColor Green # 5. Collect Client Details & Submit Activation Request + SSH Credentials to Central Admin Panel Write-Host "`n[5/9] Submitting activation request + SSH credentials to Central Admin Panel..." if ([string]::IsNullOrWhiteSpace($ClientName)) { $ClientName = Read-Host "Enter Client Full Name" } if ([string]::IsNullOrWhiteSpace($CompanyName)) { $CompanyName = Read-Host "Enter Company Name" } if ([string]::IsNullOrWhiteSpace($LicenseKey)) { $LicenseKey = Read-Host "Enter Pre-Issued License Key (or press Enter to request new approval)" } if ([string]::IsNullOrWhiteSpace($PublicDomain)) { $PublicDomain = Read-Host "Requested ERP Subdomain (e.g. acme.enigmamarketing.pk, optional)" } $actPayload = @{ action = "activate" key = $LicenseKey uuid = $hwUuid mac = $primaryMac client_name = $ClientName company = $CompanyName domain = $PublicDomain disk_hwids = $diskList hardware_info = $fingerprint.hardware_info ssh_user = $SshUser ssh_password = $sshPassword ssh_port = $SshPort local_ip = $localIp } | ConvertTo-Json -Depth 5 $actStatus = "PENDING" $actMessage = "" try { $actResp = Invoke-RestMethod -Uri "$($WorkerApiUrl.TrimEnd('/'))/activate" -Method Post -ContentType "application/json" -Body $actPayload -TimeoutSec 20 if ($actResp.license_key) { $LicenseKey = [string]$actResp.license_key } if ($actResp.status) { $actStatus = [string]$actResp.status } if ($actResp.message) { $actMessage = [string]$actResp.message } } catch { $errBody = "" if ($_.Exception.Response) { $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) $errBody = $reader.ReadToEnd() } if ($errBody -match '"status"\s*:\s*"BLOCKED"') { Write-Host "`n[!] INSTALLATION HALTED: Hardware is permanently blocked by administrator." -ForegroundColor Red Write-Host " Details: $errBody" -ForegroundColor Red exit 1 } Write-Host " Activation API notice: $($_.Exception.Message)" -ForegroundColor Yellow } Write-Host " Activation Status : $actStatus ($actMessage)" -ForegroundColor Cyan Write-Host " Assigned Key : $LicenseKey" -ForegroundColor Cyan $dbRootPassword = New-RandomHex 16 $encryptionSalt = New-RandomHex 24 $adminPassword = "Enigma@" + (New-RandomHex 4) # 6. Clone / update repository & write client-only .env + Official Whitelabel Logo Helper Write-Host "`n[6/9] Preparing ERP Enigma client stack & official static brand logo in $InstallDir..." if (Test-Path (Join-Path $InstallDir ".git")) { git -C $InstallDir pull --ff-only } else { $tempClone = Join-Path $env:TEMP "erp-enigma-clone" if (Test-Path $tempClone) { Remove-Item -Recurse -Force $tempClone } git clone --depth 1 $RepoUrl $tempClone Copy-Item -Path "$tempClone\*" -Destination $InstallDir -Recurse -Force Copy-Item -Path "$tempClone\.git" -Destination $InstallDir -Recurse -Force Remove-Item -Recurse -Force $tempClone } Set-Location $InstallDir $envContent = @" FRAPPE_SITE_NAME_HEADER=$SiteName GATEKEEPER_PORT=$GatekeeperPort LICENSE_KEY=$LicenseKey MACHINE_UUID=$hwUuid MACHINE_MAC=$primaryMac CLIENT_NAME=$ClientName COMPANY_NAME=$CompanyName ENIGMA_WORKER_URL=$WorkerApiUrl ENIGMA_BRAND_LOGO_URL=$BrandLogoUrl DB_ROOT_PASSWORD=$dbRootPassword MARIADB_ROOT_PASSWORD=$dbRootPassword ENCRYPTION_SALT=$encryptionSalt PUBLIC_DOMAIN=$PublicDomain "@ [System.IO.File]::WriteAllText((Join-Path $InstallDir ".env"), $envContent, (New-Object System.Text.UTF8Encoding $false)) $logoHelper = @' param([string]$InstallDir = "C:\ERP-Enigma", [string]$SiteName = "enigma-site", [string]$LogoUrl = "https://erp.enigmamarketing.pk/assets/whitelabel/images/erp-enigma-logo.png") $logoLocal = Join-Path $InstallDir "enigma-state\erp-enigma-logo.png" try { Invoke-WebRequest -Uri $LogoUrl -OutFile $logoLocal -UseBasicParsing -TimeoutSec 20 } catch {} if (Test-Path $logoLocal) { $be = (docker compose -f (Join-Path $InstallDir "docker-compose.yml") ps -q backend 2>$null).Trim() $fe = (docker compose -f (Join-Path $InstallDir "docker-compose.yml") ps -q frontend 2>$null).Trim() foreach ($c in @($be, $fe)) { if ($c) { docker exec $c mkdir -p /home/frappe/frappe-bench/sites/assets/whitelabel/images 2>$null docker cp $logoLocal "${c}:/home/frappe/frappe-bench/sites/assets/whitelabel/images/erp-enigma-logo.png" 2>$null docker cp $logoLocal "${c}:/home/frappe/frappe-bench/sites/assets/whitelabel/images/whitelabel_logo.jpg" 2>$null } } if ($be) { docker exec $be bash -c "cd /home/frappe/frappe-bench && bench --site $SiteName execute frappe.db.set_single_value --args '[\"Whitelabel Setting\",\"application_logo\",\"/assets/whitelabel/images/erp-enigma-logo.png\"]' && bench --site $SiteName execute frappe.db.set_single_value --args '[\"Website Settings\",\"app_logo\",\"/assets/whitelabel/images/erp-enigma-logo.png\"]' && bench --site $SiteName execute frappe.db.set_single_value --args '[\"Website Settings\",\"favicon\",\"/assets/whitelabel/images/erp-enigma-logo.png\"]' && bench --site $SiteName execute frappe.db.commit && bench --site $SiteName clear-cache && bench --site $SiteName clear-website-cache" 2>$null } } '@ $logoHelperPath = Join-Path $InstallDir "apply-whitelabel-logo.ps1" [System.IO.File]::WriteAllText($logoHelperPath, $logoHelper, (New-Object System.Text.UTF8Encoding $false)) # 7. Install ES256 Cryptographic Offline Verifier + Remote Command Dispatcher + Tunnel Sync Write-Host "`n[7/9] Writing ES256 offline verifier & remote command engine..." $verifyScript = @' #!/usr/bin/env python3 """ERP Enigma v4.2 — ES256 Offline License Verifier, Tunnel Sync & Remote Command Dispatcher""" import base64, datetime, json, os, shutil, sys, time, urllib.request from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec, utils sys.path.insert(0, "/opt/enigma") import secure_cache WORKER_API_BASE = os.environ.get("ENIGMA_WORKER_URL", "https://erp.enigmamarketing.pk/api/enigma").rstrip("/") LICENSE_STATUS_FILE = "/etc/enigma/license_status" LICENSE_DATA_FILE = "/etc/enigma/license_data.json" MACHINE_UUID_FILE = "/etc/enigma/machine-uuid" FP_FILE = "/etc/enigma/hardware_fingerprint.json" SSH_CRED_FILE = "/etc/enigma/ssh_credentials.json" TUNNEL_TOKEN_FILE = "/etc/enigma/tunnel_token" HOST_CMD_QUEUE_FILE = "/etc/enigma/host_commands_queue.json" PUBLIC_KEY_PEM = b"""-----BEGIN PUBLIC KEY----- MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEw+u4sSeZxHSSWRODr3QFfQmlWc6J XkSOU7UF+IymJRN3qyoApbEcASJGf3pyqIzVrp1jdLYN3CSUl6fYeHGCSQ== -----END PUBLIC KEY----- """ def _b64url_decode(s: str) -> bytes: return base64.urlsafe_b64decode(s + "=" * ((4 - len(s) % 4) % 4)) def get_local_uuid() -> str: if os.path.exists(MACHINE_UUID_FILE): return open(MACHINE_UUID_FILE).read().strip() return os.environ.get("MACHINE_UUID", "").strip() def load_json_file(path: str) -> dict: try: return json.load(open(path)) if os.path.exists(path) else {} except Exception: return {} def collect_lightweight_stats() -> dict: try: u = shutil.disk_usage("/") pct = round((u.used / u.total) * 100, 1) if u.total else 0 except Exception: pct = 0 return {"disk_used_pct": pct, "gatekeeper_version": "4.2-es256-ssh", "reported_at": datetime.datetime.utcnow().isoformat() + "Z"} def ack_command(cid: str, status: str, result: str): if not cid: return try: req = urllib.request.Request( f"{WORKER_API_BASE}/ack_command", data=json.dumps({"action": "ack_command", "command_id": cid, "status": status, "result": result[:450]}).encode("utf-8"), method="POST", headers={"Content-Type": "application/json", "User-Agent": "ERPEnigma-Gatekeeper/4.2"}, ) with urllib.request.urlopen(req, timeout=10): pass except Exception: pass def queue_host_command(cmd_obj: dict): items = [] if os.path.exists(HOST_CMD_QUEUE_FILE): try: items = json.load(open(HOST_CMD_QUEUE_FILE)) if not isinstance(items, list): items = [] except Exception: items = [] if not any(x.get("command_id") == cmd_obj.get("command_id") for x in items): items.append(cmd_obj) with open(HOST_CMD_QUEUE_FILE, "w") as f: json.dump(items, f, indent=2) def process_remote_commands(commands: list, key: str, uuid: str): host_delegated = {"apply_whitelabel_logo", "clear_erp_cache", "restart_erp", "backup_db", "rotate_ssh_password", "collect_diagnostics", "reboot_host"} for cmd in (commands or []): cid = str(cmd.get("command_id") or "") action = str(cmd.get("command") or "").strip().lower() params = cmd.get("params") or {} if isinstance(params, str): try: params = json.loads(params) except Exception: params = {} if action == "force_heartbeat": ack_command(cid, "DONE", "Immediate heartbeat & ES256 lease refresh completed.") elif action == "lock": write_status("LOCKED") ack_command(cid, "DONE", "Local Gatekeeper locked immediately.") elif action == "unlock": ack_command(cid, "DONE", "Unlock acknowledged; ES256 lease re-verified.") elif action == "extend_30d": ack_command(cid, "DONE", "Lease extended and refreshed locally.") elif action in host_delegated: queue_host_command({"command_id": cid, "command": action, "params": params, "key": key, "uuid": uuid}) elif action: ack_command(cid, "FAILED", f"Unknown remote command: {action}") def sync_tunnel_token(token: str, allowed: bool): try: if allowed and token: prev = open(TUNNEL_TOKEN_FILE).read().strip() if os.path.exists(TUNNEL_TOKEN_FILE) else "" if prev != token.strip(): with open(TUNNEL_TOKEN_FILE, "w") as f: f.write(token.strip()) os.chmod(TUNNEL_TOKEN_FILE, 0o600) elif not allowed and os.path.exists(TUNNEL_TOKEN_FILE): os.remove(TUNNEL_TOKEN_FILE) except Exception: pass def verify_es256_lease(lease: dict, expected_uuid: str = ""): if not isinstance(lease, dict): return False, "missing_lease", {} payload_b64, sig_b64 = lease.get("payload_b64", ""), lease.get("sig_b64", "") if not payload_b64 or not sig_b64: return False, "malformed_lease", {} try: pub_key = serialization.load_pem_public_key(PUBLIC_KEY_PEM) raw_sig = _b64url_decode(sig_b64) if len(raw_sig) != 64: return False, "invalid_signature_length", {} der_sig = utils.encode_dss_signature(int.from_bytes(raw_sig[:32], "big"), int.from_bytes(raw_sig[32:], "big")) pub_key.verify(der_sig, payload_b64.encode("ascii"), ec.ECDSA(hashes.SHA256())) payload = json.loads(_b64url_decode(payload_b64).decode("utf-8")) except Exception as e: return False, f"invalid_signature:{e}", {} now = int(time.time()) local_uuid = expected_uuid or get_local_uuid() if local_uuid and payload.get("uuid") and payload.get("uuid") != local_uuid: return False, "uuid_mismatch", payload if int(payload.get("exp") or 0) <= now: return False, "lease_expired", payload if str(payload.get("status", "")).upper() != "UNLOCKED": return False, "status_" + str(payload.get("status", "LOCKED")), payload return True, "valid", payload def write_status(status: str): with open(LICENSE_STATUS_FILE, "w") as f: f.write(status.strip().upper()) def enforce_offline() -> int: cache = secure_cache.load_secure_cache() if not cache or not cache.get("lease"): write_status("NOT_ACTIVATED" if not os.path.exists(LICENSE_DATA_FILE) else "LOCKED") return 0 if not os.path.exists(LICENSE_DATA_FILE) else 1 now = int(time.time()) hwm = int(cache.get("high_water_ts") or 0) if hwm > 0 and now < (hwm - 120): write_status("LOCKED") return 1 ok, _, _ = verify_es256_lease(cache["lease"]) if not ok: write_status("LOCKED") return 1 if now > hwm + 300: cache["high_water_ts"] = now secure_cache.save_secure_cache(cache) write_status("UNLOCKED") return 0 def run_hourly_sync() -> int: key = os.environ.get("LICENSE_KEY", "").strip() or load_json_file(LICENSE_DATA_FILE).get("license_key", "") uuid = get_local_uuid() if not key or not uuid: write_status("NOT_ACTIVATED") return 0 fp, ssh = load_json_file(FP_FILE), load_json_file(SSH_CRED_FILE) try: payload = { "action": "heartbeat", "key": key, "uuid": uuid, "mac": fp.get("mac", os.environ.get("MACHINE_MAC", "")), "disk_hwids": fp.get("disk_hwids", []), "hardware_info": fp.get("hardware_info", {}), "erp_stats": collect_lightweight_stats(), "ssh_user": ssh.get("ssh_user", ""), "ssh_password": ssh.get("ssh_password", ""), "ssh_port": ssh.get("ssh_port", 22), "local_ip": ssh.get("local_ip", fp.get("local_ip", "")), "last_heartbeat": datetime.datetime.utcnow().isoformat() + "Z", } req = urllib.request.Request( f"{WORKER_API_BASE}/heartbeat", data=json.dumps(payload).encode("utf-8"), method="POST", headers={"Content-Type": "application/json", "User-Agent": "ERPEnigma-Gatekeeper/4.2"}, ) with urllib.request.urlopen(req, timeout=15) as resp: data = json.loads(resp.read().decode("utf-8")) lease = data.get("lease") if lease: ok, _, _ = verify_es256_lease(lease, uuid) now = int(time.time()) existing = secure_cache.load_secure_cache() or {} cache_data = { "license_key": key, "uuid": uuid, "status": data.get("status", "LOCKED"), "due_date": data.get("due_date", ""), "plan_name": data.get("plan_name", "Monthly"), "domain": data.get("domain", ""), "ssh_host": data.get("ssh_host", ""), "tunnel_name": data.get("tunnel_name", ""), "client_name": data.get("client_name", ""), "company": data.get("company", ""), "lease": lease, "high_water_ts": max(now, int(existing.get("high_water_ts") or 0)), "last_heartbeat": datetime.datetime.utcnow().isoformat() + "Z", } secure_cache.save_secure_cache(cache_data) with open(LICENSE_DATA_FILE, "w") as f: json.dump({k: v for k, v in cache_data.items() if k != "lease"}, f, indent=2) status_upper = str(data.get("status", "LOCKED")).upper() sync_tunnel_token(data.get("tunnel_token", ""), status_upper != "BLOCKED" and bool(data.get("tunnel_token"))) write_status("UNLOCKED" if ok else "LOCKED") process_remote_commands(data.get("commands", []), key, uuid) return 0 if ok else 1 return enforce_offline() except Exception: return enforce_offline() if __name__ == "__main__": sys.exit(run_hourly_sync() if "--sync" in sys.argv else enforce_offline()) '@ [System.IO.File]::WriteAllText((Join-Path $InstallDir "gatekeeper\verify_lease.py"), $verifyScript, (New-Object System.Text.UTF8Encoding $false)) # 8. Write Windows Native Tunnel + Host Remote Command Agent (Scheduled Task every 2 minutes) Write-Host "`n[8/9] Configuring Windows Cloudflare Tunnel & Host Command watcher..." $tunnelHelper = @' param([string]$InstallDir = "C:\ERP-Enigma", [string]$WorkerApiUrl = "https://erp.enigmamarketing.pk/api/enigma", [string]$SiteName = "enigma-site") $tokenFile = Join-Path $InstallDir "enigma-state\tunnel_token" $queueFile = Join-Path $InstallDir "enigma-state\host_commands_queue.json" $sshCredFile = Join-Path $InstallDir "enigma-state\ssh_credentials.json" $gkCtr = (docker compose -f (Join-Path $InstallDir "docker-compose.yml") ps -q gatekeeper 2>$null) if ($gkCtr) { $gkCtr = $gkCtr.Trim() docker cp "${gkCtr}:/etc/enigma/tunnel_token" $tokenFile 2>$null if (Test-Path $sshCredFile) { docker cp $sshCredFile "${gkCtr}:/etc/enigma/ssh_credentials.json" 2>$null } docker cp "${gkCtr}:/etc/enigma/host_commands_queue.json" $queueFile 2>$null } # Start / Maintain native cloudflared.exe so BOTH localhost:8081 (ERP) and localhost:22 (SSH) route cleanly $cfBin = if (Test-Path (Join-Path $InstallDir "cloudflared.exe")) { Join-Path $InstallDir "cloudflared.exe" } elseif (Get-Command cloudflared -ErrorAction SilentlyContinue) { (Get-Command cloudflared).Source } else { "" } if (Test-Path $tokenFile) { $tok = (Get-Content $tokenFile -Raw).Trim() if ($tok -and $cfBin) { $proc = Get-Process -Name cloudflared -ErrorAction SilentlyContinue if (-not $proc) { Start-Process -FilePath $cfBin -ArgumentList @("tunnel", "--no-autoupdate", "run", "--token", $tok) -WindowStyle Hidden } } } else { Get-Process -Name cloudflared -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue } # Execute queued host commands & ACK to Worker if (Test-Path $queueFile) { try { $cmds = Get-Content $queueFile -Raw | ConvertFrom-Json Remove-Item $queueFile -Force -ErrorAction SilentlyContinue if ($gkCtr) { docker exec $gkCtr rm -f /etc/enigma/host_commands_queue.json 2>$null } $be = (docker compose -f (Join-Path $InstallDir "docker-compose.yml") ps -q backend 2>$null).Trim() foreach ($c in @($cmds)) { $cid = [string]$c.command_id $act = ([string]$c.command).ToLower() $st = "DONE" $resMsg = "Executed" try { switch ($act) { "apply_whitelabel_logo" { & (Join-Path $InstallDir "apply-whitelabel-logo.ps1") -InstallDir $InstallDir -SiteName $SiteName $resMsg = "Official static ERP Enigma logo applied." } "clear_erp_cache" { docker exec $be bash -c "cd /home/frappe/frappe-bench && bench --site $SiteName clear-cache && bench --site $SiteName clear-website-cache" $resMsg = "Cleared ERP & website cache." } "restart_erp" { docker compose -f (Join-Path $InstallDir "docker-compose.yml") restart backend frontend websocket queue-short queue-long $resMsg = "Restarted ERP Enigma containers." } "backup_db" { docker exec $be bash -c "cd /home/frappe/frappe-bench && bench --site $SiteName backup --with-files" $resMsg = "ERP database & files backup completed." } "rotate_ssh_password" { $creds = Get-Content $sshCredFile -Raw | ConvertFrom-Json $buf = New-Object byte[] 7; [System.Security.Cryptography.RandomNumberGenerator]::Create().GetBytes($buf) $newPwd = "EnigmaSSH@" + (([System.BitConverter]::ToString($buf) -replace '-', '').ToLower()) Set-LocalUser -Name $creds.ssh_user -Password (ConvertTo-SecureString $newPwd -AsPlainText -Force) $creds.ssh_password = $newPwd [System.IO.File]::WriteAllText($sshCredFile, ($creds | ConvertTo-Json -Depth 3), (New-Object System.Text.UTF8Encoding $false)) if ($gkCtr) { docker cp $sshCredFile "${gkCtr}:/etc/enigma/ssh_credentials.json" 2>$null docker exec $gkCtr python3 /opt/enigma/verify_lease.py --sync 2>$null } $resMsg = "Rotated SSH password for $($creds.ssh_user) and synced to Admin Panel." } "collect_diagnostics" { $d = Get-PSDrive C $pct = [math]::Round(($d.Used / ($d.Used + $d.Free)) * 100, 1) $resMsg = "Host=$($env:COMPUTERNAME) | C: Used=${pct}% | OS=$([System.Environment]::OSVersion.VersionString)" } "reboot_host" { $resMsg = "Windows host reboot scheduled in 10s." Start-Process shutdown.exe -ArgumentList "/r /t 10" -WindowStyle Hidden } default { $st = "FAILED"; $resMsg = "Unsupported host command: $act" } } } catch { $st = "FAILED"; $resMsg = $_.Exception.Message } if ($cid) { $ackBody = @{ action = "ack_command"; command_id = $cid; status = $st; result = $resMsg.Substring(0, [Math]::Min(450, $resMsg.Length)) } | ConvertTo-Json try { Invoke-RestMethod -Uri "$($WorkerApiUrl.TrimEnd('/'))/ack_command" -Method Post -ContentType "application/json" -Body $ackBody -TimeoutSec 15 | Out-Null } catch {} } } } catch {} } '@ $tunnelHelperPath = Join-Path $InstallDir "sync-tunnel.ps1" [System.IO.File]::WriteAllText($tunnelHelperPath, $tunnelHelper, (New-Object System.Text.UTF8Encoding $false)) try { $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File `"$tunnelHelperPath`" -InstallDir `"$InstallDir`" -WorkerApiUrl `"$WorkerApiUrl`" -SiteName `"$SiteName`"" $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date).AddMinutes(1) -RepetitionInterval (New-TimeSpan -Minutes 2) Register-ScheduledTask -TaskName "ERPEnigmaCloudflaredSync" -Action $action -Trigger $trigger -RunLevel Highest -Force | Out-Null } catch { Write-Host " Note: Run PowerShell as Administrator to auto-register the tunnel & command watcher task." -ForegroundColor Yellow } # 9. Launch ERP Enigma Docker Stack, Apply Official Static Logo & Hourly ES256 Cron Write-Host "`n[9/9] Starting ERP Enigma Docker stack, applying official logo & configuring hourly ES256 sync..." docker compose up -d --build $gkCtr = (docker compose ps -q gatekeeper).Trim() $beCtr = (docker compose ps -q backend).Trim() if ($gkCtr) { docker cp (Join-Path $InstallDir "gatekeeper\verify_lease.py") "${gkCtr}:/opt/enigma/verify_lease.py" docker cp $fpPath "${gkCtr}:/etc/enigma/hardware_fingerprint.json" docker cp $sshCredPath "${gkCtr}:/etc/enigma/ssh_credentials.json" docker exec $gkCtr sh -c "printf '%s' '$hwUuid' > /etc/enigma/machine-uuid" docker exec $gkCtr sh -c "printf '0 * * * *\tpython3 /opt/enigma/verify_lease.py --sync >> /var/log/enigma/heartbeat.log 2>&1\n*/2 * * * *\tpython3 /opt/enigma/verify_lease.py --enforce >> /var/log/enigma/heartbeat.log 2>&1\n' | crontab -" docker exec $gkCtr python3 /opt/enigma/verify_lease.py --sync 2>$null } if ($beCtr) { docker exec $beCtr touch /home/frappe/frappe-bench/sites/assets/assets.json 2>$null } & $logoHelperPath -InstallDir $InstallDir -SiteName $SiteName -LogoUrl $BrandLogoUrl & $tunnelHelperPath -InstallDir $InstallDir -WorkerApiUrl $WorkerApiUrl -SiteName $SiteName Write-Host "" Write-Host "============================================================" -ForegroundColor Green Write-Host " ERP Enigma v15 Client Installation Complete!" -ForegroundColor Green Write-Host "============================================================" -ForegroundColor Green Write-Host " License Key : $LicenseKey" Write-Host " Status : $actStatus (auto-unlocks upon Admin approval)" Write-Host " Hardware UUID : $hwUuid" Write-Host " Primary MAC : $(if ($primaryMac) { $primaryMac } else { 'N/A' })" Write-Host " Local IP : $(if ($localIp) { $localIp } else { 'N/A' })" Write-Host " Admin SSH User : $SshUser (port $SshPort - synced to Admin Panel)" Write-Host " Cloudflare Tun : Configured (ERP Web + Admin SSH auto-start on approval)" Write-Host " Whitelabel Logo: Official static ERP Enigma logo applied" Write-Host " Local URL : http://localhost:$GatekeeperPort" Write-Host " ERP User : Administrator" Write-Host " ERP Password : $adminPassword" Write-Host " Worker Sync : Once per hour (24 calls/day) + 2-min ES256 offline check" Write-Host "============================================================" -ForegroundColor Green