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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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import express, { Request, Response } from 'express';

import path from 'path';
import { AIOStreams } from './addon';
import { Config, StreamRequest } from '@aiostreams/types';
import { validateConfig } from './config';
import manifest from './manifest';
import { errorResponse } from './responses';
import {
  Settings,
  addonDetails,
  compressAndEncrypt,
  parseAndDecryptString,
  Cache,
} from '@aiostreams/utils';

const app = express();
console.log(`|INF| server > init: Starting server and loading settings...`);
Object.entries(Settings).forEach(([key, value]) => {
  switch (key) {
    case 'SECRET_KEY':
      if (value) {
        console.log(
          `|INF| server > init: ${key} = ${value.replace(/./g, '*').slice(0, 32)}`
        );
      }
      break;

    case 'BRANDING':
    case 'CUSTOM_CONFIGS':
      // Skip CUSTOM_CONFIGS processing here, handled later
      break;

    default:
      console.log(`|INF| server > init: ${key} = ${value}`);
  }
});

if (!Settings.SECRET_KEY) {
  console.warn(
    '|WRN| server > init: SECRET_KEY is not set, data encryption is disabled!'
  );
}

let CUSTOM_CONFIGS: Record<string, string> = {};
if (Settings.CUSTOM_CONFIGS) {
  try {
    CUSTOM_CONFIGS = JSON.parse(Settings.CUSTOM_CONFIGS);
    console.log(
      `|INF| server > init: Loaded ${Object.keys(CUSTOM_CONFIGS).length} custom configs under aliases ${Object.keys(CUSTOM_CONFIGS).join(', ')}`
    );
  } catch (error: any) {
    console.error(
      `|ERR| server > init: CUSTOM_CONFIGS is not valid JSON: ${error.message}`
    );
  }
}

const cache = new Cache(Settings.MAX_CACHE_SIZE);

// Built-in middleware for parsing JSON
app.use(express.json());
// Built-in middleware for parsing URL-encoded data
app.use(express.urlencoded({ extended: true }));

app.use((req, res, next) => {
  res.append('Access-Control-Allow-Origin', '*');
  res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  console.log(
    `|DBG| server > ${req.method} ${req.path.replace(/\/eyJ[\w\=]+/g, '/*******').replace(/\/E-[\w-]+/g, '/*******')}`
  );
  next();
});

app.get('/', (req, res) => {
  res.redirect('/configure');
});

app.get(
  ['/_next/*', '/assets/*', '/icon.ico', '/configure.txt'],
  (req, res) => {
    res.sendFile(path.join(__dirname, '../../frontend/out', req.path));
  }
);

if (!Settings.DISABLE_CUSTOM_CONFIG_GENERATOR_ROUTE) {
  app.get('/custom-config-generator', (req, res) => {
    res.sendFile(
      path.join(__dirname, '../../frontend/out/custom-config-generator.html')
    );
  });
}

app.get('/configure', (req, res) => {
  res.sendFile(path.join(__dirname, '../../frontend/out/configure.html'));
});

app.get('/:config/configure', (req, res) => {
  const config = req.params.config;
  if (config.startsWith('eyJ')) {
    return res.sendFile(
      path.join(__dirname, '../../frontend/out/configure.html')
    );
  }
  try {
    const configJson = encryptInfoInConfig(extractJsonConfig(config));
    const base64Config = Buffer.from(JSON.stringify(configJson)).toString(
      'base64'
    );
    res.redirect(`/${base64Config}/configure`);
  } catch (error: any) {
    console.error(`|ERR| server > Failed to extract config: ${error.message}`);
    res.status(400).send('Invalid config');
  }
});

app.get('/manifest.json', (req, res) => {
  res.status(200).json(manifest());
});

app.get('/:config/manifest.json', (req, res) => {
  const config = req.params.config;
  let configJson: Config;
  try {
    configJson = extractJsonConfig(config);
    console.log(`|DBG| server > Extracted config for manifest request`);
    configJson = decryptEncryptedInfoFromConfig(configJson);
    if (Settings.LOG_SENSITIVE_INFO) {
      console.log(`|DBG| server > Final config: ${JSON.stringify(configJson)}`);
    }
    console.log(
      `|DBG| server > Successfully removed or decrypted sensitive info`
    );
    const { valid, errorMessage } = validateConfig(configJson);
    if (!valid) {
      console.error(
        `|ERR| server > Received invalid config for manifest request: ${errorMessage}`
      );
      res.status(400).json({ error: 'Invalid config', message: errorMessage });
      return;
    }
  } catch (error: any) {
    console.error(`|ERR| server > Failed to extract config: ${error.message}`);
    res.status(400).json({ error: 'Invalid config' });
    return;
  }
  res.status(200).json(manifest(configJson));
});

// Route for /stream
app.get('/stream/:type/:id', (req: Request, res: Response) => {
  res
    .status(200)
    .json(
      errorResponse(
        'You must configure this addon to use it',
        rootUrl(req),
        '/configure'
      )
    );
});

app.get('/:config/stream/:type/:id.json', (req, res: Response): void => {
  const { config, type, id } = req.params;
  let configJson: Config;
  try {
    configJson = extractJsonConfig(config);
    console.log(`|DBG| server > Extracted config for stream request`);
    configJson = decryptEncryptedInfoFromConfig(configJson);
    if (Settings.LOG_SENSITIVE_INFO) {
      console.log(`|DBG| server > Final config: ${JSON.stringify(configJson)}`);
    }
    console.log(
      `|DBG| server > Successfully removed or decrypted sensitive info`
    );
  } catch (error: any) {
    console.error(`|ERR| server > Failed to extract config: ${error.message}`);
    res.json(
      errorResponse(
        `${error.message}, please check the logs or click this stream to create an issue on GitHub`,
        rootUrl(req),
        undefined,
        'https://github.com/Viren070/AIOStreams/issues/new?template=bug_report.yml'
      )
    );
    return;
  }

  console.log(`|DBG| server > Requesting streams for ${type} ${id}`);

  if (type !== 'movie' && type !== 'series') {
    console.error(`|ERR| server > Invalid type for stream request`);
    res.json(
      errorResponse(
        'Invalid type for stream request, must be movie or series',
        rootUrl(req),
        '/'
      )
    );
    return;
  }
  let streamRequest: StreamRequest = { id, type };

  try {
    const { valid, errorCode, errorMessage } = validateConfig(configJson);
    if (!valid) {
      console.error(
        `|ERR| server > Received invalid config: ${errorCode} - ${errorMessage}`
      );
      res.json(
        errorResponse(errorMessage ?? 'Unknown', rootUrl(req), '/configure')
      );
      return;
    }
    configJson.requestingIp =
      req.get('X-Forwarded-For') ||
      req.get('X-Real-IP') ||
      req.get('CF-Connecting-IP') ||
      req.ip;
    configJson.instanceCache = cache;
    const aioStreams = new AIOStreams(configJson);
    aioStreams.getStreams(streamRequest).then((streams) => {
      res.json({ streams: streams });
    });
  } catch (error: any) {
    console.error(`|ERR| server > Internal addon error: ${error.message}`);
    res.json(
      errorResponse(
        'An unexpected error occurred, please check the logs or create an issue on GitHub',
        rootUrl(req),
        undefined,
        'https://github.com/Viren070/AIOStreams/issues/new?template=bug_report.yml'
      )
    );
  }
});

app.post('/encrypt-user-data', (req, res) => {
  const { data } = req.body;

  if (!data) {
    console.error('|ERR| server > /encrypt-user-data: No data provided');
    res.status(400).json({ success: false, message: 'No data provided' });
    return;
  }

  try {
    if (!Settings.SECRET_KEY) {
      console.error('|ERR| server > /encrypt-user-data: Secret key not set');
      res.status(500).json({ success: false, message: 'Secret key not set' });
      return;
    }
    const { valid, errorCode, errorMessage } = validateConfig(JSON.parse(data));
    if (!valid) {
      console.error(
        `|ERR| server > /encrypt-user-data: Invalid config: ${errorCode} - ${errorMessage}`
      );
      res
        .status(200)
        .json({ success: false, message: errorMessage, error: errorMessage });
      return;
    }
    const encryptedData = compressAndEncrypt(data);
    console.log(`|DBG| server > /encrypt-user-data: Encrypted data`);
    res.status(200).json({ success: true, data: encryptedData });
  } catch (error: any) {
    console.error(`|ERR| server > /encrypt-user-data: ${error.message}`);
    res.status(500).json({ success: false, message: error.message });
  }
});

app.get('/health', (req, res) => {
  res.status(200).json({ status: 'ok' });
});

// define 404
app.use((req, res) => {
  res.status(404).sendFile(path.join(__dirname, '../../frontend/out/404.html'));
});

app.listen(Settings.PORT, () => {
  console.log(`|INF| server > init: Listening on port ${Settings.PORT}`);
});

function extractJsonConfig(config: string): Config {
  if (config.startsWith('E-') || config.startsWith('eyJ')) {
    return extractEncryptedOrEncodedConfig(config, 'Config');
  }
  if (CUSTOM_CONFIGS) {
    const customConfig = extractCustomConfig(config);
    if (customConfig) return customConfig;
  }
  throw new Error('Config was in an unexpected format');
}

function extractCustomConfig(config: string): Config | undefined {
  const customConfig = CUSTOM_CONFIGS?.[config];
  if (!customConfig) return undefined;
  console.log(
    `|DBG| server > Found custom config for alias ${config}, attempting to extract config`
  );
  return extractEncryptedOrEncodedConfig(
    customConfig,
    `CustomConfig ${config}`
  );
}

function extractEncryptedOrEncodedConfig(
  config: string,
  label: string
): Config {
  let decodedConfig: string;
  try {
    decodedConfig = isValueEncrypted(config)
      ? decryptValue(config, `${label} (encrypted)`)
      : Buffer.from(config, 'base64').toString('utf-8');
    return JSON.parse(decodedConfig);
  } catch (error: any) {
    console.error(`|ERR| Failed to parse ${label}: ${error.message}`);
    throw new Error(`Failed to parse ${label}`);
  }
}

function decryptEncryptedInfoFromConfig(config: Config): Config {
  if (config.services) {
    config.services.forEach(
      (service) =>
        service.credentials &&
        processObjectValues(
          service.credentials,
          `service ${service.id}`,
          true,
          (key, value) => isValueEncrypted(value)
        )
    );
  }

  if (config.mediaFlowConfig) {
    decryptMediaFlowConfig(config.mediaFlowConfig);
  }

  if (config.addons) {
    config.addons.forEach((addon) => {
      if (addon.options) {
        processObjectValues(
          addon.options,
          `addon ${addon.id}`,
          true,
          (key, value) =>
            isValueEncrypted(value) &&
            // Decrypt only if the option is secret
            (
              addonDetails.find((addonDetail) => addonDetail.id === addon.id)
                ?.options ?? []
            ).some((option) => option.id === key && option.secret)
        );
      }
    });
  }
  return config;
}

function decryptMediaFlowConfig(mediaFlowConfig: {
  apiPassword: string;
  proxyUrl: string;
  publicIp: string;
}): void {
  const { apiPassword, proxyUrl, publicIp } = mediaFlowConfig;
  mediaFlowConfig.apiPassword = decryptValue(
    apiPassword,
    'MediaFlow apiPassword'
  );
  mediaFlowConfig.proxyUrl = decryptValue(proxyUrl, 'MediaFlow proxyUrl');
  mediaFlowConfig.publicIp = decryptValue(publicIp, 'MediaFlow publicIp');
}

function encryptInfoInConfig(config: Config): Config {
  if (config.services) {
    config.services.forEach(
      (service) =>
        service.credentials &&
        processObjectValues(
          service.credentials,
          `service ${service.id}`,
          false,
          () => true
        )
    );
  }

  if (config.mediaFlowConfig) {
    encryptMediaFlowConfig(config.mediaFlowConfig);
  }

  if (config.addons) {
    config.addons.forEach((addon) => {
      if (addon.options) {
        processObjectValues(
          addon.options,
          `addon ${addon.id}`,
          false,
          (key) => {
            const addonDetail = addonDetails.find(
              (addonDetail) => addonDetail.id === addon.id
            );
            if (!addonDetail) return false;
            const optionDetail = addonDetail.options?.find(
              (option) => option.id === key
            );
            // Encrypt only if the option is secret
            return optionDetail?.secret ?? false;
          }
        );
      }
    });
  }
  return config;
}

function encryptMediaFlowConfig(mediaFlowConfig: {
  apiPassword: string;
  proxyUrl: string;
  publicIp: string;
}): void {
  const { apiPassword, proxyUrl, publicIp } = mediaFlowConfig;
  mediaFlowConfig.apiPassword = encryptValue(
    apiPassword,
    'MediaFlow apiPassword'
  );
  mediaFlowConfig.proxyUrl = encryptValue(proxyUrl, 'MediaFlow proxyUrl');
  mediaFlowConfig.publicIp = encryptValue(publicIp, 'MediaFlow publicIp');
}

function processObjectValues(
  obj: Record<string, any>,
  labelPrefix: string,
  decrypt: boolean,
  condition: (key: string, value: any) => boolean
): void {
  Object.keys(obj).forEach((key) => {
    const value = obj[key];
    if (condition(key, value)) {
      console.log(`|DBG| Processing ${labelPrefix} ${key}`);
      obj[key] = decrypt
        ? decryptValue(value, `${labelPrefix} ${key}`)
        : encryptValue(value, `${labelPrefix} ${key}`);
    }
  });
}

function encryptValue(value: any, label: string): any {
  if (!isValueEncrypted(value)) {
    try {
      return compressAndEncrypt(value);
    } catch (error: any) {
      console.error(`Failed to encrypt ${label}`);
      return '';
    }
  }
  return value;
}

function decryptValue(value: any, label: string): any {
  try {
    if (!isValueEncrypted(value)) return value;
    const decrypted = parseAndDecryptString(value);
    if (decrypted === null) throw new Error('Decryption failed');
    return decrypted;
  } catch (error: any) {
    console.error(`|ERR| Failed to decrypt ${label}: ${error.message}`);
    throw new Error('Failed to decrypt config');
  }
}

function isValueEncrypted(value: string | undefined): boolean {
  return value ? /^E-[0-9a-fA-F]{32}-[0-9a-fA-F]+$/.test(value) : false;
}

const rootUrl = (req: Request) =>
  `${req.protocol}://${req.hostname}${req.hostname === 'localhost' ? `:${Settings.PORT}` : ''}`;