mirror of
https://github.com/4gray/iptvnator.git
synced 2026-10-16 22:26:16 -08:00
* feat(epg): accept local XMLTV files as EPG sources Settings → EPG and the playlist dialog accepted `file://` in their form pattern, but the main process rejected everything except http(s), so a local XMLTV entry saved fine and then failed on import. Both surfaces now take a remote link, a `file:` URL, an absolute POSIX path or a Windows drive/UNC path (`classifyEpgSourceReference` in shared/interfaces), and the settings section spells out the accepted formats with examples. The EPG worker opens every source through `openEpgSourceStream`: remote links keep the validated-redirect client and trust policy, local files are read from disk behind the signature-sniffing optional gunzip stage, so .xml, .xml.gz and extension-less gzip all parse. Only hand-typed sources may be local: `extractM3uEpgUrls` harvests http(s) links only from M3U headers, since the local branch bypasses `validateRemoteUrl`. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * feat(epg): pick local XMLTV files with a native file dialog A folder button beside each EPG source row (Settings → EPG and the playlist dialog) opens the native open-file dialog and writes the chosen absolute path into the row. New `EPG_OPEN_FILE_DIALOG` IPC behind `ElectronBridgeApi.openEpgFileDialog`, gated in the renderer by `RuntimeCapabilitiesService.supportsEpgFilePicker`. The row's refresh/remove buttons carry `data-test-id`s now, and the EPG e2e suites address them by id instead of index, since the folder button became the first button in a row. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(epg): authorize local XMLTV files in the main process Review follow-up (Greptile P1, Codex P1). The renderer hands source strings to FETCH_EPG/EPG_FORCE_FETCH unchanged, so the form validator alone could not enforce the provenance rule: a compromised renderer, or a legacy `file://` entry an older version stored from an M3U header, could name any file on disk. `EpgWorkerService.startFetch` now asks a main-process `EpgLocalSourceAuthorizer` before a local path reaches the worker: a path the native picker returned is trusted at once, a hand-typed path is confirmed once in a native message box the renderer cannot fake, and a refusal is reported in the progress panel. Allowed paths persist under TRUSTED_LOCAL_EPG_SOURCES in the main-process config. The worker opens its local branch only when main set `allowLocalFile`; the service defaults to deny-all until epg.events installs the persisted authorizer. `resolvePlaylistEpgSourceState` and `filterPlaylistEpgUrlsForFetch` drop a stored non-remote entry unless it is also in `manualEpgUrls`. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(epg): fail a refused local EPG fetch instead of resolving it Review follow-up (Codex P2). A denied native confirmation now rejects the fetch after reporting the error row, so handleFetchEpg and the renderer's fetch result cannot claim the file was read. Also restores the unrelated CLAUDE.md paragraph an earlier formatter pass had reflowed into a list. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(epg): cancel a local source retired during its authorization prompt Review follow-up (Codex P2). startFetch keeps the request generation captured before awaiting the native confirmation and rechecks it afterwards: a source retired meanwhile ends as cancelled instead of starting an import that a pending clear would then have to await. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * test(epg): leave the local XMLTV e2e with a pristine settings form The local-file test ended with the EPG source field still dirty, which arms the main-process close guard: the app then waited for the unsaved changes dialog instead of closing, the close timeout killed it, and on Windows the killed process kept iptvnator.db busy (EBUSY on the data-dir cleanup) and hung the Playwright worker teardown. Discarding the form before the app closes takes the test from 15 s to 4 s locally. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: 4gray <fourgray@proton.me> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
152 lines
5.1 KiB
TypeScript
152 lines
5.1 KiB
TypeScript
import { createReadStream } from 'fs';
|
|
import { stat } from 'fs/promises';
|
|
import { PassThrough, Readable, pipeline } from 'stream';
|
|
import { ElectronBridgeTrustOptions } from '@iptvnator/shared/interfaces';
|
|
import { isPrivateNetworkUrlAccessAllowed } from '../events/url-safety';
|
|
import { epgLogger } from '../util/epg-logger';
|
|
import { resolveLocalEpgSourcePath } from '../util/epg-local-source-path';
|
|
import { createPlaylistAgentFactory } from '../util/secure-https';
|
|
import { requestWithValidatedRedirects } from '../util/validated-axios';
|
|
import { createOptionalEpgGunzip } from './epg-optional-gunzip';
|
|
import {
|
|
getEpgResponseContentEncoding,
|
|
shouldGunzipEpgResponse,
|
|
} from './epg-response-utils';
|
|
import { createDecodedEpgStream } from './epg-stream-decoder';
|
|
|
|
const loggerLabel = '[EPG Worker]';
|
|
|
|
/** Trust options plus the main-process verdict on a local file. */
|
|
export type EpgWorkerFetchOptions = ElectronBridgeTrustOptions & {
|
|
/**
|
|
* Set by `EpgWorkerService.startFetch` only after the main-process
|
|
* authorizer allowed the path (native picker or native confirmation).
|
|
* Never taken from the renderer.
|
|
*/
|
|
allowLocalFile?: boolean;
|
|
};
|
|
|
|
/**
|
|
* Opens the decoded XMLTV byte stream for an EPG source.
|
|
*
|
|
* Remote sources go through the validated-redirect HTTP client with the
|
|
* private-network and TLS trust policy. Local sources — a `file:` URL or an
|
|
* absolute path — are read from disk; gzip is detected from the file's own
|
|
* signature, so `guide.xml`, `guide.xml.gz` and a gzip file without the
|
|
* extension all work.
|
|
*
|
|
* The local branch bypasses `validateRemoteUrl`, which only knows http(s).
|
|
* Two things make that safe: header-declared M3U sources are filtered to
|
|
* remote links before they are stored (`extractM3uEpgUrls`), and the main
|
|
* process opens the branch only for a path its authorizer allowed
|
|
* (`allowLocalFile`), so neither a downloaded playlist nor a compromised
|
|
* renderer can name an arbitrary file.
|
|
*/
|
|
export async function openEpgSourceStream(
|
|
url: string,
|
|
options: EpgWorkerFetchOptions = {}
|
|
): Promise<Readable> {
|
|
const localPath = resolveLocalEpgSourcePath(url);
|
|
if (localPath) {
|
|
if (options.allowLocalFile !== true) {
|
|
throw new Error('Local EPG file was not authorized');
|
|
}
|
|
return openLocalEpgSource(localPath);
|
|
}
|
|
return openRemoteEpgSource(url, options);
|
|
}
|
|
|
|
async function openLocalEpgSource(filePath: string): Promise<Readable> {
|
|
let info: Awaited<ReturnType<typeof stat>>;
|
|
try {
|
|
info = await stat(filePath);
|
|
} catch (error) {
|
|
const code = (error as NodeJS.ErrnoException).code;
|
|
if (code === 'ENOENT' || code === 'ENOTDIR') {
|
|
throw new Error(`EPG file not found: ${filePath}`);
|
|
}
|
|
throw error;
|
|
}
|
|
if (!info.isFile()) {
|
|
throw new Error(`EPG source is not a file: ${filePath}`);
|
|
}
|
|
|
|
epgLogger.log(loggerLabel, 'Reading local EPG file');
|
|
const output = new PassThrough();
|
|
pipeline(
|
|
createReadStream(filePath),
|
|
createOptionalEpgGunzip(),
|
|
output,
|
|
(error) => {
|
|
if (error) output.destroy(error);
|
|
}
|
|
);
|
|
return output;
|
|
}
|
|
|
|
async function openRemoteEpgSource(
|
|
url: string,
|
|
options: ElectronBridgeTrustOptions
|
|
): Promise<Readable> {
|
|
// EPG URLs can originate from an untrusted M3U `url-tvg` attribute.
|
|
// Validate every redirect and require an explicit operator opt-in for
|
|
// private/LAN sources.
|
|
const response = await requestWithValidatedRedirects<Readable>(
|
|
url.trim(),
|
|
{
|
|
agentFactory: createPlaylistAgentFactory({
|
|
trustedInsecureTlsHosts: options.trustedInsecureTlsHosts,
|
|
}),
|
|
decompress: false,
|
|
method: 'GET',
|
|
responseType: 'stream',
|
|
},
|
|
{
|
|
allowPrivateNetworks:
|
|
isPrivateNetworkUrlAccessAllowed() ||
|
|
isTrustedPrivateNetworkEpgSource(url, options),
|
|
}
|
|
);
|
|
const responseUrl = response.config.url;
|
|
const isGzipped = shouldGunzipEpgResponse(url, {
|
|
headers: response.headers,
|
|
url: responseUrl,
|
|
});
|
|
const contentEncoding = getEpgResponseContentEncoding(response.headers);
|
|
|
|
if (responseUrl && responseUrl !== url) {
|
|
epgLogger.log(loggerLabel, 'Resolved EPG redirect');
|
|
}
|
|
epgLogger.log(
|
|
loggerLabel,
|
|
`EPG response detected as gzipped: ${isGzipped}`
|
|
);
|
|
if (contentEncoding) {
|
|
epgLogger.log(
|
|
loggerLabel,
|
|
`EPG response content-encoding: ${contentEncoding}`
|
|
);
|
|
}
|
|
|
|
if (response.status < 200 || response.status >= 300) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
if (!response.data) {
|
|
throw new Error('Response body is null');
|
|
}
|
|
|
|
return createDecodedEpgStream(response.data, response.headers, isGzipped);
|
|
}
|
|
|
|
function isTrustedPrivateNetworkEpgSource(
|
|
url: string,
|
|
options: ElectronBridgeTrustOptions
|
|
): boolean {
|
|
const normalizedUrl = url.trim();
|
|
return (
|
|
options.trustedPrivateNetworkEpgUrls?.some(
|
|
(trustedUrl) => trustedUrl.trim() === normalizedUrl
|
|
) ?? false
|
|
);
|
|
}
|