#include "browser/browser_app.hpp" #include "dom/html_parser.hpp" #include "style/css_engine.hpp" #include #include #include #include #include #include #include #include #include namespace astra { namespace { bool ends_with(std::string_view s, std::string_view suffix) { return s.size() >= suffix.size() && s.substr(s.size() - suffix.size()) == suffix; } bool read_local_file(const std::string& path, std::string& out) { std::ifstream f(path, std::ios::binary); if (!f) return false; std::ostringstream oss; oss << f.rdbuf(); out = oss.str(); return true; } uint64_t fnv1a_64(std::string_view s) { uint64_t h = 14695981039346656037ULL; for (unsigned char c : s) { h ^= c; h *= 1099511628211ULL; } return h; } std::string origin_storage_path(const std::string& origin_key) { std::error_code ec; std::filesystem::create_directories("/tmp/astra_origin_storage", ec); std::ostringstream oss; oss << "/tmp/astra_origin_storage/" << std::hex << fnv1a_64(origin_key) << ".kv"; return oss.str(); } std::string format_mmss(double sec) { if (sec < 0.0) sec = 0.0; int mins = static_cast(sec) / 60; double rem = sec - mins * 60; std::ostringstream oss; oss << std::setw(2) << std::setfill('0') << mins << ":" << std::fixed << std::setprecision(1) << std::setw(4) << std::setfill('0') << rem; return oss.str(); } std::string normalize_omnibox_url(std::string raw) { while (!raw.empty() && std::isspace(static_cast(raw.front()))) raw.erase(raw.begin()); while (!raw.empty() && std::isspace(static_cast(raw.back()))) raw.pop_back(); if (raw.empty()) return "astra://home"; if (raw.rfind("http://", 0) == 0 || raw.rfind("https://", 0) == 0 || raw.rfind("file://", 0) == 0 || raw.rfind("astra://", 0) == 0) { return raw; } return "https://" + raw; } std::string escape_html_text(std::string_view s) { std::string out; out.reserve(s.size()); for (char c : s) { if (c == '&') out += "&"; else if (c == '<') out += "<"; else if (c == '>') out += ">"; else if (c == '"') out += """; else out.push_back(c); } return out; } std::string json_escape_str(std::string_view s) { std::string out; out.reserve(s.size() + 4); for (char c : s) { if (c == '\\') out += "\\\\"; else if (c == '"') out += "\\\""; else if (c == '\n') out += "\\n"; else if (c == '\r') out += "\\r"; else out.push_back(c); } return out; } std::string url_encode_component(std::string_view s) { static constexpr char kHex[] = "0123456789ABCDEF"; std::string out; out.reserve(s.size() * 3 / 2 + 4); for (unsigned char c : s) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') { out.push_back(static_cast(c)); } else { out.push_back('%'); out.push_back(kHex[(c >> 4) & 0xF]); out.push_back(kHex[c & 0xF]); } } return out; } std::string to_lower_copy(std::string_view s) { std::string out(s); for (char& c : out) c = static_cast(std::tolower(static_cast(c))); return out; } void collect_form_fields(const DomNode* node, std::vector>& fields) { if (!node) return; if (node->type == NodeType::Element && (node->tag == "input" || node->tag == "textarea")) { std::string name = node->get_attr("name"); if (!name.empty()) { fields.emplace_back(name, node->get_attr("value")); } } for (const DomNode* ch : node->children) { collect_form_fields(ch, fields); } } std::string build_downloads_html(const std::vector& downloads) { size_t total_bytes = 0; for (const auto& d : downloads) { if (d.ok) total_bytes += d.bytes; } std::ostringstream html; html << "Astra Downloads — Native Manager" << "" << "
" << "
ASTRA DOWNLOADS MANAGER | SHA-256 VERIFIED | HTTP/2 + TLS 1.3 + ASTRASHIELD
" << "

Native Downloads Ledger

" << "

Every file downloaded through Astra is filtered by AstraShield + MV3 DNR, written to /tmp/astra_downloads/, and checksummed with native FIPS 180-4 SHA-256.

" << "
" << "
" << "
TOTAL FILES
" << downloads.size() << "
" << "
TOTAL SAVED
" << total_bytes << " B
" << "
INTEGRITY
SHA-256
" << "
"; if (downloads.empty()) { html << "
No downloads yet
" << "
Click any <a download> link or run: astra --download <url>
"; } else { for (auto it = downloads.rbegin(); it != downloads.rend(); ++it) { const auto& d = *it; html << "
" << "
" << escape_html_text(d.filename) << " [" << escape_html_text(d.protocol.empty() ? "http/1.1" : d.protocol) << "]
" << "
Path: " << escape_html_text(d.saved_path) << " | Size: " << d.bytes << " B | Time: " << std::fixed << std::setprecision(1) << d.elapsed_ms << " ms
" << "
SHA-256: " << escape_html_text(d.sha256_hex) << "
" << "
"; } } html << ""; return html.str(); } std::string build_home_html(const AstraShield& shield, size_t ext_count, const MemorySnapshot& mem, const CacheStats& cstats, size_t h2_count, size_t h2_mux_count, size_t dl_count) { std::ostringstream html; html << "Astra Browser v6 — Native Core" << "" << "
" << "
ASTRA v6 NATIVE C++20 | H2 MULTI-STREAM MUX | CANVAS 2D + rAF | TRY/CATCH + FOR..OF | LINEAR-GRADIENT
" << "

Astra Desktop Browser — Session 6

" << "

Multi-process e10s engine (Main + Content + RDD Media) with true single-socket HTTP/2 multi-stream multiplexing over TLS 1.3 ALPN, AstraJS v6 (try/catch/throw, for..of, requestAnimationFrame, native HTML5 <canvas> 2D), CSS linear-gradient + box-sizing: border-box (ASD5), ALSA audio waveform, and SHA-256 Downloads.

" << "
" << "
" << "
MEMORY & H2 MULTIPLEX
" << "
" << (mem.total_rss_bytes / (1024 * 1024)) << " / " << (mem.ceiling_bytes / (1024 * 1024)) << " MB
" << "
Real /proc RSS | Cache: " << cstats.hits << " | H2: " << h2_count << " (Mux: " << h2_mux_count << ")
" << "
ASTRA SHIELD PRIVACY
" << "
" << shield.blocklist_size() << " Rules | " << shield.stats().trackers_blocked << " Blocked
" << "
Total Cookie Partitioning + TLS 1.3 ALPN h2 + GPC
" << "
EXTENSIONS & DOWNLOADS
" << "
" << ext_count << " Ext | " << dl_count << " Downloads
" << "
" << "
" << "
" << "
ASTRA3D v2 SMOOTH SHADER ENGINE
" << "
" << "
ASTRAMEDIA v4 RDD INTERACTIVE PLAYER
" << "
" << "
" << ""; return html.str(); } } // namespace std::string BrowserApp::compute_sha256_hex(std::string_view data) { static constexpr uint32_t kK[64] = { 0x428a2f98u, 0x71374491u, 0xb5c0fbcfu, 0xe9b5dba5u, 0x3956c25bu, 0x59f111f1u, 0x923f82a4u, 0xab1c5ed5u, 0xd807aa98u, 0x12835b01u, 0x243185beu, 0x550c7dc3u, 0x72be5d74u, 0x80deb1feu, 0x9bdc06a7u, 0xc19bf174u, 0xe49b69c1u, 0xefbe4786u, 0x0fc19dc6u, 0x240ca1ccu, 0x2de92c6fu, 0x4a7484aau, 0x5cb0a9dcu, 0x76f988dau, 0x983e5152u, 0xa831c66du, 0xb00327c8u, 0xbf597fc7u, 0xc6e00bf3u, 0xd5a79147u, 0x06ca6351u, 0x14292967u, 0x27b70a85u, 0x2e1b2138u, 0x4d2c6dfcu, 0x53380d13u, 0x650a7354u, 0x766a0abbu, 0x81c2c92eu, 0x92722c85u, 0xa2bfe8a1u, 0xa81a664bu, 0xc24b8b70u, 0xc76c51a3u, 0xd192e819u, 0xd6990624u, 0xf40e3585u, 0x106aa070u, 0x19a4c116u, 0x1e376c08u, 0x2748774cu, 0x34b0bcb5u, 0x391c0cb3u, 0x4ed8aa4au, 0x5b9cca4fu, 0x682e6ff3u, 0x748f82eeu, 0x78a5636fu, 0x84c87814u, 0x8cc70208u, 0x90befffau, 0xa4506cebu, 0xbef9a3f7u, 0xc67178f2u }; auto rotr = [](uint32_t x, uint32_t n) -> uint32_t { return (x >> n) | (x << (32u - n)); }; uint32_t h[8] = { 0x6a09e667u, 0xbb67ae85u, 0x3c6ef372u, 0xa54ff53au, 0x510e527fu, 0x9b05688cu, 0x1f83d9abu, 0x5be0cd19u }; std::vector msg(data.begin(), data.end()); uint64_t bit_len = static_cast(msg.size()) * 8ULL; msg.push_back(0x80u); while ((msg.size() % 64) != 56) msg.push_back(0x00u); for (int i = 7; i >= 0; --i) { msg.push_back(static_cast((bit_len >> (i * 8)) & 0xFFu)); } for (size_t off = 0; off < msg.size(); off += 64) { uint32_t w[64]; for (int i = 0; i < 16; ++i) { w[i] = (static_cast(msg[off + i * 4]) << 24) | (static_cast(msg[off + i * 4 + 1]) << 16) | (static_cast(msg[off + i * 4 + 2]) << 8) | static_cast(msg[off + i * 4 + 3]); } for (int i = 16; i < 64; ++i) { uint32_t s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >> 3); uint32_t s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >> 10); w[i] = w[i - 16] + s0 + w[i - 7] + s1; } uint32_t a = h[0], b = h[1], c = h[2], d = h[3]; uint32_t e = h[4], f = h[5], g = h[6], hh = h[7]; for (int i = 0; i < 64; ++i) { uint32_t S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25); uint32_t ch = (e & f) ^ ((~e) & g); uint32_t temp1 = hh + S1 + ch + kK[i] + w[i]; uint32_t S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22); uint32_t maj = (a & b) ^ (a & c) ^ (b & c); uint32_t temp2 = S0 + maj; hh = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2; } h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh; } std::ostringstream hex; hex << std::hex << std::setfill('0'); for (int i = 0; i < 8; ++i) hex << std::setw(8) << h[i]; return hex.str(); } void BrowserApp::persist_downloads_ledger() const { std::error_code ec; std::filesystem::create_directories("/tmp/astra_downloads", ec); std::ofstream f("/tmp/astra_downloads/ledger.json", std::ios::trunc); if (!f) return; f << "[\n"; for (size_t i = 0; i < downloads_.size(); ++i) { const auto& d = downloads_[i]; f << " {\"filename\":\"" << json_escape_str(d.filename) << "\",\"url\":\"" << json_escape_str(d.url) << "\",\"saved_path\":\"" << json_escape_str(d.saved_path) << "\",\"bytes\":" << d.bytes << ",\"protocol\":\"" << json_escape_str(d.protocol) << "\",\"sha256\":\"" << d.sha256_hex << "\"}" << (i + 1 < downloads_.size() ? "," : "") << "\n"; } f << "]\n"; } DownloadRecord BrowserApp::download_url(const std::string& url, const std::string& dest_dir) { auto t0 = std::chrono::steady_clock::now(); DownloadRecord rec; rec.url = url; std::string payload; if (url.rfind("file://", 0) == 0) { std::string src_path = url.substr(7); if (!read_local_file(src_path, payload)) { rec.error = "Cannot read local file: " + src_path; return rec; } rec.protocol = "file"; } else if (url.rfind("http://", 0) == 0 || url.rfind("https://", 0) == 0) { HttpResponse resp = http_.get(url, "", false); if (resp.blocked_by_privacy || resp.blocked_by_extension) { rec.error = resp.error; return rec; } if (resp.status_code < 200 || resp.status_code >= 400) { rec.error = resp.error.empty() ? ("HTTP " + std::to_string(resp.status_code)) : resp.error; return rec; } payload = std::move(resp.body); rec.protocol = !resp.alpn_protocol.empty() ? resp.alpn_protocol : "http/1.1"; } else { rec.error = "Unsupported download scheme"; return rec; } // Derive clean filename std::string clean_url = url; size_t qpos = clean_url.find('?'); if (qpos != std::string::npos) clean_url.resize(qpos); size_t slash = clean_url.rfind('/'); std::string fname = (slash != std::string::npos && slash + 1 < clean_url.size()) ? clean_url.substr(slash + 1) : "astra_download.bin"; for (char& c : fname) { if (c == '/' || c == '\\' || c == ':' || c == '\0') c = '_'; } if (fname.empty() || fname == "." || fname == "..") fname = "astra_download.bin"; std::error_code ec; std::filesystem::create_directories(dest_dir, ec); std::string out_path = dest_dir + "/" + fname; std::ofstream out(out_path, std::ios::binary | std::ios::trunc); if (!out) { rec.error = "Cannot write download file: " + out_path; return rec; } out.write(payload.data(), static_cast(payload.size())); out.close(); auto t1 = std::chrono::steady_clock::now(); rec.filename = fname; rec.saved_path = out_path; rec.bytes = payload.size(); rec.sha256_hex = compute_sha256_hex(payload); rec.elapsed_ms = std::chrono::duration(t1 - t0).count(); rec.ok = true; downloads_.push_back(rec); persist_downloads_ledger(); return rec; } BrowserApp::BrowserApp(uint64_t ram_ceiling_bytes) : cache_("/tmp/astra_http_cache", 32ULL * 1024 * 1024), http_(shield_, &cache_), governor_(ram_ceiling_bytes) { http_.set_dnr_hook([this](const std::string& url, const std::string& top_site) { return extensions_.evaluate_dnr(url, top_site); }); } BrowserApp::~BrowserApp() { stop_workers(); } void BrowserApp::run_content_worker_loop(IpcChannel& ch) { SlabArena arena(256 * 1024); IpcMessage req; while (ch.recv(req)) { if (req.type == IpcMsgType::Shutdown) break; if (req.type == IpcMsgType::Ping) { IpcMessage pong{IpcMsgType::Pong, req.request_id, {}}; ch.send(pong); continue; } if (req.type == IpcMsgType::MemoryReportReq) { IpcMessage resp{IpcMsgType::MemoryReportResp, req.request_id, {}}; write_u32(resp.payload, static_cast(getpid())); write_u64(resp.payload, MemoryGovernor::read_process_rss_bytes(getpid())); write_u64(resp.payload, arena.bytes_used()); ch.send(resp); continue; } if (req.type == IpcMsgType::RenderHtml) { size_t off = 0; uint32_t vw = 1280, vh = 720; std::string html, extra_css; read_u32(req.payload, off, vw); read_u32(req.payload, off, vh); read_str(req.payload, off, html); read_str(req.payload, off, extra_css); arena.reset(false); HtmlDocument doc = HtmlDocument::parse(arena, html); CssStylesheet sheet; sheet.parse(doc.collect_stylesheets()); if (!extra_css.empty()) sheet.parse(extra_css); LayoutFrame* root = LayoutEngine::build_layout(arena, doc, sheet, static_cast(vw), static_cast(vh)); DisplayList dl = LayoutEngine::build_display_list(root, vw, vh); std::vector dl_blob = dl.serialize(); IpcMessage resp{IpcMsgType::DisplayListBlob, req.request_id, {}}; write_str(resp.payload, doc.title()); write_u64(resp.payload, arena.bytes_used()); write_u32(resp.payload, static_cast(dl_blob.size())); resp.payload.insert(resp.payload.end(), dl_blob.begin(), dl_blob.end()); ch.send(resp); arena.reset(true); } } } void BrowserApp::run_media_worker_loop(IpcChannel& ch) { IpcMessage req; while (ch.recv(req)) { if (req.type == IpcMsgType::Shutdown) break; if (req.type == IpcMsgType::Ping) { IpcMessage pong{IpcMsgType::Pong, req.request_id, {}}; ch.send(pong); continue; } if (req.type == IpcMsgType::DecodeVideoReq) { size_t off = 0; std::string path; uint32_t frame_idx = 0; read_str(req.payload, off, path); read_u32(req.payload, off, frame_idx); DecodedVideoFrame frame; std::string err; bool ok = MediaEngine::decode_frame(path, frame_idx, frame, &err); IpcMessage resp{IpcMsgType::DecodeVideoResp, req.request_id, {}}; write_u32(resp.payload, ok ? 1u : 0u); write_str(resp.payload, ok ? frame.codec_label : err); write_u32(resp.payload, static_cast(frame.width)); write_u32(resp.payload, static_cast(frame.height)); write_u32(resp.payload, frame.frame_index); write_u32(resp.payload, frame.total_frames); write_f32(resp.payload, static_cast(frame.pts_sec)); write_f32(resp.payload, static_cast(frame.duration_sec)); write_u32(resp.payload, frame.has_audio ? 1u : 0u); if (ok && !frame.argb.empty()) { size_t byte_len = frame.argb.size() * sizeof(uint32_t); write_u32(resp.payload, static_cast(byte_len)); const uint8_t* raw = reinterpret_cast(frame.argb.data()); resp.payload.insert(resp.payload.end(), raw, raw + byte_len); } else { write_u32(resp.payload, 0u); } ch.send(resp); } } } bool BrowserApp::start_workers() { bool ok_content = content_worker_.spawn("content", [this](IpcChannel& ch) { run_content_worker_loop(ch); }); bool ok_media = media_worker_.spawn("rdd-media", [this](IpcChannel& ch) { run_media_worker_loop(ch); }); if (ok_content) governor_.register_process(content_worker_.pid(), "content"); if (ok_media) governor_.register_process(media_worker_.pid(), "rdd-media"); return ok_content && ok_media; } void BrowserApp::stop_workers() { for (auto& [key, wp] : site_workers_) { if (wp && wp->alive()) { governor_.unregister_process(wp->pid()); wp->stop(); } } site_workers_.clear(); if (content_worker_.alive()) governor_.unregister_process(content_worker_.pid()); if (media_worker_.alive()) governor_.unregister_process(media_worker_.pid()); content_worker_.stop(); media_worker_.stop(); } size_t BrowserApp::site_isolated_worker_count() const { size_t n = content_worker_.alive() ? 1 : 0; for (const auto& [k, wp] : site_workers_) { if (wp && wp->alive()) ++n; } return n; } WorkerProcess* BrowserApp::acquire_content_worker_for_origin(const SecurityOrigin& origin) { // Isolate distinct HTTP(S) eTLD+1 sites into dedicated seccomp-sandboxed content processes (bounded to 3 extra workers) if ((origin.scheme == "http" || origin.scheme == "https") && !origin.host.empty()) { std::string key = origin.site_key(); auto it = site_workers_.find(key); if (it != site_workers_.end() && it->second && it->second->alive()) { return it->second.get(); } if (site_workers_.size() < 3) { auto wp = std::make_unique(); std::string role = "site:" + origin.host; if (wp->spawn(role, [this](IpcChannel& ch) { run_content_worker_loop(ch); })) { governor_.register_process(wp->pid(), role); WorkerProcess* raw = wp.get(); site_workers_[key] = std::move(wp); return raw; } } } return content_worker_.alive() ? &content_worker_ : nullptr; } bool BrowserApp::load_extension(const std::string& dir_path, std::string* error) { return extensions_.load_extension_dir(dir_path, error); } Tab* BrowserApp::find_tab(uint32_t id) { for (auto& t : tabs_) if (t.id == id) return &t; return nullptr; } const Tab* BrowserApp::find_tab(uint32_t id) const { for (const auto& t : tabs_) if (t.id == id) return &t; return nullptr; } uint32_t BrowserApp::new_tab(const std::string& url) { Tab t; t.id = next_tab_id_++; t.url = url; t.title = "New Tab"; t.state = TabState::Active; t.last_used_tick = ++tick_counter_; t.live_arena = std::make_unique(); for (auto& existing : tabs_) { if (existing.state == TabState::Active) existing.state = TabState::Warm; } tabs_.push_back(std::move(t)); active_tab_id_ = tabs_.back().id; address_bar_focused_ = false; if (!url.empty()) { navigate(active_tab_id_, url, true); } return active_tab_id_; } bool BrowserApp::close_tab(uint32_t tab_id) { auto it = std::find_if(tabs_.begin(), tabs_.end(), [tab_id](const Tab& t) { return t.id == tab_id; }); if (it == tabs_.end()) return false; size_t idx = static_cast(std::distance(tabs_.begin(), it)); bool was_active = (tab_id == active_tab_id_); tabs_.erase(it); address_bar_focused_ = false; if (tabs_.empty()) { new_tab("astra://home"); return true; } if (was_active) { size_t next_idx = std::min(idx, tabs_.size() - 1); switch_tab(tabs_[next_idx].id); } return true; } bool BrowserApp::go_back() { Tab* active = find_tab(active_tab_id_); if (!active || active->history_index <= 0) return false; --active->history_index; std::string target = active->history[static_cast(active->history_index)]; address_bar_focused_ = false; return navigate(active->id, target, false).ok; } bool BrowserApp::go_forward() { Tab* active = find_tab(active_tab_id_); if (!active || active->history_index < 0 || static_cast(active->history_index + 1) >= active->history.size()) { return false; } ++active->history_index; std::string target = active->history[static_cast(active->history_index)]; address_bar_focused_ = false; return navigate(active->id, target, false).ok; } bool BrowserApp::reload_active_tab() { Tab* active = find_tab(active_tab_id_); if (!active || active->url.empty()) return false; address_bar_focused_ = false; return navigate(active->id, active->url, false).ok; } void BrowserApp::focus_address_bar(bool clear_text) { Tab* active = find_tab(active_tab_id_); address_bar_focused_ = true; if (clear_text) { address_bar_buffer_.clear(); } else if (active) { address_bar_buffer_ = active->url; } if (active && active->live_doc && !active->focused_input_selector.empty()) { for (DomNode* inp : active->live_doc->query_selector_all("input")) inp->set_attr("data-astra-focused", "0"); for (DomNode* ta : active->live_doc->query_selector_all("textarea")) ta->set_attr("data-astra-focused", "0"); active->focused_input_selector.clear(); relayout_live_tab(*active); } } std::string BrowserApp::origin_storage_get(const std::string& origin_key, const std::string& k) { std::ifstream f(origin_storage_path(origin_key)); if (!f) return ""; std::string line; std::string found; while (std::getline(f, line)) { size_t tab = line.find('\t'); if (tab != std::string::npos && line.substr(0, tab) == k) { found = line.substr(tab + 1); } } return found; } void BrowserApp::origin_storage_set(const std::string& origin_key, const std::string& k, const std::string& v) { std::string path = origin_storage_path(origin_key); std::unordered_map kv; { std::ifstream f(path); std::string line; while (std::getline(f, line)) { size_t tab = line.find('\t'); if (tab != std::string::npos) kv[line.substr(0, tab)] = line.substr(tab + 1); } } std::string clean_v = v; std::replace(clean_v.begin(), clean_v.end(), '\n', ' '); std::replace(clean_v.begin(), clean_v.end(), '\r', ' '); kv[k] = clean_v; // Enforce bounded storage (max 1 MiB per origin) std::ostringstream oss; size_t total = 0; for (const auto& [ek, ev] : kv) { if (total + ek.size() + ev.size() + 2 > 1024 * 1024) break; oss << ek << '\t' << ev << '\n'; total += ek.size() + ev.size() + 2; } std::ofstream out(path, std::ios::trunc); out << oss.str(); } std::string BrowserApp::resolve_source_html(const std::string& url, std::string& final_url, bool& tls_verified_out, bool& from_cache_out, std::string& protocol_out, std::string& error_out, std::string* csp_header_out) { final_url = url; tls_verified_out = false; from_cache_out = false; protocol_out = "astra"; if (csp_header_out) csp_header_out->clear(); if (url == "astra://home" || url == "astra://start") { return build_home_html(shield_, extensions_.extensions().size(), memory_snapshot(), cache_.stats(), http_.http2_requests(), http_.http2_multiplexed_streams(), downloads_.size()); } if (url == "astra://downloads") { return build_downloads_html(downloads_); } if (url == "astra://3d") { return "Astra3D Studio" "" "

Astra3D v2 Smooth Shader Studio

" "
" "" "" "
"; } if (url.rfind("file://", 0) == 0) { protocol_out = "file"; std::string path = url.substr(7); size_t qpos = path.find_first_of("?#"); if (qpos != std::string::npos) path = path.substr(0, qpos); if (ends_with(path, ".pdf")) { ParsedDocument doc = DocViewer::parse_pdf_file(path); if (!doc.ok) { error_out = doc.error; return {}; } return DocViewer::to_astra_html(doc); } if (ends_with(path, ".md")) { ParsedDocument doc = DocViewer::parse_markdown_file(path); if (!doc.ok) { error_out = doc.error; return {}; } return DocViewer::to_astra_html(doc); } if (ends_with(path, ".obj")) { return "Astra3D Model: " + path + "" "

Native 3D OBJ Viewer

"; } if (ends_with(path, ".mp4") || ends_with(path, ".webm") || ends_with(path, ".y4m")) { return "AstraMedia Player: " + path + "" "

AstraMedia Native Video Player

"; } if (ends_with(path, ".wav")) { return "AstraMedia Audio: " + path + "" "

AstraMedia v4 Native Audio Player

"; } std::string text; if (!read_local_file(path, text)) { error_out = "Cannot open local file: " + path; return {}; } return text; } HttpResponse resp = http_.get(url, "", true); final_url = resp.final_url.empty() ? url : resp.final_url; tls_verified_out = resp.tls_verified; from_cache_out = resp.from_cache; protocol_out = !resp.alpn_protocol.empty() ? resp.alpn_protocol : "http/1.1"; if (csp_header_out) { for (const auto& [hk, hv] : resp.headers) { if (to_lower_copy(hk) == "content-security-policy") { *csp_header_out = hv; break; } } } if (resp.blocked_by_privacy || resp.blocked_by_extension) { error_out = resp.error; return "Request Blocked" "

Protected by Astra

" + resp.error + "

URL: " + final_url + "

"; } if (!resp.error.empty() || resp.status_code == 0) { error_out = resp.error.empty() ? "Network error" : resp.error; return {}; } if (resp.content_type.find("application/pdf") != std::string::npos) { ParsedDocument pdf = DocViewer::parse_pdf_bytes(resp.body, final_url); return pdf.ok ? DocViewer::to_astra_html(pdf) : ("

PDF Error

" + pdf.error + "

"); } return resp.body; } std::string BrowserApp::fetch_external_stylesheets(const HtmlDocument& doc, const std::string& base_url, size_t& loaded_count, const SecurityOrigin* doc_origin, const ContentSecurityPolicy* csp) { std::string combined; loaded_count = 0; ParsedUrl base = parse_url(base_url); std::string top_site = base.valid ? base.registrable_domain() : ""; std::vector remote_urls; for (DomNode* link : doc.query_selector_all("link")) { if (link->get_attr("rel") != "stylesheet") continue; std::string href = link->get_attr("href"); if (href.empty()) continue; std::string resolved = HttpClient::resolve_relative_url(base_url, href); if (doc_origin) { if (MixedContentBlocker::is_blocked(*doc_origin, resolved, ResourceKind::Style)) { ++security_blocks_; continue; } if (csp && csp->active() && !csp->allows_url(ResourceKind::Style, resolved, *doc_origin)) { ++security_blocks_; continue; } } if (resolved.rfind("file://", 0) == 0) { std::string css; if (read_local_file(resolved.substr(7), css)) { combined += "\n" + css; ++loaded_count; } } else if (resolved.rfind("http://", 0) == 0 || resolved.rfind("https://", 0) == 0) { remote_urls.push_back(resolved); } } if (!remote_urls.empty()) { auto responses = http_.fetch_batch(remote_urls, top_site, 4); for (const auto& r : responses) { if (!r.blocked_by_privacy && !r.blocked_by_extension && r.status_code == 200) { combined += "\n" + r.body; ++loaded_count; } } } return combined; } void BrowserApp::preload_remote_images_parallel(const HtmlDocument& doc, const std::string& base_url) { std::vector remote_imgs; for (DomNode* img : doc.query_selector_all("img")) { std::string src = img->get_attr("src"); if (src.empty()) continue; std::string resolved = HttpClient::resolve_relative_url(base_url, src); if ((resolved.rfind("http://", 0) == 0 || resolved.rfind("https://", 0) == 0) && image_cache_.find(resolved) == image_cache_.end()) { remote_imgs.push_back(resolved); if (remote_imgs.size() >= 8) break; // Bound concurrent preload per page } } if (remote_imgs.size() <= 1) return; ParsedUrl base = parse_url(base_url); auto responses = http_.fetch_batch(remote_imgs, base.valid ? base.registrable_domain() : "", 4); for (size_t i = 0; i < responses.size(); ++i) { const auto& r = responses[i]; if (!r.blocked_by_privacy && !r.blocked_by_extension && r.status_code == 200 && !r.body.empty()) { DecodedImage dec = ImageDecoder::decode_bytes( reinterpret_cast(r.body.data()), r.body.size()); if (dec.valid) { if (image_cache_.size() > 32) image_cache_.clear(); image_cache_[remote_imgs[i]] = std::move(dec); } } } } bool BrowserApp::load_image_subresource(const std::string& base_url, const std::string& src, DecodedImage& out) { if (src.empty()) return false; std::string resolved = HttpClient::resolve_relative_url(base_url, src); auto it = image_cache_.find(resolved); if (it != image_cache_.end()) { out = it->second; return out.valid; } DecodedImage decoded; if (resolved.rfind("file://", 0) == 0) { decoded = ImageDecoder::decode_file(resolved.substr(7)); } else if (resolved.rfind("http://", 0) == 0 || resolved.rfind("https://", 0) == 0) { ParsedUrl b = parse_url(base_url); HttpResponse r = http_.get(resolved, b.valid ? b.registrable_domain() : "", false); if (!r.blocked_by_privacy && !r.blocked_by_extension && r.status_code == 200 && !r.body.empty()) { decoded = ImageDecoder::decode_bytes(reinterpret_cast(r.body.data()), r.body.size()); } } else { decoded = ImageDecoder::decode_file(src); } if (decoded.valid) { if (image_cache_.size() > 32) image_cache_.clear(); // Keep decoded image RAM bounded image_cache_[resolved] = decoded; out = std::move(decoded); return true; } return false; } bool BrowserApp::render_html_via_content_ipc(const std::string& html, const std::string& extra_css, uint32_t vw, uint32_t vh, DisplayList& out_dl, std::string& out_title, size_t& out_blob_bytes, size_t& out_arena_bytes, const SecurityOrigin* doc_origin) { WorkerProcess* worker = doc_origin ? acquire_content_worker_for_origin(*doc_origin) : (content_worker_.alive() ? &content_worker_ : nullptr); if (!worker || !worker->alive()) return false; IpcMessage req{IpcMsgType::RenderHtml, next_req_id_++, {}}; write_u32(req.payload, vw); write_u32(req.payload, vh); write_str(req.payload, html); write_str(req.payload, extra_css); if (!worker->channel().send(req)) return false; IpcMessage resp; if (!worker->channel().recv(resp) || resp.type != IpcMsgType::DisplayListBlob) { return false; } size_t off = 0; uint64_t arena_used = 0; uint32_t blob_len = 0; if (!read_str(resp.payload, off, out_title)) return false; if (!read_u64(resp.payload, off, arena_used)) return false; if (!read_u32(resp.payload, off, blob_len)) return false; if (off + blob_len > resp.payload.size()) return false; std::vector blob(resp.payload.begin() + static_cast(off), resp.payload.begin() + static_cast(off + blob_len)); out_blob_bytes = blob.size(); out_arena_bytes = static_cast(arena_used); return DisplayList::deserialize(blob, out_dl); } void BrowserApp::relayout_live_tab(Tab& tab, float vw, float vh) { if (!tab.live_arena || !tab.live_doc) return; CssStylesheet sheet; sheet.parse(tab.live_doc->collect_stylesheets()); if (!tab.extra_css.empty()) sheet.parse(tab.extra_css); LayoutFrame* root = LayoutEngine::build_layout(*tab.live_arena, *tab.live_doc, sheet, vw, vh); tab.cached_display_list = LayoutEngine::build_display_list(root, static_cast(vw), static_cast(vh)); tab.arena_bytes = tab.live_arena->bytes_used(); } bool BrowserApp::submit_form_for_element(Tab& tab, DomNode* trigger_el) { if (!trigger_el) return false; DomNode* form = nullptr; for (DomNode* cur = trigger_el; cur; cur = cur->parent) { if (cur->type == NodeType::Element && cur->tag == "form") { form = cur; break; } } if (!form) return false; std::string action = form->get_attr("action"); std::string method = to_lower_copy(form->get_attr("method")); if (method.empty()) method = "get"; std::vector> fields; collect_form_fields(form, fields); std::string encoded; for (size_t i = 0; i < fields.size(); ++i) { if (i > 0) encoded.push_back('&'); encoded += url_encode_component(fields[i].first) + "=" + url_encode_component(fields[i].second); } std::string target = action.empty() ? tab.url : HttpClient::resolve_relative_url(tab.url, action); if (method == "post" && (target.rfind("http://", 0) == 0 || target.rfind("https://", 0) == 0)) { ParsedUrl base = parse_url(tab.url); HttpResponse resp = http_.post(target, encoded, "application/x-www-form-urlencoded", base.valid ? base.registrable_domain() : ""); if (resp.status_code >= 200 && resp.status_code < 400 && !resp.body.empty()) { std::string tmp_path = "/tmp/astra_form_post_resp.html"; std::ofstream f(tmp_path, std::ios::binary | std::ios::trunc); f << resp.body; f.close(); navigate(tab.id, "file://" + tmp_path, true); return true; } return false; } // Default GET submission: append URL-encoded query parameters if (!encoded.empty()) { size_t hash_pos = target.find('#'); std::string frag; if (hash_pos != std::string::npos) { frag = target.substr(hash_pos); target = target.substr(0, hash_pos); } target += (target.find('?') == std::string::npos ? "?" : "&") + encoded + frag; } navigate(tab.id, target, true); return true; } NavigationResult BrowserApp::navigate(uint32_t tab_id, const std::string& url, bool push_history) { auto t0 = std::chrono::steady_clock::now(); NavigationResult res; res.tab_id = tab_id; Tab* tab = find_tab(tab_id); if (!tab) { res.error = "Tab not found"; return res; } std::string final_url, err, proto, csp_hdr; bool tls_ok = false, cached_hit = false; std::string html = resolve_source_html(url, final_url, tls_ok, cached_hit, proto, err, &csp_hdr); if (html.empty()) { res.error = err; return res; } // Reset arena cleanly (destroy live_doc first since its nodes live in live_arena) tab->live_doc.reset(); tab->js_vm.reset(); if (!tab->live_arena) tab->live_arena = std::make_unique(); tab->live_arena->reset(false); tab->live_doc = std::make_unique(HtmlDocument::parse(*tab->live_arena, html)); tab->js_vm = std::make_unique(); tab->focused_input_selector.clear(); tab->origin = SecurityOrigin::from_url(final_url); tab->csp.clear(); tab->csp_blocks = 0; // Parse CSP from HTTP Content-Security-Policy header and if (!csp_hdr.empty()) tab->csp.parse(csp_hdr); for (DomNode* meta : tab->live_doc->query_selector_all("meta")) { if (to_lower_copy(meta->get_attr("http-equiv")) == "content-security-policy") { std::string content = meta->get_attr("content"); if (!content.empty()) tab->csp.parse(content); } } // Record baseline URL & history before scripts run so JS history.pushState/replaceState updates stick if (push_history) { if (tab->history_index >= 0 && static_cast(tab->history_index + 1) < tab->history.size()) { tab->history.resize(static_cast(tab->history_index + 1)); } if (tab->history.empty() || tab->history.back() != final_url) { tab->history.push_back(final_url); tab->history_index = static_cast(tab->history.size()) - 1; } } tab->url = final_url; // Bind disk-persisted per-origin storage, SPA history, and policy-checked network fetch (GET/POST/PUT/DELETE) ParsedUrl pu = parse_url(final_url); std::string origin_key = pu.valid ? pu.origin() : final_url; tab->js_vm->bind_storage( [this, origin_key](const std::string& k) { return origin_storage_get(origin_key, k); }, [this, origin_key](const std::string& k, const std::string& v) { origin_storage_set(origin_key, k, v); }); std::string fetch_base = final_url; uint32_t captured_tab_id = tab->id; tab->js_vm->bind_fetch([this, fetch_base, captured_tab_id](const std::string& req_url, const std::string& method, const std::string& body, const std::vector>& headers) { return perform_js_fetch(fetch_base, req_url, method, body, headers, captured_tab_id); }); tab->js_vm->bind_history([this, captured_tab_id](const std::string& new_url, bool replace) { Tab* t = find_tab(captured_tab_id); if (!t) return; t->url = new_url; t->origin = SecurityOrigin::from_url(new_url); if (replace && t->history_index >= 0 && static_cast(t->history_index) < t->history.size()) { t->history[static_cast(t->history_index)] = new_url; } else { if (t->history_index >= 0 && static_cast(t->history_index + 1) < t->history.size()) { t->history.resize(static_cast(t->history_index + 1)); } t->history.push_back(new_url); t->history_index = static_cast(t->history.size()) - 1; } }, final_url); // Load external subresources through MixedContent + CSP + AstraShield + HttpCache size_t ext_css_count = 0; std::string subresource_css = fetch_external_stylesheets(*tab->live_doc, final_url, ext_css_count, &tab->origin, &tab->csp); preload_remote_images_parallel(*tab->live_doc, final_url); // Execute page