Files
RedLintu16andClaude Opus 5.5 b67b29b40b CrossSound desktop with the DRM stubbed out
A single-commit snapshot of better-remote (7a8c4cb plus the uncommitted
remote.js work), with every DRM-bearing piece replaced by a stub that keeps
the same interface:

- src/ui/drm.js: no DRM pipelines; needsDrm/isDrmUrl false,
  bestEncryptedTranscoding null, playDrmAudio rejects. The engine switcher
  and drmVjs* helpers stay as no-ops.
- src/electron/drm.ts: initCdm/setupLicenseCors no-ops; the drm:license and
  api:stream:drm-info IPC handlers reject with "DRM is not available".
- src/api/soundcloud.ts: resolveEncryptedStream keeps its signature, rejects.
- src/electron/main.ts: license host dropped from the header rewrite.
- src/ui/pb-lease.js: the expiry self-check uses a placeholder URL instead
  of a captured DRM manifest URL (same policy values, still passes).
- scripts/vmp-sign.js, forge.config.js vmpSign: Widevine signing skipped,
  so no castLabs EVS account is needed to run or package.
- README: says DRM is stubbed here.

Go+ tracks SoundCloud only serves encrypted are unplayable and skipped;
previews and everything else play as before. No history: the private
branches' DRM code is not reachable from this commit.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 10:06:08 -07:00

296 lines
10 KiB
JavaScript
Executable File

const path = require('path');
const fs = require('fs');
const net = require('net');
const https = require('https');
const { spawn } = require('child_process');
const { app } = require('electron');
const TOR_DIR = path.join(app.getPath('userData'), 'tor');
const TOR_EXE = path.join(TOR_DIR, 'tor', 'tor.exe');
const TORRC = path.join(TOR_DIR, 'Data', 'Tor', 'torrc');
const TOR_STATE = path.join(TOR_DIR, 'Data', 'Tor', 'state');
const CONTROL_PORT = 9051;
const CONTROL_COOKIE = path.join(TOR_DIR, 'Data', 'Tor', 'control_auth_cookie');
let torProcess = null;
let _onExit = null;
let _onLog = null;
function onLog(fn) { _onLog = fn; }
function _emitLog(line) { if (_onLog) _onLog(line.trim()); }
function isTorInstalled() {
return fs.existsSync(TOR_EXE);
}
function isTorRunning() {
return torProcess !== null && torProcess.exitCode === null;
}
// ── torrc ──────────────────────────────────────────────────────────────────
function _torBrowserRc() {
const base = process.env.LOCALAPPDATA || '';
return path.join(base, 'Tor Browser', 'Browser', 'TorBrowser', 'Data', 'Tor', 'torrc');
}
function readTorrc() {
if (fs.existsSync(TORRC)) return fs.readFileSync(TORRC, 'utf8');
const tb = _torBrowserRc();
if (fs.existsSync(tb)) return fs.readFileSync(tb, 'utf8');
return '# No torrc found.\n# Download standalone Tor below, or point to your Tor Browser installation.\n';
}
function writeTorrc(content) {
if (fs.existsSync(path.dirname(TORRC))) {
fs.writeFileSync(TORRC, content, 'utf8');
return true;
}
const tb = _torBrowserRc();
if (fs.existsSync(path.dirname(tb))) {
fs.writeFileSync(tb, content, 'utf8');
return true;
}
return false;
}
// ── Download / install ─────────────────────────────────────────────────────
const FALLBACK_VERSION = '15.0.8';
const BASE_URL = 'https://archive.torproject.org/tor-package-archive/torbrowser/';
async function _getLatestVersion() {
return new Promise((resolve) => {
const req = https.get(BASE_URL, { timeout: 8000 }, (res) => {
let html = '';
res.on('data', c => html += c);
res.on('end', () => {
const versions = [...html.matchAll(/href="(\d+\.\d+\.\d+)\/"/g)]
.map(m => m[1]);
if (!versions.length) return resolve(FALLBACK_VERSION);
versions.sort((a, b) => {
const [av, bv] = [a, b].map(v => v.split('.').map(Number));
for (let i = 0; i < 3; i++) if (av[i] !== bv[i]) return bv[i] - av[i];
return 0;
});
resolve(versions[0]);
});
});
req.on('error', () => resolve(FALLBACK_VERSION));
req.on('timeout', () => { req.destroy(); resolve(FALLBACK_VERSION); });
});
}
function _platformBundle() {
const p = process.platform;
if (p === 'win32') return 'tor-expert-bundle-windows-x86_64';
if (p === 'darwin') return process.arch === 'arm64'
? 'tor-expert-bundle-macos-aarch64'
: 'tor-expert-bundle-macos-x86_64';
return 'tor-expert-bundle-linux-x86_64';
}
function _downloadFile(url, dest, onProgress) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
const get = (u) => {
console.log('[tor] downloading:', u);
https.get(u, (res) => {
if (res.statusCode === 301 || res.statusCode === 302) {
return get(res.headers.location);
}
if (res.statusCode !== 200) {
file.close();
fs.unlink(dest, () => {});
return reject(new Error(`HTTP ${res.statusCode} for ${u}`));
}
const total = parseInt(res.headers['content-length'], 10) || 0;
let received = 0;
res.on('data', chunk => {
received += chunk.length;
if (onProgress && total) onProgress(Math.round(received / total * 100));
});
res.pipe(file);
file.on('finish', () => file.close(resolve));
}).on('error', err => { fs.unlink(dest, () => {}); reject(err); });
};
get(url);
});
}
async function downloadAndInstall(onProgress) {
fs.mkdirSync(TOR_DIR, { recursive: true });
const version = await _getLatestVersion();
console.log('[tor] latest version detected:', version);
const filename = `${_platformBundle()}-${version}.tar.gz`;
const url = `${BASE_URL}${version}/${filename}`;
const archive = path.join(TOR_DIR, filename);
await _downloadFile(url, archive, onProgress);
// Use the Windows built-in tar.exe explicitly to avoid Git's tar (which can't handle Windows drive letters)
const tarExe = process.platform === 'win32'
? path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe')
: 'tar';
await new Promise((resolve, reject) => {
const tar = spawn(tarExe, ['-xzf', archive, '-C', TOR_DIR], { stdio: 'pipe' });
let stderr = '';
tar.stderr.on('data', d => { stderr += d; });
tar.stdout.on('data', d => { console.log('[tar stdout]', d.toString()); });
tar.on('close', code => {
if (stderr) console.error('[tar stderr]', stderr);
console.log('[tar] exit code:', code);
try { fs.unlinkSync(archive); } catch {}
code === 0 ? resolve() : reject(new Error(`tar exited ${code}: ${stderr.trim()}`));
});
tar.on('error', reject);
});
// Create a default torrc pointing to the bundled GeoIP files and data dir
fs.mkdirSync(path.dirname(TORRC), { recursive: true });
const geoipDir = path.join(TOR_DIR, 'data');
const dataDir = path.join(TOR_DIR, 'Data', 'Tor');
fs.writeFileSync(TORRC,
`DataDirectory ${dataDir}\n` +
`GeoIPFile ${path.join(geoipDir, 'geoip')}\n` +
`GeoIPv6File ${path.join(geoipDir, 'geoip6')}\n` +
'# Example: set exit country\n' +
'# ExitNodes {us}\n' +
'# StrictNodes 1\n',
'utf8'
);
}
// ── Process management ─────────────────────────────────────────────────────
function startTor(onExit, onReady) {
if (isTorRunning()) { if (onReady) onReady(); return; }
_onExit = onExit || null;
const geoipDir = path.join(TOR_DIR, 'data');
const args = fs.existsSync(TORRC) ? ['-f', TORRC] : [];
// Always pass GeoIP paths so country-based exit selection works
args.push(
'--GeoIPFile', path.join(geoipDir, 'geoip'),
'--GeoIPv6File', path.join(geoipDir, 'geoip6'),
'--DataDirectory', path.join(TOR_DIR, 'Data', 'Tor'),
'--ControlPort', String(CONTROL_PORT),
'--CookieAuthentication', '1',
);
// Log active torrc so we can verify ExitNodes/StrictNodes are set correctly
try {
const torrcContent = fs.readFileSync(TORRC, 'utf8');
console.log('[tor] Starting with torrc:\n' + torrcContent.trim().split('\n').map(l => ' ' + l).join('\n'));
} catch { console.warn('[tor] Could not read torrc before start.'); }
console.log('[tor] Spawn args:', args.join(' '));
const proc = spawn(TOR_EXE, args, { stdio: 'pipe', detached: false });
torProcess = proc;
let bootstrapped = false;
proc.stdout.on('data', (data) => {
const line = data.toString();
process.stdout.write('[tor] ' + line);
if (/exit.?node|strictnode|ExitNode|StrictNode/i.test(line)) {
console.log('[tor][EXIT-POLICY]', line.trim());
}
// Only forward meaningful notice/warn/err lines to the UI log
const trimmed = line.trim();
if (/\[(notice|warn|err)\]/i.test(trimmed)) {
_emitLog(trimmed);
}
if (!bootstrapped && line.includes('Bootstrapped 100%')) {
bootstrapped = true;
_emitLog('✓ Bootstrapped 100% — Tor is ready.');
console.log('[tor] Fully bootstrapped and ready.');
if (onReady) onReady();
}
});
proc.stderr.on('data', (data) => {
process.stderr.write('[tor stderr] ' + data.toString());
});
proc.on('exit', (code, signal) => {
// Ignore exit from a previous process if a new one has already started
if (torProcess !== proc) return;
console.warn(`[tor] Process exited — code: ${code}, signal: ${signal}`);
torProcess = null;
if (_onExit) _onExit();
});
}
function stopTor() {
if (!isTorRunning()) return Promise.resolve();
_onExit = null; // don't fire the exit callback when we stop it intentionally
const proc = torProcess;
torProcess = null;
return new Promise((resolve) => {
proc.once('exit', resolve);
proc.kill();
});
}
function _controlCommand(commands) {
return new Promise((resolve, reject) => {
if (!isTorRunning()) return reject(new Error('Tor is not running'));
if (!fs.existsSync(CONTROL_COOKIE)) return reject(new Error('Control cookie not found'));
const cookie = fs.readFileSync(CONTROL_COOKIE).toString('hex');
const client = net.connect(CONTROL_PORT, '127.0.0.1', () => {
client.write(`AUTHENTICATE ${cookie}\r\n`);
for (const cmd of commands) client.write(cmd + '\r\n');
client.write('QUIT\r\n');
});
let response = '';
client.on('data', d => { response += d.toString(); });
client.on('end', () => {
console.log('[tor] Control response:', response.trim());
if (response.includes('250')) resolve(response);
else reject(new Error('Unexpected control response: ' + response.trim()));
});
client.on('error', reject);
});
}
function newIdentity() {
return _controlCommand(['SIGNAL NEWNYM']);
}
function reloadConfig() {
return _controlCommand(['SIGNAL RELOAD']);
}
// lyrebird.exe handles obfs4 and meek; conjure-client.exe handles conjure
const PT_DIR = path.join(TOR_DIR, 'tor', 'pluggable_transports');
function getPluggableTransportPath() {
const lyrebird = path.join(PT_DIR, 'lyrebird.exe');
const conjure = path.join(PT_DIR, 'conjure-client.exe');
return {
lyrebird: fs.existsSync(lyrebird) ? lyrebird : null,
conjure: fs.existsSync(conjure) ? conjure : null,
};
}
function getTorrcPath() { return TORRC; }
function clearState() {
if (fs.existsSync(TOR_STATE)) {
fs.unlinkSync(TOR_STATE);
console.log('[tor] Deleted state file so new exit node settings take full effect.');
}
}
module.exports = {
isTorInstalled,
isTorRunning,
downloadAndInstall,
startTor,
stopTor,
newIdentity,
reloadConfig,
getPluggableTransportPath,
getTorrcPath,
clearState,
readTorrc,
writeTorrc,
onLog,
};