Spaces:
Build error
Build error
File size: 6,055 Bytes
0bfe2e3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
import { Config } from '@aiostreams/types';
import { Settings } from './settings';
import { getTextHash } from './crypto';
import { Cache } from './cache';
import { createLogger, maskSensitiveInfo } from './logger';
const logger = createLogger('stremthru');
const cache = Cache.getInstance<string, string>('publicIp');
const PRIVATE_CIDR = /^(10\.|127\.|172\.(1[6-9]|2[0-9]|3[01])\.|192\.168\.)/;
export async function generateStremThruStreams(
stremThruConfig: Config['stremThruConfig'],
streams: {
url: string;
filename?: string;
headers?: {
request?: Record<string, string>;
response?: Record<string, string>;
};
}[]
): Promise<string[] | null> {
if (!streams.length) {
return [];
}
if (!stremThruConfig) {
throw new Error('StremThru configuration is missing');
}
const proxyUrl = new URL(stremThruConfig.url.replace(/\/$/, ''));
const generateUrlsEndpoint = '/v0/proxy';
proxyUrl.pathname = `${proxyUrl.pathname === '/' ? '' : proxyUrl.pathname}${generateUrlsEndpoint}`;
const headers: Record<string, string> = {
'Content-Type': 'application/x-www-form-urlencoded',
};
const data = new URLSearchParams();
streams.forEach((stream, i) => {
data.append('url', stream.url);
let req_headers = '';
if (stream.headers?.request) {
for (const [key, value] of Object.entries(stream.headers.request)) {
req_headers += `${key}: ${value}\n`;
}
}
data.append(`req_headers[${i}]`, req_headers);
if (stream.filename) {
data.append(`filename[${i}]`, stream.filename);
}
});
if (Settings.ENCRYPT_STREMTHRU_URLS) {
headers['X-StremThru-Authorization'] =
`Basic ${stremThruConfig.credential}`;
} else {
proxyUrl.searchParams.set('token', stremThruConfig.credential);
}
try {
if (Settings.LOG_SENSITIVE_INFO) {
logger.debug(`POST ${proxyUrl.toString()}`);
} else {
logger.debug(
`POST ${proxyUrl.protocol}://${maskSensitiveInfo(proxyUrl.hostname)}${proxyUrl.port ? `:${proxyUrl.port}` : ''}/${generateUrlsEndpoint}`
);
}
const response = await fetch(proxyUrl.toString(), {
method: 'POST',
headers,
body: data,
signal: AbortSignal.timeout(Settings.STREMTHRU_TIMEOUT),
});
if (!response.ok) {
throw new Error(`${response.status}: ${response.statusText}`);
}
let responseData: any;
try {
responseData = await response.json();
} catch (error) {
const text = await response.text();
logger.debug(`Response body: ${text}`);
throw new Error('Failed to parse JSON response from StremThru');
}
if (responseData.error) {
throw new Error(responseData.error);
}
if (responseData.data?.items) {
return responseData.data.items;
} else {
throw new Error('No URLs were returned from StremThru');
}
} catch (error) {
logger.error(
`Failed to generate StremThru URLs using request to ${maskSensitiveInfo(proxyUrl.toString())}: ${error}`
);
return null;
}
}
export async function getStremThruPublicIp(
stremThruConfig: Config['stremThruConfig']
) {
try {
if (!stremThruConfig) {
logger.error('stremThruConfig is missing');
throw new Error('StremThru configuration is missing');
}
if (!stremThruConfig?.url) {
logger.error('stremThruUrl is missing');
throw new Error('StremThru URL is missing');
}
if (stremThruConfig.publicIp) {
return stremThruConfig.publicIp;
}
const stremThruUrl = new URL(stremThruConfig.url.replace(/\/$/, ''));
if (PRIVATE_CIDR.test(stremThruUrl.hostname)) {
// StremThru URL is a private IP address
logger.error('StremThru URL is a private IP address so returning null');
return null;
}
const cacheKey = getTextHash(
`stremThruPublicIp:${stremThruConfig.url}:${stremThruConfig.credential}`
);
const cachedPublicIp = cache ? cache.get(cacheKey) : null;
if (cachedPublicIp) {
logger.debug(`Returning cached public IP`);
return cachedPublicIp;
}
const proxyIpUrl = stremThruUrl;
const proxyIpPath = '/v0/health/__debug__';
proxyIpUrl.pathname = `${proxyIpUrl.pathname === '/' ? '' : proxyIpUrl.pathname}${proxyIpPath}`;
if (Settings.LOG_SENSITIVE_INFO) {
logger.debug(`GET ${proxyIpUrl.toString()}`);
} else {
logger.debug(`GET ${proxyIpUrl}`);
}
const response = await fetch(proxyIpUrl.toString(), {
method: 'GET',
headers: {
'X-StremThru-Authorization': `Basic ${stremThruConfig.credential}`,
},
signal: AbortSignal.timeout(Settings.STREMTHRU_TIMEOUT),
});
if (!response.ok) {
throw new Error(`${response.status}: ${response.statusText}`);
}
const data = await response.json();
const publicIp =
typeof data.data?.ip?.exposed === 'object' // available from `v0.71.0`
? data.data.ip.exposed['*'] || data.data.ip.machine
: data.data?.ip?.machine;
if (publicIp && cache) {
cache.set(cacheKey, publicIp, Settings.CACHE_STREMTHRU_IP_TTL);
} else {
logger.error(
`StremThru did not respond with a public IP address, please check a valid credential was used. Response: ${JSON.stringify(data)}`
);
}
return publicIp;
} catch (error: any) {
logger.error(`Failed to get StremThru public IP: ${error.message}`);
return null;
}
}
export function getStremThruConfig(userConfig: Config) {
const stremThruConfig = userConfig.stremThruConfig;
return {
stremThruEnabled:
stremThruConfig?.stremThruEnabled ||
Settings.DEFAULT_STREMTHRU_URL !== '',
url: stremThruConfig?.url || Settings.DEFAULT_STREMTHRU_URL,
credential:
stremThruConfig?.credential || Settings.DEFAULT_STREMTHRU_CREDENTIAL,
publicIp: stremThruConfig?.publicIp || Settings.DEFAULT_STREMTHRU_PUBLIC_IP,
proxiedAddons: stremThruConfig?.proxiedAddons || null,
proxiedServices: stremThruConfig?.proxiedServices || null,
};
}
|