v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var ai = A.ai;
- var t = ai.t;
-
- var VERSION = 1;
- var KEY = "relay";
- var FOLDER = "athera-relay";
- var HOME = "https://code.atherastudio.eu";
- 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"];
- var FORWARD = ["Content-Type", "Accept", "Authorization", "X-Api-Key", "X-Subscription-Token"];
-
- var keyCache = null;
-
- function quote(s) {
- return "'" + String(s).replace(/\\/g, "\\\\").replace(/'/g, "\\'") + "'";
- }
-
- function origins() {
- var list = [HOME, "null"];
- if (/^https?:$/.test(location.protocol) && list.indexOf(location.origin) < 0) list.push(location.origin);
- return list;
- }
-
- function php(hash, pages) {
- return [
- "<?php",
- "",
- "const ATHERA_RELAY_VERSION = " + VERSION + ";",
- "const ATHERA_KEY_HASH = " + quote(hash) + ";",
- "const ATHERA_ALLOW_PAGES = " + (pages ? "true" : "false") + ";",
- "const ATHERA_ORIGINS = [" + origins().map(quote).join(", ") + "];",
- "const ATHERA_API_HOSTS = [" + API_HOSTS.map(quote).join(", ") + "];",
- "const ATHERA_FORWARD = [" + FORWARD.map(quote).join(", ") + "];",
- "const ATHERA_MAX_BODY = 1048576;",
- "const ATHERA_MAX_PAGE = 2097152;",
- "const ATHERA_TIMEOUT = 60;",
- "",
- "function athera_json($status, $data)",
- "{",
- " if (!headers_sent()) {",
- " http_response_code($status);",
- " header('Content-Type: application/json; charset=utf-8');",
- " header('Cache-Control: no-store');",
- " }",
- " echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);",
- " exit;",
- "}",
- "",
- "function athera_header($name)",
- "{",
- " static $all = null;",
- " if ($all === null) {",
- " $all = [];",
- " if (function_exists('getallheaders')) {",
- " foreach ((array) getallheaders() as $k => $v) {",
- " $all[strtolower((string) $k)] = (string) $v;",
- " }",
- " }",
- " }",
- " $lower = strtolower($name);",
- " if (isset($all[$lower])) {",
- " return $all[$lower];",
- " }",
- " $key = 'HTTP_' . strtoupper(str_replace('-', '_', $name));",
- " if (isset($_SERVER[$key])) {",
- " return (string) $_SERVER[$key];",
- " }",
- " if (isset($_SERVER['REDIRECT_' . $key])) {",
- " return (string) $_SERVER['REDIRECT_' . $key];",
- " }",
- " return '';",
- "}",
- "",
- "function athera_public_ip($host)",
- "{",
- " $host = trim($host, '[]');",
- " $ips = filter_var($host, FILTER_VALIDATE_IP) ? [$host] : gethostbynamel($host);",
- " if (!$ips) {",
- " return '';",
- " }",
- " foreach ($ips as $ip) {",
- " if (!filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {",
- " return '';",
- " }",
- " 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)) {",
- " return '';",
- " }",
- " }",
- " return $ips[0];",
- "}",
- "",
- "function athera_join($base, $location)",
- "{",
- " if (preg_match('#^https?://#i', $location)) {",
- " return $location;",
- " }",
- " $p = parse_url($base);",
- " $root = $p['scheme'] . '://' . $p['host'] . (isset($p['port']) ? ':' . $p['port'] : '');",
- " if (strpos($location, '//') === 0) {",
- " return $p['scheme'] . ':' . $location;",
- " }",
- " if (strpos($location, '/') === 0) {",
- " return $root . $location;",
- " }",
- " $path = isset($p['path']) ? preg_replace('#/[^/]*$#', '/', $p['path']) : '/';",
- " return $root . $path . $location;",
- "}",
- "",
- "function athera_stream($url, $method, $headers, $body)",
- "{",
- " @set_time_limit(ATHERA_TIMEOUT + 30);",
- " while (ob_get_level() > 0) {",
- " @ob_end_clean();",
- " }",
- " header('X-Accel-Buffering: no');",
- " header('Cache-Control: no-store');",
- " $ch = curl_init($url);",
- " curl_setopt_array($ch, [",
- " CURLOPT_CUSTOMREQUEST => $method,",
- " CURLOPT_HTTPHEADER => $headers,",
- " CURLOPT_FOLLOWLOCATION => false,",
- " CURLOPT_CONNECTTIMEOUT => 10,",
- " CURLOPT_TIMEOUT => ATHERA_TIMEOUT,",
- " CURLOPT_ENCODING => '',",
- " CURLOPT_HEADERFUNCTION => function ($ch, $line) {",
- " if (preg_match('#^HTTP/\\S+\\s+(\\d{3})#', $line, $m)) {",
- " http_response_code((int) $m[1]);",
- " } elseif (preg_match('/^content-type:\\s*([^\\r\\n]+)/i', $line, $m)) {",
- " header('Content-Type: ' . trim($m[1]));",
- " }",
- " return strlen($line);",
- " },",
- " CURLOPT_WRITEFUNCTION => function ($ch, $chunk) {",
- " echo $chunk;",
- " flush();",
- " return strlen($chunk);",
- " },",
- " ]);",
- " if ($method === 'POST') {",
- " curl_setopt($ch, CURLOPT_POSTFIELDS, $body);",
- " }",
- " if (curl_exec($ch) === false && !headers_sent()) {",
- " athera_json(502, ['error' => 'upstream', 'detail' => curl_error($ch)]);",
- " }",
- " exit;",
- "}",
- "",
- "function athera_page($url)",
- "{",
- " if (!ATHERA_ALLOW_PAGES) {",
- " athera_json(403, ['error' => 'pages_off']);",
- " }",
- " @set_time_limit(ATHERA_TIMEOUT + 30);",
- " for ($hop = 0; $hop < 6; $hop++) {",
- " $p = parse_url($url);",
- " $scheme = strtolower(isset($p['scheme']) ? $p['scheme'] : '');",
- " if (!in_array($scheme, ['http', 'https'], true) || empty($p['host']) || isset($p['user']) || isset($p['pass'])) {",
- " athera_json(400, ['error' => 'target']);",
- " }",
- " $port = isset($p['port']) ? (int) $p['port'] : ($scheme === 'https' ? 443 : 80);",
- " if (!in_array($port, [80, 443, 8080, 8443], true)) {",
- " athera_json(403, ['error' => 'port']);",
- " }",
- " $ip = athera_public_ip($p['host']);",
- " if ($ip === '') {",
- " athera_json(403, ['error' => 'private']);",
- " }",
- " $buffer = '';",
- " $truncated = false;",
- " $location = '';",
- " $ch = curl_init($url);",
- " curl_setopt_array($ch, [",
- " CURLOPT_RESOLVE => [trim($p['host'], '[]') . ':' . $port . ':' . $ip],",
- " CURLOPT_FOLLOWLOCATION => false,",
- " CURLOPT_CONNECTTIMEOUT => 10,",
- " CURLOPT_TIMEOUT => ATHERA_TIMEOUT,",
- " CURLOPT_ENCODING => '',",
- " CURLOPT_HTTPHEADER => ['Accept: text/html,application/xhtml+xml,text/plain;q=0.9,*/*;q=0.5', 'User-Agent: AtheraRelay/' . ATHERA_RELAY_VERSION . ' (+' . " + quote(HOME) + " . ')'],",
- " CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$location) {",
- " if (preg_match('/^location:\\s*([^\\r\\n]+)/i', $line, $m)) {",
- " $location = trim($m[1]);",
- " }",
- " return strlen($line);",
- " },",
- " CURLOPT_WRITEFUNCTION => function ($ch, $chunk) use (&$buffer, &$truncated) {",
- " $room = ATHERA_MAX_PAGE - strlen($buffer);",
- " if ($room <= 0) {",
- " $truncated = true;",
- " return -1;",
- " }",
- " $buffer .= substr($chunk, 0, $room);",
- " return strlen($chunk);",
- " },",
- " ]);",
- " $ok = curl_exec($ch);",
- " $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);",
- " $type = (string) curl_getinfo($ch, CURLINFO_CONTENT_TYPE);",
- " if ($ok === false && !$truncated) {",
- " athera_json(502, ['error' => 'upstream', 'detail' => curl_error($ch)]);",
- " }",
- " if (in_array($status, [301, 302, 303, 307, 308], true) && $location !== '') {",
- " $url = athera_join($url, $location);",
- " continue;",
- " }",
- " $text = preg_match('#^(text/|application/(xhtml\\+xml|xml|json|ld\\+json|rss\\+xml|atom\\+xml))#i', $type) === 1;",
- " $content = $text ? $buffer : '';",
- " if ($text && preg_match('/charset=([\\w-]+)/i', $type, $m) && strtolower($m[1]) !== 'utf-8' && function_exists('mb_convert_encoding')) {",
- " $converted = @mb_convert_encoding($content, 'UTF-8', $m[1]);",
- " if ($converted !== false) {",
- " $content = $converted;",
- " }",
- " }",
- " athera_json(200, ['url' => $url, 'status' => $status, 'type' => $type, 'content' => $content, 'truncated' => $truncated]);",
- " }",
- " athera_json(508, ['error' => 'redirects']);",
- "}",
- "",
- "$origin = athera_header('Origin');",
- "$origin_ok = $origin !== '' && (in_array($origin, ATHERA_ORIGINS, true) || preg_match('#^https?://(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$#', $origin) === 1);",
- "header('X-Content-Type-Options: nosniff');",
- "header('Referrer-Policy: no-referrer');",
- "if ($origin_ok) {",
- " header('Access-Control-Allow-Origin: ' . $origin);",
- " header('Vary: Origin');",
- " header('Access-Control-Allow-Methods: GET, POST, OPTIONS');",
- " $requested = preg_replace('/[^A-Za-z0-9_, -]/', '', athera_header('Access-Control-Request-Headers'));",
- " header('Access-Control-Allow-Headers: ' . ($requested !== '' ? $requested : 'Content-Type, X-Athera-Key, X-Athera-Target, X-Athera-Mode'));",
- " header('Access-Control-Max-Age: 600');",
- " if (athera_header('Access-Control-Request-Private-Network') === 'true') {",
- " header('Access-Control-Allow-Private-Network: true');",
- " }",
- "}",
- "$method = isset($_SERVER['REQUEST_METHOD']) ? strtoupper($_SERVER['REQUEST_METHOD']) : 'GET';",
- "if ($method === 'OPTIONS') {",
- " http_response_code($origin_ok ? 204 : 403);",
- " exit;",
- "}",
- "if ($origin !== '' && !$origin_ok) {",
- " athera_json(403, ['error' => 'origin']);",
- "}",
- "$key = athera_header('X-Athera-Key');",
- "if (strlen(ATHERA_KEY_HASH) !== 64 || $key === '' || !hash_equals(ATHERA_KEY_HASH, hash('sha256', $key))) {",
- " athera_json(401, ['error' => 'key']);",
- "}",
- "if (!function_exists('curl_init')) {",
- " athera_json(500, ['error' => 'curl']);",
- "}",
- "$mode = strtolower(athera_header('X-Athera-Mode'));",
- "if ($mode === 'ping') {",
- " athera_json(200, ['ok' => true, 'relay' => 'athera', 'version' => ATHERA_RELAY_VERSION, 'pages' => ATHERA_ALLOW_PAGES, 'php' => PHP_VERSION]);",
- "}",
- "$target = athera_header('X-Athera-Target');",
- "if ($mode === 'page') {",
- " athera_page($target);",
- "}",
- "$parts = parse_url($target);",
- "if (!$parts || strtolower(isset($parts['scheme']) ? $parts['scheme'] : '') !== 'https' || empty($parts['host']) || isset($parts['user']) || isset($parts['port'])) {",
- " athera_json(400, ['error' => 'target']);",
- "}",
- "if (!in_array(strtolower($parts['host']), ATHERA_API_HOSTS, true)) {",
- " athera_json(403, ['error' => 'host', 'host' => $parts['host']]);",
- "}",
- "if ($method !== 'GET' && $method !== 'POST') {",
- " athera_json(405, ['error' => 'method']);",
- "}",
- "$body = '';",
- "if ($method === 'POST') {",
- " $body = (string) file_get_contents('php://input', false, null, 0, ATHERA_MAX_BODY + 1);",
- " if (strlen($body) > ATHERA_MAX_BODY) {",
- " athera_json(413, ['error' => 'size']);",
- " }",
- "}",
- "$forward = [];",
- "foreach (ATHERA_FORWARD as $name) {",
- " $value = athera_header($name);",
- " if ($value !== '') {",
- " $forward[] = $name . ': ' . $value;",
- " }",
- "}",
- "athera_stream($target, $method, $forward, $body);",
- ""
- ].join("\n");
- }
-
- function htaccess() {
- return [
- "DirectoryIndex relay.php",
- "Options -Indexes",
- "",
- "<IfModule mod_setenvif.c>",
- " SetEnvIf Authorization \"(.+)\" HTTP_AUTHORIZATION=$1",
- "</IfModule>",
- "",
- "<IfModule mod_rewrite.c>",
- " RewriteEngine On",
- " RewriteCond %{HTTPS} !=on",
- " RewriteCond %{HTTP:X-Forwarded-Proto} !=https",
- " RewriteCond %{HTTP_HOST} !^(localhost|127\\.0\\.0\\.1)(:\\d+)?$",
- " RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]",
- "</IfModule>",
- "",
- "<FilesMatch \"^(?!relay\\.php$)\">",
- " Require all denied",
- "</FilesMatch>",
- "",
- "<IfModule mod_headers.c>",
- " Header always set X-Content-Type-Options \"nosniff\"",
- " Header always set Referrer-Policy \"no-referrer\"",
- " Header always set Cache-Control \"no-store\"",
- "</IfModule>",
- ""
- ].join("\n");
- }
-
- function base64url(bytes) {
- var s = "";
- for (var i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
- return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
- }
-
- async function sha256(text) {
- var buf = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
- return Array.prototype.map.call(new Uint8Array(buf), function (b) { return (b < 16 ? "0" : "") + b.toString(16); }).join("");
- }
-
- async function getKey() {
- if (keyCache === null) keyCache = (await ai.keys.get(KEY)) || "";
- return keyCache;
- }
-
- function download(name, text) {
- var a = document.createElement("a");
- a.href = URL.createObjectURL(new Blob([text], { type: "text/plain;charset=utf-8" }));
- a.download = name;
- document.body.appendChild(a);
- a.click();
- a.remove();
- setTimeout(function () { URL.revokeObjectURL(a.href); }, 30000);
- }
-
- async function writeFile(dir, name, text) {
- var handle = await dir.getFileHandle(name, { create: true });
- var w = await handle.createWritable();
- await w.write(text);
- await w.close();
- }
-
- function relayError(code, params) {
- return Object.assign(new Error(t("ai.relay.err_" + code, params || {})), { code: code });
- }
-
- async function headers(target, mode, extra) {
- var key = await getKey();
- if (!key) throw relayError("no_key");
- var h = Object.assign({}, extra || {}, { "X-Athera-Key": key });
- if (target) h["X-Athera-Target"] = target;
- if (mode) h["X-Athera-Mode"] = mode;
- return h;
- }
-
- var relay = (ai.relay = {
- FOLDER: FOLDER,
- API_HOSTS: API_HOSTS,
-
- hasKey: async function () {
- return !!(await getKey());
- },
-
- hash: function () {
- return ai.get("relay.hash");
- },
-
- newKey: async function () {
- var bytes = new Uint8Array(32);
- crypto.getRandomValues(bytes);
- var key = "athr_" + base64url(bytes);
- await ai.keys.set(KEY, key);
- keyCache = key;
- ai.set("relay.hash", await sha256(key));
- A.emit("ai-relay", "key");
- return key;
- },
-
- ensureKey: async function () {
- if (!(await getKey()) || !/^[0-9a-f]{64}$/.test(ai.get("relay.hash"))) await relay.newKey();
- return ai.get("relay.hash");
- },
-
- files: async function () {
- var hash = await relay.ensureKey();
- return { php: php(hash, !!ai.get("relay.pages")), htaccess: htaccess() };
- },
-
- download: async function (which) {
- var f = await relay.files();
- if (which === "htaccess") download("relayhtaccess.txt", f.htaccess);
- else download("relayphp.txt", f.php);
- },
-
- canSave: function () {
- return typeof window.showDirectoryPicker === "function";
- },
-
- saveToFolder: async function () {
- var f = await relay.files();
- var root = await window.showDirectoryPicker({ mode: "readwrite", id: "athera-relay" });
- var dir = await root.getDirectoryHandle(FOLDER, { create: true });
- await writeFile(dir, "relay.php", f.php);
- var htaccessName = ".htaccess";
- try {
- await writeFile(dir, ".htaccess", f.htaccess);
- } catch (e) {
- htaccessName = "htaccess.txt";
- await writeFile(dir, htaccessName, f.htaccess);
- }
- return { folder: root.name + "/" + FOLDER, htaccess: htaccessName };
- },
-
- headers: headers,
-
- test: async function (url) {
- url = String(url || ai.get("relay.url") || "").trim();
- if (!ai.validRelay(url)) throw relayError("url");
- var res;
- try {
- res = await fetch(url, { method: "GET", headers: await headers("", "ping"), credentials: "omit", referrerPolicy: "no-referrer", cache: "no-store" });
- } catch (e) {
- throw relayError("network");
- }
- var data = null;
- try { data = await res.json(); } catch (e) { data = null; }
- if (res.status === 401) throw relayError("key");
- if (res.status === 403 && data && data.error === "origin") throw relayError("origin");
- if (data && data.error === "curl") throw relayError("curl");
- if (!res.ok || !data || data.relay !== "athera") throw relayError("response", { status: res.status });
- return { version: data.version, pages: !!data.pages, php: data.php || "", outdated: data.version < VERSION };
- },
-
- page: async function (target, signal) {
- var url = ai.relayUrl();
- if (!url) throw relayError("off");
- var res = await fetch(url, { method: "GET", headers: await headers(target, "page"), signal: signal, credentials: "omit", referrerPolicy: "no-referrer", cache: "no-store" });
- var data = null;
- try { data = await res.json(); } catch (e) { data = null; }
- if (res.status === 401) throw relayError("key");
- if (data && data.error === "pages_off") throw relayError("pages_off");
- if (data && (data.error === "private" || data.error === "port")) throw relayError("private");
- if (!res.ok || !data || typeof data.content !== "string") throw relayError("response", { status: res.status });
- return data;
- }
- });
-
- A.on("ai-keys", function () { keyCache = null; });
- })();
-