WebOrbiton
v1.5.0

AtheraStudio Code

458 lines · 18.6 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var ai = A.ai;
  6. var t = ai.t;
  7. ​
  8. var VERSION = 1;
  9. var KEY = "relay";
  10. var FOLDER = "athera-relay";
  11. var HOME = "https://code.atherastudio.eu";
  12. var API_HOSTS = ["cloud.webatlasindex.pl", "api.tavily.com", "api.firecrawl.dev", "google.serper.dev", "api.exa.ai", "api.search.brave.com", "www.searchapi.io", "api.mojeek.com", "platform.yep.com", "serpapi.com"];
  13. var FORWARD = ["Content-Type", "Accept", "Authorization", "X-Api-Key", "X-Subscription-Token"];
  14. ​
  15. var keyCache = null;
  16. ​
  17. function quote(s) {
  18. return "'" + String(s).replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'";
  19. }
  20. ​
  21. function origins() {
  22. var list = [HOME, "null"];
  23. if (/^https?:$/.test(location.protocol) && list.indexOf(location.origin) < 0) list.push(location.origin);
  24. return list;
  25. }
  26. ​
  27. function php(hash, pages) {
  28. return [
  29. "<?php",
  30. "",
  31. "const ATHERA_RELAY_VERSION = " + VERSION + ";",
  32. "const ATHERA_KEY_HASH = " + quote(hash) + ";",
  33. "const ATHERA_ALLOW_PAGES = " + (pages ? "true" : "false") + ";",
  34. "const ATHERA_ORIGINS = [" + origins().map(quote).join(", ") + "];",
  35. "const ATHERA_API_HOSTS = [" + API_HOSTS.map(quote).join(", ") + "];",
  36. "const ATHERA_FORWARD = [" + FORWARD.map(quote).join(", ") + "];",
  37. "const ATHERA_MAX_BODY = 1048576;",
  38. "const ATHERA_MAX_PAGE = 2097152;",
  39. "const ATHERA_TIMEOUT = 60;",
  40. "",
  41. "function athera_json($status, $data)",
  42. "{",
  43. " if (!headers_sent()) {",
  44. " http_response_code($status);",
  45. " header('Content-Type: application/json; charset=utf-8');",
  46. " header('Cache-Control: no-store');",
  47. " }",
  48. " echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);",
  49. " exit;",
  50. "}",
  51. "",
  52. "function athera_header($name)",
  53. "{",
  54. " static $all = null;",
  55. " if ($all === null) {",
  56. " $all = [];",
  57. " if (function_exists('getallheaders')) {",
  58. " foreach ((array) getallheaders() as $k => $v) {",
  59. " $all[strtolower((string) $k)] = (string) $v;",
  60. " }",
  61. " }",
  62. " }",
  63. " $lower = strtolower($name);",
  64. " if (isset($all[$lower])) {",
  65. " return $all[$lower];",
  66. " }",
  67. " $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));",
  68. " if (isset($_SERVER[$key])) {",
  69. " return (string) $_SERVER[$key];",
  70. " }",
  71. " if (isset($_SERVER['REDIRECT_' . $key])) {",
  72. " return (string) $_SERVER['REDIRECT_' . $key];",
  73. " }",
  74. " return '';",
  75. "}",
  76. "",
  77. "function athera_public_ip($host)",
  78. "{",
  79. " $host = trim($host, '[]');",
  80. " $ips = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : gethostbynamel($host);",
  81. " if (!$ips) {",
  82. " return '';",
  83. " }",
  84. " foreach ($ips as $ip) {",
  85. " if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {",
  86. " return '';",
  87. " }",
  88. " if (preg_match('/^(0\\.|100\\.(6[4-9]|[7-9][0-9]|1[01][0-9]|12[0-7])\\.|169\\.254\\.|192\\.0\\.0\\.|198\\.1[89]\\.)/', $ip)) {",
  89. " return '';",
  90. " }",
  91. " }",
  92. " return $ips[0];",
  93. "}",
  94. "",
  95. "function athera_join($base, $location)",
  96. "{",
  97. " if (preg_match('#^https?://#i', $location)) {",
  98. " return $location;",
  99. " }",
  100. " $p = parse_url($base);",
  101. " $root = $p['scheme'] . '://' . $p['host'] . (isset($p['port']) ? ':' . $p['port'] : '');",
  102. " if (strpos($location, '//') === 0) {",
  103. " return $p['scheme'] . ':' . $location;",
  104. " }",
  105. " if (strpos($location, '/') === 0) {",
  106. " return $root . $location;",
  107. " }",
  108. " $path = isset($p['path']) ? preg_replace('#/[^/]*$#', '/', $p['path']) : '/';",
  109. " return $root . $path . $location;",
  110. "}",
  111. "",
  112. "function athera_stream($url, $method, $headers, $body)",
  113. "{",
  114. " @set_time_limit(ATHERA_TIMEOUT + 30);",
  115. " while (ob_get_level() > 0) {",
  116. " @ob_end_clean();",
  117. " }",
  118. " header('X-Accel-Buffering: no');",
  119. " header('Cache-Control: no-store');",
  120. " $ch = curl_init($url);",
  121. " curl_setopt_array($ch, [",
  122. " CURLOPT_CUSTOMREQUEST => $method,",
  123. " CURLOPT_HTTPHEADER => $headers,",
  124. " CURLOPT_FOLLOWLOCATION => false,",
  125. " CURLOPT_CONNECTTIMEOUT => 10,",
  126. " CURLOPT_TIMEOUT => ATHERA_TIMEOUT,",
  127. " CURLOPT_ENCODING => '',",
  128. " CURLOPT_HEADERFUNCTION => function ($ch, $line) {",
  129. " if (preg_match('#^HTTP/\\S+\\s+(\\d{3})#', $line, $m)) {",
  130. " http_response_code((int) $m[1]);",
  131. " } elseif (preg_match('/^content-type:\\s*([^\\r\\n]+)/i', $line, $m)) {",
  132. " header('Content-Type: ' . trim($m[1]));",
  133. " }",
  134. " return strlen($line);",
  135. " },",
  136. " CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {",
  137. " echo $chunk;",
  138. " flush();",
  139. " return strlen($chunk);",
  140. " },",
  141. " ]);",
  142. " if ($method === 'POST') {",
  143. " curl_setopt($ch, CURLOPT_POSTFIELDS, $body);",
  144. " }",
  145. " if (curl_exec($ch) === false && !headers_sent()) {",
  146. " athera_json(502, ['error' => 'upstream', 'detail' => curl_error($ch)]);",
  147. " }",
  148. " exit;",
  149. "}",
  150. "",
  151. "function athera_page($url)",
  152. "{",
  153. " if (!ATHERA_ALLOW_PAGES) {",
  154. " athera_json(403, ['error' => 'pages_off']);",
  155. " }",
  156. " @set_time_limit(ATHERA_TIMEOUT + 30);",
  157. " for ($hop = 0; $hop < 6; $hop++) {",
  158. " $p = parse_url($url);",
  159. " $scheme = strtolower(isset($p['scheme']) ? $p['scheme'] : '');",
  160. " if (!in_array($scheme, ['http', 'https'], true) || empty($p['host']) || isset($p['user']) || isset($p['pass'])) {",
  161. " athera_json(400, ['error' => 'target']);",
  162. " }",
  163. " $port = isset($p['port']) ? (int) $p['port'] : ($scheme === 'https' ? 443 : 80);",
  164. " if (!in_array($port, [80, 443, 8080, 8443], true)) {",
  165. " athera_json(403, ['error' => 'port']);",
  166. " }",
  167. " $ip = athera_public_ip($p['host']);",
  168. " if ($ip === '') {",
  169. " athera_json(403, ['error' => 'private']);",
  170. " }",
  171. " $buffer = '';",
  172. " $truncated = false;",
  173. " $location = '';",
  174. " $ch = curl_init($url);",
  175. " curl_setopt_array($ch, [",
  176. " CURLOPT_RESOLVE => [trim($p['host'], '[]') . ':' . $port . ':' . $ip],",
  177. " CURLOPT_FOLLOWLOCATION => false,",
  178. " CURLOPT_CONNECTTIMEOUT => 10,",
  179. " CURLOPT_TIMEOUT => ATHERA_TIMEOUT,",
  180. " CURLOPT_ENCODING => '',",
  181. " CURLOPT_HTTPHEADER => ['Accept: text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5', 'User-Agent: AtheraRelay/' . ATHERA_RELAY_VERSION . ' (+' . " + quote(HOME) + " . ')'],",
  182. " CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$location) {",
  183. " if (preg_match('/^location:\\s*([^\\r\\n]+)/i', $line, $m)) {",
  184. " $location = trim($m[1]);",
  185. " }",
  186. " return strlen($line);",
  187. " },",
  188. " CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$buffer, &$truncated) {",
  189. " $room = ATHERA_MAX_PAGE - strlen($buffer);",
  190. " if ($room <= 0) {",
  191. " $truncated = true;",
  192. " return -1;",
  193. " }",
  194. " $buffer .= substr($chunk, 0, $room);",
  195. " return strlen($chunk);",
  196. " },",
  197. " ]);",
  198. " $ok = curl_exec($ch);",
  199. " $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);",
  200. " $type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);",
  201. " if ($ok === false && !$truncated) {",
  202. " athera_json(502, ['error' => 'upstream', 'detail' => curl_error($ch)]);",
  203. " }",
  204. " if (in_array($status, [301, 302, 303, 307, 308], true) && $location !== '') {",
  205. " $url = athera_join($url, $location);",
  206. " continue;",
  207. " }",
  208. " $text = preg_match('#^(text/|application/(xhtml\\+xml|xml|json|ld\\+json|rss\\+xml|atom\\+xml))#i', $type) === 1;",
  209. " $content = $text ? $buffer : '';",
  210. " if ($text && preg_match('/charset=([\\w-]+)/i', $type, $m) && strtolower($m[1]) !== 'utf-8' && function_exists('mb_convert_encoding')) {",
  211. " $converted = @mb_convert_encoding($content, 'UTF-8', $m[1]);",
  212. " if ($converted !== false) {",
  213. " $content = $converted;",
  214. " }",
  215. " }",
  216. " athera_json(200, ['url' => $url, 'status' => $status, 'type' => $type, 'content' => $content, 'truncated' => $truncated]);",
  217. " }",
  218. " athera_json(508, ['error' => 'redirects']);",
  219. "}",
  220. "",
  221. "$origin = athera_header('Origin');",
  222. "$origin_ok = $origin !== '' && (in_array($origin, ATHERA_ORIGINS, true) || preg_match('#^https?://(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$#', $origin) === 1);",
  223. "header('X-Content-Type-Options: nosniff');",
  224. "header('Referrer-Policy: no-referrer');",
  225. "if ($origin_ok) {",
  226. " header('Access-Control-Allow-Origin: ' . $origin);",
  227. " header('Vary: Origin');",
  228. " header('Access-Control-Allow-Methods: GET, POST, OPTIONS');",
  229. " $requested = preg_replace('/[^A-Za-z0-9_, -]/', '', athera_header('Access-Control-Request-Headers'));",
  230. " header('Access-Control-Allow-Headers: ' . ($requested !== '' ? $requested : 'Content-Type, X-Athera-Key, X-Athera-Target, X-Athera-Mode'));",
  231. " header('Access-Control-Max-Age: 600');",
  232. " if (athera_header('Access-Control-Request-Private-Network') === 'true') {",
  233. " header('Access-Control-Allow-Private-Network: true');",
  234. " }",
  235. "}",
  236. "$method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';",
  237. "if ($method === 'OPTIONS') {",
  238. " http_response_code($origin_ok ? 204 : 403);",
  239. " exit;",
  240. "}",
  241. "if ($origin !== '' && !$origin_ok) {",
  242. " athera_json(403, ['error' => 'origin']);",
  243. "}",
  244. "$key = athera_header('X-Athera-Key');",
  245. "if (strlen(ATHERA_KEY_HASH) !== 64 || $key === '' || !hash_equals(ATHERA_KEY_HASH, hash('sha256', $key))) {",
  246. " athera_json(401, ['error' => 'key']);",
  247. "}",
  248. "if (!function_exists('curl_init')) {",
  249. " athera_json(500, ['error' => 'curl']);",
  250. "}",
  251. "$mode = strtolower(athera_header('X-Athera-Mode'));",
  252. "if ($mode === 'ping') {",
  253. " athera_json(200, ['ok' => true, 'relay' => 'athera', 'version' => ATHERA_RELAY_VERSION, 'pages' => ATHERA_ALLOW_PAGES, 'php' => PHP_VERSION]);",
  254. "}",
  255. "$target = athera_header('X-Athera-Target');",
  256. "if ($mode === 'page') {",
  257. " athera_page($target);",
  258. "}",
  259. "$parts = parse_url($target);",
  260. "if (!$parts || strtolower(isset($parts['scheme']) ? $parts['scheme'] : '') !== 'https' || empty($parts['host']) || isset($parts['user']) || isset($parts['port'])) {",
  261. " athera_json(400, ['error' => 'target']);",
  262. "}",
  263. "if (!in_array(strtolower($parts['host']), ATHERA_API_HOSTS, true)) {",
  264. " athera_json(403, ['error' => 'host', 'host' => $parts['host']]);",
  265. "}",
  266. "if ($method !== 'GET' && $method !== 'POST') {",
  267. " athera_json(405, ['error' => 'method']);",
  268. "}",
  269. "$body = '';",
  270. "if ($method === 'POST') {",
  271. " $body = (string) file_get_contents('php://input', false, null, 0, ATHERA_MAX_BODY + 1);",
  272. " if (strlen($body) > ATHERA_MAX_BODY) {",
  273. " athera_json(413, ['error' => 'size']);",
  274. " }",
  275. "}",
  276. "$forward = [];",
  277. "foreach (ATHERA_FORWARD as $name) {",
  278. " $value = athera_header($name);",
  279. " if ($value !== '') {",
  280. " $forward[] = $name . ': ' . $value;",
  281. " }",
  282. "}",
  283. "athera_stream($target, $method, $forward, $body);",
  284. ""
  285. ].join("\n");
  286. }
  287. ​
  288. function htaccess() {
  289. return [
  290. "DirectoryIndex relay.php",
  291. "Options -Indexes",
  292. "",
  293. "<IfModule mod_setenvif.c>",
  294. " SetEnvIf Authorization \"(.+)\" HTTP_AUTHORIZATION=$1",
  295. "</IfModule>",
  296. "",
  297. "<IfModule mod_rewrite.c>",
  298. " RewriteEngine On",
  299. " RewriteCond %{HTTPS} !=on",
  300. " RewriteCond %{HTTP:X-Forwarded-Proto} !=https",
  301. " RewriteCond %{HTTP_HOST} !^(localhost|127\\.0\\.0\\.1)(:\\d+)?$",
  302. " RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]",
  303. "</IfModule>",
  304. "",
  305. "<FilesMatch \"^(?!relay\\.php$)\">",
  306. " Require all denied",
  307. "</FilesMatch>",
  308. "",
  309. "<IfModule mod_headers.c>",
  310. " Header always set X-Content-Type-Options \"nosniff\"",
  311. " Header always set Referrer-Policy \"no-referrer\"",
  312. " Header always set Cache-Control \"no-store\"",
  313. "</IfModule>",
  314. ""
  315. ].join("\n");
  316. }
  317. ​
  318. function base64url(bytes) {
  319. var s = "";
  320. for (var i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
  321. return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
  322. }
  323. ​
  324. async function sha256(text) {
  325. var buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
  326. return Array.prototype.map.call(new Uint8Array(buf), function (b) { return (b < 16 ? "0" : "") + b.toString(16); }).join("");
  327. }
  328. ​
  329. async function getKey() {
  330. if (keyCache === null) keyCache = (await ai.keys.get(KEY)) || "";
  331. return keyCache;
  332. }
  333. ​
  334. function download(name, text) {
  335. var a = document.createElement("a");
  336. a.href = URL.createObjectURL(new Blob([text], { type: "text/plain;charset=utf-8" }));
  337. a.download = name;
  338. document.body.appendChild(a);
  339. a.click();
  340. a.remove();
  341. setTimeout(function () { URL.revokeObjectURL(a.href); }, 30000);
  342. }
  343. ​
  344. async function writeFile(dir, name, text) {
  345. var handle = await dir.getFileHandle(name, { create: true });
  346. var w = await handle.createWritable();
  347. await w.write(text);
  348. await w.close();
  349. }
  350. ​
  351. function relayError(code, params) {
  352. return Object.assign(new Error(t("ai.relay.err_" + code, params || {})), { code: code });
  353. }
  354. ​
  355. async function headers(target, mode, extra) {
  356. var key = await getKey();
  357. if (!key) throw relayError("no_key");
  358. var h = Object.assign({}, extra || {}, { "X-Athera-Key": key });
  359. if (target) h["X-Athera-Target"] = target;
  360. if (mode) h["X-Athera-Mode"] = mode;
  361. return h;
  362. }
  363. ​
  364. var relay = (ai.relay = {
  365. FOLDER: FOLDER,
  366. API_HOSTS: API_HOSTS,
  367. ​
  368. hasKey: async function () {
  369. return !!(await getKey());
  370. },
  371. ​
  372. hash: function () {
  373. return ai.get("relay.hash");
  374. },
  375. ​
  376. newKey: async function () {
  377. var bytes = new Uint8Array(32);
  378. crypto.getRandomValues(bytes);
  379. var key = "athr_" + base64url(bytes);
  380. await ai.keys.set(KEY, key);
  381. keyCache = key;
  382. ai.set("relay.hash", await sha256(key));
  383. A.emit("ai-relay", "key");
  384. return key;
  385. },
  386. ​
  387. ensureKey: async function () {
  388. if (!(await getKey()) || !/^[0-9a-f]{64}$/.test(ai.get("relay.hash"))) await relay.newKey();
  389. return ai.get("relay.hash");
  390. },
  391. ​
  392. files: async function () {
  393. var hash = await relay.ensureKey();
  394. return { php: php(hash, !!ai.get("relay.pages")), htaccess: htaccess() };
  395. },
  396. ​
  397. download: async function (which) {
  398. var f = await relay.files();
  399. if (which === "htaccess") download("relayhtaccess.txt", f.htaccess);
  400. else download("relayphp.txt", f.php);
  401. },
  402. ​
  403. canSave: function () {
  404. return typeof window.showDirectoryPicker === "function";
  405. },
  406. ​
  407. saveToFolder: async function () {
  408. var f = await relay.files();
  409. var root = await window.showDirectoryPicker({ mode: "readwrite", id: "athera-relay" });
  410. var dir = await root.getDirectoryHandle(FOLDER, { create: true });
  411. await writeFile(dir, "relay.php", f.php);
  412. var htaccessName = ".htaccess";
  413. try {
  414. await writeFile(dir, ".htaccess", f.htaccess);
  415. } catch (e) {
  416. htaccessName = "htaccess.txt";
  417. await writeFile(dir, htaccessName, f.htaccess);
  418. }
  419. return { folder: root.name + "/" + FOLDER, htaccess: htaccessName };
  420. },
  421. ​
  422. headers: headers,
  423. ​
  424. test: async function (url) {
  425. url = String(url || ai.get("relay.url") || "").trim();
  426. if (!ai.validRelay(url)) throw relayError("url");
  427. var res;
  428. try {
  429. res = await fetch(url, { method: "GET", headers: await headers("", "ping"), credentials: "omit", referrerPolicy: "no-referrer", cache: "no-store" });
  430. } catch (e) {
  431. throw relayError("network");
  432. }
  433. var data = null;
  434. try { data = await res.json(); } catch (e) { data = null; }
  435. if (res.status === 401) throw relayError("key");
  436. if (res.status === 403 && data && data.error === "origin") throw relayError("origin");
  437. if (data && data.error === "curl") throw relayError("curl");
  438. if (!res.ok || !data || data.relay !== "athera") throw relayError("response", { status: res.status });
  439. return { version: data.version, pages: !!data.pages, php: data.php || "", outdated: data.version < VERSION };
  440. },
  441. ​
  442. page: async function (target, signal) {
  443. var url = ai.relayUrl();
  444. if (!url) throw relayError("off");
  445. var res = await fetch(url, { method: "GET", headers: await headers(target, "page"), signal: signal, credentials: "omit", referrerPolicy: "no-referrer", cache: "no-store" });
  446. var data = null;
  447. try { data = await res.json(); } catch (e) { data = null; }
  448. if (res.status === 401) throw relayError("key");
  449. if (data && data.error === "pages_off") throw relayError("pages_off");
  450. if (data && (data.error === "private" || data.error === "port")) throw relayError("private");
  451. if (!res.ok || !data || typeof data.content !== "string") throw relayError("response", { status: res.status });
  452. return data;
  453. }
  454. });
  455. ​
  456. A.on("ai-keys", function () { keyCache = null; });
  457. })();
  458. ​