Compare commits

..

139 Commits
v1.1.1 ... main

Author SHA1 Message Date
a2010e9dc1 v1.1.62 2026-11-07 11:27:19 -08:00
8a6c515601 pontentially fixed auto update 2026-11-07 11:20:42 -08:00
8abcdf2c16 v1.1.61 2026-11-07 11:11:56 -08:00
4e2e7c1e6f v1.1.60 2026-11-06 13:35:36 -08:00
8678870c2d added tmdb key 2026-11-06 13:27:55 -08:00
1be2aea1dd maybe created auto updater? 2026-11-06 13:26:45 -08:00
c5909d656d v1.1.59 2026-11-06 13:14:55 -08:00
3f45e00b5c v1.1.58 2026-11-05 19:34:52 -08:00
ec5950b6ca added discord rpc 2026-11-05 19:22:42 -08:00
a506a2efb4 fix: enforce manifest-based component downloads and validate package URLs during release builds 2026-11-04 21:30:54 -08:00
b0096a2073 v1.1.57 2026-11-04 21:27:25 -08:00
8a333d6770 potentially fixed mac support 2026-11-04 21:19:30 -08:00
9c4d250640 updated 2026-11-01 14:16:41 -08:00
03ed2f0e53 fixed lock file 2026-11-01 14:16:04 -08:00
47c97fdf21 refactor: move component archives to GitLab Package Registry and keep release assets minimal 2026-10-30 23:00:25 -07:00
e7204589a4 v1.1.54 2026-10-30 22:58:34 -07:00
3e2dbd312e feat: add signed Windows launcher self-updates with SHA-256 verification 2026-10-30 22:50:07 -07:00
79dd5e7465 Signed per-component updater, release 1.1.55 2026-10-30 22:38:38 -07:00
0c6a9d1e5b v1.1.54 2026-10-30 20:13:21 -07:00
609891f478 updated debug 2026-10-30 20:02:41 -07:00
b201510b5a v1.1.53 2026-10-30 19:37:14 -07:00
acd46d665b fixed image issue 2026-10-30 19:23:15 -07:00
f07c0ea0fd v1.1.52 2026-10-30 19:08:41 -07:00
aaa0df5f17 fixed an extreme ammount of issues 2026-10-30 19:01:30 -07:00
08950e101f v1.1.51 2026-10-30 17:43:06 -07:00
f8aa86eecf fixed UI issue 2026-10-30 17:36:45 -07:00
587d70c46a v1.1.50 2026-10-29 22:28:46 -07:00
e738ea158b huge rewrite 2026-10-29 22:19:03 -07:00
25358e9c17 v1.1.49 2026-10-25 21:38:44 -07:00
Devin Bot
998e16674c updated git ignore 2026-10-25 20:11:43 -07:00
Devin Bot
179372dad3 Pin Tauri packages to matching versions 2026-10-25 20:11:32 -07:00
Devin Bot
59d25f53dd v1.1.48 2026-10-25 19:53:06 -07:00
Devin Bot
4ed853b5ae v1.1.47 2026-10-25 19:32:10 -07:00
Devin Bot
1b2c97e74b potentially fixed auto updater, made sdk also up to date 2026-10-25 19:27:25 -07:00
Devin Bot
d9ae75e9cb v1.1.46 2026-10-24 18:32:54 -07:00
Devin Bot
51951ac192 removed floating nav, made the updater better...? 2026-10-24 18:28:09 -07:00
Devin Bot
c131515209 added white icon 2026-10-24 18:13:14 -07:00
Devin Bot
b44f59f4b7 v1.1.45 2026-10-23 20:47:05 -07:00
Devin Bot
35087d24e8 fixed logo, updated sdk , changed frontend to support server.js n it runs it well 2026-10-23 20:13:01 -07:00
2435ee51e6 fixed image path 2026-10-12 19:19:36 -07:00
59f4d9855f v1.1.43 2026-10-11 16:38:00 -07:00
928b40230c v1.1.42 2026-10-11 16:27:46 -07:00
59bc589a85 updated 2026-10-11 16:22:36 -07:00
63809ba2af v1.1.42 2026-10-11 16:16:54 -07:00
0918f8e8aa v1.1.43 2026-10-11 16:15:58 -07:00
4d085c33e1 Fix Tauri dependency version mismatch 2026-10-03 10:49:46 -07:00
e71e73d166 v1.1.42 2026-10-03 10:38:23 -07:00
d5e54939a8 v1.1.41 2026-09-26 12:13:10 -07:00
76296cc7c2 allow localhost connections for update service in CSP 2026-09-26 12:07:52 -07:00
c416f17e81 v1.1.40 2026-09-26 11:54:15 -07:00
2c4501fa5f ui tweaks 2026-09-26 11:49:14 -07:00
eca4d017de v1.1.39 2026-09-21 19:33:06 -07:00
33727a79c5 possibly fixed auto updater? hid buttons untill shown and made the yes/no actually respond to something 2026-09-21 19:22:18 -07:00
99e45fd7ff Merge branch 'main' of https://gitlab.com/vyla-entertainment/home 2026-09-21 18:43:21 -07:00
adf237dac0 v1.1.38 2026-09-21 18:43:20 -07:00
23021d6524 Add new file 2026-09-18 10:11:09 -07:00
97ba68bd97 v1.1.37 2026-09-13 19:38:39 -07:00
2de96960d9 fixed update issue 2026-09-13 19:32:21 -07:00
8fd8be0d05 v1.1.36 2026-09-13 18:59:54 -07:00
e3283fff45 updated sdk 2026-09-13 18:51:05 -07:00
64ed5981be v1.1.35 2026-09-07 11:26:23 -07:00
ba8266bd86 fixed files not downloading properly 2026-09-07 11:21:39 -07:00
bb39db0272 v1.1.34 2026-09-06 19:37:27 -07:00
d799da3d2a v1.1.33 2026-09-06 11:01:48 -07:00
f4aaf2fa7c removed stream-api & auth no need, fixed some issues aswell 2026-09-06 10:55:14 -07:00
8ce4edc251 prevented unnecessary automatic updates 2026-09-05 17:03:18 -07:00
bef6fd2326 updated md's 2026-09-05 16:49:20 -07:00
774f9a5e03 V1.1.32 2026-09-05 11:51:46 -07:00
250e7972f2 v1.1.31 2026-09-05 11:25:38 -07:00
5082d51ebc fixed 2026-09-05 11:24:28 -07:00
ed66b894c1 v1.1.30 2026-09-05 11:07:49 -07:00
11d6c346e8 resolve Rust state lifetime errors in Node service handlers 2026-09-05 11:00:31 -07:00
c986194e64 v1.1.29 2026-09-05 10:26:01 -07:00
33e285953c prevent macOS HTTPS upgrade for localhost resources 2026-09-05 10:21:18 -07:00
f46869f967 v1.1.28 2026-09-05 09:31:35 -07:00
b19e6b21c9 use 127.0.0.1 for macOS localhost navigation to avoid ATS SSL errors 2026-09-05 09:15:27 -07:00
c8ea2598b9 v1.1.27 2026-09-04 23:20:34 -07:00
e3257b8a3a v1.1.25 2026-09-04 23:16:26 -07:00
fbb5a4437d v1.1.25 2026-09-04 23:01:44 -07:00
dbaab9a00e fixed mismatch 2026-09-04 22:55:31 -07:00
fc49bb93a7 allow localhost subresource loads in WKWebView 2026-09-04 22:52:34 -07:00
9229f0c2dd added this 2026-09-04 22:45:47 -07:00
843abf7df4 supported devtools 2026-09-04 22:39:33 -07:00
27fda0430b v1.1.23 2026-09-04 22:37:36 -07:00
8b49d679bd add macOS ATS exception domain for localhost webview requests 2026-09-04 22:37:15 -07:00
62883b3180 v1.1.22 2026-09-04 22:27:50 -07:00
3c6ae0125b use location.replace for WKWebView navigation 2026-09-04 22:27:24 -07:00
be0810ea6d fix: only check platform-matching node binary extension; bump to 1.1.20 2026-09-04 22:02:38 -07:00
dff55060e7 fix: only check platform-matching node binary extension 2026-09-04 22:02:16 -07:00
df767b5ffc v1.1.20 2026-09-04 21:54:10 -07:00
1b70c6784a resolve bundled resources under both _up_ and up folder names 2026-09-04 21:53:44 -07:00
e25e1c93f9 chore: bump version to 1.1.19 2026-09-04 21:37:32 -07:00
4c708ad97c preserve execute bit on bundled macOS node binary 2026-09-04 21:34:41 -07:00
b81a4e044b v1.1.18 2026-09-04 21:19:06 -07:00
f6aa2daa01 fixed (os error 13) 2026-09-04 21:13:11 -07:00
e03eb38adc v1.1.17 2026-09-04 21:04:44 -07:00
2b690b47c1 fixed typo 2026-09-04 20:58:53 -07:00
dffbdb92a5 v1.1.16 2026-09-04 20:52:21 -07:00
45d6515f2e fixed some issues...? 2026-09-04 20:46:08 -07:00
a3e6a278fe v1.1.15 2026-09-04 20:15:10 -07:00
7ffc20ee48 fixed harmless warning 2026-09-04 20:11:01 -07:00
ddf3abb314 add macOS Node runtime and appdata support 2026-09-04 20:08:27 -07:00
ec50c4e07f v1.1.14 2026-09-04 19:55:59 -07:00
49b2a7622b added debug text 2026-09-04 19:51:27 -07:00
b8e474cb92 Fix Mac tar extraction argument parsing 2026-09-04 19:35:21 -07:00
8b29c9e3c7 Fix Mac Node architecture and resources bundle 2026-09-04 19:30:40 -07:00
5dab61b359 Fix release installer path detection 2026-09-04 19:17:05 -07:00
eab843aa16 Detect and upload macOS DMG bundle 2026-09-04 19:10:21 -07:00
b757f741b7 Fix release log object and multi-platform extension replacement 2026-09-04 19:04:10 -07:00
5f4c47a07c Handle duplicate release asset links 2026-09-04 18:58:51 -07:00
32677c9fb2 Fix Tauri window builder for macOS 2026-09-04 18:53:56 -07:00
7eab57cfd9 Fix Rust PATH and lock release version 2026-09-04 18:50:17 -07:00
c8fc7da64d Configure free Mac cloud workflow 2026-09-04 18:47:30 -07:00
88c1824bf7 removed the gitlab yml 2026-09-04 18:45:22 -07:00
a50cb2b6b8 Fix Windows instance type 2026-09-04 18:45:15 -07:00
971eae4af1 Add Windows and macOS Codemagic workflows 2026-09-04 18:44:28 -07:00
1400d538f3 support mac user test 2026-09-04 18:32:40 -07:00
b1d01d94da v1.1.13 2026-09-04 14:38:43 -07:00
9d7e218ff6 v1.1.12 2026-09-01 20:20:53 -07:00
c19e1e2cf7 fixed downloading update ( sorry lmfao ) 2026-09-01 20:14:28 -07:00
6b06bc8170 v1.1.11 2026-09-01 19:45:46 -07:00
769c0dadcd possibly fixed the auto updater, and fixed the node processes closing 2026-09-01 19:39:27 -07:00
414ef73e1d v1.1.10 2026-09-01 13:41:06 -07:00
01c04111bd remove obfuscation, fix UI scroll stutters, and fix dynamic config loading in updater 2026-09-01 13:26:41 -07:00
a729bb81a3 v1.1.9 2026-09-01 13:12:12 -07:00
547eb59709 disable express static caching to resolve stale UI on app updates 2026-08-28 16:57:17 -07:00
d774bed69b v1.1.8 2026-08-28 16:51:14 -07:00
393a007e4a optimize runtime performance, eliminate AV flags, and apply maximum JS obfuscation 2026-08-28 16:41:47 -07:00
cb3028387c removed launch button 2026-08-28 15:53:06 -07:00
f689fcac03 v1.1.7 2026-08-27 20:05:12 -07:00
b1d949ada2 overhaul loader UI with shader rays, liquid glass styling, and interactive launch flow 2026-08-27 19:58:40 -07:00
1f48bb3815 released v1.1.6 2026-08-26 20:10:16 -07:00
dfb0893316 automate fresh repo cloning, resolve asset caching, and auto-update Vyla SDK at startup 2026-08-26 20:03:08 -07:00
08c70a2c6d clean old nsis bundles and strictly match installer version to prevent uploading outdated exe 2026-08-22 21:56:18 -07:00
1092d359ab clean old nsis bundles and strictly match installer version to prevent uploading outdated exe 2026-08-22 21:48:23 -07:00
dcba2a2438 place WebView2Loader in root resources to guarantee NSIS extraction alongside executable 2026-08-22 21:43:12 -07:00
8f99096bfb place WebView2Loader in root resources to guarantee NSIS extraction alongside executable 2026-08-22 21:36:42 -07:00
2f5efe45c4 remove static webview2 link override to enable proper mingw dynamic bundling 2026-08-22 21:17:30 -07:00
403eb59370 released v1.1.1 2026-08-22 21:06:18 -07:00
47 changed files with 10906 additions and 2431 deletions

7
.gitignore vendored
View File

@@ -1,5 +1,4 @@
node_modules/ node_modules/
package-lock.json
dist/ dist/
dist-build/ dist-build/
@@ -35,4 +34,8 @@ yarn-error.log*
*.tmp *.tmp
*.temp *.temp
download-temp.zip download-temp.zip
.env
release-assets/

View File

@@ -0,0 +1 @@
bash -c 'pkill -9 -x node 2>/dev/null; pkill -9 -x "Vyla Home" 2>/dev/null; pkill -9 -x "vyla-home" 2>/dev/null; rm -rf "$HOME/Library/Application Support/com.vyla.home" "$HOME/Library/Application Support/vyla-home" "$HOME/Library/Application Support/Vyla Home" "$HOME/Library/Caches/com.vyla.home" "$HOME/Library/Caches/vyla-home" "$HOME/Library/Caches/Vyla Home" "$HOME/Library/WebKit/com.vyla.home" "$HOME/Library/WebKit/vyla-home" "$HOME/Library/WebKit/Vyla Home" "$HOME/Library/Logs/Vyla Home" "$HOME/Library/Preferences/com.vyla.home.plist" "$HOME/.vyla-home" "/Applications/Vyla Home.app" "/Applications/vyla-home.app" "$HOME/Applications/Vyla Home.app" "$HOME/Applications/vyla-home.app" "src-tauri/target" "dist-build" "temp-validation-extract" "dist" "frontend" "player" "auth-proxy" "stream-api" "logs" "*.log" "download-temp.zip" "update-payload.zip" "manifest.json" "validation-report.json" "config/encrypted-credentials.json" "config/credentials.json"; echo "Vyla Home cleanup complete."'

3
DOCUEMENTATION/FIXES.md Normal file
View File

@@ -0,0 +1,3 @@
If someone get's a Webview2 error, they need to download the WebView2Loader.dll and drag it in bin
bin\WebView2Loader.dll

View File

@@ -16,4 +16,22 @@ To release it, run:
```powershell ```powershell
npm run release:full npm run release:full
``` ```
Fixing os error 32
```powershell
Stop-Process -Name "vyla-home", "node", "cargo" -Force -ErrorAction SilentlyContinue
```
Fake an old local version:
```powershell
'{"version":"0.0.1","sha256":null}' | Set-Content "$env:APPDATA\vyla-home\vyla-home-files\version.json"
```
Fake a test?
```powershell
$env:VYLA_TEST_UI="1"; npm run dev
```

47
LICENSE Normal file
View File

@@ -0,0 +1,47 @@
Vyla Home Attribution License (VHAL) v1.0
Copyright (c) 2026 Vyla Entertainment
Permission is hereby granted, free of charge, to any person obtaining a copy of the Vyla Home source code and associated documentation (the “Software”), to use, copy, modify, merge, publish, and distribute the Software, subject to the following conditions:
1. Attribution
Any public distribution, publication, derivative work, modified version, or substantial use of the Software must provide clear and visible credit to Vyla Entertainment and Vyla Home.
The attribution must substantially state:
“Based on Vyla Home by Vyla Entertainment”
The attribution must appear in a location reasonably visible to users of the Software, such as an About page, credits section, documentation, repository, application information page, or other comparable location.
2. Preservation of License
Copies or substantial portions of the Software must include a copy of this license and the original copyright notice.
3. Modified Versions
Modified versions may be created and distributed under different terms, provided that the attribution requirements of Section 1 and the preservation requirements of Section 2 remain in effect.
4. No Implication of Endorsement
Use of the Software does not grant permission to imply that Vyla Entertainment endorses, sponsors, or officially supports any modified version or derivative work unless Vyla Entertainment has provided explicit written permission.
5. Trademarks
This license does not grant permission to use the Vyla Entertainment or Vyla Home names, logos, trademarks, service marks, or other branding except as necessary to satisfy the attribution requirement of this license.
6. Commercial Use
Commercial use, sale, and distribution of the Software and derivative works are permitted, provided that all applicable requirements of this license are satisfied.
7. No Warranty
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
IN NO EVENT SHALL VYLA ENTERTAINMENT OR THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
8. Acceptance
By using, copying, modifying, publishing, or distributing the Software, you agree to the terms of this license.
If any provision of this license is found to be unenforceable, the remaining provisions shall remain in effect.

View File

@@ -1,29 +1,24 @@
# Vyla Home # Vyla Home
Vyla Home is a desktop version of Vyla, built to run entirely on your own computer instead of on [vyla.cc](https://vyla.cc). A desktop application that provides a fast, secure, and private way to access the Vyla media ecosystem. Vyla Home runs everything locally on your computer, giving you quick access to streaming services without relying on external servers.
## Why this exists ## What It Does
Running Vyla as a hosted website has been a constant source of stress. Hosting providers routinely block or throttle traffic coming from data centers, which is exactly where most affordable hosting lives. Every workaround for that involves paid infrastructure — residential proxies, dedicated IPs, premium tiers — that isn't realistic to keep funding long-term. Vyla Home is a native desktop app that:
On top of that, there's the standing fear that comes with depending on someone else's infrastructure: a provider changes their policy, a server gets flagged, an account gets suspended, and everything just stops working with no warning. That uncertainty has genuinely cost some sleep. Waking up wondering if the whole project got wiped overnight isn't a sustainable way to build something. - **Runs locally** - All services run on your computer for maximum privacy and speed
- **Manages streaming services** - Handles authentication and streaming APIs automatically
- **Updates automatically** - Keeps itself up to date with the latest features and fixes
- **Works offline** - Core functionality doesn't require constant internet connectivity
- **Keeps your data secure** - Your credentials and settings are encrypted and stored locally
Vyla Home is the answer to that. Instead of fighting hosting providers forever, the app runs locally on your own machine. No data center traffic to block. No hosting bills. No one else's finger on the switch. ## How It Works
## What it actually is When you launch Vyla Home, it:
Vyla Home packages up the same player, streaming, and live-sports features as the website, wrapped in a small desktop app. When you open it: 1. Starts the necessary background services (media player server)
2. Loads your saved settings and credentials (encrypted for security)
3. Checks for updates and installs them if available
4. Opens the user interface in a secure, embedded browser window
- It grabs the latest version automatically Everything happens on your machine - your data never leaves your computer except when communicating directly with streaming services.
- It starts everything up locally on your computer
- The interface opens in its own window, just like the website did
Everything runs for you, on your machine, for your own personal use.
## What this is not
This isn't a public service or a way to redistribute anything. It's a personal media player for personal use — think of it as watching things you already have access to, through your own local player, instead of a public streaming platform. Nothing here is intended to be shared, resold, or run as a service for other people.
## Status
Might not be actively worked on. Expect various bugs — this is a solo project built to solve a real problem, not a polished commercial product.

Binary file not shown.

View File

@@ -1,12 +1,11 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const crypto = require('crypto'); const crypto = require('crypto');
const JavaScriptObfuscator = require('javascript-obfuscator');
const AdmZip = require('adm-zip'); const AdmZip = require('adm-zip');
const { execSync } = require('child_process'); const { execSync } = require('child_process');
const BUILD_DIR = path.join(__dirname, 'dist-build'); const BUILD_DIR = path.join(__dirname, 'dist-build');
const REPOS = ['frontend', 'player', 'auth-proxy', 'stream-api']; const REPOS = ['frontend', 'player'];
const TEMP_EXTRACT_DIR = path.join(__dirname, 'temp-validation-extract'); const TEMP_EXTRACT_DIR = path.join(__dirname, 'temp-validation-extract');
@@ -15,22 +14,25 @@ const GITLAB_GROUP = 'vyla-entertainment';
const REPO_CONFIG = { const REPO_CONFIG = {
'frontend': { name: 'frontend', branch: 'main' }, 'frontend': { name: 'frontend', branch: 'main' },
'player': { name: 'player', branch: 'main' }, 'player': { name: 'player', branch: 'main' },
'auth-proxy': { name: 'auth-proxy', branch: 'main' },
'stream-api': { name: 'stream-api', branch: 'main' },
}; };
const clonedRepos = new Set();
function clonePrivateRepo(repoConfig, targetDir) { function clonePrivateRepo(repoConfig, targetDir) {
const repoUrl = `https://gitlab.com/${GITLAB_GROUP}/${repoConfig.name}.git`; if (fs.existsSync(targetDir)) {
console.log(`Removing stale ${repoConfig.name} before fresh clone...`);
fs.rmSync(targetDir, { recursive: true, force: true });
}
const token = process.env.GITLAB_TOKEN || process.env.VYLA_GITLAB_TOKEN;
const auth = token ? `oauth2:${token}@` : '';
const repoUrl = `https://${auth}gitlab.com/${GITLAB_GROUP}/${repoConfig.name}.git`;
try { try {
if (fs.existsSync(targetDir)) {
fs.rmSync(targetDir, { recursive: true, force: true });
}
execSync(`git clone --depth 1 --branch ${repoConfig.branch} ${repoUrl} ${targetDir}`, { execSync(`git clone --depth 1 --branch ${repoConfig.branch} ${repoUrl} ${targetDir}`, {
stdio: 'inherit' stdio: 'inherit'
}); });
clonedRepos.add(repoConfig.name);
} catch (error) { } catch (error) {
throw new Error(`Failed to clone ${repoConfig.name}: ${error.message}`); throw new Error(`Failed to clone ${repoConfig.name}: ${error.message}`);
} }
@@ -71,22 +73,7 @@ function cleanBuildDir() {
fs.mkdirSync(BUILD_DIR, { recursive: true }); fs.mkdirSync(BUILD_DIR, { recursive: true });
} }
function obfuscateFile(filePath, isEsm = false) { let credentialsId = null;
const content = fs.readFileSync(filePath, 'utf8');
const result = JavaScriptObfuscator.obfuscate(content, {
compact: true,
controlFlowFlattening: false,
deadCodeInjection: false,
debugProtection: false,
numbersToExpressions: false,
simplify: true,
stringArray: true,
stringArrayThreshold: 0.4,
stringArrayEncoding: [],
module: isEsm
});
fs.writeFileSync(filePath, result.getObfuscatedCode(), 'utf8');
}
function encryptCredentialsFile() { function encryptCredentialsFile() {
const CryptoUtils = require('./crypto-utils'); const CryptoUtils = require('./crypto-utils');
@@ -124,6 +111,7 @@ function encryptCredentialsFile() {
} }
} }
credentialsId = crypto.createHash('sha256').update(JSON.stringify(credentials)).digest('hex');
const buildKey = CryptoUtils.deriveKey('vyla-home-build-key', 'vyla-home-payload-salt-v1'); const buildKey = CryptoUtils.deriveKey('vyla-home-build-key', 'vyla-home-payload-salt-v1');
const encryptedData = CryptoUtils.encryptObject(credentials, buildKey); const encryptedData = CryptoUtils.encryptObject(credentials, buildKey);
@@ -168,13 +156,6 @@ function processFolder(src, dest) {
if (pkg.type === 'module') isEsm = true; if (pkg.type === 'module') isEsm = true;
} catch (e) { } } catch (e) { }
} }
for (const filePath of jsFiles) {
try {
obfuscateFile(filePath, isEsm);
} catch (e) {
}
}
} }
function getFileChecksum(filePath) { function getFileChecksum(filePath) {
@@ -194,9 +175,6 @@ function validatePayload(zipPath) {
zip.extractAllTo(TEMP_EXTRACT_DIR, true); zip.extractAllTo(TEMP_EXTRACT_DIR, true);
const requiredFiles = [ const requiredFiles = [
'player/index.html',
'auth-proxy/server.js',
'stream-api/server.js',
'frontend/index.html' 'frontend/index.html'
]; ];
@@ -254,6 +232,32 @@ function validatePayload(zipPath) {
return validationResults.checksum; return validationResults.checksum;
} }
function directoryId(dir) {
const hash = crypto.createHash('sha256');
const walk = (current, rel) => {
for (const name of fs.readdirSync(current).sort()) {
const full = path.join(current, name);
const relPath = rel ? `${rel}/${name}` : name;
if (fs.statSync(full).isDirectory()) {
walk(full, relPath);
} else {
hash.update(`${relPath}\0${getFileChecksum(full)}\n`);
}
}
};
walk(dir, '');
return hash.digest('hex');
}
function signManifest(manifest) {
const key = process.env.VYLA_UPDATE_SIGNING_KEY;
if (!key) {
throw new Error('VYLA_UPDATE_SIGNING_KEY is required to sign the update manifest.');
}
const UpdateClient = require('./update-client');
return crypto.sign(null, Buffer.from(UpdateClient.canonicalManifest(manifest)), key.replace(/\\n/g, '\n')).toString('base64');
}
async function build() { async function build() {
try { try {
cloneAllRepos(); cloneAllRepos();
@@ -332,6 +336,9 @@ async function build() {
} }
const zipPath = path.join(__dirname, 'update-payload.zip'); const zipPath = path.join(__dirname, 'update-payload.zip');
if (fs.existsSync(zipPath)) {
fs.rmSync(zipPath, { force: true });
}
zip.writeZip(zipPath); zip.writeZip(zipPath);
const checksum = validatePayload(zipPath); const checksum = validatePayload(zipPath);
@@ -341,20 +348,50 @@ async function build() {
const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8')); const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, 'package.json'), 'utf8'));
wrapperVersion = pkg.version || '2.0.0'; wrapperVersion = pkg.version || '2.0.0';
} catch (e) { } } catch (e) { }
const releaseVersion = (process.env.RELEASE_VERSION || wrapperVersion).replace(/^v/, '');
const assetsDir = path.join(__dirname, 'release-assets');
fs.rmSync(assetsDir, { recursive: true, force: true });
fs.mkdirSync(assetsDir, { recursive: true });
const components = {};
const addComponent = (name, fill, id) => {
const file = `${name}.zip`;
const target = path.join(assetsDir, file);
const componentZip = new AdmZip();
fill(componentZip);
componentZip.writeZip(target);
components[name] = { file, sha256: getFileChecksum(target), id, size: fs.statSync(target).size };
};
for (const repo of REPOS) {
const destRepo = path.join(BUILD_DIR, repo);
addComponent(repo, (z) => z.addLocalFolder(destRepo, repo), directoryId(destRepo));
}
addComponent('config', (z) => z.addLocalFolder(configDir, 'config'), directoryId(configDir));
const bundledCredentials = path.join(BUILD_DIR, 'encrypted-credentials.json');
if (fs.existsSync(bundledCredentials) && credentialsId) {
addComponent('secrets', (z) => z.addFile('encrypted-credentials.json', fs.readFileSync(bundledCredentials)), credentialsId);
}
const manifest = { const manifest = {
version: wrapperVersion, version: releaseVersion,
sha256: checksum, sha256: checksum,
timestamp: new Date().toISOString(), timestamp: new Date().toISOString(),
hasEncryptedCredentials: !!encryptedCredentialsPath hasEncryptedCredentials: !!encryptedCredentialsPath,
components
}; };
manifest.signature = signManifest(manifest);
fs.writeFileSync(path.join(__dirname, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf8'); fs.writeFileSync(path.join(__dirname, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf8');
for (const repo of REPOS) { for (const repo of REPOS) {
const repoPath = path.join(__dirname, repo); if (clonedRepos.has(repo)) {
if (fs.existsSync(repoPath)) { const repoPath = path.join(__dirname, repo);
fs.rmSync(repoPath, { recursive: true, force: true }); if (fs.existsSync(repoPath)) {
fs.rmSync(repoPath, { recursive: true, force: true });
}
} }
} }

46
codemagic.yaml Normal file
View File

@@ -0,0 +1,46 @@
workflows:
macos-release:
name: Build macOS Release
max_build_duration: 60
instance_type: mac_mini_m2
environment:
groups:
- gitlab_credentials
node: 22.14.0
cache:
cache_paths:
- $HOME/.cargo/registry
- $HOME/.cargo/git
- src-tauri/target
scripts:
- name: Setup Rust toolchain
script: |
if ! command -v cargo &> /dev/null; then
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
fi
- name: Install dependencies
script: |
export PATH="$HOME/.cargo/bin:$PATH"
npm ci
- name: Build & Publish macOS Release
script: |
export PATH="$HOME/.cargo/bin:$PATH"
PACKAGE_VERSION=$(node -p "require('./package.json').version")
node release.js --installer --tag="v$PACKAGE_VERSION"
- name: Verify bundled node permissions
script: |
if [ -f "bin/node" ]; then
chmod +x bin/node
xattr -cr bin/node || true
ls -la bin/node
file bin/node
fi
APP_NODE=$(find src-tauri/target/release/bundle -name "node" -path "*bin*" 2>/dev/null | head -1)
if [ -n "$APP_NODE" ]; then
chmod +x "$APP_NODE"
xattr -cr "$APP_NODE" || true
ls -la "$APP_NODE"
fi
artifacts:
- src-tauri/target/release/bundle/dmg/*.dmg
- src-tauri/target/release/bundle/macos/*.app

View File

@@ -1,16 +1,5 @@
{ {
"player": { "player": {
"TMDB_KEY": "YOUR_TMDB_KEY_HERE", "TMDB_KEY": "YOUR_TMDB_KEY_HERE"
"API_KEY": "YOUR_API_KEY_HERE"
},
"auth-proxy": {
"VITE_API_KEY": "YOUR_VITE_API_KEY_HERE",
"PROXY_VITE_API_KEY": "YOUR_PROXY_VITE_API_KEY_HERE"
},
"stream-api": {
"TMDB_API_KEY": "YOUR_TMDB_API_KEY_HERE",
"GA_MEASUREMENT_ID": "YOUR_GA_MEASUREMENT_ID_HERE",
"GA_API_SECRET": "YOUR_GA_API_SECRET_HERE",
"TOKEN_SECRET": "YOUR_TOKEN_SECRET_HERE"
} }
} }

View File

@@ -1,20 +1,11 @@
{ {
"player": { "player": {
"PORT": "3001", "PORT": "3000"
"BASE_URL": "http://localhost:7860",
"BYPASS_AUTH": "true"
}, },
"auth-proxy": { "discord": {
"PORT": "3000", "enabled": true,
"VITE_BASE_URL": "http://localhost:7860", "clientId": "1394887879154598038",
"DEV_BYPASS_AUTH": "true" "logoImage": "vyla_logo",
}, "tmdbApiKey": "3f6703f3e2a0b2b40fe4fbb3e1546244"
"stream-api": {
"PORT": "7860",
"PROXY_URL": "https://txt.primebox.workers.dev",
"PROXY_STREAMS": "true",
"ENABLE_DEBUG_ROUTE": "true",
"BYPASS_AUTH": "true",
"TOKEN_SECRET": "vyla_default_secure_token_secret_local_dev_32chars"
} }
} }

View File

@@ -2,40 +2,17 @@
"frontend": [ "frontend": [
{ {
"find": "https://player.vyla.cc", "find": "https://player.vyla.cc",
"replace": "http://localhost:3001" "replace": "http://localhost:3000"
}, },
{ {
"find": "http://player.vyla.cc", "find": "http://player.vyla.cc",
"replace": "http://localhost:3001"
},
{
"find": "https://api.vyla.cc",
"replace": "http://localhost:7860"
},
{
"find": "https://auth.vyla.cc",
"replace": "http://localhost:3000" "replace": "http://localhost:3000"
} }
], ],
"player": [ "player": [
{
"find": "https://api.vyla.cc",
"replace": "http://localhost:7860"
},
{
"find": "https://auth.vyla.cc",
"replace": "http://localhost:3000"
},
{ {
"find": "https://player.vyla.cc", "find": "https://player.vyla.cc",
"replace": "http://localhost:4890" "replace": "http://localhost:4890"
} }
], ]
"auth-proxy": [
{
"find": "https://player.vyla.cc",
"replace": "http://localhost:3001"
}
],
"stream-api": []
} }

View File

@@ -1,31 +1,30 @@
const crypto = require('crypto'); const crypto = require('crypto');
const os = require('os'); const os = require('os');
const { execSync } = require('child_process'); const fs = require('fs');
const path = require('path');
class CryptoUtils { class CryptoUtils {
static getMachineKey(cacheDir) { static getMachineKey(cacheDir) {
const path = require('path');
const fs = require('fs');
const cachePath = cacheDir ? path.join(cacheDir, '.machine-key-cache') : null; const cachePath = cacheDir ? path.join(cacheDir, '.machine-key-cache') : null;
if (cachePath && fs.existsSync(cachePath)) { if (cachePath && fs.existsSync(cachePath)) {
try { try {
const cached = fs.readFileSync(cachePath, 'utf8').trim(); const cached = fs.readFileSync(cachePath, 'utf8').trim();
if (cached) return cached; if (cached && cached.length === 64) return cached;
} catch (e) { } catch (e) {
} }
} }
let key; let key;
try { try {
const isMac = os.platform() === 'darwin';
const machineId = [ const machineId = [
os.hostname(), isMac ? '' : os.hostname(),
os.platform(), os.platform(),
os.arch(), os.arch(),
os.cpus()[0].model, os.cpus()[0] ? os.cpus()[0].model : '',
this.getMachineId(),
process.env.COMPUTERNAME || '', process.env.COMPUTERNAME || '',
process.env.USERNAME || '' process.env.USERNAME || (isMac ? os.userInfo().username : '')
].join('|'); ].join('|');
const hash = crypto.createHash('sha256'); const hash = crypto.createHash('sha256');
@@ -46,34 +45,6 @@ class CryptoUtils {
return key; return key;
} }
static getMachineId() {
if (os.platform() === 'win32') {
try {
return execSync('wmic csproduct get uuid').toString().split('\n')[1].trim();
} catch (e) {
}
try {
const out = execSync('reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid').toString();
const match = out.match(/MachineGuid\s+REG_SZ\s+([^\r\n]+)/);
if (match) return match[1].trim();
} catch (e) {
}
return 'unknown-machine';
} else if (os.platform() === 'darwin') {
try {
return execSync('ioreg -rd1 -c IOPlatformExpertDevice | awk -F\'"\' \'/IOPlatformUUID/{print $4}\'').toString().trim();
} catch (e) {
return 'unknown-machine';
}
} else {
try {
return execSync('cat /etc/machine-id 2>/dev/null || cat /var/lib/dbus/machine-id 2>/dev/null').toString().trim();
} catch (e) {
return 'unknown-machine';
}
}
}
static deriveKey(machineKey, salt = 'vyla-home-salt') { static deriveKey(machineKey, salt = 'vyla-home-salt') {
const hash = crypto.createHash('sha256'); const hash = crypto.createHash('sha256');
hash.update(machineKey + salt); hash.update(machineKey + salt);
@@ -96,11 +67,11 @@ class CryptoUtils {
} }
} }
static decrypt(encryptedData, key) { static decrypt(ciphertext, key) {
try { try {
const parts = encryptedData.split(':'); const parts = ciphertext.split(':');
if (parts.length !== 3) { if (parts.length !== 3) {
throw new Error('Invalid encrypted data format'); throw new Error('Invalid ciphertext format');
} }
const iv = Buffer.from(parts[0], 'hex'); const iv = Buffer.from(parts[0], 'hex');
@@ -120,25 +91,14 @@ class CryptoUtils {
} }
static encryptObject(obj, key) { static encryptObject(obj, key) {
const json = JSON.stringify(obj); const jsonString = JSON.stringify(obj);
return this.encrypt(json, key); return this.encrypt(jsonString, key);
} }
static decryptObject(encryptedData, key) { static decryptObject(ciphertext, key) {
const json = this.decrypt(encryptedData, key); const jsonString = this.decrypt(ciphertext, key);
return JSON.parse(json); return JSON.parse(jsonString);
}
static hashData(data) {
const hash = crypto.createHash('sha256');
hash.update(data);
return hash.digest('hex');
}
static verifyHash(data, expectedHash) {
const actualHash = this.hashData(data);
return actualHash === expectedHash;
} }
} }
module.exports = CryptoUtils; module.exports = CryptoUtils;

442
discord-rpc.js Normal file
View File

@@ -0,0 +1,442 @@
const net = require('net');
const path = require('path');
const https = require('https');
const crypto = require('crypto');
const DEFAULT_CLIENT_ID = '1394887879154598038';
const DEFAULT_LOGO = 'vyla_logo';
const TMDB_IMAGE_BASE = 'https://image.tmdb.org/t/p/w500';
const OP = { HANDSHAKE: 0, FRAME: 1, CLOSE: 2, PING: 3, PONG: 4 };
function ipcPaths() {
const out = [];
if (process.platform === 'win32') {
for (let i = 0; i < 10; i++) out.push(`\\\\?\\pipe\\discord-ipc-${i}`);
return out;
}
const bases = [...new Set([process.env.XDG_RUNTIME_DIR, process.env.TMPDIR, process.env.TMP, process.env.TEMP, '/tmp'].filter(Boolean))];
for (const base of bases) {
for (let i = 0; i < 10; i++) {
out.push(path.join(base, `discord-ipc-${i}`));
out.push(path.join(base, 'app', 'com.discordapp.Discord', `discord-ipc-${i}`));
out.push(path.join(base, 'snap.discord', `discord-ipc-${i}`));
}
}
return out;
}
class DiscordIpc {
constructor(clientId, log) {
this.clientId = clientId;
this.log = log || (() => { });
this.socket = null;
this.ready = false;
this.connecting = false;
this.stopped = true;
this.buffer = Buffer.alloc(0);
this.retryTimer = null;
this.desired = null;
}
start() {
this.stopped = false;
this.connect();
}
stop() {
this.stopped = true;
clearTimeout(this.retryTimer);
const s = this.socket;
this.socket = null;
this.ready = false;
if (s) {
try { s.destroy(); } catch (e) { }
}
}
scheduleRetry() {
if (this.stopped) return;
clearTimeout(this.retryTimer);
this.retryTimer = setTimeout(() => this.connect(), 15000);
}
connect() {
if (this.stopped || this.socket || this.connecting) return;
this.connecting = true;
const paths = ipcPaths();
const attempt = (i) => {
if (this.stopped) { this.connecting = false; return; }
if (i >= paths.length) {
this.connecting = false;
this.scheduleRetry();
return;
}
const sock = net.createConnection(paths[i]);
let opened = false;
sock.once('error', () => {
if (!opened) {
sock.destroy();
attempt(i + 1);
}
});
sock.once('connect', () => {
opened = true;
this.connecting = false;
this.attach(sock);
});
};
attempt(0);
}
attach(sock) {
this.socket = sock;
this.buffer = Buffer.alloc(0);
this.ready = false;
sock.on('data', (chunk) => this.onData(sock, chunk));
sock.on('error', () => { });
sock.on('close', () => {
if (this.socket === sock) {
this.socket = null;
this.ready = false;
this.log('Discord IPC closed');
this.scheduleRetry();
}
});
this.send(OP.HANDSHAKE, { v: 1, client_id: this.clientId });
}
send(op, payload) {
if (!this.socket) return;
const body = Buffer.from(JSON.stringify(payload), 'utf8');
const header = Buffer.alloc(8);
header.writeInt32LE(op, 0);
header.writeInt32LE(body.length, 4);
try {
this.socket.write(Buffer.concat([header, body]));
} catch (e) { }
}
onData(sock, chunk) {
if (this.socket !== sock) return;
this.buffer = Buffer.concat([this.buffer, chunk]);
while (this.buffer.length >= 8) {
const op = this.buffer.readInt32LE(0);
const len = this.buffer.readInt32LE(4);
if (len < 0 || len > 1024 * 1024) {
sock.destroy();
return;
}
if (this.buffer.length < 8 + len) return;
const raw = this.buffer.slice(8, 8 + len).toString('utf8');
this.buffer = this.buffer.slice(8 + len);
let payload = {};
try { payload = JSON.parse(raw); } catch (e) { }
this.handle(sock, op, payload);
}
}
handle(sock, op, payload) {
if (op === OP.PING) {
this.send(OP.PONG, payload);
} else if (op === OP.CLOSE) {
this.log(`Discord closed the connection: ${JSON.stringify(payload)}`);
sock.destroy();
} else if (op === OP.FRAME) {
if (payload.evt === 'READY') {
this.ready = true;
this.log('Discord RPC ready');
this.flush();
} else if (payload.evt === 'ERROR') {
this.log(`Discord RPC error: ${JSON.stringify(payload.data)}`);
}
}
}
flush() {
if (!this.ready) return;
const args = { pid: process.pid };
if (this.desired) args.activity = this.desired;
this.send(OP.FRAME, { cmd: 'SET_ACTIVITY', args, nonce: crypto.randomUUID() });
}
setActivity(activity) {
this.desired = activity || null;
this.flush();
}
}
function parseRoute(href) {
let u;
try { u = new URL(href); } catch (e) { return { kind: 'idle' }; }
if (u.pathname !== '/' && u.pathname !== '/index.html') return { kind: 'idle' };
const p = u.searchParams;
const id = (p.get('id') || '').trim();
if (!/^\d+$/.test(id)) return { kind: 'idle' };
const type = (p.get('type') || '').toLowerCase();
if (type === 'movie' || type === 'tv') {
return { kind: 'browse', type, id };
}
const season = parseInt(p.get('season'), 10);
const episode = parseInt(p.get('episode'), 10);
if (Number.isFinite(season) && Number.isFinite(episode)) {
return { kind: 'watch', type: 'tv', id, season, episode };
}
return { kind: 'watch', type: 'movie', id };
}
function getJson(url, headers) {
return new Promise((resolve, reject) => {
const req = https.get(url, { headers: { 'User-Agent': 'VylaHome-Client', 'Accept': 'application/json', ...(headers || {}) } }, (res) => {
let data = '';
res.on('data', (c) => { data += c; });
res.on('end', () => {
if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode}`));
return;
}
try { resolve(JSON.parse(data)); } catch (e) { reject(new Error('Invalid JSON')); }
});
});
req.on('error', reject);
req.setTimeout(8000, () => {
req.destroy();
reject(new Error('Request timeout'));
});
});
}
function clip(s, max = 128) {
const str = String(s || '').trim();
return str.length > max ? str.slice(0, max - 1) + '…' : str;
}
function cleanPageTitle(t) {
const s = String(t || '').replace(/\s*[-|–—•]\s*Vyla.*$/i, '').trim();
if (!s || /^vyla/i.test(s)) return null;
return s;
}
class VylaPresence {
constructor({ getConfig, log }) {
this.getConfig = getConfig || (() => ({}));
this.log = log || (() => { });
this.windows = new Map();
this.ipc = null;
this.started = false;
this.metaCache = new Map();
this.pageMemory = new Map();
this.lastStart = 0;
this.watchKey = null;
this.watchStart = 0;
this.lastActivityKey = null;
this.timer = null;
this.token = 0;
}
settings() {
const cfg = (this.getConfig() || {}).discord || {};
const clientId = [process.env.VYLA_DISCORD_CLIENT_ID, cfg.clientId, DEFAULT_CLIENT_ID]
.map((v) => String(v || '').trim())
.find((v) => /^\d{17,20}$/.test(v)) || '';
const tmdbKey = String(process.env.VYLA_TMDB_API_KEY || cfg.tmdbApiKey || '').trim();
return {
enabled: cfg.enabled !== false,
clientId: /^\d{17,20}$/.test(clientId) ? clientId : '',
logo: cfg.logoImage || DEFAULT_LOGO,
tmdbKey: /^YOUR_/i.test(tmdbKey) ? '' : tmdbKey
};
}
start() {
if (this.started) return;
const s = this.settings();
if (!s.enabled) {
this.log('Discord presence disabled in config.');
return;
}
if (!s.clientId) {
this.log('Discord presence not started: no clientId configured.');
return;
}
this.started = true;
this.ipc = new DiscordIpc(s.clientId, (m) => this.log(m));
this.ipc.start();
this.refresh();
}
stop() {
clearTimeout(this.timer);
this.started = false;
if (this.ipc) {
this.ipc.stop();
this.ipc = null;
}
}
report(payload) {
if (!payload || !payload.label) return;
this.log(`report ${payload.label}: ${payload.closed ? 'closed' : payload.url}`);
if (payload.closed) {
this.windows.delete(payload.label);
} else {
this.windows.set(payload.label, {
url: String(payload.url || ''),
title: String(payload.title || ''),
image: String(payload.image || ''),
position: Number(payload.position),
duration: Number(payload.duration),
paused: payload.paused === true,
at: Date.now()
});
}
this.refresh();
}
current() {
let best = null;
for (const w of this.windows.values()) {
if (!best || w.at >= best.at) best = w;
}
return best;
}
refresh() {
if (!this.started) return;
clearTimeout(this.timer);
this.timer = setTimeout(() => this.apply().catch((e) => this.log(`Presence update failed: ${e.message}`)), 400);
}
async fetchMeta(route) {
const s = this.settings();
if (!s.tmdbKey) return null;
const key = `${route.type}:${route.id}`;
if (this.metaCache.has(key)) return this.metaCache.get(key);
try {
const bearer = s.tmdbKey.length > 40;
const url = `https://api.themoviedb.org/3/${route.type}/${route.id}` + (bearer ? '' : `?api_key=${encodeURIComponent(s.tmdbKey)}`);
const d = await getJson(url, bearer ? { Authorization: `Bearer ${s.tmdbKey}` } : null);
const meta = {
title: d.title || d.name || null,
poster: d.poster_path ? `${TMDB_IMAGE_BASE}${d.poster_path}` : null,
runtime: d.runtime || (Array.isArray(d.episode_run_time) && d.episode_run_time[0]) || 0
};
this.metaCache.set(key, meta);
return meta;
} catch (e) {
this.log(`TMDB lookup failed for ${key}: ${e.message}`);
return null;
}
}
async fetchEpisodeName(route) {
const s = this.settings();
if (!s.tmdbKey) return null;
const key = `ep:${route.id}:${route.season}:${route.episode}`;
if (this.metaCache.has(key)) return this.metaCache.get(key);
try {
const bearer = s.tmdbKey.length > 40;
const url = `https://api.themoviedb.org/3/tv/${route.id}/season/${route.season}/episode/${route.episode}` + (bearer ? '' : `?api_key=${encodeURIComponent(s.tmdbKey)}`);
const d = await getJson(url, bearer ? { Authorization: `Bearer ${s.tmdbKey}` } : null);
const info = { name: d.name || null, runtime: d.runtime || 0 };
this.metaCache.set(key, info);
return info;
} catch (e) {
return null;
}
}
async apply() {
const token = ++this.token;
const s = this.settings();
const win = this.current();
const route = win ? parseRoute(win.url) : { kind: 'idle' };
let activity;
if (route.kind === 'idle') {
this.watchKey = null;
activity = {
type: 0,
details: 'On Vyla Home',
assets: { large_image: s.logo, large_text: 'Vyla Home' }
};
} else {
const meta = await this.fetchMeta(route);
const episode = (route.kind === 'watch' && route.type === 'tv' ? await this.fetchEpisodeName(route) : null) || {};
if (token !== this.token) return;
const pageTitle = win ? cleanPageTitle(win.title) : null;
const pageImage = win && /^https:\/\//i.test(win.image) ? win.image : null;
const memKey = `${route.type}:${route.id}`;
const mem = this.pageMemory.get(memKey) || {};
if (pageTitle) mem.title = pageTitle;
if (pageImage) mem.poster = pageImage;
this.pageMemory.set(memKey, mem);
const title = (meta && meta.title) || pageTitle || mem.title || (route.type === 'tv' ? 'a TV show' : 'a movie');
const poster = (meta && meta.poster) || pageImage || mem.poster;
const assets = {
large_image: poster || s.logo,
large_text: clip(title)
};
if (poster) {
assets.small_image = s.logo;
assets.small_text = 'Vyla Home';
}
if (route.kind === 'browse') {
this.watchKey = null;
activity = {
type: 0,
details: 'Browsing Vyla',
state: clip(`Browsing ${title}`),
assets
};
} else {
const key = route.type === 'tv' ? `tv:${route.id}:${route.season}:${route.episode}` : `movie:${route.id}`;
if (this.watchKey !== key) {
this.watchKey = key;
this.watchStart = Date.now();
this.lastStart = 0;
}
const runtimeMin = episode.runtime || (meta && meta.runtime) || 0;
let timestamps;
if (win && Number.isFinite(win.duration) && win.duration > 0) {
if (win.paused) {
this.lastStart = 0;
} else {
let start = Date.now() - Math.round(win.position * 1000);
if (this.lastStart && Math.abs(start - this.lastStart) < 4000) start = this.lastStart;
this.lastStart = start;
timestamps = { start, end: start + Math.round(win.duration * 1000) };
}
} else if (runtimeMin) {
timestamps = { start: this.watchStart, end: this.watchStart + runtimeMin * 60000 };
} else {
timestamps = { start: this.watchStart };
}
activity = {
type: 3,
details: clip(`Watching ${title}`),
assets
};
if (timestamps) activity.timestamps = timestamps;
if (route.type === 'tv') {
activity.state = clip(`Season ${route.season}, Episode ${route.episode}` + (episode.name ? ` · ${episode.name}` : ''));
}
}
}
const sig = JSON.stringify(activity);
if (sig === this.lastActivityKey) return;
this.lastActivityKey = sig;
this.log(`activity: ${sig}`);
if (this.ipc) this.ipc.setActivity(activity);
}
}
VylaPresence.parseRoute = parseRoute;
module.exports = VylaPresence;

612
file-updater.js Normal file
View File

@@ -0,0 +1,612 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const zlib = require('zlib');
const https = require('https');
const AdmZip = require('adm-zip');
const SDK_NAME = '@vyla-entertainment/sdk';
const SDK_LATEST_URL = 'https://registry.npmjs.org/@vyla-entertainment%2Fsdk/latest';
const ALLOWED_ROOTS = ['frontend', 'player'];
const MAX_TARBALL = 100 * 1024 * 1024;
const MAX_FILE = 50 * 1024 * 1024;
const LIVE_HOSTS = ['gitlab.com'];
const REPO_API = 'https://gitlab.com/api/v4/projects/vyla-entertainment%2F';
const verParts = (v) => String(v || '').replace(/^v/, '').split(/[.\-+]/).map((n) => parseInt(n, 10) || 0);
const cmpVer = (a, b) => {
const x = verParts(a);
const y = verParts(b);
for (let i = 0; i < Math.max(x.length, y.length); i++) {
if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) - (y[i] || 0);
}
return 0;
};
const sha256Buf = (buf) => crypto.createHash('sha256').update(buf).digest('hex');
const sha256File = (p) => sha256Buf(fs.readFileSync(p));
const gitBlobSha = (buf) => crypto.createHash('sha1').update(Buffer.concat([Buffer.from(`blob ${buf.length}\0`), buf])).digest('hex');
const hooks = { notice: null };
function fetchBuffer(url, { headers = {}, maxBytes, hosts, redirects = 0, retries = 0 }) {
return new Promise((resolve, reject) => {
if (redirects > 5) return reject(new Error('Too many redirects'));
let u;
try { u = new URL(url); } catch (e) { return reject(new Error('Invalid URL')); }
if (u.protocol !== 'https:' || !hosts.includes(u.hostname)) {
return reject(new Error(`Host not allowed: ${u.hostname}`));
}
const req = https.get({
hostname: u.hostname,
port: 443,
path: u.pathname + u.search,
headers: { 'User-Agent': 'VylaHome-Client', ...headers }
}, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume();
const next = new URL(res.headers.location, url).toString();
const keep = new URL(next).hostname === u.hostname ? headers : {};
fetchBuffer(next, { headers: keep, maxBytes, hosts, redirects: redirects + 1 }).then(resolve, reject);
return;
}
if (res.statusCode === 429 && retries < 4) {
res.resume();
const wait = Math.min(parseInt(res.headers['retry-after'], 10) || 5, 30) * 1000;
if (hooks.notice) hooks.notice(`GitLab rate limit (HTTP 429). Retrying in ${Math.round(wait / 1000)}s (${retries + 1}/4)...`);
setTimeout(() => {
fetchBuffer(url, { headers, maxBytes, hosts, redirects, retries: retries + 1 }).then(resolve, reject);
}, wait);
return;
}
if (res.statusCode !== 200) {
res.resume();
reject(new Error(`HTTP ${res.statusCode}`));
return;
}
const chunks = [];
let size = 0;
res.on('data', (c) => {
size += c.length;
if (size > maxBytes) {
req.destroy();
reject(new Error('Response too large'));
return;
}
chunks.push(c);
});
res.on('end', () => resolve(Buffer.concat(chunks)));
res.on('error', reject);
});
req.on('error', reject);
req.setTimeout(30000, () => {
req.destroy();
reject(new Error('Request timeout'));
});
});
}
function safeRel(rel) {
if (typeof rel !== 'string' || !rel || rel.includes('\0') || rel.includes('\\')) return null;
const norm = path.posix.normalize(rel);
if (norm !== rel || norm.startsWith('/') || norm.endsWith('/')) return null;
const parts = norm.split('/');
if (parts.length < 2 || !ALLOWED_ROOTS.includes(parts[0])) return null;
if (parts.some((p) => p === '..' || p === '.' || p === 'node_modules' || p === '.git')) return null;
return norm;
}
function extractTar(tar, destDir) {
const root = path.resolve(destDir);
let offset = 0;
while (offset + 512 <= tar.length) {
const header = tar.subarray(offset, offset + 512);
if (header.every((b) => b === 0)) break;
let name = header.toString('utf8', 0, 100).replace(/\0.*$/, '');
const prefix = header.toString('utf8', 345, 500).replace(/\0.*$/, '');
if (prefix) name = `${prefix}/${name}`;
const size = parseInt(header.toString('utf8', 124, 136).replace(/\0.*$/, '').trim(), 8) || 0;
const type = String.fromCharCode(header[156]);
offset += 512;
const data = tar.subarray(offset, offset + size);
offset += Math.ceil(size / 512) * 512;
if ((type !== '0' && type !== '\0') || !name.startsWith('package/')) continue;
const rel = path.posix.normalize(name.slice('package/'.length));
if (!rel || rel.startsWith('..') || rel.startsWith('/') || rel.endsWith('/')) {
throw new Error(`Unsafe path in tarball: ${name}`);
}
const full = path.resolve(root, rel);
if (!full.startsWith(root + path.sep)) {
throw new Error(`Unsafe path in tarball: ${name}`);
}
fs.mkdirSync(path.dirname(full), { recursive: true });
fs.writeFileSync(full, data);
}
}
class FileUpdater {
constructor(appDataPath, updateClient) {
this.appDataPath = appDataPath;
this.updateClient = updateClient;
this.onProgress = null;
this.statePath = path.join(appDataPath, 'file-state.json');
}
set onNotice(fn) {
hooks.notice = fn;
}
sdkHeaders() {
const h = { Accept: 'application/json' };
if (process.env.NPM_TOKEN) h.Authorization = `Bearer ${process.env.NPM_TOKEN}`;
return h;
}
liveHeaders(extra = {}) {
const t = this.updateClient && this.updateClient.token;
return t ? { ...extra, 'PRIVATE-TOKEN': t } : extra;
}
target(rel) {
const root = path.resolve(this.appDataPath);
const full = path.resolve(root, ...rel.split('/'));
if (!full.startsWith(root + path.sep)) throw new Error(`Path escape: ${rel}`);
return full;
}
readState() {
try {
const s = JSON.parse(fs.readFileSync(this.statePath, 'utf8'));
return {
seq: typeof s.seq === 'number' ? s.seq : null,
base: s.base && typeof s.base === 'object' ? s.base : {},
remote: s.remote && typeof s.remote === 'object' ? s.remote : {},
local: s.local && typeof s.local === 'object' ? s.local : {},
commits: s.commits && typeof s.commits === 'object' ? s.commits : {}
};
} catch (e) {
return { seq: null, base: {}, remote: {}, local: {}, commits: {} };
}
}
writeState(state) {
const cur = this.readState();
const next = {
seq: state.seq !== undefined ? state.seq : cur.seq,
base: state.base || cur.base,
remote: state.remote || cur.remote,
local: state.local || cur.local,
commits: state.commits || cur.commits
};
fs.mkdirSync(this.appDataPath, { recursive: true });
const tmp = `${this.statePath}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next), 'utf8');
fs.renameSync(tmp, this.statePath);
}
snapshotBase() {
const base = {};
const walk = (dir, rel) => {
for (const name of fs.readdirSync(dir)) {
if (name === 'node_modules' || name === '.git') continue;
const full = path.join(dir, name);
const r = `${rel}/${name}`;
const st = fs.lstatSync(full);
if (st.isDirectory()) walk(full, r);
else if (st.isFile()) base[r] = sha256File(full);
}
};
for (const root of ALLOWED_ROOTS) {
const dir = path.join(this.appDataPath, root);
if (fs.existsSync(dir)) walk(dir, root);
}
this.writeState({ seq: this.readState().seq, base, remote: {}, local: {}, commits: {} });
}
zipMatches(zipPath, sha256) {
try {
return sha256File(zipPath) === String(sha256).trim().toLowerCase();
} catch (e) {
return false;
}
}
async checkFiles() {
const versionFile = path.join(this.appDataPath, 'version.json');
let local;
try {
local = JSON.parse(fs.readFileSync(versionFile, 'utf8'));
} catch (e) {
return { seq: 0, changes: [] };
}
const release = await this.updateClient.checkForUpdates();
const norm = (v) => String(v || '').replace(/^v/, '').trim();
if (!release || !release.sha256 || !local.sha256) return { seq: 0, changes: [] };
if (norm(release.version) !== norm(local.version) || release.sha256 === local.sha256) {
return { seq: 0, changes: [] };
}
const zipPath = path.join(this.appDataPath, 'pending-ui.zip');
if (!this.zipMatches(zipPath, release.sha256)) {
fs.rmSync(zipPath, { force: true });
await this.updateClient.downloadUpdate(release, zipPath, this.onProgress);
if (!this.zipMatches(zipPath, release.sha256)) {
fs.rmSync(zipPath, { force: true });
throw new Error('Update archive checksum mismatch');
}
}
const state = this.readState();
const zip = new AdmZip(zipPath);
const changes = [];
for (const entry of zip.getEntries()) {
if (entry.isDirectory) continue;
const rel = safeRel(entry.entryName);
if (!rel) continue;
const data = entry.getData();
const hash = sha256Buf(data);
const full = this.target(rel);
if (!fs.existsSync(full)) {
changes.push({ path: rel, sha256: hash, size: data.length, status: 'added' });
continue;
}
const baseline = state.base[rel] || sha256File(full);
if (baseline !== hash) {
changes.push({ path: rel, sha256: hash, size: data.length, status: 'modified' });
}
}
if (changes.length === 0) {
fs.writeFileSync(versionFile, JSON.stringify({ version: release.version, sha256: release.sha256 }, null, 2), 'utf8');
fs.rmSync(zipPath, { force: true });
return { seq: 0, changes: [] };
}
this.pending = { release, zipPath, total: changes.length };
return { seq: 0, changes };
}
async applyFiles(changes, seq, replacements, onFile) {
if (!this.pending) throw new Error('No pending update');
const { release, zipPath, total } = this.pending;
const zip = new AdmZip(zipPath);
const staged = [];
for (let i = 0; i < changes.length; i++) {
const c = changes[i];
const entry = zip.getEntry(c.path);
if (!entry) throw new Error(`Missing in archive: ${c.path}`);
const data = entry.getData();
if (sha256Buf(data) !== c.sha256) throw new Error(`Checksum mismatch: ${c.path}`);
staged.push({ c, data: this.applyReplacements(c.path, data, replacements) });
if (onFile) onFile(c.path, i + 1, changes.length);
}
const done = [];
try {
for (const s of staged) {
const full = this.target(s.c.path);
const prev = fs.existsSync(full) ? fs.readFileSync(full) : null;
fs.mkdirSync(path.dirname(full), { recursive: true });
fs.writeFileSync(`${full}.vyla-tmp`, s.data);
fs.renameSync(`${full}.vyla-tmp`, full);
done.push({ full, prev });
}
} catch (e) {
for (const d of done.reverse()) {
try {
if (d.prev === null) fs.rmSync(d.full, { force: true });
else fs.writeFileSync(d.full, d.prev);
} catch (x) { }
}
throw e;
}
const state = this.readState();
for (const s of staged) state.base[s.c.path] = s.c.sha256;
this.writeState({ seq: state.seq, base: state.base });
if (changes.length === total) {
fs.writeFileSync(
path.join(this.appDataPath, 'version.json'),
JSON.stringify({ version: release.version, sha256: release.sha256 }, null, 2),
'utf8'
);
fs.rmSync(zipPath, { force: true });
this.pending = null;
}
}
applyReplacements(rel, buf, replacements) {
const list = (replacements && replacements[rel.split('/')[0]]) || [];
if (!list.length) return buf;
let text = buf.toString('utf8');
let changed = false;
for (const rep of list) {
if (rep && rep.find && text.includes(rep.find)) {
text = text.split(rep.find).join(rep.replace);
changed = true;
}
}
return changed ? Buffer.from(text, 'utf8') : buf;
}
async loadArchive(root) {
const buf = await fetchBuffer(`${REPO_API}${root}/repository/archive.zip?sha=main`, { headers: this.liveHeaders(), maxBytes: 600 * 1024 * 1024, hosts: LIVE_HOSTS });
const zip = new AdmZip(buf);
const map = new Map();
for (const entry of zip.getEntries()) {
if (entry.isDirectory) continue;
const name = entry.entryName;
const i = name.indexOf('/');
if (i < 0) continue;
map.set(`${root}/${name.slice(i + 1)}`, entry);
}
return map;
}
fetchRepoFile(rel) {
const hit = this.archive && this.archive.get(rel);
if (hit) return Promise.resolve(hit.getData());
const parts = rel.split('/');
const root = parts.shift();
const file = encodeURIComponent(parts.join('/'));
return fetchBuffer(`${REPO_API}${root}/repository/files/${file}/raw?ref=main`, { headers: this.liveHeaders(), maxBytes: MAX_FILE, hosts: LIVE_HOSTS });
}
async headCommit(root) {
try {
const raw = await fetchBuffer(`${REPO_API}${root}/repository/commits/main`, {
headers: this.liveHeaders({ Accept: 'application/json' }),
maxBytes: 1024 * 1024,
hosts: LIVE_HOSTS,
retries: 3
});
const id = JSON.parse(raw.toString('utf8')).id;
return /^[0-9a-f]{40}$/.test(id) ? id : null;
} catch (e) {
return null;
}
}
localIntact(root, state) {
const prefix = `${root}/`;
const keys = Object.keys(state.remote).filter((k) => k.startsWith(prefix));
if (keys.length === 0) return false;
for (const rel of keys) {
try {
if (sha256File(this.target(rel)) !== state.local[rel]) return false;
} catch (e) {
return false;
}
}
return true;
}
async checkRepos() {
const state = this.readState();
const changes = [];
const remoteIds = {};
const checkedRoots = [];
const errors = [];
const verified = { remote: {}, local: {} };
const commits = {};
this.archive = new Map();
for (const root of ALLOWED_ROOTS) {
const head = await this.headCommit(root);
if (this.localIntact(root, state) && (!head || head === state.commits[root])) continue;
let map;
try {
map = await this.loadArchive(root);
} catch (e) {
errors.push(`${root}: ${e.message}`);
continue;
}
if (map.size === 0) {
errors.push(`${root}: empty archive`);
continue;
}
checkedRoots.push(root);
if (head) commits[root] = head;
for (const [key, entry] of map) {
const rel = safeRel(key);
if (!rel) continue;
const data = entry.getData();
const id = gitBlobSha(data);
remoteIds[rel] = id;
const full = this.target(rel);
let ok = false;
let localHash = null;
if (fs.existsSync(full)) {
const buf = fs.readFileSync(full);
localHash = sha256Buf(buf);
ok = gitBlobSha(buf) === id || (state.remote[rel] === id && state.local[rel] === localHash);
}
if (ok) {
verified.remote[rel] = id;
verified.local[rel] = localHash;
} else {
changes.push({ path: rel, sha256: id, size: data.length });
this.archive.set(rel, entry);
}
}
}
if (checkedRoots.length === 0) {
if (errors.length) throw new Error(errors.join(' | '));
return { seq: state.seq === null ? 0 : state.seq, changes: [], removed: [], verified, commits };
}
const tracked = new Set([...Object.keys(state.base), ...Object.keys(state.remote)]);
const removed = [...tracked].filter((rel) =>
checkedRoots.includes(rel.split('/')[0]) &&
!remoteIds[rel] &&
safeRel(rel) &&
fs.existsSync(this.target(rel))
);
if (changes.length === 0 && removed.length === 0) {
for (const k of Object.keys(verified.remote)) {
state.remote[k] = verified.remote[k];
state.local[k] = verified.local[k];
}
this.writeState({ remote: state.remote, local: state.local, commits: { ...state.commits, ...commits } });
this.archive = null;
}
return { seq: state.seq === null ? 0 : state.seq, changes, removed, verified, commits };
}
async applyLive(info, replacements, onFile) {
const staged = [];
const total = info.changes.length;
let next = 0;
if (!this.archive) this.archive = new Map();
let finished = 0;
let failure = null;
const worker = async () => {
while (next < total && !failure) {
const c = info.changes[next++];
try {
const data = await this.fetchRepoFile(c.path);
if (gitBlobSha(data) !== c.sha256) throw new Error(`Checksum mismatch: ${c.path}`);
staged.push({ c, data: this.applyReplacements(c.path, data, replacements) });
finished++;
if (onFile) onFile(c.path, finished, total);
} catch (e) {
failure = e;
}
}
};
await Promise.all(Array.from({ length: Math.min(4, total) }, worker));
this.archive = null;
if (failure) throw failure;
const done = [];
try {
for (const s of staged) {
const full = this.target(s.c.path);
const prev = fs.existsSync(full) ? fs.readFileSync(full) : null;
fs.mkdirSync(path.dirname(full), { recursive: true });
fs.writeFileSync(`${full}.vyla-tmp`, s.data);
fs.renameSync(`${full}.vyla-tmp`, full);
done.push({ full, prev });
}
for (const rel of info.removed) {
const full = this.target(rel);
if (!fs.existsSync(full)) continue;
const prev = fs.readFileSync(full);
fs.rmSync(full, { force: true });
done.push({ full, prev });
}
} catch (e) {
for (const d of done.reverse()) {
try {
if (d.prev === null) fs.rmSync(d.full, { force: true });
else fs.writeFileSync(d.full, d.prev);
} catch (x) { }
}
throw e;
}
const state = this.readState();
for (const s of staged) {
state.base[s.c.path] = s.c.sha256;
state.remote[s.c.path] = s.c.sha256;
state.local[s.c.path] = sha256Buf(s.data);
}
for (const rel of info.removed) {
delete state.base[rel];
delete state.remote[rel];
delete state.local[rel];
}
const v = info.verified || { remote: {}, local: {} };
for (const k of Object.keys(v.remote)) {
state.remote[k] = v.remote[k];
state.local[k] = v.local[k];
}
state.commits = { ...state.commits, ...(info.commits || {}) };
this.writeState({ seq: info.seq, base: state.base, remote: state.remote, local: state.local, commits: state.commits });
}
installedSdk() {
const roots = [this.appDataPath, path.join(this.appDataPath, 'frontend'), path.join(this.appDataPath, 'player')];
const found = [];
for (const root of roots) {
const dir = path.join(root, 'node_modules', ...SDK_NAME.split('/'));
try {
const version = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version;
if (version) found.push({ dir, version });
} catch (e) { }
}
return found;
}
recoverSdk() {
for (const root of [this.appDataPath, path.join(this.appDataPath, 'frontend'), path.join(this.appDataPath, 'player')]) {
const dir = path.join(root, 'node_modules', ...SDK_NAME.split('/'));
const old = `${dir}.vyla-old`;
const stage = `${dir}.vyla-new`;
try {
if (!fs.existsSync(dir) && fs.existsSync(old)) fs.renameSync(old, dir);
fs.rmSync(stage, { recursive: true, force: true });
if (fs.existsSync(dir)) fs.rmSync(old, { recursive: true, force: true });
} catch (e) { }
}
}
async checkSdk() {
const raw = await fetchBuffer(SDK_LATEST_URL, {
headers: this.sdkHeaders(),
maxBytes: 5 * 1024 * 1024,
hosts: ['registry.npmjs.org']
});
const meta = JSON.parse(raw.toString('utf8'));
const integrity = String((meta.dist && meta.dist.integrity) || '').split(' ').find((s) => s.startsWith('sha512-'));
if (!meta.version || !meta.dist || !meta.dist.tarball || !integrity) {
throw new Error('Registry response missing version or integrity');
}
const installed = this.installedSdk();
const targets = installed.filter((i) => cmpVer(i.version, meta.version) < 0);
const current = targets.length ? targets.map((t) => t.version).sort(cmpVer)[0] : meta.version;
return {
outdated: targets.length > 0,
current,
latest: meta.version,
tarball: meta.dist.tarball,
integrity,
dirs: targets.map((t) => t.dir)
};
}
async installSdk(info) {
const tgz = await fetchBuffer(info.tarball, {
headers: this.sdkHeaders(),
maxBytes: MAX_TARBALL,
hosts: ['registry.npmjs.org']
});
const digest = `sha512-${crypto.createHash('sha512').update(tgz).digest('base64')}`;
if (digest !== info.integrity) throw new Error('SDK integrity check failed');
const tar = zlib.gunzipSync(tgz, { maxOutputLength: 300 * 1024 * 1024 });
for (const dir of info.dirs) {
const stage = `${dir}.vyla-new`;
const old = `${dir}.vyla-old`;
fs.rmSync(stage, { recursive: true, force: true });
fs.rmSync(old, { recursive: true, force: true });
fs.mkdirSync(stage, { recursive: true });
extractTar(tar, stage);
const version = JSON.parse(fs.readFileSync(path.join(stage, 'package.json'), 'utf8')).version;
if (version !== info.latest) {
fs.rmSync(stage, { recursive: true, force: true });
throw new Error('SDK version mismatch in tarball');
}
const had = fs.existsSync(dir);
if (had) fs.renameSync(dir, old);
try {
fs.renameSync(stage, dir);
} catch (e) {
if (had) fs.renameSync(old, dir);
throw e;
}
fs.rmSync(old, { recursive: true, force: true });
}
}
}
module.exports = FileUpdater;

View File

@@ -1,178 +0,0 @@
const { execSync, spawnSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const REPOS = {
frontend: { branch: 'main' },
player: { branch: 'main' },
'stream-api': { branch: 'main' },
'auth-proxy': { branch: 'main' }
};
const GITLAB_GROUP = 'vyla-entertainment';
class GitlabClient {
constructor(appDataPath, credentialManager) {
this.appDataPath = appDataPath;
this.credentialManager = credentialManager;
}
getToken() {
return this.credentialManager.getCredential('gitlab', 'TOKEN') || null;
}
setToken(token) {
this.credentialManager.setCredential('gitlab', 'TOKEN', token);
}
hasToken() {
return !!this.getToken();
}
buildRepoUrl(repoName) {
const token = this.getToken();
if (token) {
return `https://oauth2:${token}@gitlab.com/${GITLAB_GROUP}/${repoName}.git`;
}
return `https://gitlab.com/${GITLAB_GROUP}/${repoName}.git`;
}
repoDir(repoName) {
return path.join(this.appDataPath, repoName);
}
isRepoCloned(repoName) {
const gitDir = path.join(this.repoDir(repoName), '.git');
return fs.existsSync(gitDir);
}
allReposCloned() {
return Object.keys(REPOS).every((name) => this.isRepoCloned(name));
}
cloneRepo(repoName, onLog) {
const { branch } = REPOS[repoName];
const targetDir = this.repoDir(repoName);
const url = this.buildRepoUrl(repoName);
if (fs.existsSync(targetDir)) {
fs.rmSync(targetDir, { recursive: true, force: true });
}
if (onLog) onLog(`Cloning ${repoName}...`);
const result = spawnSync('git', ['clone', '--depth', '1', '--branch', branch, url, targetDir], {
stdio: 'pipe',
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }
});
if (result.status !== 0) {
const stderr = result.stderr ? result.stderr.toString() : 'unknown error';
throw new Error(`Failed to clone ${repoName}: ${stderr}`);
}
}
cloneAll(onLog) {
for (const repoName of Object.keys(REPOS)) {
this.cloneRepo(repoName, onLog);
}
}
installDependencies(repoName, onLog) {
const repoDir = this.repoDir(repoName);
const pkgJsonPath = path.join(repoDir, 'package.json');
if (!fs.existsSync(pkgJsonPath)) {
return;
}
if (onLog) onLog(`Installing dependencies for ${repoName}...`);
const result = spawnSync('npm', ['install', '--omit=dev'], {
cwd: repoDir,
stdio: 'pipe',
shell: process.platform === 'win32'
});
if (result.status !== 0) {
const stderr = result.stderr ? result.stderr.toString() : 'unknown error';
throw new Error(`npm install failed for ${repoName}: ${stderr}`);
}
}
installAllDependencies(onLog) {
for (const repoName of Object.keys(REPOS)) {
this.installDependencies(repoName, onLog);
}
}
getLocalHead(repoName) {
const repoDir = this.repoDir(repoName);
try {
return execSync('git rev-parse HEAD', { cwd: repoDir }).toString().trim();
} catch (e) {
return null;
}
}
getRemoteHead(repoName) {
const { branch } = REPOS[repoName];
const repoDir = this.repoDir(repoName);
const url = this.buildRepoUrl(repoName);
try {
const output = execSync(`git ls-remote "${url}" refs/heads/${branch}`, { cwd: repoDir }).toString().trim();
return output.split('\t')[0] || null;
} catch (e) {
return null;
}
}
checkForUpdates() {
const outdated = [];
for (const repoName of Object.keys(REPOS)) {
const local = this.getLocalHead(repoName);
const remote = this.getRemoteHead(repoName);
if (local && remote && local !== remote) {
outdated.push(repoName);
}
}
return outdated;
}
updateRepo(repoName, onLog) {
const { branch } = REPOS[repoName];
const repoDir = this.repoDir(repoName);
if (onLog) onLog(`Updating ${repoName}...`);
const fetchResult = spawnSync('git', ['fetch', 'origin', branch], {
cwd: repoDir,
stdio: 'pipe',
env: { ...process.env, GIT_TERMINAL_PROMPT: '0' }
});
if (fetchResult.status !== 0) {
const stderr = fetchResult.stderr ? fetchResult.stderr.toString() : 'unknown error';
throw new Error(`Failed to fetch ${repoName}: ${stderr}`);
}
const resetResult = spawnSync('git', ['reset', '--hard', `origin/${branch}`], {
cwd: repoDir,
stdio: 'pipe'
});
if (resetResult.status !== 0) {
const stderr = resetResult.stderr ? resetResult.stderr.toString() : 'unknown error';
throw new Error(`Failed to reset ${repoName}: ${stderr}`);
}
}
updateAll(repoNames, onLog) {
for (const repoName of repoNames) {
this.updateRepo(repoName, onLog);
this.installDependencies(repoName, onLog);
}
}
}
module.exports = GitlabClient

573
main.js
View File

@@ -5,27 +5,36 @@ const express = require('express');
const ServiceManager = require('./service-manager'); const ServiceManager = require('./service-manager');
const Patcher = require('./patcher'); const Patcher = require('./patcher');
const UpdateClient = require('./update-client'); const UpdateClient = require('./update-client');
const FileUpdater = require('./file-updater');
const VylaPresence = require('./discord-rpc');
function getDefaultAppData() {
if (process.platform === 'darwin') {
return path.join(os.homedir(), 'Library', 'Application Support', 'vyla-home', 'vyla-home-files');
}
if (process.platform === 'linux') {
return path.join(os.homedir(), '.local', 'share', 'vyla-home', 'vyla-home-files');
}
return path.join(os.homedir(), 'AppData', 'Roaming', 'vyla-home', 'vyla-home-files');
}
const defaultAppData = path.join(os.homedir(), 'AppData', 'Roaming', 'vyla-home', 'vyla-home-files');
const APPDATA_DIR = (process.env.APPDATA_PATH && !process.env.APPDATA_PATH.includes('com.vyla.home')) const APPDATA_DIR = (process.env.APPDATA_PATH && !process.env.APPDATA_PATH.includes('com.vyla.home'))
? process.env.APPDATA_PATH ? process.env.APPDATA_PATH
: defaultAppData; : getDefaultAppData();
const LOGS_DIR = path.join(APPDATA_DIR, 'logs'); const LOGS_DIR = path.join(APPDATA_DIR, 'logs');
try { fs.mkdirSync(LOGS_DIR, { recursive: true }); } catch (e) { } try { fs.mkdirSync(LOGS_DIR, { recursive: true }); } catch (e) { }
const debugLogPath = path.join(LOGS_DIR, 'node-debug.log'); const debugLogPath = path.join(LOGS_DIR, 'node-debug.log');
function debugLog(msg) { function debugLog(msg) {
try { fs.appendFileSync(debugLogPath, `[NODE] ${msg}\n`, 'utf8'); } catch (e) { } try { fs.appendFile(debugLogPath, `[NODE] ${msg}\n`, 'utf8', () => { }); } catch (e) { }
} }
debugLog("--- Node.js Process Started ---"); debugLog("--- Node.js Process Started ---");
let serviceManager; let serviceManager;
let expressApp; let updateDecisionHandler = null;
let expressServer;
let playerExpressApp;
let playerExpressServer;
debugLog(`AppData Dir: ${APPDATA_DIR}`); debugLog(`AppData Dir: ${APPDATA_DIR}`);
@@ -34,57 +43,26 @@ function sendToTauri(event, data) {
process.stdout.write(JSON.stringify({ event, data }) + '\n'); process.stdout.write(JSON.stringify({ event, data }) + '\n');
} }
function sameTabNavMiddleware(rootDir) { process.stdin.resume();
return (req, res, next) => { require('readline').createInterface({ input: process.stdin }).on('line', (line) => {
if (req.method !== 'GET') return next(); try {
const isHtmlRequest = req.path === '/' || req.path.endsWith('/') || req.path.endsWith('.html'); const msg = JSON.parse(line);
if (!isHtmlRequest) return next(); if (msg && msg.type === 'presence') presence.report(msg.payload);
} catch (e) { }
const filePath = req.path === '/' || req.path.endsWith('/')
? path.join(rootDir, req.path, 'index.html')
: path.join(rootDir, req.path);
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) return next();
const injected = data.replace(
'</head>',
`<script>
document.addEventListener('click', function(e) {
const a = e.target.closest('a[target]');
if (a && a.target === '_blank') a.removeAttribute('target');
}, true);
window.open = function(url) {
if (url) window.location.href = url;
return window;
};
</script></head>`
);
res.set('Content-Type', 'text/html');
res.send(injected);
});
};
}
const cmdApp = express();
cmdApp.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
res.header('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
}); });
cmdApp.get('/__tauri_cmd/:cmd', (req, res) => { process.stdin.on('end', () => {
debugLog(`[CMD-SERVER:4892] Command received: ${req.params.cmd} (window: ${req.query.window || 'main'})`); debugLog('stdin closed - parent died. Self-terminating...');
sendToTauri('tauri-cmd', { cmd: req.params.cmd, url: req.query.url, window: req.query.window }); process.exit(0);
res.sendStatus(200); });
process.stdin.on('error', () => {
process.exit(0);
}); });
cmdApp.listen(4892, '0.0.0.0', () => debugLog("[CMD-SERVER] Dedicated command server listening on 0.0.0.0:4892"));
process.on('uncaughtException', (err) => { process.on('uncaughtException', (err) => {
debugLog(`CRITICAL UNCAUGHT EXCEPTION: ${err.stack || err.message}`); debugLog(`CRITICAL UNCAUGHT EXCEPTION: ${err.stack || err.message}`);
if (err.code === 'EPIPE') { if (err.code === 'EPIPE' || err.code === 'EOF') {
debugLog('Pipe to parent closed - parent process gone, exiting'); debugLog('Pipe to parent closed - parent process gone, exiting');
process.exit(1); process.exit(0);
} }
try { sendToTauri('error', { message: err.message }); } catch (e) { } try { sendToTauri('error', { message: err.message }); } catch (e) { }
}); });
@@ -95,208 +73,382 @@ process.on('unhandledRejection', (reason) => {
sendToTauri('error', { message: reason && reason.message ? reason.message : String(reason) }); sendToTauri('error', { message: reason && reason.message ? reason.message : String(reason) });
}); });
const envConfig = JSON.parse(fs.readFileSync(path.join(__dirname, 'config/env.json'), 'utf8')); function getEnvConfig() {
const replacementsConfig = JSON.parse(fs.readFileSync(path.join(__dirname, 'config/replacements.json'), 'utf8')); try {
const appPath = path.join(APPDATA_DIR, 'config/env.json');
if (fs.existsSync(appPath)) return JSON.parse(fs.readFileSync(appPath, 'utf8'));
return JSON.parse(fs.readFileSync(path.join(__dirname, 'config/env.json'), 'utf8'));
} catch (e) { return {}; }
}
function getReplacementsConfig() {
try {
const appPath = path.join(APPDATA_DIR, 'config/replacements.json');
if (fs.existsSync(appPath)) return JSON.parse(fs.readFileSync(appPath, 'utf8'));
return JSON.parse(fs.readFileSync(path.join(__dirname, 'config/replacements.json'), 'utf8'));
} catch (e) { return {}; }
}
function liveReposEnabled() {
const cfg = getEnvConfig();
return !!(cfg.updater && cfg.updater.liveRepos === true);
}
const updateClient = new UpdateClient(APPDATA_DIR); const updateClient = new UpdateClient(APPDATA_DIR);
const presence = new VylaPresence({ getConfig: getEnvConfig, log: debugLog });
const fileUpdater = new FileUpdater(APPDATA_DIR, updateClient);
fileUpdater.onNotice = (message) => sendToTauri('notice', { message });
let lastFilePercent = -1;
fileUpdater.onProgress = (downloaded, total) => {
const percent = total > 0 ? Math.round((downloaded / total) * 100) : 0;
if (percent === lastFilePercent) return;
lastFilePercent = percent;
sendToTauri('download-progress', { downloaded, total, percent });
};
function withTimeout(promise, ms) {
return Promise.race([promise, new Promise((resolve) => setTimeout(() => resolve(null), ms))]);
}
function portInUse(port) {
return new Promise((resolve) => {
const socket = new (require('net').Socket)();
socket.setTimeout(500);
socket.once('connect', () => {
socket.destroy();
resolve(true);
});
socket.once('error', () => resolve(false));
socket.once('timeout', () => {
socket.destroy();
resolve(false);
});
socket.connect(port, '127.0.0.1');
});
}
async function start() { async function start() {
debugLog("Inside start() function"); debugLog("Inside start() function");
sendToTauri('status', { message: 'Initializing patcher...' }); sendToTauri('status', { message: 'Loading core configuration files...' });
const patcher = new Patcher(APPDATA_DIR); const patcher = new Patcher(APPDATA_DIR);
serviceManager = new ServiceManager(APPDATA_DIR, envConfig); serviceManager = new ServiceManager(APPDATA_DIR, getEnvConfig());
const installBuild = async (release) => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const tempZipPath = path.join(APPDATA_DIR, 'download-temp.zip');
let attempts = 0;
let downloadSuccess = false;
while (attempts < 3 && !downloadSuccess) { const downloadVerified = async (name, item, dest) => {
attempts++; let lastError;
for (let attempt = 1; attempt <= 3; attempt++) {
fs.rmSync(dest, { force: true });
try { try {
debugLog(`Attempting to download update (Attempt ${attempts})...`); sendToTauri('status', { message: `Downloading ${name} (attempt ${attempt}/3)...` });
sendToTauri('status', { message: `Downloading update (Attempt ${attempts}/3)...` }); let lastPercent = -1;
await updateClient.downloadUpdate(item, dest, (downloaded, total) => {
await updateClient.downloadUpdate(release, tempZipPath, (downloaded, total) => {
const percent = total > 0 ? Math.round((downloaded / total) * 100) : 0; const percent = total > 0 ? Math.round((downloaded / total) * 100) : 0;
sendToTauri('download-progress', { downloaded, total, percent }); if (percent !== lastPercent) {
lastPercent = percent;
sendToTauri('download-progress', { downloaded, total, percent });
}
}); });
sendToTauri('status', { message: `Verifying ${name} SHA-256...` });
debugLog('Download complete. Verifying checksum...'); if (!patcher.verifyChecksum(dest, item.sha256)) {
sendToTauri('status', { message: 'Verifying payload checksum...' });
if (!patcher.verifyChecksum(tempZipPath, release.sha256)) {
throw new Error('SHA-256 checksum verification failed.'); throw new Error('SHA-256 checksum verification failed.');
} }
return;
debugLog('Checksum verified. Extracting...');
sendToTauri('status', { message: 'Extracting update files...' });
patcher.purgeOldCode();
patcher.extractZipPayload(tempZipPath);
if (!patcher.verifyExtraction()) {
throw new Error('Extraction verification failed: critical startup files missing.');
}
debugLog('Extraction complete. Applying patches...');
sendToTauri('status', { message: 'Applying patches & configuring...' });
patcher.applyPatches(replacementsConfig);
patcher.bridgeCredentials(serviceManager.credentialManager);
patcher.saveCurrentVersion(release.version, release.sha256);
if (fs.existsSync(tempZipPath)) {
fs.unlinkSync(tempZipPath);
}
downloadSuccess = true;
debugLog('Update installed successfully!');
} catch (err) { } catch (err) {
debugLog(`Download/Install error on attempt ${attempts}: ${err.message}`); lastError = err;
if (fs.existsSync(tempZipPath)) { fs.rmSync(dest, { force: true });
try { fs.unlinkSync(tempZipPath); } catch (e) { } debugLog(`Download error for ${name} on attempt ${attempt}: ${err.message}`);
if (attempt < 3) {
await sleep(err.retryAfterMs || 2000 * 2 ** (attempt - 1) + Math.floor(Math.random() * 500));
} }
if (attempts >= 3) {
throw new Error(`Failed to download and verify build after 3 attempts: ${err.message}`);
}
await new Promise(r => setTimeout(r, 2000));
} }
} }
throw new Error(`Failed to download ${name} after 3 attempts: ${lastError.message}`);
};
const installBuild = async (release) => {
const names = patcher.staleComponents(release);
if (names.length === 0) return;
const stagingDir = path.join(APPDATA_DIR, '.staging');
fs.rmSync(stagingDir, { recursive: true, force: true });
fs.mkdirSync(stagingDir, { recursive: true });
const tempFiles = [];
try {
for (let i = 0; i < names.length; i++) {
const name = names[i];
const tempZip = path.join(APPDATA_DIR, `download-${name}.zip`);
tempFiles.push(tempZip);
await downloadVerified(name, release.components[name], tempZip);
sendToTauri('status', { message: `Unpacking ${name}...` });
let lastEmit = 0;
await patcher.extractToStaging(tempZip, (file, done, total) => {
const now = Date.now();
if (done !== total && now - lastEmit < 40) return;
lastEmit = now;
sendToTauri('extract-progress', { file, done, total, percent: Math.round((done / total) * 100) });
}, i > 0);
fs.rmSync(tempZip, { force: true });
}
sendToTauri('status', { message: 'Verifying file integrity...' });
if (!patcher.verifyStaged(stagingDir, names)) {
throw new Error('Extraction verification failed: critical startup files missing.');
}
sendToTauri('status', { message: 'Replacing old version...' });
patcher.commitStaging(stagingDir);
} catch (err) {
fs.rmSync(stagingDir, { recursive: true, force: true });
for (const f of tempFiles) fs.rmSync(f, { force: true });
throw err;
}
try {
sendToTauri('status', { message: 'Applying configuration patches...' });
patcher.applyPatches(getReplacementsConfig(), names);
sendToTauri('status', { message: 'Migrating security credentials...' });
patcher.bridgeCredentials(serviceManager.credentialManager);
if (!patcher.verifyExtraction()) {
throw new Error('Post-install verification failed.');
}
const current = patcher.getCurrentComponents();
const next = {};
for (const name of Object.keys(release.components)) {
next[name] = names.includes(name) ? release.components[name].id : current[name];
}
patcher.saveCurrentVersion(release.version, release.sha256, next);
patcher.writeIntegrity(names);
} catch (err) {
try { patcher.rollback(); } catch (x) { debugLog(`Rollback failed: ${x.message}`); }
throw err;
}
patcher.finalizeCommit();
if (liveReposEnabled()) fileUpdater.snapshotBase();
serviceManager.envConfig = getEnvConfig();
debugLog(`Update installed successfully: ${names.join(', ')}`);
}; };
try { try {
if (patcher.recoverInterrupted()) {
debugLog('Recovered from an interrupted update.');
sendToTauri('notice', { message: 'Recovered from an interrupted update.' });
}
fileUpdater.recoverSdk();
sendToTauri('status', { message: 'Inspecting local workspace and installed files...' });
const isFirstRun = !patcher.verifyExtraction(); const isFirstRun = !patcher.verifyExtraction();
const localVersion = patcher.getCurrentVersion(); const localVersion = patcher.getCurrentVersion();
const localSha = patcher.getCurrentSha(); const localSha = patcher.getCurrentSha();
debugLog(`Is First Run: ${isFirstRun}, Local Version: ${localVersion}`); debugLog(`Is First Run: ${isFirstRun}, Local Version: ${localVersion}, Local SHA: ${localSha}`);
sendToTauri('status', { message: 'Checking for updates...' }); sendToTauri('status', { message: 'Connecting to update servers...' });
let release = null; let release = null;
try { try {
debugLog("Fetching updates from updateClient..."); debugLog("Fetching updates from updateClient...");
release = await updateClient.checkForUpdates(); release = await updateClient.checkForUpdates(isFirstRun);
debugLog(`Update check finished. Found: ${release ? release.version : 'None'}`); debugLog(`Update check finished. Found: ${release ? release.version : 'None'}`);
} catch (e) { } catch (e) {
debugLog(`Update check failed (offline?): ${e.message}`); debugLog(`Update check failed: ${e.message}`);
sendToTauri('notice', { message: `Update check skipped: ${e.message}` });
}
const normalizeVer = (v) => (v || '').toString().replace(/^v/, '').trim();
const parseVer = (v) => normalizeVer(v).split(/[.\-+]/).map((n) => parseInt(n, 10) || 0);
const isNewer = (remote, local) => {
const a = parseVer(remote);
const b = parseVer(local);
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const x = a[i] || 0;
const y = b[i] || 0;
if (x !== y) return x > y;
}
return false;
};
if (release && release.installer && process.platform === 'win32' && process.env.VYLA_DEV !== '1') {
const appVersion = process.env.VYLA_APP_VERSION || '0.0.0';
const tried = updateClient.readCache().selfUpdate || {};
const recentlyTried = tried.version === release.installer.version && Date.now() - (tried.at || 0) < 10 * 60 * 1000;
if (isNewer(release.installer.version, appVersion) && !recentlyTried) {
try {
const dest = path.join(APPDATA_DIR, `vyla-installer-${normalizeVer(release.installer.version)}.exe`);
sendToTauri('status', { message: 'Downloading launcher update...' });
await downloadVerified('launcher', release.installer, dest);
updateClient.writeCache({ selfUpdate: { version: release.installer.version, at: Date.now() } });
sendToTauri('status', { message: 'Removing old version and installing the latest...' });
sendToTauri('self-update', { path: dest });
await sleep(30000);
sendToTauri('notice', { message: 'Launcher update did not start. Continuing on the current version.' });
} catch (err) {
debugLog(`Launcher update failed: ${err.message}`);
sendToTauri('notice', { message: `Launcher update failed: ${err.message}` });
}
}
} }
if (release) { if (release) {
const hasUpdate = release.version !== localVersion || (release.sha256 && release.sha256 !== localSha); const stale = patcher.staleComponents(release);
if (isFirstRun) { const broken = stale.some((name) => !patcher.componentIntact(name));
debugLog("First run. Installing remote build..."); const sameVersion = normalizeVer(release.version) === normalizeVer(localVersion);
await installBuild(release); const hasUpdate = stale.length > 0 && (broken || isNewer(release.version, localVersion) || sameVersion);
} else if (hasUpdate) {
debugLog("Update available. Prompting user..."); if (hasUpdate) {
const tempApp = express(); debugLog(`Installing components: ${stale.join(', ')}`);
let userDecision = null; sendToTauri('status', {
tempApp.use((req, res, next) => { message: isFirstRun ? 'First run detected. Preparing initial installation...' : `Updating to ${release.version}...`
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
res.header('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
}); });
tempApp.get('/update/info', (req, res) => { try {
res.json({ available: true, current: localVersion, latest: release.version });
});
tempApp.post('/update/yes', (req, res) => { userDecision = true; res.sendStatus(200); });
tempApp.post('/update/no', (req, res) => { userDecision = false; res.sendStatus(200); });
const tempServer = await new Promise((resolve) => {
const s = tempApp.listen(4891, '127.0.0.1', () => resolve(s));
});
sendToTauri('update-available', { current: localVersion, latest: release.version });
while (userDecision === null) {
await new Promise(r => setTimeout(r, 200));
}
await new Promise((resolve) => tempServer.close(resolve));
if (userDecision) {
debugLog("User accepted update.");
await installBuild(release); await installBuild(release);
} else { updateClient.recordSuccess();
debugLog("User skipped update."); } catch (err) {
updateClient.recordFailure();
debugLog(`Update failed: ${err.message}`);
sendToTauri('notice', { message: `Update failed: ${err.message}` });
} }
} else { } else {
debugLog("Already on the latest version."); debugLog("Already on the latest version.");
sendToTauri('status', { message: 'Up to date.' });
} }
} else if (isFirstRun) { }
debugLog("No remote release found, but it's the first run. Looking for local update-payload.zip...");
const localZip = path.join(__dirname, 'update-payload.zip'); if (!patcher.verifyExtraction()) {
if (fs.existsSync(localZip)) { debugLog("No usable install. Looking for local update-payload.zip...");
sendToTauri('status', { message: 'Extracting initial local payload...' }); sendToTauri('status', { message: 'Looking for local payload archive...' });
patcher.purgeOldCode(); const payloadRoots = [
patcher.extractZipPayload(localZip); process.env.VYLA_PAYLOAD_DIR,
patcher.applyPatches(replacementsConfig); __dirname,
patcher.bridgeCredentials(serviceManager.credentialManager); process.cwd(),
patcher.saveCurrentVersion("1.0.0"); path.resolve(__dirname, '..', '..', '..', '..'),
APPDATA_DIR
].filter(Boolean);
const payloadRoot = payloadRoots.find((r) => fs.existsSync(path.join(r, 'update-payload.zip')));
const localZip = payloadRoot ? path.join(payloadRoot, 'update-payload.zip') : null;
if (localZip) {
sendToTauri('status', { message: 'Extracting local baseline payload...' });
const stagingDir = await patcher.extractToStaging(localZip);
if (!patcher.verifyStaged(stagingDir, ['frontend', 'player'])) {
fs.rmSync(stagingDir, { recursive: true, force: true });
throw new Error('Bundled payload is incomplete.');
}
patcher.commitStaging(stagingDir);
try {
patcher.applyPatches(getReplacementsConfig());
patcher.bridgeCredentials(serviceManager.credentialManager);
let ver = "1.0.0";
let manSha = null;
let ids = {};
try {
const man = JSON.parse(fs.readFileSync(path.join(payloadRoot, 'manifest.json'), 'utf8'));
ver = man.version || ver;
manSha = man.sha256 || null;
ids = Object.fromEntries(Object.entries(man.components || {}).map(([k, v]) => [k, v.id]));
} catch (e) { }
patcher.saveCurrentVersion(ver, manSha, ids);
patcher.writeIntegrity(['frontend', 'player']);
} catch (e) {
try { patcher.rollback(); } catch (x) { }
throw e;
}
patcher.finalizeCommit();
if (liveReposEnabled()) fileUpdater.snapshotBase();
serviceManager.envConfig = getEnvConfig();
debugLog("Local payload extracted successfully."); debugLog("Local payload extracted successfully.");
} else { } else {
debugLog("No local payload found!"); debugLog("No local payload found!");
} }
} }
sendToTauri('status', { message: 'Validating critical components...' });
if (!patcher.verifyExtraction()) { if (!patcher.verifyExtraction()) {
throw new Error('No application files found. Check your internet connection and try again.'); throw new Error('No usable install and no valid signed release or bundled payload was found. Check your internet connection and relaunch, or reinstall the app.');
} }
sendToTauri('status', { message: 'Loading credentials...' }); const liveRepos = liveReposEnabled();
sendToTauri('status', { message: liveRepos ? 'Checking UI files and SDK...' : 'Checking SDK...' });
const [filesCheck, sdkCheck] = await Promise.all([
liveRepos
? withTimeout(fileUpdater.checkRepos().catch((e) => {
debugLog(`Live file check failed: ${e.message}`);
sendToTauri('notice', { message: `File check failed: ${e.message}` });
return null;
}), 60000)
: Promise.resolve(null),
withTimeout(fileUpdater.checkSdk().catch((e) => {
debugLog(`SDK check failed: ${e.message}`);
sendToTauri('notice', { message: `SDK check failed: ${e.message}` });
return null;
}), 12000)
]);
if (liveRepos) {
debugLog(`Repo check result: ${filesCheck ? `${filesCheck.changes.length} change(s)` : 'failed or timed out'}`);
}
if (filesCheck && (filesCheck.changes.length > 0 || filesCheck.removed.length > 0)) {
sendToTauri('status', { message: `Updating ${filesCheck.changes.length} file(s)...` });
try {
await fileUpdater.applyLive(filesCheck, getReplacementsConfig(), (file, done, total) => {
sendToTauri('extract-progress', { file, done, total, percent: Math.round((done / total) * 100) });
});
sendToTauri('status', { message: `Updated ${filesCheck.changes.length} file(s).` });
} catch (e) {
debugLog(`File update failed: ${e.message}`);
sendToTauri('notice', { message: `File update failed: ${e.message}` });
}
}
if (sdkCheck && sdkCheck.outdated) {
sendToTauri('status', { message: `Updating SDK (${sdkCheck.latest})...` });
try {
await fileUpdater.installSdk(sdkCheck);
sendToTauri('status', { message: `SDK updated to ${sdkCheck.latest}.` });
} catch (e) {
debugLog(`SDK install failed: ${e.message}`);
sendToTauri('status', { message: `SDK update failed: ${e.message}` });
}
}
sendToTauri('status', { message: 'Loading encrypted credentials...' });
serviceManager.credentialManager.loadCredentials(); serviceManager.credentialManager.loadCredentials();
sendToTauri('status', { message: 'Starting backend services...' }); const busyPorts = [];
for (const port of [3000, 4890]) {
if (await portInUse(port)) busyPorts.push(port);
}
if (busyPorts.length > 0) {
throw new Error(`Port ${busyPorts.join(' and ')} is already in use by another program. Close it or any other running Vyla Home, then relaunch.`);
}
sendToTauri('status', { message: 'Starting services (player, frontend)...' });
await serviceManager.startServices([ await serviceManager.startServices([
{ name: 'auth-proxy', relativeDir: 'auth-proxy' }, { name: 'player', relativeDir: 'player', startScript: 'server.js' },
{ name: 'stream-api', relativeDir: 'stream-api' }, { name: 'frontend', relativeDir: 'frontend', startScript: 'server.js' }
]); ]);
debugLog("Backend services spawn requested."); debugLog("Backend services spawn requested.");
const playerDir = path.join(APPDATA_DIR, 'player'); sendToTauri('status', { message: 'Waiting for microservices to bind...' });
playerExpressApp = express(); try {
playerExpressApp.use((req, res, next) => { await serviceManager.waitForPorts([3000, 4890], 60000);
res.header('Access-Control-Allow-Origin', '*'); } catch (e) {
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS'); throw new Error(`${e.message}. Check logs in ${LOGS_DIR}`);
res.header('Access-Control-Allow-Headers', '*'); }
if (req.method === 'OPTIONS') return res.sendStatus(200); debugLog("Ports 3000 and 4890 are ready.");
next(); try { presence.start(); } catch (e) { debugLog(`Presence start failed: ${e.message}`); }
});
playerExpressApp.get('/__tauri_cmd/:cmd', (req, res) => {
debugLog(`[PLAYER-SERVER:3001] Command received: ${req.params.cmd} (window: ${req.query.window || 'main'})`);
sendToTauri('tauri-cmd', { cmd: req.params.cmd, url: req.query.url, window: req.query.window });
res.sendStatus(200);
});
playerExpressApp.use(sameTabNavMiddleware(playerDir));
playerExpressApp.use(express.static(playerDir, { maxAge: '1d', etag: true }));
playerExpressApp.get('*', (req, res) => { res.sendFile(path.join(playerDir, 'index.html')); });
playerExpressServer = playerExpressApp.listen(3001, '0.0.0.0');
debugLog("Player Express running on 3001");
sendToTauri('status', { message: 'Waiting for ports 3000, 3001, 7860...' }); sendToTauri('status', { message: 'All backend services running and healthy.' });
await serviceManager.waitForPorts([3000, 3001, 7860]); debugLog("Sending READY to Tauri.");
debugLog("Ports 3000, 3001, 7860 are ready."); sendToTauri('ready', { url: 'http://127.0.0.1:4890' });
const frontendDir = path.join(APPDATA_DIR, 'frontend');
expressApp = express();
expressApp.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
res.header('Access-Control-Allow-Headers', '*');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
});
expressApp.get('/__tauri_cmd/:cmd', (req, res) => {
debugLog(`[FRONTEND-SERVER:4890] Command received: ${req.params.cmd} (window: ${req.query.window || 'main'})`);
sendToTauri('tauri-cmd', { cmd: req.params.cmd, url: req.query.url, window: req.query.window });
res.sendStatus(200);
});
expressApp.use(sameTabNavMiddleware(frontendDir));
expressApp.use(express.static(frontendDir, { maxAge: '1d', etag: true }));
expressApp.get('*', (req, res) => { res.sendFile(path.join(frontendDir, 'index.html')); });
const FRONTEND_PORT = 4890;
expressServer = expressApp.listen(FRONTEND_PORT, '0.0.0.0', () => {
debugLog("Frontend Express running on 4890. Sending READY to Tauri.");
sendToTauri('ready', { url: `http://localhost:${FRONTEND_PORT}` });
});
} catch (error) { } catch (error) {
debugLog(`Fatal Start Error: ${error.message}`); debugLog(`Fatal Start Error: ${error.message}`);
@@ -305,21 +457,20 @@ async function start() {
} }
process.on('exit', () => { process.on('exit', () => {
try { presence.stop(); } catch (e) { }
if (serviceManager) { if (serviceManager) {
for (const name of Object.keys(serviceManager.processes)) { serviceManager.stopAll();
const proc = serviceManager.processes[name];
if (proc && proc.child) {
try { proc.child.kill('SIGKILL'); } catch (e) { }
}
}
} }
}); });
process.on('SIGINT', async () => { process.on('SIGINT', () => {
if (expressServer) expressServer.close(); process.exit(0);
if (playerExpressServer) playerExpressServer.close(); });
if (serviceManager) await serviceManager.stopAll(); process.on('SIGTERM', () => {
process.exit(0);
});
process.on('SIGHUP', () => {
process.exit(0); process.exit(0);
}); });
start(); start();

1538
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,57 +1,25 @@
{ {
"name": "vyla-home", "name": "vyla-home",
"version": "1.1.0", "version": "1.1.62",
"description": "Vyla Home Desktop App Launcher", "description": "Vyla Home Desktop App Launcher",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
"dev": "tauri dev", "dev": "tauri dev",
"build:payload": "node build-pipeline.js", "build:payload": "node build-pipeline.js",
"build": "node -e \"require('child_process').execSync('tauri build', {stdio:'inherit', env:Object.assign({}, process.env, {WEBVIEW2_STATIC_LIB:'1'})})\"", "build": "tauri build",
"release": "node release.js", "release": "node release.js",
"release:full": "node release.js --installer" "release:full": "node release.js --installer"
}, },
"dependencies": { "dependencies": {
"@tauri-apps/api": "^2.0.0", "@tauri-apps/api": "2.12.1",
"@tauri-apps/plugin-shell": "^2.0.0", "@tauri-apps/plugin-opener": "2.7.0",
"@tauri-apps/plugin-process": "^2.0.0", "@tauri-apps/plugin-process": "2.4.0",
"@vyla-entertainment/sdk": "^1.10.0", "@tauri-apps/plugin-shell": "2.5.0",
"adm-zip": "^0.6.0", "@vyla-entertainment/sdk": "^1.20.0",
"express": "^4.19.2" "adm-zip": "^0.6.1",
"express": "^4.22.3"
}, },
"devDependencies": { "devDependencies": {
"@tauri-apps/cli": "^2.0.0", "@tauri-apps/cli": "2.12.1"
"javascript-obfuscator": "^4.1.0"
},
"build": {
"appId": "com.vyla.home",
"productName": "Vyla Home",
"directories": {
"output": "dist"
},
"files": [
"main.js",
"preload.js",
"service-manager.js",
"patcher.js",
"crypto-utils.js",
"credential-manager.js",
"update-client.js",
"gitlab-client.js",
"config/**/*",
"build/icon.ico",
"build/logo.txt",
"package.json"
],
"win": {
"target": "nsis",
"icon": "build/icon.ico"
},
"nsis": {
"oneClick": false,
"allowToChangeInstallationDirectory": true,
"installerIcon": "build/icon.ico",
"uninstallerIcon": "build/icon.ico",
"installerHeaderIcon": "build/icon.ico"
}
} }
} }

View File

@@ -4,6 +4,29 @@ const crypto = require('crypto');
const AdmZip = require('adm-zip'); const AdmZip = require('adm-zip');
const CryptoUtils = require('./crypto-utils'); const CryptoUtils = require('./crypto-utils');
const COMPONENT_PROBES = {
frontend: 'frontend/server.js',
player: 'player/server.js',
config: 'config/env.json',
secrets: 'encrypted-credentials.json'
};
const COMMIT_ALLOWED = new Set(['frontend', 'player', 'config', 'encrypted-credentials.json']);
function renameSafe(from, to) {
let last;
for (let i = 0; i < 6; i++) {
try {
fs.renameSync(from, to);
return;
} catch (e) {
last = e;
if (!['EPERM', 'EBUSY', 'EACCES', 'ENOTEMPTY'].includes(e.code)) throw e;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 250 * (i + 1));
}
}
throw last;
}
class Patcher { class Patcher {
constructor(appDataPath) { constructor(appDataPath) {
this.appDataPath = appDataPath; this.appDataPath = appDataPath;
@@ -51,10 +74,103 @@ class Patcher {
return true; return true;
} }
saveCurrentVersion(version, sha256 = null) { saveCurrentVersion(version, sha256 = null, components = null) {
const versionFile = path.join(this.appDataPath, 'version.json'); const versionFile = path.join(this.appDataPath, 'version.json');
fs.mkdirSync(this.appDataPath, { recursive: true }); fs.mkdirSync(this.appDataPath, { recursive: true });
fs.writeFileSync(versionFile, JSON.stringify({ version, sha256 }, null, 2), 'utf8'); const tmp = `${versionFile}.tmp`;
fs.writeFileSync(tmp, JSON.stringify({ version, sha256, components: components || {} }, null, 2), 'utf8');
renameSafe(tmp, versionFile);
}
getCurrentComponents() {
try {
const c = JSON.parse(fs.readFileSync(path.join(this.appDataPath, 'version.json'), 'utf8')).components;
return c && typeof c === 'object' ? c : {};
} catch (e) {
return {};
}
}
integrityPath() {
return path.join(this.appDataPath, 'integrity.json');
}
readIntegrity() {
try {
return JSON.parse(fs.readFileSync(this.integrityPath(), 'utf8'));
} catch (e) {
return {};
}
}
writeIntegrity(names) {
const all = this.readIntegrity();
for (const name of names) {
if (name !== 'frontend' && name !== 'player') continue;
const files = {};
const walk = (dir, rel) => {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
const r = `${rel}/${entry.name}`;
if (r.includes('/node_modules/@vyla-entertainment/sdk')) continue;
if (entry.isDirectory()) walk(full, r);
else if (entry.isFile()) files[r] = fs.statSync(full).size;
}
};
walk(path.join(this.appDataPath, name), name);
all[name] = files;
}
const tmp = `${this.integrityPath()}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(all), 'utf8');
renameSafe(tmp, this.integrityPath());
}
integrityOk(name) {
const files = this.readIntegrity()[name];
if (!files) return true;
for (const [rel, size] of Object.entries(files)) {
try {
if (fs.statSync(path.join(this.appDataPath, rel)).size !== size) return false;
} catch (e) {
return false;
}
}
return true;
}
componentIntact(name) {
const probe = COMPONENT_PROBES[name];
if (!probe || name === 'secrets') return true;
try {
if (fs.statSync(path.join(this.appDataPath, probe)).size <= 0) return false;
} catch (e) {
return false;
}
return this.integrityOk(name);
}
staleComponents(release) {
const local = this.getCurrentComponents();
const names = Object.keys(release.components);
const stale = new Set(names.filter((n) => !this.componentIntact(n) || local[n] !== release.components[n].id));
if (stale.has('config')) {
for (const n of ['frontend', 'player']) {
if (release.components[n]) stale.add(n);
}
}
return [...stale];
}
verifyStaged(stagingDir, names) {
return names.every((name) => {
const probe = COMPONENT_PROBES[name];
if (!probe) return true;
try {
return fs.statSync(path.join(stagingDir, probe)).size > 0;
} catch (e) {
return false;
}
});
} }
purgeOldCode() { purgeOldCode() {
@@ -64,42 +180,196 @@ class Patcher {
if (fs.existsSync(fullPath)) { if (fs.existsSync(fullPath)) {
try { try {
fs.rmSync(fullPath, { recursive: true, force: true }); fs.rmSync(fullPath, { recursive: true, force: true });
} catch (e) { } catch (e) { }
try {
const trashPath = fullPath + '.trash.' + Date.now();
fs.renameSync(fullPath, trashPath);
} catch (renameErr) {
console.warn(`Could not remove or rename ${fullPath}. It will be overwritten.`);
}
}
} }
} }
} }
extractZipPayload(zipPath) { extractZipPayload(zipPath) {
const zip = new AdmZip(zipPath); const zip = new AdmZip(zipPath);
const entries = zip.getEntries();
if (!entries || entries.length === 0) {
throw new Error('Archive is empty, invalid, or truncated.');
}
const targetDir = path.resolve(this.appDataPath);
for (const entry of entries) {
const entryPath = path.normalize(entry.entryName);
const resolvedPath = path.resolve(targetDir, entryPath);
if (!resolvedPath.startsWith(targetDir)) {
throw new Error(`Directory traversal attempt detected in archive: ${entry.entryName}`);
}
}
zip.extractAllTo(this.appDataPath, true); zip.extractAllTo(this.appDataPath, true);
} }
verifyChecksum(zipPath, expectedSha256) { async extractToStaging(zipPath, onFile, keep = false) {
if (!expectedSha256) return true; const stagingDir = path.join(this.appDataPath, '.staging');
const hash = crypto.createHash('sha256'); if (!keep) fs.rmSync(stagingDir, { recursive: true, force: true });
const data = fs.readFileSync(zipPath); fs.mkdirSync(stagingDir, { recursive: true });
hash.update(data); const zip = new AdmZip(zipPath);
const calculated = hash.digest('hex'); const entries = zip.getEntries().filter((e) => !e.isDirectory);
return calculated === expectedSha256; if (entries.length === 0) {
throw new Error('Downloaded archive is empty, invalid, or truncated.');
}
const resolvedStaging = path.resolve(stagingDir);
for (const entry of entries) {
const entryPath = path.normalize(entry.entryName);
const resolvedPath = path.resolve(resolvedStaging, entryPath);
if (!resolvedPath.startsWith(resolvedStaging + path.sep)) {
throw new Error(`Directory traversal attempt detected: ${entry.entryName}`);
}
}
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
zip.extractEntryTo(entry, stagingDir, true, true);
if (onFile) onFile(entry.entryName, i + 1, entries.length);
if (i % 20 === 0) await new Promise((resolve) => setImmediate(resolve));
}
return stagingDir;
} }
verifyExtraction() { journalPath() {
return path.join(this.appDataPath, '.update-journal.json');
}
backupDir() {
return path.join(this.appDataPath, '.backup');
}
commitStaging(stagingDir) {
const names = fs.readdirSync(stagingDir);
const unexpected = names.filter((n) => !COMMIT_ALLOWED.has(n));
if (unexpected.length > 0) {
throw new Error(`Unexpected top-level entries in update: ${unexpected.join(', ')}`);
}
const backup = this.backupDir();
fs.rmSync(backup, { recursive: true, force: true });
fs.mkdirSync(backup, { recursive: true });
const versionFile = path.join(this.appDataPath, 'version.json');
if (fs.existsSync(versionFile)) {
fs.copyFileSync(versionFile, path.join(backup, 'version.json.bak'));
}
const journal = { names, hadOld: {}, installed: [] };
for (const name of names) {
journal.hadOld[name] = fs.existsSync(path.join(this.appDataPath, name));
}
const save = () => {
const tmp = `${this.journalPath()}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(journal), 'utf8');
renameSafe(tmp, this.journalPath());
};
save();
try {
for (const name of names) {
const dest = path.join(this.appDataPath, name);
if (journal.hadOld[name]) {
renameSafe(dest, path.join(backup, name));
}
journal.installed.push(name);
save();
renameSafe(path.join(stagingDir, name), dest);
}
} catch (e) {
try { this.rollback(); } catch (x) { }
throw e;
}
fs.rmSync(stagingDir, { recursive: true, force: true });
}
rollback() {
let journal;
try {
journal = JSON.parse(fs.readFileSync(this.journalPath(), 'utf8'));
} catch (e) {
return false;
}
const backup = this.backupDir();
const hadOld = journal.hadOld || {};
const installed = journal.installed || [];
for (const name of journal.names || []) {
const dest = path.join(this.appDataPath, name);
const saved = path.join(backup, name);
if (hadOld[name]) {
if (fs.existsSync(saved)) {
fs.rmSync(dest, { recursive: true, force: true });
renameSafe(saved, dest);
}
} else if (installed.includes(name)) {
fs.rmSync(dest, { recursive: true, force: true });
}
}
const versionFile = path.join(this.appDataPath, 'version.json');
const savedVersion = path.join(backup, 'version.json.bak');
if (fs.existsSync(savedVersion)) {
fs.copyFileSync(savedVersion, versionFile);
} else {
fs.rmSync(versionFile, { force: true });
}
fs.rmSync(backup, { recursive: true, force: true });
fs.rmSync(this.journalPath(), { force: true });
fs.rmSync(path.join(this.appDataPath, '.staging'), { recursive: true, force: true });
return true;
}
finalizeCommit() {
fs.rmSync(this.backupDir(), { recursive: true, force: true });
fs.rmSync(this.journalPath(), { force: true });
for (const dir of ['stream-api', 'auth-proxy']) {
fs.rmSync(path.join(this.appDataPath, dir), { recursive: true, force: true });
}
}
recoverInterrupted() {
const had = fs.existsSync(this.journalPath());
if (had && !this.rollback()) {
fs.rmSync(this.journalPath(), { force: true });
fs.rmSync(this.backupDir(), { recursive: true, force: true });
}
fs.rmSync(path.join(this.appDataPath, '.staging'), { recursive: true, force: true });
try {
for (const f of fs.readdirSync(this.appDataPath)) {
if (/^download-.*\.zip$/.test(f)) fs.rmSync(path.join(this.appDataPath, f), { force: true });
}
} catch (e) { }
return had;
}
verifyChecksum(zipPath, expectedSha256) {
if (!expectedSha256) return false;
const hash = crypto.createHash('sha256');
const fd = fs.openSync(zipPath, 'r');
const buf = Buffer.alloc(1024 * 1024);
try {
let n;
while ((n = fs.readSync(fd, buf, 0, buf.length, null)) > 0) {
hash.update(buf.subarray(0, n));
}
} finally {
fs.closeSync(fd);
}
return hash.digest('hex') === String(expectedSha256).trim().toLowerCase();
}
verifyExtraction(root = this.appDataPath) {
const requiredFiles = [ const requiredFiles = [
'player/index.html', 'frontend/server.js',
'auth-proxy/server.js', 'player/server.js'
'stream-api/server.js',
'frontend/index.html'
]; ];
for (const file of requiredFiles) { for (const file of requiredFiles) {
const fullPath = path.join(this.appDataPath, file); const fullPath = path.join(root, file);
if (!fs.existsSync(fullPath)) { if (!fs.existsSync(fullPath)) {
return false; return false;
} }
@@ -107,19 +377,23 @@ class Patcher {
if (stat.size === 0) { if (stat.size === 0) {
return false; return false;
} }
const sampleSize = Math.min(stat.size, 4096); try {
const fd = fs.openSync(fullPath, 'r'); const sampleSize = Math.min(stat.size, 4096);
const buffer = Buffer.alloc(sampleSize); const fd = fs.openSync(fullPath, 'r');
fs.readSync(fd, buffer, 0, sampleSize, 0); const buffer = Buffer.alloc(sampleSize);
fs.closeSync(fd); fs.readSync(fd, buffer, 0, sampleSize, 0);
if (buffer.every(byte => byte === 0)) { fs.closeSync(fd);
if (buffer.every(byte => byte === 0)) {
return false;
}
} catch (e) {
return false; return false;
} }
} }
return true; return true;
} }
processDirectory(dir, replacementList) { processDirectory(dir, replacementList = []) {
const files = fs.readdirSync(dir); const files = fs.readdirSync(dir);
for (const file of files) { for (const file of files) {
const fullPath = path.join(dir, file); const fullPath = path.join(dir, file);
@@ -129,36 +403,32 @@ class Patcher {
if (file === 'node_modules' || file === '.git') continue; if (file === 'node_modules' || file === '.git') continue;
this.processDirectory(fullPath, replacementList); this.processDirectory(fullPath, replacementList);
} else if (stat.isFile()) { } else if (stat.isFile()) {
const ext = path.extname(fullPath).toLowerCase(); let content = fs.readFileSync(fullPath, 'utf8');
if (['.js', '.html', '.css', '.json', '.xml', '.txt'].includes(ext)) { let modified = false;
let content = fs.readFileSync(fullPath, 'utf8');
let modified = false;
for (const rep of replacementList) { for (const rep of replacementList) {
if (content.includes(rep.find)) { if (content.includes(rep.find)) {
content = content.split(rep.find).join(rep.replace); content = content.split(rep.find).join(rep.replace);
modified = true; modified = true;
}
} }
}
if (modified) { if (modified) {
fs.writeFileSync(fullPath, content, 'utf8'); fs.writeFileSync(fullPath, content, 'utf8');
}
} }
} }
} }
} }
applyPatches(replacements) { applyPatches(replacements, only = null) {
for (const [componentName, replacementList] of Object.entries(replacements)) { const targetDirs = ['frontend', 'player'].filter((d) => !only || only.includes(d));
if (!replacementList || replacementList.length === 0) continue; for (const dirName of targetDirs) {
const dirPath = path.join(this.appDataPath, dirName);
const componentDir = path.join(this.appDataPath, componentName); if (!fs.existsSync(dirPath)) continue;
if (!fs.existsSync(componentDir)) continue; const replacementList = replacements[dirName] || [];
this.processDirectory(dirPath, replacementList);
this.processDirectory(componentDir, replacementList);
} }
} }
} }
module.exports = Patcher; module.exports = Patcher;

View File

@@ -1,5 +0,0 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('vylaHome', {
sendUpdateChoice: (choice) => ipcRenderer.send('update-choice', choice)
});

View File

@@ -2,6 +2,8 @@ const fs = require('fs');
const path = require('path'); const path = require('path');
const https = require('https'); const https = require('https');
const { execSync } = require('child_process'); const { execSync } = require('child_process');
const crypto = require('crypto');
const UpdateClient = require('./update-client');
const GITLAB_PROJECT_PATH = 'vyla-entertainment%2Fhome'; const GITLAB_PROJECT_PATH = 'vyla-entertainment%2Fhome';
const PROJECT_ID = process.env.CI_PROJECT_ID || GITLAB_PROJECT_PATH; const PROJECT_ID = process.env.CI_PROJECT_ID || GITLAB_PROJECT_PATH;
@@ -78,57 +80,104 @@ function uploadFileToGitLabPackage(filePath, packageName, version, fileName) {
} }
function createGitLabRelease(tag, releaseLinks) { function createGitLabRelease(tag, releaseLinks) {
const sendRequest = (method, path) => { const sendRequest = (method, reqPath, data = null) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let currentRef = 'main'; const options = {
try {
currentRef = execSync('git rev-parse HEAD').toString().trim();
} catch (e) { }
const postData = JSON.stringify({
name: `Vyla Home Release ${tag}`,
tag_name: tag,
ref: currentRef,
description: `Automated local release ${tag}`,
assets: {
links: releaseLinks
}
});
const req = https.request({
hostname: 'gitlab.com', hostname: 'gitlab.com',
port: 443, port: 443,
path: path, path: reqPath,
method: method, method: method,
headers: { headers: {
'PRIVATE-TOKEN': TOKEN, 'PRIVATE-TOKEN': TOKEN,
'Content-Type': 'application/json', 'Content-Type': 'application/json'
'Content-Length': Buffer.byteLength(postData)
} }
}, (res) => { };
let postData = '';
if (data) {
postData = JSON.stringify(data);
options.headers['Content-Length'] = Buffer.byteLength(postData);
}
const req = https.request(options, (res) => {
let body = ''; let body = '';
res.on('data', chunk => body += chunk); res.on('data', chunk => body += chunk);
res.on('end', () => { res.on('end', () => {
if (res.statusCode === 200 || res.statusCode === 201) { if (res.statusCode >= 200 && res.statusCode < 300) {
resolve(JSON.parse(body)); try { resolve(body ? JSON.parse(body) : {}); } catch (e) { resolve({}); }
} else if (res.statusCode === 409 && method === 'POST') {
console.log(`Release ${tag} already exists, updating assets...`);
sendRequest('PUT', `/api/v4/projects/${PROJECT_ID}/releases/${encodeURIComponent(tag)}`)
.then(resolve)
.catch(reject);
} else { } else {
reject(new Error(`Failed to publish release (HTTP ${res.statusCode}): ${body}`)); reject(new Error(`HTTP ${res.statusCode}: ${body}`));
} }
}); });
}); });
req.on('error', reject); req.on('error', reject);
req.write(postData); if (data) req.write(postData);
req.end(); req.end();
}); });
}; };
return sendRequest('POST', `/api/v4/projects/${PROJECT_ID}/releases`); let currentRef = 'main';
try {
currentRef = execSync('git rev-parse HEAD').toString().trim();
} catch (e) { }
const releaseData = {
name: `Vyla Home Release ${tag}`,
tag_name: tag,
ref: currentRef,
description: `Automated Multi-Platform Release ${tag}`,
assets: {
links: releaseLinks
}
};
return sendRequest('POST', `/api/v4/projects/${PROJECT_ID}/releases`, releaseData)
.catch(err => {
if (err.message.includes('HTTP 409')) {
console.log(`[CI Sync] Release ${tag} already exists. Appending our OS-specific files to it...`);
let promiseChain = Promise.resolve();
const linksPath = `/api/v4/projects/${PROJECT_ID}/releases/${encodeURIComponent(tag)}/assets/links`;
const hasInstaller = releaseLinks.some((l) => l.link_type === 'package');
for (const link of releaseLinks) {
promiseChain = promiseChain.then(async () => {
const current = await sendRequest('GET', linksPath);
const clash = (Array.isArray(current) ? current : []).find((l) => l.name === link.name);
if (clash && link.name === 'manifest.json' && hasInstaller) {
await sendRequest('DELETE', `${linksPath}/${clash.id}`);
} else if (clash) {
console.log(`[CI Sync] Asset link '${link.name}' is already attached. Skipping.`);
return;
}
await sendRequest('POST', linksPath, {
name: link.name,
url: link.url,
link_type: link.link_type
});
});
}
return promiseChain.then(() => ({ name: `Vyla Home Release ${tag}`, tag_name: tag }));
}
throw err;
});
}
function injectDiscordConfig() {
const envPath = path.join(__dirname, 'config', 'env.json');
const cfg = fs.existsSync(envPath) ? JSON.parse(fs.readFileSync(envPath, 'utf8')) : {};
const tmdb = process.env.TMDB_API_KEY || process.env.TMDB_KEY || '3f6703f3e2a0b2b40fe4fbb3e1546244';
const clientId = process.env.DISCORD_CLIENT_ID || '';
cfg.discord = cfg.discord || {};
if (tmdb) {
cfg.discord.tmdbApiKey = tmdb;
} else {
console.log('[WARNING] No TMDB_API_KEY or TMDB_KEY set. Discord posters will fall back to page data.');
}
if (clientId) cfg.discord.clientId = clientId;
fs.mkdirSync(path.dirname(envPath), { recursive: true });
fs.writeFileSync(envPath, JSON.stringify(cfg, null, 2) + '\n', 'utf8');
} }
async function main() { async function main() {
@@ -139,8 +188,10 @@ async function main() {
console.log(`Building Vyla Home Release (${version})`); console.log(`Building Vyla Home Release (${version})`);
injectDiscordConfig();
console.log('[1/4] Building update payload and manifest...'); console.log('[1/4] Building update payload and manifest...');
execSync('node build-pipeline.js', { stdio: 'inherit' }); execSync('node build-pipeline.js', { stdio: 'inherit', env: { ...process.env, RELEASE_VERSION: version } });
const payloadPath = path.join(__dirname, 'update-payload.zip'); const payloadPath = path.join(__dirname, 'update-payload.zip');
const manifestPath = path.join(__dirname, 'manifest.json'); const manifestPath = path.join(__dirname, 'manifest.json');
@@ -155,32 +206,86 @@ async function main() {
if (isFullBuild) { if (isFullBuild) {
console.log('Ensuring bundled Node.js runtime...'); console.log('Ensuring bundled Node.js runtime...');
await ensureBundledNode(); await ensureBundledNode();
console.log('Ensuring WebView2Loader.dll is present for packaging...');
await ensureWebView2Loader(); await ensureWebView2Loader();
console.log('Compiling Windows Tauri installer locally...'); const bundleDir = path.join(__dirname, 'src-tauri', 'target', 'release', 'bundle');
execSync('npm run build', { if (fs.existsSync(bundleDir)) {
stdio: 'inherit' fs.rmSync(bundleDir, { recursive: true, force: true });
}); }
const nsisDir = path.join(__dirname, 'src-tauri/target/release/bundle/nsis'); console.log('Compiling native Tauri application...');
if (fs.existsSync(nsisDir)) { execSync('npm run build', { stdio: 'inherit' });
const files = fs.readdirSync(nsisDir).filter(f => f.endsWith('.exe'));
if (files.length > 0) { const targetVersion = version.startsWith('v') ? version.substring(1) : version;
const originalName = files[0];
installerPath = path.join(nsisDir, originalName); if (process.platform === 'win32') {
installerUploadName = originalName.replace(/\s+/g, '-'); const nsisDir = path.join(__dirname, 'src-tauri', 'target', 'release', 'bundle', 'nsis');
if (fs.existsSync(nsisDir)) {
const files = fs.readdirSync(nsisDir).filter(f => f.endsWith('.exe') && f.includes(targetVersion));
if (files.length > 0) {
installerPath = path.join(nsisDir, files[0]);
installerUploadName = files[0].replace(/\s+/g, '-');
}
}
} else {
const dmgDir = path.join(__dirname, 'src-tauri', 'target', 'release', 'bundle', 'dmg');
console.log(`Checking for Mac installer in: ${dmgDir}`);
if (fs.existsSync(dmgDir)) {
const files = fs.readdirSync(dmgDir).filter(f => f.endsWith('.dmg') && f.includes(targetVersion));
if (files.length > 0) {
installerPath = path.join(dmgDir, files[0]);
installerUploadName = files[0].replace(/\s+/g, '-');
console.log(`Found Mac installer: ${installerUploadName}`);
} else {
console.log(`[WARNING] No .dmg found containing version ${targetVersion}`);
}
} }
} }
} }
if (installerPath && installerUploadName && process.platform === 'win32') {
const signingKey = process.env.VYLA_UPDATE_SIGNING_KEY;
if (!signingKey) {
throw new Error('VYLA_UPDATE_SIGNING_KEY is required to sign the installer entry.');
}
const installerBuf = fs.readFileSync(installerPath);
const signedManifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
signedManifest.installer = {
file: installerUploadName,
sha256: crypto.createHash('sha256').update(installerBuf).digest('hex'),
size: installerBuf.length,
version: version.replace(/^v/, '')
};
delete signedManifest.signature;
signedManifest.signature = crypto.sign(null, Buffer.from(UpdateClient.canonicalManifest(signedManifest)), signingKey.replace(/\\n/g, '\n')).toString('base64');
fs.writeFileSync(manifestPath, JSON.stringify(signedManifest, null, 2), 'utf8');
}
console.log('[2/4] Uploading artifacts to GitLab Package Registry...'); console.log('[2/4] Uploading artifacts to GitLab Package Registry...');
const timestamp = Date.now();
console.log('Uploading update-payload.zip...'); console.log('Uploading update-payload.zip...');
const payloadUrl = await uploadFileToGitLabPackage(payloadPath, 'vyla-home', version, 'update-payload.zip'); const payloadUrl = await uploadFileToGitLabPackage(payloadPath, 'vyla-home', version, `update-payload-${timestamp}.zip`);
const manifestData = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
for (const [name, c] of Object.entries(manifestData.components || {})) {
console.log(`Uploading ${c.file}...`);
c.url = await uploadFileToGitLabPackage(path.join(__dirname, 'release-assets', c.file), 'vyla-home', version, `${name}-${timestamp}.zip`);
if (!c.url || !c.url.includes('/packages/generic/vyla-home/')) {
throw new Error(`Upload for ${name} did not return a package URL.`);
}
}
const signingKeyPem = process.env.VYLA_UPDATE_SIGNING_KEY;
if (!signingKeyPem) {
throw new Error('VYLA_UPDATE_SIGNING_KEY is required to sign the update manifest.');
}
delete manifestData.signature;
manifestData.signature = crypto.sign(null, Buffer.from(UpdateClient.canonicalManifest(manifestData)), signingKeyPem.replace(/\\n/g, '\n')).toString('base64');
fs.writeFileSync(manifestPath, JSON.stringify(manifestData, null, 2), 'utf8');
console.log('Uploading manifest.json...'); console.log('Uploading manifest.json...');
const manifestUrl = await uploadFileToGitLabPackage(manifestPath, 'vyla-home', version, 'manifest.json'); const manifestUrl = await uploadFileToGitLabPackage(manifestPath, 'vyla-home', version, `manifest-${timestamp}.json`);
const releaseLinks = [ const releaseLinks = [
{ name: 'update-payload.zip', url: payloadUrl, link_type: 'other' }, { name: 'update-payload.zip', url: payloadUrl, link_type: 'other' },
@@ -189,18 +294,25 @@ async function main() {
if (installerPath && installerUploadName) { if (installerPath && installerUploadName) {
console.log(`Uploading installer ${installerUploadName}...`); console.log(`Uploading installer ${installerUploadName}...`);
const installerUrl = await uploadFileToGitLabPackage(installerPath, 'vyla-home', version, installerUploadName); const ext = path.extname(installerUploadName);
const installerUnique = installerUploadName.replace(ext, `-${timestamp}${ext}`);
const installerUrl = await uploadFileToGitLabPackage(installerPath, 'vyla-home', version, installerUnique);
releaseLinks.push({ name: installerUploadName, url: installerUrl, link_type: 'package' }); releaseLinks.push({ name: installerUploadName, url: installerUrl, link_type: 'package' });
} else {
console.log(`[WARNING] No installer was selected for upload! (isFullBuild: ${isFullBuild})`);
} }
console.log('[3/4] Publishing GitLab Release...'); console.log('[3/4] Publishing GitLab Release...');
const release = await createGitLabRelease(version, releaseLinks); await createGitLabRelease(version, releaseLinks);
console.log(`[4/4] Release successfully created: ${release.name} (${release.tag_name})`); console.log(`[4/4] Release process successfully completed for ${version}!`);
} }
function ensureBundledNode() { function ensureBundledNode() {
const os = require('os');
const binDir = path.join(__dirname, 'bin'); const binDir = path.join(__dirname, 'bin');
const nodeExePath = path.join(binDir, 'node.exe'); const isWin = os.platform() === 'win32';
const nodeExeName = isWin ? 'node.exe' : 'node';
const nodeExePath = path.join(binDir, nodeExeName);
const nodeVersion = 'v22.14.0'; const nodeVersion = 'v22.14.0';
const versionMarker = path.join(binDir, `node-${nodeVersion}.marker`); const versionMarker = path.join(binDir, `node-${nodeVersion}.marker`);
@@ -212,61 +324,78 @@ function ensureBundledNode() {
fs.mkdirSync(binDir, { recursive: true }); fs.mkdirSync(binDir, { recursive: true });
console.log(`Downloading standalone Node.js ${nodeVersion} runtime for bundling...`); console.log(`Downloading standalone Node.js ${nodeVersion} runtime for bundling...`);
const nodeUrl = `https://nodejs.org/dist/${nodeVersion}/win-x64/node.exe`;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fileStream = fs.createWriteStream(nodeExePath); const download = (url, dest, cb) => {
https.get(nodeUrl, (res) => { https.get(url, (res) => {
if (res.statusCode === 302 || res.statusCode === 301) { if (res.statusCode === 302 || res.statusCode === 301) {
https.get(res.headers.location, (redirectRes) => { return download(res.headers.location, dest, cb);
redirectRes.pipe(fileStream); }
fileStream.on('finish', () => { const fileStream = fs.createWriteStream(dest);
fileStream.close(); res.pipe(fileStream);
fs.writeFileSync(versionMarker, nodeVersion, 'utf8'); fileStream.on('finish', () => {
resolve(); fileStream.close();
}); cb();
}).on('error', reject); });
return; }).on('error', reject);
} };
res.pipe(fileStream);
fileStream.on('finish', () => { if (isWin) {
fileStream.close(); const nodeUrl = `https://nodejs.org/dist/${nodeVersion}/win-x64/node.exe`;
download(nodeUrl, nodeExePath, () => {
fs.writeFileSync(versionMarker, nodeVersion, 'utf8'); fs.writeFileSync(versionMarker, nodeVersion, 'utf8');
resolve(); resolve();
}); });
}).on('error', (err) => { } else {
try { fs.unlinkSync(nodeExePath); } catch (e) { } const arch = os.arch() === 'arm64' ? 'arm64' : 'x64';
reject(err); const platform = os.platform() === 'darwin' ? 'darwin' : 'linux';
}); const tarName = `node-${nodeVersion}-${platform}-${arch}`;
const nodeUrl = `https://nodejs.org/dist/${nodeVersion}/${tarName}.tar.gz`;
const tarPath = path.join(binDir, 'node.tar.gz');
download(nodeUrl, tarPath, () => {
try {
execSync(`tar -xzf node.tar.gz ${tarName}/bin/node`, { cwd: binDir });
const extractedNode = path.join(binDir, tarName, 'bin', 'node');
const finalNode = path.join(binDir, 'node');
fs.renameSync(extractedNode, finalNode);
fs.rmSync(path.join(binDir, tarName), { recursive: true, force: true });
fs.unlinkSync(tarPath);
fs.chmodSync(finalNode, 0o755);
try {
execSync(`xattr -d com.apple.quarantine "${finalNode}"`);
} catch (_) { }
fs.writeFileSync(versionMarker, nodeVersion, 'utf8');
resolve();
} catch (e) {
reject(e);
}
});
}
}); });
} }
function ensureWebView2Loader() { function ensureWebView2Loader() {
const os = require('os');
if (os.platform() !== 'win32') return Promise.resolve();
const releaseDir = path.join(__dirname, 'src-tauri', 'target', 'release'); const releaseDir = path.join(__dirname, 'src-tauri', 'target', 'release');
const binDir = path.join(__dirname, 'bin'); const rootDllPath = path.join(__dirname, 'src-tauri', 'WebView2Loader.dll');
fs.mkdirSync(releaseDir, { recursive: true }); fs.mkdirSync(releaseDir, { recursive: true });
fs.mkdirSync(binDir, { recursive: true });
const targetDllPath = path.join(releaseDir, 'WebView2Loader.dll'); const targetDllPath = path.join(releaseDir, 'WebView2Loader.dll');
const binDllPath = path.join(binDir, 'WebView2Loader.dll');
const buildDir = path.join(__dirname, 'src-tauri', 'target', 'release', 'build'); if (fs.existsSync(rootDllPath) && fs.existsSync(targetDllPath)) {
if (fs.existsSync(buildDir)) { return Promise.resolve();
const entries = fs.readdirSync(buildDir);
for (const entry of entries) {
if (entry.startsWith('webview2-com-sys-')) {
const candidate = path.join(buildDir, entry, 'out', 'x64', 'WebView2Loader.dll');
if (fs.existsSync(candidate)) {
fs.copyFileSync(candidate, targetDllPath);
fs.copyFileSync(candidate, binDllPath);
return Promise.resolve();
}
}
}
} }
const AdmZip = require('adm-zip'); const AdmZip = require('adm-zip');
const tempNupkg = path.join(__dirname, 'temp-wv2.zip'); const tempNupkg = path.join(__dirname, 'temp-wv2.zip');
const nupkgUrl = 'https://www.nuget.org/api/v2/package/Microsoft.Web.WebView2/1.0.4129.50'; const nupkgUrl = 'https://www.nuget.org/api/v2/package/Microsoft.Web.WebView2/1.0.2903.40';
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fileStream = fs.createWriteStream(tempNupkg); const fileStream = fs.createWriteStream(tempNupkg);
@@ -281,12 +410,16 @@ function ensureWebView2Loader() {
try { try {
const zip = new AdmZip(tempNupkg); const zip = new AdmZip(tempNupkg);
const zipEntries = zip.getEntries(); const zipEntries = zip.getEntries();
const dllEntry = zipEntries.find(e => e.entryName.includes('x64/WebView2Loader.dll') || e.entryName.includes('x64\\WebView2Loader.dll')); const dllEntry = zipEntries.find(e =>
e.entryName.includes('x64/WebView2Loader.dll') ||
e.entryName.includes('x64\\WebView2Loader.dll')
);
if (dllEntry) { if (dllEntry) {
fs.writeFileSync(targetDllPath, dllEntry.getData()); const buffer = dllEntry.getData();
fs.writeFileSync(binDllPath, dllEntry.getData()); fs.writeFileSync(targetDllPath, buffer);
fs.writeFileSync(rootDllPath, buffer);
} }
fs.unlinkSync(tempNupkg); try { fs.unlinkSync(tempNupkg); } catch (_) { }
resolve(); resolve();
} catch (e) { } catch (e) {
try { fs.unlinkSync(tempNupkg); } catch (_) { } try { fs.unlinkSync(tempNupkg); } catch (_) { }

View File

@@ -21,8 +21,7 @@ class ServiceManager {
try { try {
const logPath = path.join(this.logsDir, `${name}.log`); const logPath = path.join(this.logsDir, `${name}.log`);
const timestamp = new Date().toISOString(); const timestamp = new Date().toISOString();
fs.appendFileSync(logPath, `[${timestamp}] ${line}\n`, 'utf8'); fs.appendFile(logPath, `[${timestamp}] ${line}\n`, 'utf8', () => { });
process.stdout.write(JSON.stringify({ event: "service-log", data: { service: name, message: line } }) + '\n'); process.stdout.write(JSON.stringify({ event: "service-log", data: { service: name, message: line } }) + '\n');
} catch (e) { } catch (e) {
} }
@@ -41,18 +40,25 @@ class ServiceManager {
} }
let tokenSecret = process.env.TOKEN_SECRET || let tokenSecret = process.env.TOKEN_SECRET ||
process.env.STREAM_API_TOKEN_SECRET || this.credentialManager.getCredential('player', 'TOKEN_SECRET');
this.credentialManager.getCredential('stream-api', 'TOKEN_SECRET');
if (!tokenSecret || tokenSecret.length < 32) { if (!tokenSecret || tokenSecret.length < 32) {
tokenSecret = require('crypto').randomBytes(32).toString('hex'); tokenSecret = require('crypto').randomBytes(32).toString('hex');
this.credentialManager.setCredential('stream-api', 'TOKEN_SECRET', tokenSecret); this.credentialManager.setCredential('player', 'TOKEN_SECRET', tokenSecret);
} }
const defaultPorts = {
player: 3000,
frontend: 4890
};
const env = { const env = {
...process.env, ...process.env,
...(process.platform === 'darwin'
? { PATH: [process.env.PATH, '/opt/homebrew/bin', '/usr/local/bin', '/usr/bin', '/bin'].filter(Boolean).join(path.delimiter) }
: {}),
PORT: (this.envConfig[name] && this.envConfig[name].PORT) || defaultPorts[name] || process.env.PORT || 3000,
TOKEN_SECRET: tokenSecret, TOKEN_SECRET: tokenSecret,
STREAM_API_TOKEN_SECRET: tokenSecret,
...(this.envConfig[name] || {}), ...(this.envConfig[name] || {}),
...(this.credentialManager.getServiceCredentials(name) || {}) ...(this.credentialManager.getServiceCredentials(name) || {})
}; };
@@ -111,7 +117,7 @@ class ServiceManager {
this.startService(name, relativeDir, startScript).catch(err => { this.startService(name, relativeDir, startScript).catch(err => {
this.logToFile(name, `Failed to restart: ${err.message}`); this.logToFile(name, `Failed to restart: ${err.message}`);
}); });
}, 3000); }, 1500);
} }
}); });
} }
@@ -122,7 +128,7 @@ class ServiceManager {
)); ));
} }
async stopAll() { stopAll() {
this.isStopping = true; this.isStopping = true;
for (const name of Object.keys(this.stableTimers)) { for (const name of Object.keys(this.stableTimers)) {
if (this.stableTimers[name]) { if (this.stableTimers[name]) {
@@ -130,20 +136,14 @@ class ServiceManager {
} }
} }
this.stableTimers = {}; this.stableTimers = {};
const killPromises = Object.keys(this.processes).map((name) => { for (const name of Object.keys(this.processes)) {
const procInfo = this.processes[name]; const procInfo = this.processes[name];
if (procInfo && procInfo.child) { if (procInfo && procInfo.child) {
this.logToFile(name, `Killing service`); try {
return new Promise((resolve) => { procInfo.child.kill('SIGTERM');
procInfo.child.removeAllListeners('exit'); } catch (e) { }
procInfo.child.on('exit', () => resolve());
procInfo.child.kill();
});
} }
return Promise.resolve(); }
});
await Promise.all(killPromises);
this.processes = {}; this.processes = {};
} }
@@ -175,10 +175,10 @@ class ServiceManager {
}); });
if (connected) return true; if (connected) return true;
await new Promise(r => setTimeout(r, 500)); await new Promise(r => setTimeout(r, 40));
} }
throw new Error(`Timeout waiting for port ${port}`); throw new Error(`Timeout waiting for port ${port}`);
} }
} }
module.exports = ServiceManager; module.exports = ServiceManager;

Binary file not shown.

Before

Width:  |  Height:  |  Size: 27 KiB

4911
src-tauri/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "vyla-home" name = "vyla-home"
version = "1.1.0" version = "1.1.62"
description = "Vyla Home Desktop App Launcher" description = "Vyla Home Desktop App Launcher"
edition = "2021" edition = "2021"
@@ -8,10 +8,26 @@ edition = "2021"
tauri-build = { version = "2", features = [] } tauri-build = { version = "2", features = [] }
[dependencies] [dependencies]
tauri = { version = "2", features = ["devtools"] } tauri = { version = "2", features = [] }
tauri-plugin-opener = "2" tauri-plugin-opener = "2"
tauri-plugin-process = "2"
tauri-plugin-shell = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
url = "2" window-vibrancy = "0.8"
[target.'cfg(target_os = "macos")'.dependencies]
objc2 = "0.5"
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[profile.release]
opt-level = 3
lto = true
codegen-units = 1
strip = true
panic = "abort"
[profile.dev]
opt-level = 0
debug = true
incremental = true

15
src-tauri/Info.plist Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsLocalNetworking</key>
<true/>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
</dict>
</dict>
</plist>

Binary file not shown.

View File

@@ -1,3 +1,58 @@
fn main() { fn main() {
tauri_build::build(); println!("cargo:rerun-if-changed=src/main.rs");
println!("cargo:rerun-if-changed=tauri.conf.json");
println!("cargo:rerun-if-changed=capabilities");
for f in [
"main.js",
"service-manager.js",
"file-updater.js",
"patcher.js",
"crypto-utils.js",
"credential-manager.js",
"update-client.js",
"discord-rpc.js",
] {
println!("cargo:rerun-if-changed=../{}", f);
}
println!("cargo:rerun-if-changed=../config");
if std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default() == "windows" {
if let (Ok(manifest_dir), Ok(out_dir)) = (std::env::var("CARGO_MANIFEST_DIR"), std::env::var("OUT_DIR")) {
let mut target_dir = std::path::PathBuf::from(out_dir);
target_dir.pop();
target_dir.pop();
target_dir.pop();
let dll_src = std::path::Path::new(&manifest_dir).join("WebView2Loader.dll");
let dll_dest = target_dir.join("WebView2Loader.dll");
if dll_src.exists() {
let _ = std::fs::copy(dll_src, dll_dest);
}
}
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let node_path = std::path::Path::new("../bin/node");
if node_path.exists() {
let _ = std::fs::set_permissions(
node_path,
std::fs::Permissions::from_mode(0o755),
);
}
}
tauri_build::try_build(
tauri_build::Attributes::new().app_manifest(
tauri_build::AppManifest::new().commands(&[
"win_minimize",
"win_maximize",
"win_close",
"win_drag",
"open_new_window",
"report_location",
]),
),
)
.expect("failed to run tauri-build");
} }

View File

@@ -1,40 +1,43 @@
{ {
"$schema": "../gen/schemas/desktop-schema.json", "$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default", "identifier": "default",
"description": "Default permissions for Vyla Home main window and popups", "description": "Window and opener permissions for local and localhost-served pages",
"local": true,
"windows": [ "windows": [
"main", "*"
"win_*" ],
"webviews": [
"*"
], ],
"remote": { "remote": {
"urls": [ "urls": [
"http://localhost:4890/*", "http://localhost:*",
"http://localhost:3001/*", "http://localhost:*/*",
"http://localhost:3000/*", "http://127.0.0.1:*",
"http://localhost:7860/*", "http://127.0.0.1:*/*"
"http://127.0.0.1:4890/*",
"http://127.0.0.1:3001/*",
"http://127.0.0.1:3000/*",
"http://127.0.0.1:7860/*"
] ]
}, },
"permissions": [ "permissions": [
"core:default",
"core:window:allow-minimize",
"core:window:allow-maximize",
"core:window:allow-unmaximize",
"core:window:allow-is-maximized",
"core:window:allow-close",
"core:window:allow-start-dragging",
"core:webview:allow-create-webview-window",
"core:webview:allow-print",
"shell:allow-open",
"process:allow-exit",
"core:app:default",
"allow-win-minimize", "allow-win-minimize",
"allow-win-maximize", "allow-win-maximize",
"allow-win-close", "allow-win-close",
"allow-win-drag", "allow-win-drag",
"allow-open-new-window" "allow-open-new-window",
"allow-report-location",
"core:default",
"core:window:allow-start-dragging",
"core:window:allow-minimize",
"core:window:allow-maximize",
"core:window:allow-unmaximize",
"core:window:allow-toggle-maximize",
"core:window:allow-close",
"core:window:allow-destroy",
"core:window:allow-is-maximized",
"core:window:allow-is-fullscreen",
"core:window:allow-set-fullscreen",
"core:window:allow-set-focus",
"core:window:allow-show",
"core:window:allow-hide",
"opener:default"
] ]
} }

File diff suppressed because one or more lines are too long

View File

@@ -1 +1 @@
{"default":{"identifier":"default","description":"Default permissions for Vyla Home main window and popups","remote":{"urls":["http://localhost:4890/*","http://localhost:3001/*","http://localhost:3000/*","http://localhost:7860/*","http://127.0.0.1:4890/*","http://127.0.0.1:3001/*","http://127.0.0.1:3000/*","http://127.0.0.1:7860/*"]},"local":true,"windows":["main","win_*"],"permissions":["core:default","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-is-maximized","core:window:allow-close","core:window:allow-start-dragging","core:webview:allow-create-webview-window","core:webview:allow-print","shell:allow-open","process:allow-exit","core:app:default","allow-win-minimize","allow-win-maximize","allow-win-close","allow-win-drag","allow-open-new-window"]}} {"default":{"identifier":"default","description":"Window and opener permissions for local and localhost-served pages","remote":{"urls":["http://localhost:*","http://localhost:*/*","http://127.0.0.1:*","http://127.0.0.1:*/*"]},"local":true,"windows":["*"],"webviews":["*"],"permissions":["allow-win-minimize","allow-win-maximize","allow-win-close","allow-win-drag","allow-open-new-window","allow-report-location","core:default","core:window:allow-start-dragging","core:window:allow-minimize","core:window:allow-maximize","core:window:allow-unmaximize","core:window:allow-toggle-maximize","core:window:allow-close","core:window:allow-destroy","core:window:allow-is-maximized","core:window:allow-is-fullscreen","core:window:allow-set-fullscreen","core:window:allow-set-focus","core:window:allow-show","core:window:allow-hide","opener:default"]}}

View File

@@ -302,216 +302,6 @@
} }
} }
}, },
{
"if": {
"properties": {
"identifier": {
"anyOf": [
{
"description": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`",
"type": "string",
"const": "shell:default",
"markdownDescription": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`"
},
{
"description": "Enables the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-execute",
"markdownDescription": "Enables the execute command without any pre-configured scope."
},
{
"description": "Enables the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-kill",
"markdownDescription": "Enables the kill command without any pre-configured scope."
},
{
"description": "Enables the open command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-open",
"markdownDescription": "Enables the open command without any pre-configured scope."
},
{
"description": "Enables the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-spawn",
"markdownDescription": "Enables the spawn command without any pre-configured scope."
},
{
"description": "Enables the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-stdin-write",
"markdownDescription": "Enables the stdin_write command without any pre-configured scope."
},
{
"description": "Denies the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-execute",
"markdownDescription": "Denies the execute command without any pre-configured scope."
},
{
"description": "Denies the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-kill",
"markdownDescription": "Denies the kill command without any pre-configured scope."
},
{
"description": "Denies the open command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-open",
"markdownDescription": "Denies the open command without any pre-configured scope."
},
{
"description": "Denies the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-spawn",
"markdownDescription": "Denies the spawn command without any pre-configured scope."
},
{
"description": "Denies the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-stdin-write",
"markdownDescription": "Denies the stdin_write command without any pre-configured scope."
}
]
}
}
},
"then": {
"properties": {
"allow": {
"items": {
"title": "ShellScopeEntry",
"description": "Shell scope entry.",
"anyOf": [
{
"type": "object",
"required": [
"cmd",
"name"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"cmd": {
"description": "The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.",
"type": "string"
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"name",
"sidecar"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
},
"sidecar": {
"description": "If this command is a sidecar command.",
"type": "boolean"
}
},
"additionalProperties": false
}
]
}
},
"deny": {
"items": {
"title": "ShellScopeEntry",
"description": "Shell scope entry.",
"anyOf": [
{
"type": "object",
"required": [
"cmd",
"name"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"cmd": {
"description": "The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.",
"type": "string"
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"name",
"sidecar"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
},
"sidecar": {
"description": "If this command is a sidecar command.",
"type": "boolean"
}
},
"additionalProperties": false
}
]
}
}
}
},
"properties": {
"identifier": {
"description": "Identifier of the permission or permission set.",
"allOf": [
{
"$ref": "#/definitions/Identifier"
}
]
}
}
},
{ {
"properties": { "properties": {
"identifier": { "identifier": {
@@ -555,10 +345,10 @@
"description": "Permission identifier", "description": "Permission identifier",
"oneOf": [ "oneOf": [
{ {
"description": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`", "description": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`\n- `allow-report-location`",
"type": "string", "type": "string",
"const": "default", "const": "default",
"markdownDescription": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`" "markdownDescription": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`\n- `allow-report-location`"
}, },
{ {
"description": "Allows opening a new webview window", "description": "Allows opening a new webview window",
@@ -566,6 +356,12 @@
"const": "allow-open-new-window", "const": "allow-open-new-window",
"markdownDescription": "Allows opening a new webview window" "markdownDescription": "Allows opening a new webview window"
}, },
{
"description": "Allows reporting the current page to the backend",
"type": "string",
"const": "allow-report-location",
"markdownDescription": "Allows reporting the current page to the backend"
},
{ {
"description": "Allows closing the window", "description": "Allows closing the window",
"type": "string", "type": "string",
@@ -590,6 +386,42 @@
"const": "allow-win-minimize", "const": "allow-win-minimize",
"markdownDescription": "Allows minimizing the window" "markdownDescription": "Allows minimizing the window"
}, },
{
"description": "Denies the open_new_window command without any pre-configured scope.",
"type": "string",
"const": "deny-open-new-window",
"markdownDescription": "Denies the open_new_window command without any pre-configured scope."
},
{
"description": "Denies the report_location command without any pre-configured scope.",
"type": "string",
"const": "deny-report-location",
"markdownDescription": "Denies the report_location command without any pre-configured scope."
},
{
"description": "Denies the win_close command without any pre-configured scope.",
"type": "string",
"const": "deny-win-close",
"markdownDescription": "Denies the win_close command without any pre-configured scope."
},
{
"description": "Denies the win_drag command without any pre-configured scope.",
"type": "string",
"const": "deny-win-drag",
"markdownDescription": "Denies the win_drag command without any pre-configured scope."
},
{
"description": "Denies the win_maximize command without any pre-configured scope.",
"type": "string",
"const": "deny-win-maximize",
"markdownDescription": "Denies the win_maximize command without any pre-configured scope."
},
{
"description": "Denies the win_minimize command without any pre-configured scope.",
"type": "string",
"const": "deny-win-minimize",
"markdownDescription": "Denies the win_minimize command without any pre-configured scope."
},
{ {
"description": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`", "description": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`",
"type": "string", "type": "string",
@@ -626,6 +458,12 @@
"const": "core:app:allow-default-window-icon", "const": "core:app:allow-default-window-icon",
"markdownDescription": "Enables the default_window_icon command without any pre-configured scope." "markdownDescription": "Enables the default_window_icon command without any pre-configured scope."
}, },
{
"description": "Enables the exit command without any pre-configured scope.",
"type": "string",
"const": "core:app:allow-exit",
"markdownDescription": "Enables the exit command without any pre-configured scope."
},
{ {
"description": "Enables the fetch_data_store_identifiers command without any pre-configured scope.", "description": "Enables the fetch_data_store_identifiers command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -716,6 +554,12 @@
"const": "core:app:deny-default-window-icon", "const": "core:app:deny-default-window-icon",
"markdownDescription": "Denies the default_window_icon command without any pre-configured scope." "markdownDescription": "Denies the default_window_icon command without any pre-configured scope."
}, },
{
"description": "Denies the exit command without any pre-configured scope.",
"type": "string",
"const": "core:app:deny-exit",
"markdownDescription": "Denies the exit command without any pre-configured scope."
},
{ {
"description": "Denies the fetch_data_store_identifiers command without any pre-configured scope.", "description": "Denies the fetch_data_store_identifiers command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -1976,6 +1820,12 @@
"const": "core:window:allow-set-fullscreen", "const": "core:window:allow-set-fullscreen",
"markdownDescription": "Enables the set_fullscreen command without any pre-configured scope." "markdownDescription": "Enables the set_fullscreen command without any pre-configured scope."
}, },
{
"description": "Enables the set_fullscreen_on_monitor command without any pre-configured scope.",
"type": "string",
"const": "core:window:allow-set-fullscreen-on-monitor",
"markdownDescription": "Enables the set_fullscreen_on_monitor command without any pre-configured scope."
},
{ {
"description": "Enables the set_icon command without any pre-configured scope.", "description": "Enables the set_icon command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -2444,6 +2294,12 @@
"const": "core:window:deny-set-fullscreen", "const": "core:window:deny-set-fullscreen",
"markdownDescription": "Denies the set_fullscreen command without any pre-configured scope." "markdownDescription": "Denies the set_fullscreen command without any pre-configured scope."
}, },
{
"description": "Denies the set_fullscreen_on_monitor command without any pre-configured scope.",
"type": "string",
"const": "core:window:deny-set-fullscreen-on-monitor",
"markdownDescription": "Denies the set_fullscreen_on_monitor command without any pre-configured scope."
},
{ {
"description": "Denies the set_icon command without any pre-configured scope.", "description": "Denies the set_icon command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -2653,102 +2509,6 @@
"type": "string", "type": "string",
"const": "opener:deny-reveal-item-in-dir", "const": "opener:deny-reveal-item-in-dir",
"markdownDescription": "Denies the reveal_item_in_dir command without any pre-configured scope." "markdownDescription": "Denies the reveal_item_in_dir command without any pre-configured scope."
},
{
"description": "This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n\n#### This default permission set includes:\n\n- `allow-exit`\n- `allow-restart`",
"type": "string",
"const": "process:default",
"markdownDescription": "This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n\n#### This default permission set includes:\n\n- `allow-exit`\n- `allow-restart`"
},
{
"description": "Enables the exit command without any pre-configured scope.",
"type": "string",
"const": "process:allow-exit",
"markdownDescription": "Enables the exit command without any pre-configured scope."
},
{
"description": "Enables the restart command without any pre-configured scope.",
"type": "string",
"const": "process:allow-restart",
"markdownDescription": "Enables the restart command without any pre-configured scope."
},
{
"description": "Denies the exit command without any pre-configured scope.",
"type": "string",
"const": "process:deny-exit",
"markdownDescription": "Denies the exit command without any pre-configured scope."
},
{
"description": "Denies the restart command without any pre-configured scope.",
"type": "string",
"const": "process:deny-restart",
"markdownDescription": "Denies the restart command without any pre-configured scope."
},
{
"description": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`",
"type": "string",
"const": "shell:default",
"markdownDescription": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`"
},
{
"description": "Enables the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-execute",
"markdownDescription": "Enables the execute command without any pre-configured scope."
},
{
"description": "Enables the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-kill",
"markdownDescription": "Enables the kill command without any pre-configured scope."
},
{
"description": "Enables the open command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-open",
"markdownDescription": "Enables the open command without any pre-configured scope."
},
{
"description": "Enables the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-spawn",
"markdownDescription": "Enables the spawn command without any pre-configured scope."
},
{
"description": "Enables the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-stdin-write",
"markdownDescription": "Enables the stdin_write command without any pre-configured scope."
},
{
"description": "Denies the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-execute",
"markdownDescription": "Denies the execute command without any pre-configured scope."
},
{
"description": "Denies the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-kill",
"markdownDescription": "Denies the kill command without any pre-configured scope."
},
{
"description": "Denies the open command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-open",
"markdownDescription": "Denies the open command without any pre-configured scope."
},
{
"description": "Denies the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-spawn",
"markdownDescription": "Denies the spawn command without any pre-configured scope."
},
{
"description": "Denies the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-stdin-write",
"markdownDescription": "Denies the stdin_write command without any pre-configured scope."
} }
] ]
}, },
@@ -2862,50 +2622,6 @@
"type": "string" "type": "string"
} }
] ]
},
"ShellScopeEntryAllowedArg": {
"description": "A command argument allowed to be executed by the webview API.",
"anyOf": [
{
"description": "A non-configurable argument that is passed to the command in the order it was specified.",
"type": "string"
},
{
"description": "A variable that is set while calling the command from the webview API.",
"type": "object",
"required": [
"validator"
],
"properties": {
"raw": {
"description": "Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.",
"default": false,
"type": "boolean"
},
"validator": {
"description": "[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: <https://docs.rs/regex/latest/regex/#syntax>",
"type": "string"
}
},
"additionalProperties": false
}
]
},
"ShellScopeEntryAllowedArgs": {
"description": "A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration.",
"anyOf": [
{
"description": "Use a simple boolean to allow all or disable all arguments to this command configuration.",
"type": "boolean"
},
{
"description": "A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.",
"type": "array",
"items": {
"$ref": "#/definitions/ShellScopeEntryAllowedArg"
}
}
]
} }
} }
} }

View File

@@ -302,216 +302,6 @@
} }
} }
}, },
{
"if": {
"properties": {
"identifier": {
"anyOf": [
{
"description": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`",
"type": "string",
"const": "shell:default",
"markdownDescription": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`"
},
{
"description": "Enables the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-execute",
"markdownDescription": "Enables the execute command without any pre-configured scope."
},
{
"description": "Enables the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-kill",
"markdownDescription": "Enables the kill command without any pre-configured scope."
},
{
"description": "Enables the open command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-open",
"markdownDescription": "Enables the open command without any pre-configured scope."
},
{
"description": "Enables the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-spawn",
"markdownDescription": "Enables the spawn command without any pre-configured scope."
},
{
"description": "Enables the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-stdin-write",
"markdownDescription": "Enables the stdin_write command without any pre-configured scope."
},
{
"description": "Denies the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-execute",
"markdownDescription": "Denies the execute command without any pre-configured scope."
},
{
"description": "Denies the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-kill",
"markdownDescription": "Denies the kill command without any pre-configured scope."
},
{
"description": "Denies the open command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-open",
"markdownDescription": "Denies the open command without any pre-configured scope."
},
{
"description": "Denies the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-spawn",
"markdownDescription": "Denies the spawn command without any pre-configured scope."
},
{
"description": "Denies the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-stdin-write",
"markdownDescription": "Denies the stdin_write command without any pre-configured scope."
}
]
}
}
},
"then": {
"properties": {
"allow": {
"items": {
"title": "ShellScopeEntry",
"description": "Shell scope entry.",
"anyOf": [
{
"type": "object",
"required": [
"cmd",
"name"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"cmd": {
"description": "The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.",
"type": "string"
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"name",
"sidecar"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
},
"sidecar": {
"description": "If this command is a sidecar command.",
"type": "boolean"
}
},
"additionalProperties": false
}
]
}
},
"deny": {
"items": {
"title": "ShellScopeEntry",
"description": "Shell scope entry.",
"anyOf": [
{
"type": "object",
"required": [
"cmd",
"name"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"cmd": {
"description": "The command name. It can start with a variable that resolves to a system base directory. The variables are: `$AUDIO`, `$CACHE`, `$CONFIG`, `$DATA`, `$LOCALDATA`, `$DESKTOP`, `$DOCUMENT`, `$DOWNLOAD`, `$EXE`, `$FONT`, `$HOME`, `$PICTURE`, `$PUBLIC`, `$RUNTIME`, `$TEMPLATE`, `$VIDEO`, `$RESOURCE`, `$LOG`, `$TEMP`, `$APPCONFIG`, `$APPDATA`, `$APPLOCALDATA`, `$APPCACHE`, `$APPLOG`.",
"type": "string"
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
}
},
"additionalProperties": false
},
{
"type": "object",
"required": [
"name",
"sidecar"
],
"properties": {
"args": {
"description": "The allowed arguments for the command execution.",
"allOf": [
{
"$ref": "#/definitions/ShellScopeEntryAllowedArgs"
}
]
},
"name": {
"description": "The name for this allowed shell command configuration.\n\nThis name will be used inside of the webview API to call this command along with any specified arguments.",
"type": "string"
},
"sidecar": {
"description": "If this command is a sidecar command.",
"type": "boolean"
}
},
"additionalProperties": false
}
]
}
}
}
},
"properties": {
"identifier": {
"description": "Identifier of the permission or permission set.",
"allOf": [
{
"$ref": "#/definitions/Identifier"
}
]
}
}
},
{ {
"properties": { "properties": {
"identifier": { "identifier": {
@@ -555,10 +345,10 @@
"description": "Permission identifier", "description": "Permission identifier",
"oneOf": [ "oneOf": [
{ {
"description": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`", "description": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`\n- `allow-report-location`",
"type": "string", "type": "string",
"const": "default", "const": "default",
"markdownDescription": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`" "markdownDescription": "Default permissions for Vyla Home app commands\n#### This permission set includes:\n\n- `allow-win-minimize`\n- `allow-win-maximize`\n- `allow-win-close`\n- `allow-win-drag`\n- `allow-open-new-window`\n- `allow-report-location`"
}, },
{ {
"description": "Allows opening a new webview window", "description": "Allows opening a new webview window",
@@ -566,6 +356,12 @@
"const": "allow-open-new-window", "const": "allow-open-new-window",
"markdownDescription": "Allows opening a new webview window" "markdownDescription": "Allows opening a new webview window"
}, },
{
"description": "Allows reporting the current page to the backend",
"type": "string",
"const": "allow-report-location",
"markdownDescription": "Allows reporting the current page to the backend"
},
{ {
"description": "Allows closing the window", "description": "Allows closing the window",
"type": "string", "type": "string",
@@ -590,6 +386,42 @@
"const": "allow-win-minimize", "const": "allow-win-minimize",
"markdownDescription": "Allows minimizing the window" "markdownDescription": "Allows minimizing the window"
}, },
{
"description": "Denies the open_new_window command without any pre-configured scope.",
"type": "string",
"const": "deny-open-new-window",
"markdownDescription": "Denies the open_new_window command without any pre-configured scope."
},
{
"description": "Denies the report_location command without any pre-configured scope.",
"type": "string",
"const": "deny-report-location",
"markdownDescription": "Denies the report_location command without any pre-configured scope."
},
{
"description": "Denies the win_close command without any pre-configured scope.",
"type": "string",
"const": "deny-win-close",
"markdownDescription": "Denies the win_close command without any pre-configured scope."
},
{
"description": "Denies the win_drag command without any pre-configured scope.",
"type": "string",
"const": "deny-win-drag",
"markdownDescription": "Denies the win_drag command without any pre-configured scope."
},
{
"description": "Denies the win_maximize command without any pre-configured scope.",
"type": "string",
"const": "deny-win-maximize",
"markdownDescription": "Denies the win_maximize command without any pre-configured scope."
},
{
"description": "Denies the win_minimize command without any pre-configured scope.",
"type": "string",
"const": "deny-win-minimize",
"markdownDescription": "Denies the win_minimize command without any pre-configured scope."
},
{ {
"description": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`", "description": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`",
"type": "string", "type": "string",
@@ -626,6 +458,12 @@
"const": "core:app:allow-default-window-icon", "const": "core:app:allow-default-window-icon",
"markdownDescription": "Enables the default_window_icon command without any pre-configured scope." "markdownDescription": "Enables the default_window_icon command without any pre-configured scope."
}, },
{
"description": "Enables the exit command without any pre-configured scope.",
"type": "string",
"const": "core:app:allow-exit",
"markdownDescription": "Enables the exit command without any pre-configured scope."
},
{ {
"description": "Enables the fetch_data_store_identifiers command without any pre-configured scope.", "description": "Enables the fetch_data_store_identifiers command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -716,6 +554,12 @@
"const": "core:app:deny-default-window-icon", "const": "core:app:deny-default-window-icon",
"markdownDescription": "Denies the default_window_icon command without any pre-configured scope." "markdownDescription": "Denies the default_window_icon command without any pre-configured scope."
}, },
{
"description": "Denies the exit command without any pre-configured scope.",
"type": "string",
"const": "core:app:deny-exit",
"markdownDescription": "Denies the exit command without any pre-configured scope."
},
{ {
"description": "Denies the fetch_data_store_identifiers command without any pre-configured scope.", "description": "Denies the fetch_data_store_identifiers command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -1976,6 +1820,12 @@
"const": "core:window:allow-set-fullscreen", "const": "core:window:allow-set-fullscreen",
"markdownDescription": "Enables the set_fullscreen command without any pre-configured scope." "markdownDescription": "Enables the set_fullscreen command without any pre-configured scope."
}, },
{
"description": "Enables the set_fullscreen_on_monitor command without any pre-configured scope.",
"type": "string",
"const": "core:window:allow-set-fullscreen-on-monitor",
"markdownDescription": "Enables the set_fullscreen_on_monitor command without any pre-configured scope."
},
{ {
"description": "Enables the set_icon command without any pre-configured scope.", "description": "Enables the set_icon command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -2444,6 +2294,12 @@
"const": "core:window:deny-set-fullscreen", "const": "core:window:deny-set-fullscreen",
"markdownDescription": "Denies the set_fullscreen command without any pre-configured scope." "markdownDescription": "Denies the set_fullscreen command without any pre-configured scope."
}, },
{
"description": "Denies the set_fullscreen_on_monitor command without any pre-configured scope.",
"type": "string",
"const": "core:window:deny-set-fullscreen-on-monitor",
"markdownDescription": "Denies the set_fullscreen_on_monitor command without any pre-configured scope."
},
{ {
"description": "Denies the set_icon command without any pre-configured scope.", "description": "Denies the set_icon command without any pre-configured scope.",
"type": "string", "type": "string",
@@ -2653,102 +2509,6 @@
"type": "string", "type": "string",
"const": "opener:deny-reveal-item-in-dir", "const": "opener:deny-reveal-item-in-dir",
"markdownDescription": "Denies the reveal_item_in_dir command without any pre-configured scope." "markdownDescription": "Denies the reveal_item_in_dir command without any pre-configured scope."
},
{
"description": "This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n\n#### This default permission set includes:\n\n- `allow-exit`\n- `allow-restart`",
"type": "string",
"const": "process:default",
"markdownDescription": "This permission set configures which\nprocess features are by default exposed.\n\n#### Granted Permissions\n\nThis enables to quit via `allow-exit` and restart via `allow-restart`\nthe application.\n\n#### This default permission set includes:\n\n- `allow-exit`\n- `allow-restart`"
},
{
"description": "Enables the exit command without any pre-configured scope.",
"type": "string",
"const": "process:allow-exit",
"markdownDescription": "Enables the exit command without any pre-configured scope."
},
{
"description": "Enables the restart command without any pre-configured scope.",
"type": "string",
"const": "process:allow-restart",
"markdownDescription": "Enables the restart command without any pre-configured scope."
},
{
"description": "Denies the exit command without any pre-configured scope.",
"type": "string",
"const": "process:deny-exit",
"markdownDescription": "Denies the exit command without any pre-configured scope."
},
{
"description": "Denies the restart command without any pre-configured scope.",
"type": "string",
"const": "process:deny-restart",
"markdownDescription": "Denies the restart command without any pre-configured scope."
},
{
"description": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`",
"type": "string",
"const": "shell:default",
"markdownDescription": "This permission set configures which\nshell functionality is exposed by default.\n\n#### Granted Permissions\n\nIt allows to use the `open` functionality with a reasonable\nscope pre-configured. It will allow opening `http(s)://`,\n`tel:` and `mailto:` links.\n\n#### This default permission set includes:\n\n- `allow-open`"
},
{
"description": "Enables the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-execute",
"markdownDescription": "Enables the execute command without any pre-configured scope."
},
{
"description": "Enables the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-kill",
"markdownDescription": "Enables the kill command without any pre-configured scope."
},
{
"description": "Enables the open command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-open",
"markdownDescription": "Enables the open command without any pre-configured scope."
},
{
"description": "Enables the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-spawn",
"markdownDescription": "Enables the spawn command without any pre-configured scope."
},
{
"description": "Enables the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:allow-stdin-write",
"markdownDescription": "Enables the stdin_write command without any pre-configured scope."
},
{
"description": "Denies the execute command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-execute",
"markdownDescription": "Denies the execute command without any pre-configured scope."
},
{
"description": "Denies the kill command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-kill",
"markdownDescription": "Denies the kill command without any pre-configured scope."
},
{
"description": "Denies the open command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-open",
"markdownDescription": "Denies the open command without any pre-configured scope."
},
{
"description": "Denies the spawn command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-spawn",
"markdownDescription": "Denies the spawn command without any pre-configured scope."
},
{
"description": "Denies the stdin_write command without any pre-configured scope.",
"type": "string",
"const": "shell:deny-stdin-write",
"markdownDescription": "Denies the stdin_write command without any pre-configured scope."
} }
] ]
}, },
@@ -2862,50 +2622,6 @@
"type": "string" "type": "string"
} }
] ]
},
"ShellScopeEntryAllowedArg": {
"description": "A command argument allowed to be executed by the webview API.",
"anyOf": [
{
"description": "A non-configurable argument that is passed to the command in the order it was specified.",
"type": "string"
},
{
"description": "A variable that is set while calling the command from the webview API.",
"type": "object",
"required": [
"validator"
],
"properties": {
"raw": {
"description": "Marks the validator as a raw regex, meaning the plugin should not make any modification at runtime.\n\nThis means the regex will not match on the entire string by default, which might be exploited if your regex allow unexpected input to be considered valid. When using this option, make sure your regex is correct.",
"default": false,
"type": "boolean"
},
"validator": {
"description": "[regex] validator to require passed values to conform to an expected input.\n\nThis will require the argument value passed to this variable to match the `validator` regex before it will be executed.\n\nThe regex string is by default surrounded by `^...$` to match the full string. For example the `https?://\\w+` regex would be registered as `^https?://\\w+$`.\n\n[regex]: <https://docs.rs/regex/latest/regex/#syntax>",
"type": "string"
}
},
"additionalProperties": false
}
]
},
"ShellScopeEntryAllowedArgs": {
"description": "A set of command arguments allowed to be executed by the webview API.\n\nA value of `true` will allow any arguments to be passed to the command. `false` will disable all arguments. A list of [`ShellScopeEntryAllowedArg`] will set those arguments as the only valid arguments to be passed to the attached command configuration.",
"anyOf": [
{
"description": "Use a simple boolean to allow all or disable all arguments to this command configuration.",
"type": "boolean"
},
{
"description": "A specific set of [`ShellScopeEntryAllowedArg`] that are valid to call for the command configuration.",
"type": "array",
"items": {
"$ref": "#/definitions/ShellScopeEntryAllowedArg"
}
}
]
} }
} }
} }

View File

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-open-new-window"
description = "Enables the open_new_window command without any pre-configured scope."
commands.allow = ["open_new_window"]
[[permission]]
identifier = "deny-open-new-window"
description = "Denies the open_new_window command without any pre-configured scope."
commands.deny = ["open_new_window"]

View File

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-report-location"
description = "Enables the report_location command without any pre-configured scope."
commands.allow = ["report_location"]
[[permission]]
identifier = "deny-report-location"
description = "Denies the report_location command without any pre-configured scope."
commands.deny = ["report_location"]

View File

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-win-close"
description = "Enables the win_close command without any pre-configured scope."
commands.allow = ["win_close"]
[[permission]]
identifier = "deny-win-close"
description = "Denies the win_close command without any pre-configured scope."
commands.deny = ["win_close"]

View File

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-win-drag"
description = "Enables the win_drag command without any pre-configured scope."
commands.allow = ["win_drag"]
[[permission]]
identifier = "deny-win-drag"
description = "Denies the win_drag command without any pre-configured scope."
commands.deny = ["win_drag"]

View File

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-win-maximize"
description = "Enables the win_maximize command without any pre-configured scope."
commands.allow = ["win_maximize"]
[[permission]]
identifier = "deny-win-maximize"
description = "Denies the win_maximize command without any pre-configured scope."
commands.deny = ["win_maximize"]

View File

@@ -0,0 +1,11 @@
# Automatically generated - DO NOT EDIT!
[[permission]]
identifier = "allow-win-minimize"
description = "Enables the win_minimize command without any pre-configured scope."
commands.allow = ["win_minimize"]
[[permission]]
identifier = "deny-win-minimize"
description = "Denies the win_minimize command without any pre-configured scope."
commands.deny = ["win_minimize"]

View File

@@ -3,27 +3,38 @@
[[permission]] [[permission]]
identifier = "allow-win-minimize" identifier = "allow-win-minimize"
description = "Allows minimizing the window" description = "Allows minimizing the window"
commands.allow = ["win_minimize"] [[permission.allow]]
cmd = "win_minimize"
[[permission]] [[permission]]
identifier = "allow-win-maximize" identifier = "allow-win-maximize"
description = "Allows maximizing/unmaximizing the window" description = "Allows maximizing/unmaximizing the window"
commands.allow = ["win_maximize"] [[permission.allow]]
cmd = "win_maximize"
[[permission]] [[permission]]
identifier = "allow-win-close" identifier = "allow-win-close"
description = "Allows closing the window" description = "Allows closing the window"
commands.allow = ["win_close"] [[permission.allow]]
cmd = "win_close"
[[permission]] [[permission]]
identifier = "allow-win-drag" identifier = "allow-win-drag"
description = "Allows dragging the window" description = "Allows dragging the window"
commands.allow = ["win_drag"] [[permission.allow]]
cmd = "win_drag"
[[permission]] [[permission]]
identifier = "allow-open-new-window" identifier = "allow-open-new-window"
description = "Allows opening a new webview window" description = "Allows opening a new webview window"
commands.allow = ["open_new_window"] [[permission.allow]]
cmd = "open_new_window"
[[permission]]
identifier = "allow-report-location"
description = "Allows reporting the current page to the backend"
[[permission.allow]]
cmd = "report_location"
[[set]] [[set]]
identifier = "default" identifier = "default"
@@ -33,5 +44,6 @@ permissions = [
"allow-win-maximize", "allow-win-maximize",
"allow-win-close", "allow-win-close",
"allow-win-drag", "allow-win-drag",
"allow-open-new-window" "allow-open-new-window",
"allow-report-location"
] ]

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
{ {
"$schema": "https://schema.tauri.app/config/2", "$schema": "https://schema.tauri.app/config/2",
"productName": "Vyla Home", "productName": "Vyla Home",
"version": "1.1.0", "version": "1.1.62",
"identifier": "com.vyla.home", "identifier": "com.vyla.home",
"build": { "build": {
"frontendDist": "../ui" "frontendDist": "../ui"
@@ -9,7 +9,7 @@
"app": { "app": {
"withGlobalTauri": true, "withGlobalTauri": true,
"security": { "security": {
"csp": null "csp": "default-src 'self' http://localhost:* http://127.0.0.1:*; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://localhost:* http://127.0.0.1:*; style-src 'self' 'unsafe-inline' http://localhost:* http://127.0.0.1:*; img-src 'self' data: blob: https: http://localhost:* http://127.0.0.1:*; font-src 'self' data: http://localhost:* http://127.0.0.1:*; connect-src 'self' ipc: http://ipc.localhost http://localhost:* http://127.0.0.1:* ws://localhost:* ws://127.0.0.1:*"
} }
}, },
"bundle": { "bundle": {
@@ -22,21 +22,28 @@
"icons/icon.icns", "icons/icon.icns",
"icons/icon.ico" "icons/icon.ico"
], ],
"macOS": {
"exceptionDomain": "localhost",
"infoPlist": "Info.plist"
},
"windows": { "windows": {
"webviewInstallMode": { "webviewInstallMode": {
"type": "downloadBootstrapper" "type": "downloadBootstrapper"
} }
}, },
"resources": [ "resources": [
"../bin/*", "WebView2Loader.dll",
"../bin/**/*",
"../main.js", "../main.js",
"../service-manager.js", "../service-manager.js",
"../file-updater.js",
"../patcher.js", "../patcher.js",
"../crypto-utils.js", "../crypto-utils.js",
"../credential-manager.js", "../credential-manager.js",
"../update-client.js", "../update-client.js",
"../discord-rpc.js",
"../config/**/*", "../config/**/*",
"../node_modules/**/*" "../node_modules/**/*"
] ]
} }
} }

File diff suppressed because it is too large Load Diff

BIN
ui/white_favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 223 KiB

View File

@@ -1,5 +1,14 @@
const https = require('https'); const https = require('https');
const fs = require('fs'); const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const UPDATE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAKIuPPzTCGdTksi7hp+V4urau6mMQt2XhNlEfRVbjNZ4=
-----END PUBLIC KEY-----`;
const MIN_CHECK_INTERVAL_MS = 15 * 60 * 1000;
const MAX_RETRY_AFTER_MS = 120000;
const MAX_BACKOFF_MS = 6 * 60 * 60 * 1000;
const GITLAB_GROUP = 'vyla-entertainment'; const GITLAB_GROUP = 'vyla-entertainment';
const GITLAB_REPO = 'home'; const GITLAB_REPO = 'home';
@@ -10,6 +19,8 @@ const ALLOWED_REDIRECT_HOSTS = [
'storage.googleapis.com' 'storage.googleapis.com'
]; ];
const httpsAgent = new https.Agent({ keepAlive: true, maxSockets: 32 });
function isAllowedHost(url) { function isAllowedHost(url) {
try { try {
const hostname = new URL(url).hostname; const hostname = new URL(url).hostname;
@@ -23,42 +34,117 @@ function isAllowedHost(url) {
} }
} }
function normalizeTag(v) {
return String(v || '').replace(/^v/, '').trim();
}
function canonicalManifest(manifest) {
const parts = Object.keys(manifest.components || {}).sort().map((name) => {
const c = manifest.components[name];
return `${name}:${c.file}:${c.sha256}:${c.id}:${c.size}`;
});
const lines = ['vyla-manifest-v2', normalizeTag(manifest.version), manifest.sha256, ...parts];
if (manifest.installer) {
const i = manifest.installer;
lines.push(`installer:${i.file}:${i.sha256}:${i.size}:${normalizeTag(i.version)}`);
}
return lines.join('\n');
}
function verifyManifest(manifest) {
if (!manifest || typeof manifest.signature !== 'string' || !manifest.components) return false;
try {
return crypto.verify(null, Buffer.from(canonicalManifest(manifest)), UPDATE_PUBLIC_KEY, Buffer.from(manifest.signature, 'base64'));
} catch (e) {
return false;
}
}
class UpdateClient { class UpdateClient {
constructor(appDataPath, token = null) { constructor(appDataPath, token = null) {
this.appDataPath = appDataPath; this.appDataPath = appDataPath;
this.token = token || process.env.GITLAB_TOKEN || process.env.VYLA_GITLAB_TOKEN || null; this.token = token || process.env.GITLAB_TOKEN || process.env.VYLA_GITLAB_TOKEN || null;
} }
fetchJson(url) { cachePath() {
return path.join(this.appDataPath, 'update-cache.json');
}
readCache() {
try {
return JSON.parse(fs.readFileSync(this.cachePath(), 'utf8'));
} catch (e) {
return {};
}
}
writeCache(patch) {
try {
fs.mkdirSync(this.appDataPath, { recursive: true });
fs.writeFileSync(this.cachePath(), JSON.stringify({ ...this.readCache(), ...patch }), 'utf8');
} catch (e) { }
}
recordFailure() {
const failures = (this.readCache().failures || 0) + 1;
const delay = Math.min(5 * 60 * 1000 * 2 ** (failures - 1), MAX_BACKOFF_MS);
this.writeCache({ failures, blockedUntil: Date.now() + delay });
}
recordSuccess() {
this.writeCache({ failures: 0, blockedUntil: 0 });
}
cacheUsable(release) {
return !!release && !!release.components && verifyManifest(release.manifest);
}
fetchJson(url, etag = null, attempt = 0) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const urlObj = new URL(url); const urlObj = new URL(url);
const headers = { const headers = {
'User-Agent': 'VylaHome-Client', 'User-Agent': 'VylaHome-Client',
'Accept': 'application/json' 'Accept': 'application/json',
'Cache-Control': 'no-cache'
}; };
if (this.token) { if (this.token) {
headers['PRIVATE-TOKEN'] = this.token; headers['PRIVATE-TOKEN'] = this.token;
} }
if (etag) {
headers['If-None-Match'] = etag;
}
const requestOptions = { const requestOptions = {
hostname: urlObj.hostname, hostname: urlObj.hostname,
port: 443, port: 443,
path: urlObj.pathname + urlObj.search, path: urlObj.pathname + urlObj.search,
method: 'GET', method: 'GET',
headers headers,
agent: httpsAgent
}; };
const req = https.request(requestOptions, (res) => { const req = https.request(requestOptions, (res) => {
let data = ''; let data = '';
res.on('data', (chunk) => { data += chunk; }); res.on('data', (chunk) => { data += chunk; });
res.on('end', () => { res.on('end', () => {
if (res.statusCode === 304) {
resolve({ notModified: true, etag });
return;
}
if ((res.statusCode === 429 || res.statusCode >= 500) && attempt < 3) {
const retryAfter = parseInt(res.headers['retry-after'], 10);
const base = Number.isFinite(retryAfter) ? retryAfter * 1000 : 1000 * 2 ** attempt;
const wait = Math.min(base, MAX_RETRY_AFTER_MS) + Math.floor(Math.random() * 1000);
setTimeout(() => this.fetchJson(url, etag, attempt + 1).then(resolve, reject), wait);
return;
}
if (res.statusCode !== 200) { if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`)); reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
return; return;
} }
try { try {
resolve(JSON.parse(data)); resolve({ data: JSON.parse(data), etag: res.headers.etag || null });
} catch (e) { } catch (e) {
reject(new Error('Invalid JSON response')); reject(new Error('Invalid JSON response'));
} }
@@ -98,7 +184,8 @@ class UpdateClient {
hostname: urlObj.hostname, hostname: urlObj.hostname,
port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80), port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
path: urlObj.pathname + urlObj.search, path: urlObj.pathname + urlObj.search,
headers headers,
agent: httpsAgent
}; };
const req = https.get(requestOptions, (res) => { const req = https.get(requestOptions, (res) => {
@@ -114,7 +201,13 @@ class UpdateClient {
} }
if (res.statusCode !== 200) { if (res.statusCode !== 200) {
reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`)); res.resume();
const err = new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`);
const retryAfter = parseInt(res.headers['retry-after'], 10);
if (Number.isFinite(retryAfter)) {
err.retryAfterMs = Math.min(retryAfter * 1000, MAX_RETRY_AFTER_MS);
}
reject(err);
return; return;
} }
@@ -132,7 +225,14 @@ class UpdateClient {
}); });
file.on('finish', () => { file.on('finish', () => {
file.close(resolve); file.close(() => {
if (totalSize && downloadedSize < totalSize) {
fs.unlink(destPath, () => { });
reject(new Error(`Download truncated: Received ${downloadedSize} of ${totalSize} bytes.`));
} else {
resolve();
}
});
}); });
file.on('error', (err) => { file.on('error', (err) => {
@@ -146,10 +246,10 @@ class UpdateClient {
reject(err); reject(err);
}); });
req.setTimeout(120000, () => { req.setTimeout(900000, () => {
req.destroy(); req.destroy();
fs.unlink(destPath, () => { }); fs.unlink(destPath, () => { });
reject(new Error('Download timeout')); reject(new Error('Download timeout (15 minutes reached)'));
}); });
}; };
@@ -180,7 +280,8 @@ class UpdateClient {
hostname: urlObj.hostname, hostname: urlObj.hostname,
port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80), port: urlObj.port || (urlObj.protocol === 'https:' ? 443 : 80),
path: urlObj.pathname + urlObj.search, path: urlObj.pathname + urlObj.search,
headers headers,
agent: httpsAgent
}; };
const req = https.get(requestOptions, (res) => { const req = https.get(requestOptions, (res) => {
@@ -222,31 +323,122 @@ class UpdateClient {
}); });
} }
async checkForUpdates() { async checkForUpdates(force = false) {
const releases = await this.fetchJson(RELEASES_API); const cache = this.readCache();
if (!releases || releases.length === 0) { const now = Date.now();
if (!force && cache.blockedUntil && now < cache.blockedUntil) {
return null; return null;
} }
const release = releases[0]; if (!force && cache.checkedAt && now - cache.checkedAt < MIN_CHECK_INTERVAL_MS && this.cacheUsable(cache.release)) {
return cache.release;
}
const payloadAsset = (release.assets && release.assets.links ? release.assets.links : []).find(a => a.name === 'update-payload.zip'); const listUrl = `${RELEASES_API}?per_page=20&order_by=released_at&sort=desc`;
const manifestAsset = (release.assets && release.assets.links ? release.assets.links : []).find(a => a.name === 'manifest.json'); let result = await this.fetchJson(listUrl, force ? null : cache.etag);
if (result.notModified) {
if (this.cacheUsable(cache.release)) {
this.writeCache({ checkedAt: now });
return cache.release;
}
result = await this.fetchJson(listUrl, null);
}
if (!payloadAsset) { const releases = result.data;
if (!Array.isArray(releases) || releases.length === 0) {
return null; return null;
} }
let sha256 = null; const verParts = (v) => String(v || '').replace(/^v/, '').split(/[.\-+]/).map((n) => parseInt(n, 10) || 0);
if (manifestAsset) { const cmp = (a, b) => {
const manifest = await this.fetchAssetJson(manifestAsset.url); const x = verParts(a);
sha256 = manifest.sha256 || null; const y = verParts(b);
} for (let i = 0; i < Math.max(x.length, y.length); i++) {
if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) - (y[i] || 0);
return { }
version: release.tag_name, return 0;
url: payloadAsset.url,
sha256
}; };
const ordered = releases.slice().sort((a, b) => cmp(b.tag_name, a.tag_name));
const release = ordered[0];
const links = release.assets && release.assets.links ? release.assets.links : [];
const manifestAsset = links.find((a) => a.name === 'manifest.json');
if (!manifestAsset) {
throw new Error(`Release ${release.tag_name} has no manifest.json.`);
}
const manifest = await this.fetchAssetJson(manifestAsset.url);
if (!manifest.components) {
throw new Error(`Release ${release.tag_name} has no signed component manifest.`);
}
if (!verifyManifest(manifest)) {
throw new Error('Update manifest signature is invalid.');
}
if (normalizeTag(manifest.version) !== normalizeTag(release.tag_name)) {
throw new Error('Update manifest version does not match the release tag.');
}
const components = {};
for (const [name, c] of Object.entries(manifest.components)) {
const direct = typeof c.url === 'string' &&
c.url.startsWith('https://') &&
isAllowedHost(c.url) &&
c.url.includes('/packages/generic/vyla-home/');
const url = direct ? c.url : null;
if (!url) {
throw new Error(`Release ${release.tag_name} manifest has no download URL for ${c.file}.`);
}
components[name] = { url, sha256: c.sha256, id: c.id, size: c.size };
}
let installer = null;
if (manifest.installer) {
const installerLink = links.find((a) => a.name === manifest.installer.file);
if (installerLink) {
installer = {
url: installerLink.url,
sha256: manifest.installer.sha256,
size: manifest.installer.size,
version: manifest.installer.version
};
}
}
if (!installer) {
installer = await this.findInstaller(ordered, release.tag_name);
}
const out = {
version: release.tag_name,
sha256: manifest.sha256 || null,
manifest,
components,
installer
};
this.writeCache({ checkedAt: now, etag: result.etag || null, release: out });
return out;
}
async findInstaller(ordered, skipTag) {
for (const r of ordered.slice(0, 6)) {
if (r.tag_name === skipTag) continue;
const rl = r.assets && r.assets.links ? r.assets.links : [];
const ma = rl.find((a) => a.name === 'manifest.json');
if (!ma) continue;
try {
const m = await this.fetchAssetJson(ma.url);
if (!m.installer || !verifyManifest(m)) continue;
const link = rl.find((a) => a.name === m.installer.file);
if (!link) continue;
return {
url: link.url,
sha256: m.installer.sha256,
size: m.installer.size,
version: m.installer.version
};
} catch (e) { }
}
return null;
} }
async downloadUpdate(release, destPath, onProgress) { async downloadUpdate(release, destPath, onProgress) {
@@ -255,4 +447,7 @@ class UpdateClient {
} }
} }
module.exports = UpdateClient; UpdateClient.canonicalManifest = canonicalManifest;
UpdateClient.verifyManifest = verifyManifest;
module.exports = UpdateClient;