Implement VoidBuildSystem v1 (Plans 01-19) with VoidLibrary integration
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
VoidBuildSystem CI / build-and-test-gcc16 (push) Failing after 3s
This commit is contained in:
1 parent
3cac890ce9
commit
ab64147f9d
114 files changed
+23777
-1392
No files matched your search
@@ -0,0 +1,96 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Build::Registry {
|
||||
|
||||
struct HttpRequest {
|
||||
std::string method;
|
||||
std::string raw_target;
|
||||
std::string path;
|
||||
std::map<std::string, std::string, std::less<>> query;
|
||||
std::map<std::string, std::string, std::less<>> headers; // lowercase header keys
|
||||
std::map<std::string, std::string, std::less<>> cookies;
|
||||
std::string body;
|
||||
|
||||
[[nodiscard]] std::optional<std::string_view>
|
||||
header(std::string_view lower_name) const noexcept;
|
||||
[[nodiscard]] std::optional<std::string_view> cookie(std::string_view name) const noexcept;
|
||||
};
|
||||
|
||||
struct HttpResponse {
|
||||
std::uint16_t status{200};
|
||||
std::string reason{"OK"};
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
std::vector<std::string> set_cookies;
|
||||
std::string body;
|
||||
|
||||
static HttpResponse json(std::uint16_t status, std::string payload);
|
||||
static HttpResponse error_json(std::uint16_t status, std::string_view code,
|
||||
std::string_view message);
|
||||
};
|
||||
|
||||
using HttpHandler = std::function<HttpResponse(const HttpRequest &)>;
|
||||
|
||||
struct HttpServerOptions {
|
||||
std::string bind_address{"127.0.0.1"}; // Loopback default (Plan 16).
|
||||
std::uint16_t port{0}; // 0 = ephemeral OS port.
|
||||
std::size_t max_header_bytes{64ULL * 1024ULL};
|
||||
std::size_t max_body_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
};
|
||||
|
||||
// Concrete loopback HTTP/1.1 TCP server adapter (VL-004).
|
||||
class HttpServer {
|
||||
public:
|
||||
HttpServer() = default;
|
||||
~HttpServer() noexcept;
|
||||
|
||||
HttpServer(const HttpServer &) = delete;
|
||||
HttpServer &operator=(const HttpServer &) = delete;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
start(const HttpServerOptions &options, HttpHandler handler);
|
||||
|
||||
void stop() noexcept;
|
||||
|
||||
[[nodiscard]] std::uint16_t bound_port() const noexcept { return bound_port_; }
|
||||
[[nodiscard]] bool running() const noexcept { return running_.load(); }
|
||||
|
||||
private:
|
||||
void accept_loop();
|
||||
void handle_client(int client_fd);
|
||||
|
||||
int listen_fd_{-1};
|
||||
std::uint16_t bound_port_{0};
|
||||
HttpServerOptions options_;
|
||||
HttpHandler handler_;
|
||||
std::atomic<bool> running_{false};
|
||||
std::thread accept_thread_;
|
||||
};
|
||||
|
||||
// Simple loopback HTTP/1.1 client helper for testing and local registry operations.
|
||||
struct HttpClientResponse {
|
||||
std::uint16_t status{0};
|
||||
std::map<std::string, std::string, std::less<>> headers;
|
||||
std::vector<std::string> set_cookies;
|
||||
std::string body;
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<HttpClientResponse, Void::Result::Error>
|
||||
send_loopback_http(std::uint16_t port, std::string_view method, std::string_view target,
|
||||
const std::map<std::string, std::string, std::less<>> &headers = {},
|
||||
std::string_view body = {});
|
||||
|
||||
} // namespace Void::Build::Registry
|
||||
@@ -0,0 +1,150 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Build/Registry/HttpServer.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Build::Registry {
|
||||
|
||||
enum class Role { Reader, Publisher, Admin };
|
||||
|
||||
struct UserRecord {
|
||||
std::string username;
|
||||
Role role{Role::Reader};
|
||||
std::string password_salt_hex;
|
||||
std::string password_hash_hex;
|
||||
bool active{true};
|
||||
};
|
||||
|
||||
struct ApiTokenRecord {
|
||||
std::string token_id;
|
||||
std::string username;
|
||||
std::string label;
|
||||
std::string token_sha256; // Never stores plaintext bearer secret!
|
||||
std::set<std::string> scopes; // "read", "publish", "admin"
|
||||
std::int64_t expires_epoch{0}; // 0 = no expiry
|
||||
bool revoked{false};
|
||||
};
|
||||
|
||||
struct SessionRecord {
|
||||
std::string session_id_hash;
|
||||
std::string username;
|
||||
std::string csrf_token;
|
||||
std::int64_t expires_epoch{0};
|
||||
};
|
||||
|
||||
struct ReleaseMeta {
|
||||
std::string version;
|
||||
std::string sha256;
|
||||
std::uint64_t size_bytes{0};
|
||||
bool yanked{false};
|
||||
std::string publisher;
|
||||
std::int64_t published_epoch{0};
|
||||
};
|
||||
|
||||
struct PackageMeta {
|
||||
std::string name;
|
||||
std::string description;
|
||||
bool is_private{false};
|
||||
std::set<std::string> owners;
|
||||
std::map<std::string, ReleaseMeta, std::less<>> releases; // version -> ReleaseMeta
|
||||
};
|
||||
|
||||
struct AuditEntry {
|
||||
std::int64_t timestamp{0};
|
||||
std::string actor;
|
||||
std::string action;
|
||||
std::string target;
|
||||
std::string outcome;
|
||||
std::string detail; // Always secret-redacted!
|
||||
};
|
||||
|
||||
struct RegistryConfig {
|
||||
std::filesystem::path data_dir;
|
||||
std::filesystem::path web_root;
|
||||
std::string bind_address{"127.0.0.1"};
|
||||
std::uint16_t port{0};
|
||||
std::uint64_t max_upload_bytes{32ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t max_storage_bytes{2ULL * 1024ULL * 1024ULL * 1024ULL};
|
||||
std::string bootstrap_admin_user{"admin"};
|
||||
std::string bootstrap_admin_password; // Required on initial empty DB creation.
|
||||
};
|
||||
|
||||
// Hosted C++ Package Registry Service (Plan 16 + Plan 17 API/UI backend):
|
||||
// - Filesystem CAS blobs + transactional durable metadata
|
||||
// - Immutable source/binary releases (idempotent same bytes, 409 Conflict on overwrite)
|
||||
// - Archive traversal/symlink validation (never executes uploaded recipes!)
|
||||
// - Reader/Publisher/Admin roles, package ownership, private/public isolation
|
||||
// - Hashed scoped bearer tokens + HttpOnly SameSite=Strict sessions with CSRF protection
|
||||
// - Secret-redacted audit log, orphan GC, storage quotas, consistent backup/restore.
|
||||
class RegistryService {
|
||||
public:
|
||||
[[nodiscard]] static Void::Result::Result<std::unique_ptr<RegistryService>, Void::Result::Error>
|
||||
open(RegistryConfig config);
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error> start_http();
|
||||
void stop_http() noexcept;
|
||||
[[nodiscard]] std::uint16_t bound_port() const noexcept { return server_.bound_port(); }
|
||||
|
||||
// Handles a single HTTP request (directly testable without sockets too!).
|
||||
[[nodiscard]] HttpResponse handle_request(const HttpRequest &req);
|
||||
|
||||
// Consistent metadata + CAS blob backup and restore (Plan 16 acceptance #4).
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
backup_to(const std::filesystem::path &backup_dir);
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
restore_from(const std::filesystem::path &backup_dir);
|
||||
|
||||
// Direct user/token helpers for bootstrap and test fixtures.
|
||||
[[nodiscard]] Void::Result::Result<void, Void::Result::Error>
|
||||
create_user(std::string username, std::string password, Role role);
|
||||
[[nodiscard]] Void::Result::Result<std::string, Void::Result::Error>
|
||||
create_token(std::string username, std::string label, std::set<std::string> scopes,
|
||||
std::int64_t expires_epoch = 0);
|
||||
|
||||
private:
|
||||
explicit RegistryService(RegistryConfig config);
|
||||
|
||||
struct Principal {
|
||||
std::string username;
|
||||
Role role{Role::Reader};
|
||||
std::set<std::string> scopes;
|
||||
bool via_session_cookie{false};
|
||||
std::string csrf_token;
|
||||
};
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> load_locked();
|
||||
Void::Result::Result<void, Void::Result::Error> save_locked();
|
||||
std::optional<Principal> authenticate_locked(const HttpRequest &req,
|
||||
std::string &auth_err) const;
|
||||
bool check_csrf_locked(const HttpRequest &req, const Principal &p) const;
|
||||
void append_audit_locked(std::string actor, std::string action, std::string target,
|
||||
std::string outcome, std::string detail);
|
||||
std::uint64_t total_storage_bytes_locked() const;
|
||||
std::filesystem::path blob_path(std::string_view sha256) const;
|
||||
HttpResponse serve_static_web_asset(std::string_view req_path) const;
|
||||
|
||||
RegistryConfig config_;
|
||||
std::filesystem::path blobs_dir_;
|
||||
std::filesystem::path meta_file_;
|
||||
std::filesystem::path lock_file_;
|
||||
mutable std::mutex mu_;
|
||||
|
||||
std::map<std::string, UserRecord, std::less<>> users_;
|
||||
std::map<std::string, ApiTokenRecord, std::less<>> tokens_;
|
||||
std::map<std::string, SessionRecord, std::less<>> sessions_;
|
||||
std::map<std::string, PackageMeta, std::less<>> packages_;
|
||||
std::vector<AuditEntry> audits_;
|
||||
HttpServer server_;
|
||||
};
|
||||
|
||||
} // namespace Void::Build::Registry
|
||||
@@ -0,0 +1,446 @@
|
||||
#include <Void/Build/Registry/HttpServer.hpp>
|
||||
|
||||
#include <Void/Build/Util/Json.hpp>
|
||||
#include <Void/System/Types.hpp>
|
||||
#include <Void/Text/Str.hpp>
|
||||
#include <Void/Text/Url.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <arpa/inet.h>
|
||||
#include <array>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <format>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
|
||||
namespace Void::Build::Registry {
|
||||
namespace {
|
||||
|
||||
Void::Result::Error sys_err(int err, std::string msg) {
|
||||
return Void::System::make_system_error(Void::System::map_errno_to_system_code(err),
|
||||
std::move(msg), err);
|
||||
}
|
||||
|
||||
std::string to_lower(std::string_view s) { return Void::Str::to_lower_ascii(s); }
|
||||
|
||||
std::string trim(std::string_view s) { return std::string{Void::Str::trim_ascii(s)}; }
|
||||
|
||||
std::string url_decode(std::string_view s) {
|
||||
return Void::Encoding::Url::decode(s, /*plus_as_space=*/true).value_or(std::string{s});
|
||||
}
|
||||
|
||||
std::string default_reason(std::uint16_t status) {
|
||||
switch (status) {
|
||||
case 200:
|
||||
return "OK";
|
||||
case 201:
|
||||
return "Created";
|
||||
case 204:
|
||||
return "No Content";
|
||||
case 400:
|
||||
return "Bad Request";
|
||||
case 401:
|
||||
return "Unauthorized";
|
||||
case 403:
|
||||
return "Forbidden";
|
||||
case 404:
|
||||
return "Not Found";
|
||||
case 405:
|
||||
return "Method Not Allowed";
|
||||
case 409:
|
||||
return "Conflict";
|
||||
case 413:
|
||||
return "Payload Too Large";
|
||||
case 422:
|
||||
return "Unprocessable Entity";
|
||||
case 500:
|
||||
return "Internal Server Error";
|
||||
default:
|
||||
return "OK";
|
||||
}
|
||||
}
|
||||
|
||||
bool send_all(int fd, std::string_view data) {
|
||||
std::size_t off = 0;
|
||||
while (off < data.size()) {
|
||||
const ssize_t n = ::send(fd, data.data() + off, data.size() - off, MSG_NOSIGNAL);
|
||||
if (n < 0) {
|
||||
if (errno == EINTR) {
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
off += static_cast<std::size_t>(n);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void parse_query(std::string_view qs, std::map<std::string, std::string, std::less<>> &out) {
|
||||
std::size_t pos = 0;
|
||||
while (pos < qs.size()) {
|
||||
const auto amp = qs.find('&', pos);
|
||||
const auto pair =
|
||||
qs.substr(pos, amp == std::string_view::npos ? std::string_view::npos : amp - pos);
|
||||
if (!pair.empty()) {
|
||||
const auto eq = pair.find('=');
|
||||
if (eq == std::string_view::npos) {
|
||||
out[url_decode(pair)] = "";
|
||||
} else {
|
||||
out[url_decode(pair.substr(0, eq))] = url_decode(pair.substr(eq + 1));
|
||||
}
|
||||
}
|
||||
if (amp == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = amp + 1;
|
||||
}
|
||||
}
|
||||
|
||||
void parse_cookies(std::string_view header_val,
|
||||
std::map<std::string, std::string, std::less<>> &out) {
|
||||
std::size_t pos = 0;
|
||||
while (pos < header_val.size()) {
|
||||
const auto semi = header_val.find(';', pos);
|
||||
const auto part = header_val.substr(
|
||||
pos, semi == std::string_view::npos ? std::string_view::npos : semi - pos);
|
||||
const auto eq = part.find('=');
|
||||
if (eq != std::string_view::npos) {
|
||||
out[trim(part.substr(0, eq))] = trim(part.substr(eq + 1));
|
||||
}
|
||||
if (semi == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = semi + 1;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
std::optional<std::string_view> HttpRequest::header(std::string_view lower_name) const noexcept {
|
||||
const auto it = headers.find(lower_name);
|
||||
if (it == headers.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
std::optional<std::string_view> HttpRequest::cookie(std::string_view name) const noexcept {
|
||||
const auto it = cookies.find(name);
|
||||
if (it == cookies.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
HttpResponse HttpResponse::json(std::uint16_t status, std::string payload) {
|
||||
HttpResponse res;
|
||||
res.status = status;
|
||||
res.reason = default_reason(status);
|
||||
res.headers["Content-Type"] = "application/json; charset=utf-8";
|
||||
res.body = std::move(payload);
|
||||
return res;
|
||||
}
|
||||
|
||||
HttpResponse HttpResponse::error_json(std::uint16_t status, std::string_view code,
|
||||
std::string_view message) {
|
||||
return json(status, "{\"error\":{\"code\":" + Util::json_quote(code) +
|
||||
",\"message\":" + Util::json_quote(message) + "}}\n");
|
||||
}
|
||||
|
||||
HttpServer::~HttpServer() noexcept { stop(); }
|
||||
|
||||
Void::Result::Result<void, Void::Result::Error> HttpServer::start(const HttpServerOptions &options,
|
||||
HttpHandler handler) {
|
||||
stop();
|
||||
options_ = options;
|
||||
handler_ = std::move(handler);
|
||||
|
||||
const int fd = ::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) {
|
||||
return std::unexpected{sys_err(errno, "HttpServer: socket() failed")};
|
||||
}
|
||||
int opt = 1;
|
||||
(void)::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
|
||||
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(options.port);
|
||||
if (::inet_pton(AF_INET, options.bind_address.c_str(), &addr.sin_addr) != 1) {
|
||||
(void)::close(fd);
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::invalid_argument,
|
||||
std::format("HttpServer: invalid IPv4 bind address '{}'", options.bind_address))};
|
||||
}
|
||||
|
||||
if (::bind(fd, reinterpret_cast<const sockaddr *>(&addr), sizeof(addr)) != 0) {
|
||||
const int err = errno;
|
||||
(void)::close(fd);
|
||||
return std::unexpected{sys_err(err, "HttpServer: bind() failed")};
|
||||
}
|
||||
if (::listen(fd, 64) != 0) {
|
||||
const int err = errno;
|
||||
(void)::close(fd);
|
||||
return std::unexpected{sys_err(err, "HttpServer: listen() failed")};
|
||||
}
|
||||
|
||||
sockaddr_in actual{};
|
||||
socklen_t len = sizeof(actual);
|
||||
if (::getsockname(fd, reinterpret_cast<sockaddr *>(&actual), &len) == 0) {
|
||||
bound_port_ = ntohs(actual.sin_port);
|
||||
}
|
||||
|
||||
listen_fd_ = fd;
|
||||
running_.store(true);
|
||||
accept_thread_ = std::thread([this] { accept_loop(); });
|
||||
return {};
|
||||
}
|
||||
|
||||
void HttpServer::stop() noexcept {
|
||||
running_.store(false);
|
||||
if (listen_fd_ >= 0) {
|
||||
(void)::shutdown(listen_fd_, SHUT_RDWR);
|
||||
(void)::close(listen_fd_);
|
||||
listen_fd_ = -1;
|
||||
}
|
||||
if (accept_thread_.joinable()) {
|
||||
accept_thread_.join();
|
||||
}
|
||||
bound_port_ = 0;
|
||||
}
|
||||
|
||||
void HttpServer::accept_loop() {
|
||||
while (running_.load()) {
|
||||
struct pollfd pfd{listen_fd_, POLLIN, 0};
|
||||
const int ready = ::poll(&pfd, 1, 50);
|
||||
if (ready <= 0) {
|
||||
continue;
|
||||
}
|
||||
const int client_fd = ::accept4(listen_fd_, nullptr, nullptr, SOCK_CLOEXEC);
|
||||
if (client_fd < 0) {
|
||||
continue;
|
||||
}
|
||||
// Handle client connection with bounded read timeout.
|
||||
handle_client(client_fd);
|
||||
(void)::close(client_fd);
|
||||
}
|
||||
}
|
||||
|
||||
void HttpServer::handle_client(int client_fd) {
|
||||
struct timeval tv{10, 0};
|
||||
(void)::setsockopt(client_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
|
||||
(void)::setsockopt(client_fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
|
||||
|
||||
auto write_response = [&](HttpResponse resp) {
|
||||
if (resp.reason.empty()) {
|
||||
resp.reason = default_reason(resp.status);
|
||||
}
|
||||
// Default security headers (Plan 16/17).
|
||||
resp.headers.emplace("X-Content-Type-Options", "nosniff");
|
||||
resp.headers.emplace("X-Frame-Options", "DENY");
|
||||
resp.headers.emplace("Referrer-Policy", "no-referrer");
|
||||
resp.headers.emplace(
|
||||
"Content-Security-Policy",
|
||||
"default-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'");
|
||||
resp.headers["Content-Length"] = std::to_string(resp.body.size());
|
||||
resp.headers["Connection"] = "close";
|
||||
|
||||
std::string wire = std::format("HTTP/1.1 {} {}\r\n", resp.status, resp.reason);
|
||||
for (const auto &[k, v] : resp.headers) {
|
||||
wire += k + ": " + v + "\r\n";
|
||||
}
|
||||
for (const auto &cookie : resp.set_cookies) {
|
||||
wire += "Set-Cookie: " + cookie + "\r\n";
|
||||
}
|
||||
wire += "\r\n";
|
||||
wire += resp.body;
|
||||
(void)send_all(client_fd, wire);
|
||||
};
|
||||
|
||||
std::string raw;
|
||||
std::array<char, 16384> buf{};
|
||||
std::size_t header_end = std::string::npos;
|
||||
|
||||
while (header_end == std::string::npos) {
|
||||
const ssize_t n = ::recv(client_fd, buf.data(), buf.size(), 0);
|
||||
if (n <= 0) {
|
||||
return;
|
||||
}
|
||||
raw.append(buf.data(), static_cast<std::size_t>(n));
|
||||
header_end = raw.find("\r\n\r\n");
|
||||
if (header_end == std::string::npos && raw.size() > options_.max_header_bytes) {
|
||||
write_response(HttpResponse::error_json(431, "headers_too_large",
|
||||
"HTTP headers exceed maximum size"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const std::string_view header_block{raw.data(), header_end};
|
||||
const auto first_crlf = header_block.find("\r\n");
|
||||
const auto req_line = header_block.substr(0, first_crlf);
|
||||
const auto sp1 = req_line.find(' ');
|
||||
const auto sp2 =
|
||||
sp1 == std::string_view::npos ? std::string_view::npos : req_line.find(' ', sp1 + 1);
|
||||
if (sp1 == std::string_view::npos || sp2 == std::string_view::npos) {
|
||||
write_response(HttpResponse::error_json(400, "bad_request", "malformed HTTP request line"));
|
||||
return;
|
||||
}
|
||||
|
||||
HttpRequest req;
|
||||
req.method = std::string{req_line.substr(0, sp1)};
|
||||
req.raw_target = std::string{req_line.substr(sp1 + 1, sp2 - sp1 - 1)};
|
||||
const auto qpos = req.raw_target.find('?');
|
||||
if (qpos == std::string::npos) {
|
||||
req.path = req.raw_target;
|
||||
} else {
|
||||
req.path = req.raw_target.substr(0, qpos);
|
||||
parse_query(std::string_view{req.raw_target}.substr(qpos + 1), req.query);
|
||||
}
|
||||
|
||||
if (first_crlf != std::string_view::npos) {
|
||||
std::size_t pos = first_crlf + 2;
|
||||
while (pos < header_block.size()) {
|
||||
const auto next = header_block.find("\r\n", pos);
|
||||
const auto line = header_block.substr(
|
||||
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
|
||||
const auto colon = line.find(':');
|
||||
if (colon != std::string_view::npos) {
|
||||
const auto name = to_lower(trim(line.substr(0, colon)));
|
||||
const auto val = trim(line.substr(colon + 1));
|
||||
req.headers[name] = val;
|
||||
if (name == "cookie") {
|
||||
parse_cookies(val, req.cookies);
|
||||
}
|
||||
}
|
||||
if (next == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = next + 2;
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t content_length = 0;
|
||||
if (const auto cl = req.header("content-length")) {
|
||||
try {
|
||||
content_length = static_cast<std::size_t>(std::stoull(std::string{*cl}));
|
||||
} catch (...) {
|
||||
write_response(HttpResponse::error_json(400, "bad_content_length",
|
||||
"invalid Content-Length header"));
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (content_length > options_.max_body_bytes) {
|
||||
write_response(HttpResponse::error_json(413, "payload_too_large",
|
||||
"request body exceeds configured limit"));
|
||||
return;
|
||||
}
|
||||
|
||||
req.body = raw.substr(header_end + 4);
|
||||
while (req.body.size() < content_length) {
|
||||
const std::size_t want = std::min(buf.size(), content_length - req.body.size());
|
||||
const ssize_t n = ::recv(client_fd, buf.data(), want, 0);
|
||||
if (n <= 0) {
|
||||
write_response(
|
||||
HttpResponse::error_json(400, "truncated_body", "truncated HTTP request body"));
|
||||
return;
|
||||
}
|
||||
req.body.append(buf.data(), static_cast<std::size_t>(n));
|
||||
}
|
||||
if (req.body.size() > content_length) {
|
||||
req.body.resize(content_length);
|
||||
}
|
||||
|
||||
try {
|
||||
write_response(handler_(req));
|
||||
} catch (const std::exception &ex) {
|
||||
write_response(HttpResponse::error_json(500, "internal_error", ex.what()));
|
||||
}
|
||||
}
|
||||
|
||||
Void::Result::Result<HttpClientResponse, Void::Result::Error>
|
||||
send_loopback_http(std::uint16_t port, std::string_view method, std::string_view target,
|
||||
const std::map<std::string, std::string, std::less<>> &headers,
|
||||
std::string_view body) {
|
||||
const int fd = ::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0);
|
||||
if (fd < 0) {
|
||||
return std::unexpected{sys_err(errno, "send_loopback_http: socket() failed")};
|
||||
}
|
||||
Void::System::OwnedFd guard{fd};
|
||||
|
||||
sockaddr_in addr{};
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_port = htons(port);
|
||||
(void)::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
|
||||
if (::connect(fd, reinterpret_cast<const sockaddr *>(&addr), sizeof(addr)) != 0) {
|
||||
return std::unexpected{sys_err(errno, "send_loopback_http: connect() failed")};
|
||||
}
|
||||
|
||||
std::string req = std::format("{} {} HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nConnection: close\r\n"
|
||||
"Content-Length: {}\r\n",
|
||||
method, target, port, body.size());
|
||||
for (const auto &[k, v] : headers) {
|
||||
req += k + ": " + v + "\r\n";
|
||||
}
|
||||
req += "\r\n";
|
||||
req += body;
|
||||
if (!send_all(fd, req)) {
|
||||
return std::unexpected{sys_err(errno, "send_loopback_http: send() failed")};
|
||||
}
|
||||
|
||||
std::string raw;
|
||||
std::array<char, 16384> buf{};
|
||||
for (;;) {
|
||||
const ssize_t n = ::recv(fd, buf.data(), buf.size(), 0);
|
||||
if (n > 0) {
|
||||
raw.append(buf.data(), static_cast<std::size_t>(n));
|
||||
} else if (n == 0) {
|
||||
break;
|
||||
} else if (errno != EINTR) {
|
||||
return std::unexpected{sys_err(errno, "send_loopback_http: recv() failed")};
|
||||
}
|
||||
}
|
||||
|
||||
const auto hdr_end = raw.find("\r\n\r\n");
|
||||
if (hdr_end == std::string::npos) {
|
||||
return std::unexpected{Void::System::make_system_error(
|
||||
Void::System::SystemErrorCode::io_error, "malformed HTTP response")};
|
||||
}
|
||||
|
||||
HttpClientResponse resp;
|
||||
const std::string_view header_block{raw.data(), hdr_end};
|
||||
const auto first_crlf = header_block.find("\r\n");
|
||||
const auto status_line = header_block.substr(0, first_crlf);
|
||||
const auto sp1 = status_line.find(' ');
|
||||
if (sp1 != std::string_view::npos) {
|
||||
resp.status =
|
||||
static_cast<std::uint16_t>(std::stoi(std::string{status_line.substr(sp1 + 1, 3)}));
|
||||
}
|
||||
if (first_crlf != std::string_view::npos) {
|
||||
std::size_t pos = first_crlf + 2;
|
||||
while (pos < header_block.size()) {
|
||||
const auto next = header_block.find("\r\n", pos);
|
||||
const auto line = header_block.substr(
|
||||
pos, next == std::string_view::npos ? std::string_view::npos : next - pos);
|
||||
const auto colon = line.find(':');
|
||||
if (colon != std::string_view::npos) {
|
||||
const auto name = to_lower(trim(line.substr(0, colon)));
|
||||
const auto val = trim(line.substr(colon + 1));
|
||||
if (name == "set-cookie") {
|
||||
resp.set_cookies.push_back(val);
|
||||
} else {
|
||||
resp.headers[name] = val;
|
||||
}
|
||||
}
|
||||
if (next == std::string_view::npos) {
|
||||
break;
|
||||
}
|
||||
pos = next + 2;
|
||||
}
|
||||
}
|
||||
resp.body = raw.substr(hdr_end + 4);
|
||||
return resp;
|
||||
}
|
||||
|
||||
} // namespace Void::Build::Registry
|
||||
@@ -0,0 +1,89 @@
|
||||
#include <Void/Build/BootstrapConfig.hpp>
|
||||
#include <Void/Build/Registry/RegistryService.hpp>
|
||||
#include <Void/Configuration/Argparse.hpp>
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/System/SignalWatcher.hpp>
|
||||
#include <Void/Text/Str.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
std::string data_dir;
|
||||
std::string web_root;
|
||||
std::string bind_address;
|
||||
std::string port_str;
|
||||
std::string pass_env;
|
||||
|
||||
const std::string default_web_root =
|
||||
(std::filesystem::path{Void::Build::Bootstrap::source_dir} / "registry" / "web").string();
|
||||
|
||||
Void::Argparse::Parser parser{
|
||||
"vbs-registry",
|
||||
"Loopback-default VoidBuildSystem package registry service and web administration UI."};
|
||||
parser
|
||||
.option_default("--data-dir", "", "registry metadata and CAS directory", data_dir,
|
||||
"registry-data")
|
||||
.option_default("--web-root", "", "static web admin assets directory", web_root,
|
||||
default_web_root)
|
||||
.option_default("--bind", "", "IPv4 bind address", bind_address, "127.0.0.1")
|
||||
.option_default("--port", "", "listening TCP port (0 for ephemeral)", port_str, "8080")
|
||||
.option_default("--admin-password-env", "",
|
||||
"environment variable holding bootstrap admin password", pass_env,
|
||||
"VBS_REGISTRY_ADMIN_PASSWORD");
|
||||
|
||||
if (argc == 2 && (std::string_view{argv[1]} == "--help" || std::string_view{argv[1]} == "-h")) {
|
||||
std::cout << parser.help();
|
||||
return 0;
|
||||
}
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (std::string_view{argv[i]} == "--help" || std::string_view{argv[i]} == "-h") {
|
||||
std::cerr << "vbs-registry: --help must be used alone\n";
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
if (auto parsed = parser.parse(argc, argv); !parsed) {
|
||||
std::cerr << "vbs-registry: " << parsed.error() << '\n';
|
||||
return 2;
|
||||
}
|
||||
|
||||
int port_int = 0;
|
||||
if (!Void::Str::to_int(port_str, port_int) || port_int < 0 || port_int > 65535) {
|
||||
std::cerr << "vbs-registry: invalid --port value '" << port_str << "'\n";
|
||||
return 2;
|
||||
}
|
||||
|
||||
Void::Build::Registry::RegistryConfig cfg;
|
||||
cfg.data_dir = data_dir;
|
||||
cfg.web_root = web_root;
|
||||
cfg.bind_address = bind_address;
|
||||
cfg.port = static_cast<std::uint16_t>(port_int);
|
||||
if (auto pw = Void::Configuration::get_env(pass_env); pw) {
|
||||
cfg.bootstrap_admin_password = std::move(*pw);
|
||||
}
|
||||
|
||||
auto signals = Void::Process::SignalWatcher::create();
|
||||
auto svc = Void::Build::Registry::RegistryService::open(std::move(cfg));
|
||||
if (!svc) {
|
||||
std::cerr << "vbs-registry: failed opening registry: " << svc.error().message() << '\n';
|
||||
return 1;
|
||||
}
|
||||
if (auto started = (*svc)->start_http(); !started) {
|
||||
std::cerr << "vbs-registry: failed starting HTTP server: " << started.error().message()
|
||||
<< '\n';
|
||||
return 1;
|
||||
}
|
||||
|
||||
std::cout << "vbs-registry listening on http://" << bind_address << ":" << (*svc)->bound_port()
|
||||
<< " (SIGINT/SIGTERM to stop)\n"
|
||||
<< std::flush;
|
||||
|
||||
if (signals) {
|
||||
(void)signals->wait();
|
||||
}
|
||||
(*svc)->stop_http();
|
||||
return 0;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,375 @@
|
||||
"use strict";
|
||||
|
||||
// VoidBuildSystem Registry Web UI (Plan 17)
|
||||
// Security invariants:
|
||||
// - Never uses innerHTML on untrusted server data (DOM nodes + textContent only -> XSS safe).
|
||||
// - Uses HttpOnly cookie sessions + X-CSRF-Token header on every mutation.
|
||||
// - Never reports optimistic success before durable server confirmation; prevents double submits.
|
||||
|
||||
const state = {
|
||||
user: null,
|
||||
csrfToken: "",
|
||||
};
|
||||
|
||||
function el(tag, attrs = {}, text = "") {
|
||||
const node = document.createElement(tag);
|
||||
for (const [k, v] of Object.entries(attrs)) {
|
||||
if (k === "class") node.className = v;
|
||||
else node.setAttribute(k, v);
|
||||
}
|
||||
if (text !== "") node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
function showBanner(message, isError = false) {
|
||||
const b = document.getElementById("status-banner");
|
||||
b.textContent = message;
|
||||
b.className = isError ? "banner error" : "banner";
|
||||
b.hidden = false;
|
||||
}
|
||||
|
||||
function clearBanner() {
|
||||
document.getElementById("status-banner").hidden = true;
|
||||
}
|
||||
|
||||
async function apiJson(path, options = {}) {
|
||||
const headers = Object.assign({}, options.headers || {});
|
||||
if (options.method && options.method !== "GET" && state.csrfToken) {
|
||||
headers["X-CSRF-Token"] = state.csrfToken;
|
||||
}
|
||||
const resp = await fetch(path, Object.assign({ credentials: "same-origin" }, options, { headers }));
|
||||
let data = null;
|
||||
try {
|
||||
data = await resp.json();
|
||||
} catch {
|
||||
data = null;
|
||||
}
|
||||
if (!resp.ok) {
|
||||
const msg = data && data.error && data.error.message ? data.error.message : `HTTP ${resp.status}`;
|
||||
throw new Error(msg);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
function setView(viewName) {
|
||||
clearBanner();
|
||||
for (const sec of document.querySelectorAll("main > section")) {
|
||||
sec.hidden = sec.id !== `view-${viewName}`;
|
||||
}
|
||||
for (const btn of document.querySelectorAll(".nav-btn[data-view]")) {
|
||||
btn.classList.toggle("active", btn.dataset.view === viewName);
|
||||
}
|
||||
if (viewName === "packages") loadPackages();
|
||||
if (viewName === "tokens") loadTokens();
|
||||
if (viewName === "admin") loadAdmin();
|
||||
}
|
||||
|
||||
function updateNavForSession() {
|
||||
const loggedIn = Boolean(state.user);
|
||||
const role = state.user ? state.user.role : "";
|
||||
document.getElementById("nav-login").hidden = loggedIn;
|
||||
document.getElementById("btn-logout").hidden = !loggedIn;
|
||||
document.getElementById("nav-tokens").hidden = !loggedIn;
|
||||
document.getElementById("nav-publish").hidden = !(role === "publisher" || role === "admin");
|
||||
document.getElementById("nav-admin").hidden = role !== "admin";
|
||||
}
|
||||
|
||||
async function refreshSession() {
|
||||
try {
|
||||
const me = await apiJson("/api/v1/auth/me");
|
||||
state.user = { username: me.username, role: me.role };
|
||||
state.csrfToken = me.csrf_token || "";
|
||||
} catch {
|
||||
state.user = null;
|
||||
state.csrfToken = "";
|
||||
}
|
||||
updateNavForSession();
|
||||
}
|
||||
|
||||
async function loadPackages() {
|
||||
const list = document.getElementById("packages-list");
|
||||
list.replaceChildren(el("p", { class: "muted" }, "Loading packages..."));
|
||||
const q = document.getElementById("search-input").value.trim();
|
||||
const url = q ? `/api/v1/packages?q=${encodeURIComponent(q)}` : "/api/v1/packages";
|
||||
try {
|
||||
const data = await apiJson(url);
|
||||
list.replaceChildren();
|
||||
if (!data.packages || data.packages.length === 0) {
|
||||
list.appendChild(el("p", { class: "muted" }, "No packages matched."));
|
||||
return;
|
||||
}
|
||||
for (const pkg of data.packages) {
|
||||
const card = el("div", { class: "card" });
|
||||
const info = el("div");
|
||||
info.appendChild(el("strong", {}, pkg.name));
|
||||
if (pkg.is_private) info.appendChild(el("span", { class: "muted" }, " [private]"));
|
||||
info.appendChild(el("div", { class: "muted" }, pkg.description || "No description"));
|
||||
const btn = el("button", { type: "button" }, `Inspect (${pkg.release_count})`);
|
||||
btn.addEventListener("click", () => loadPackageDetail(pkg.name));
|
||||
card.append(info, btn);
|
||||
list.appendChild(card);
|
||||
}
|
||||
} catch (err) {
|
||||
showBanner(`Failed loading packages: ${err.message}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadPackageDetail(name) {
|
||||
const box = document.getElementById("package-detail");
|
||||
box.hidden = false;
|
||||
box.replaceChildren(el("p", { class: "muted" }, `Loading ${name}...`));
|
||||
try {
|
||||
const pkg = await apiJson(`/api/v1/packages/${encodeURIComponent(name)}`);
|
||||
box.replaceChildren();
|
||||
box.appendChild(el("h3", {}, pkg.name));
|
||||
box.appendChild(el("p", { class: "muted" }, pkg.description || "No description"));
|
||||
box.appendChild(el("p", { class: "muted" }, `Owners: ${(pkg.owners || []).join(", ")}`));
|
||||
|
||||
const tbl = el("table");
|
||||
const thead = el("thead");
|
||||
const tr = el("tr");
|
||||
for (const col of ["Version", "SHA-256", "Bytes", "Status", "Actions"]) {
|
||||
tr.appendChild(el("th", {}, col));
|
||||
}
|
||||
thead.appendChild(tr);
|
||||
tbl.appendChild(thead);
|
||||
|
||||
const tbody = el("tbody");
|
||||
for (const rel of pkg.releases || []) {
|
||||
const row = el("tr");
|
||||
row.appendChild(el("td", {}, rel.version));
|
||||
row.appendChild(el("td", {}, rel.sha256.slice(0, 16) + "..."));
|
||||
row.appendChild(el("td", {}, String(rel.size_bytes)));
|
||||
row.appendChild(el("td", {}, rel.yanked ? "Yanked" : "Active"));
|
||||
const actTd = el("td");
|
||||
const dl = el("a", {
|
||||
href: `/api/v1/packages/${encodeURIComponent(pkg.name)}/${encodeURIComponent(rel.version)}/download`,
|
||||
}, "Download");
|
||||
actTd.appendChild(dl);
|
||||
if (state.user && (state.user.role === "admin" || state.user.role === "publisher")) {
|
||||
const ybtn = el("button", { type: "button" }, rel.yanked ? "Unyank" : "Yank");
|
||||
ybtn.style.marginLeft = "0.5rem";
|
||||
ybtn.addEventListener("click", async () => {
|
||||
ybtn.disabled = true;
|
||||
try {
|
||||
await apiJson(
|
||||
`/api/v1/packages/${encodeURIComponent(pkg.name)}/${encodeURIComponent(rel.version)}/yank`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ yanked: !rel.yanked }),
|
||||
},
|
||||
);
|
||||
showBanner(`${pkg.name}@${rel.version} updated.`);
|
||||
await loadPackageDetail(pkg.name);
|
||||
} catch (e) {
|
||||
showBanner(e.message, true);
|
||||
} finally {
|
||||
ybtn.disabled = false;
|
||||
}
|
||||
});
|
||||
actTd.appendChild(ybtn);
|
||||
}
|
||||
row.appendChild(actTd);
|
||||
tbody.appendChild(row);
|
||||
}
|
||||
tbl.appendChild(tbody);
|
||||
box.appendChild(tbl);
|
||||
} catch (err) {
|
||||
showBanner(`Failed loading package detail: ${err.message}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadTokens() {
|
||||
const box = document.getElementById("tokens-list");
|
||||
box.replaceChildren(el("p", { class: "muted" }, "Loading tokens..."));
|
||||
try {
|
||||
const data = await apiJson("/api/v1/tokens");
|
||||
box.replaceChildren();
|
||||
for (const t of data.tokens || []) {
|
||||
const card = el("div", { class: "card" });
|
||||
const txt = `${t.label || t.token_id} (${t.username}) — scopes: ${(t.scopes || []).join(", ")} — ${t.revoked ? "REVOKED" : "active"}`;
|
||||
card.appendChild(el("span", {}, txt));
|
||||
if (!t.revoked) {
|
||||
const rev = el("button", { type: "button" }, "Revoke");
|
||||
rev.addEventListener("click", async () => {
|
||||
rev.disabled = true;
|
||||
try {
|
||||
await apiJson(`/api/v1/tokens/${encodeURIComponent(t.token_id)}`, { method: "DELETE" });
|
||||
showBanner(`Revoked token ${t.token_id}`);
|
||||
await loadTokens();
|
||||
} catch (e) {
|
||||
showBanner(e.message, true);
|
||||
}
|
||||
});
|
||||
card.appendChild(rev);
|
||||
}
|
||||
box.appendChild(card);
|
||||
}
|
||||
} catch (err) {
|
||||
showBanner(err.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAdmin() {
|
||||
try {
|
||||
const [st, us, au] = await Promise.all([
|
||||
apiJson("/api/v1/admin/storage"),
|
||||
apiJson("/api/v1/users"),
|
||||
apiJson("/api/v1/audit"),
|
||||
]);
|
||||
document.getElementById("storage-stats").textContent =
|
||||
`Storage: ${st.used_bytes} / ${st.quota_bytes} bytes across ${st.package_count} packages`;
|
||||
|
||||
const ubox = document.getElementById("users-list");
|
||||
ubox.replaceChildren();
|
||||
for (const u of us.users || []) {
|
||||
ubox.appendChild(el("div", { class: "card" }, `${u.username} — role: ${u.role}`));
|
||||
}
|
||||
|
||||
const abox = document.getElementById("audit-list");
|
||||
abox.replaceChildren();
|
||||
for (const a of (au.audits || []).slice(-50).reverse()) {
|
||||
abox.appendChild(
|
||||
el("div", { class: "muted" }, `[${a.timestamp}] ${a.actor} ${a.action} ${a.target} => ${a.outcome} ${a.detail}`),
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
showBanner(err.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
document.querySelectorAll(".nav-btn[data-view]").forEach((btn) => {
|
||||
btn.addEventListener("click", () => setView(btn.dataset.view));
|
||||
});
|
||||
|
||||
document.getElementById("btn-search").addEventListener("click", loadPackages);
|
||||
document.getElementById("search-input").addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") loadPackages();
|
||||
});
|
||||
|
||||
document.getElementById("login-form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const btn = document.getElementById("btn-login-submit");
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await apiJson("/api/v1/auth/login", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
username: document.getElementById("login-username").value,
|
||||
password: document.getElementById("login-password").value,
|
||||
}),
|
||||
});
|
||||
state.user = { username: res.username, role: res.role };
|
||||
state.csrfToken = res.csrf_token || "";
|
||||
updateNavForSession();
|
||||
showBanner(`Signed in as ${res.username} (${res.role}).`);
|
||||
setView("packages");
|
||||
} catch (err) {
|
||||
showBanner(`Sign in failed: ${err.message}`, true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("btn-logout").addEventListener("click", async () => {
|
||||
try {
|
||||
await apiJson("/api/v1/auth/logout", { method: "POST" });
|
||||
} catch {}
|
||||
state.user = null;
|
||||
state.csrfToken = "";
|
||||
updateNavForSession();
|
||||
setView("packages");
|
||||
showBanner("Signed out.");
|
||||
});
|
||||
|
||||
document.getElementById("publish-form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const btn = document.getElementById("btn-publish-submit");
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const name = document.getElementById("pub-name").value.trim();
|
||||
const version = document.getElementById("pub-version").value.trim();
|
||||
const desc = document.getElementById("pub-desc").value.trim();
|
||||
const isPriv = document.getElementById("pub-private").checked;
|
||||
const file = document.getElementById("pub-file").files[0];
|
||||
if (!file) throw new Error("Choose a .tar archive first");
|
||||
const buf = await file.arrayBuffer();
|
||||
const res = await apiJson(
|
||||
`/api/v1/packages/${encodeURIComponent(name)}/${encodeURIComponent(version)}`,
|
||||
{
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/x-tar",
|
||||
"X-Package-Description": desc,
|
||||
"X-Package-Private": isPriv ? "true" : "false",
|
||||
},
|
||||
body: buf,
|
||||
},
|
||||
);
|
||||
showBanner(`Published ${res.name || name}@${res.version || version} (sha256=${res.sha256}).`);
|
||||
} catch (err) {
|
||||
showBanner(`Publish failed: ${err.message}`, true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("token-form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const btn = document.getElementById("btn-token-create");
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const scopes = Array.from(document.querySelectorAll("#token-form input[name='scope']:checked")).map(
|
||||
(n) => n.value,
|
||||
);
|
||||
const res = await apiJson("/api/v1/tokens", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ label: document.getElementById("tok-label").value.trim(), scopes }),
|
||||
});
|
||||
const box = document.getElementById("created-token-box");
|
||||
box.textContent = `Save this token now (shown once only): ${res.token}`;
|
||||
box.hidden = false;
|
||||
await loadTokens();
|
||||
} catch (err) {
|
||||
showBanner(`Token creation failed: ${err.message}`, true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("user-form").addEventListener("submit", async (e) => {
|
||||
e.preventDefault();
|
||||
const btn = document.getElementById("btn-user-create");
|
||||
btn.disabled = true;
|
||||
try {
|
||||
await apiJson("/api/v1/users", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
username: document.getElementById("u-name").value.trim(),
|
||||
password: document.getElementById("u-pass").value,
|
||||
role: document.getElementById("u-role").value,
|
||||
}),
|
||||
});
|
||||
showBanner("User saved.");
|
||||
await loadAdmin();
|
||||
} catch (err) {
|
||||
showBanner(err.message, true);
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
(async function init() {
|
||||
try {
|
||||
await apiJson("/api/v1/health");
|
||||
document.getElementById("health-badge").textContent = "Healthy";
|
||||
} catch {
|
||||
document.getElementById("health-badge").textContent = "Unavailable";
|
||||
}
|
||||
await refreshSession();
|
||||
await loadPackages();
|
||||
})();
|
||||
@@ -0,0 +1,106 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>VoidBuildSystem Package Registry</title>
|
||||
<link rel="stylesheet" href="/styles.css">
|
||||
</head>
|
||||
<body>
|
||||
<header class="topbar">
|
||||
<div class="brand">
|
||||
<h1>VoidBuildSystem Registry</h1>
|
||||
<span class="badge" id="health-badge" role="status">Connecting...</span>
|
||||
</div>
|
||||
<nav aria-label="Primary navigation">
|
||||
<button type="button" class="nav-btn active" data-view="packages">Packages</button>
|
||||
<button type="button" class="nav-btn" data-view="publish" id="nav-publish" hidden>Publish</button>
|
||||
<button type="button" class="nav-btn" data-view="tokens" id="nav-tokens" hidden>Tokens</button>
|
||||
<button type="button" class="nav-btn" data-view="admin" id="nav-admin" hidden>Admin</button>
|
||||
<button type="button" class="nav-btn" data-view="login" id="nav-login">Sign In</button>
|
||||
<button type="button" class="nav-btn" id="btn-logout" hidden>Sign Out</button>
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<div id="status-banner" class="banner" role="alert" aria-live="polite" hidden></div>
|
||||
|
||||
<section id="view-packages" class="panel">
|
||||
<div class="toolbar">
|
||||
<label for="search-input" class="sr-only">Search packages</label>
|
||||
<input id="search-input" type="search" placeholder="Search packages by name or description...">
|
||||
<button type="button" id="btn-search">Search</button>
|
||||
</div>
|
||||
<div id="packages-list" class="grid"></div>
|
||||
<div id="package-detail" class="detail" hidden></div>
|
||||
</section>
|
||||
|
||||
<section id="view-login" class="panel" hidden>
|
||||
<h2>Sign In</h2>
|
||||
<form id="login-form">
|
||||
<label for="login-username">Username</label>
|
||||
<input id="login-username" name="username" autocomplete="username" required>
|
||||
<label for="login-password">Password</label>
|
||||
<input id="login-password" name="password" type="password" autocomplete="current-password" required>
|
||||
<button type="submit" id="btn-login-submit">Sign In</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section id="view-publish" class="panel" hidden>
|
||||
<h2>Publish Immutable Release</h2>
|
||||
<form id="publish-form">
|
||||
<label for="pub-name">Package Name</label>
|
||||
<input id="pub-name" required pattern="[A-Za-z0-9_.\-]{1,64}">
|
||||
<label for="pub-version">SemVer Version</label>
|
||||
<input id="pub-version" required placeholder="1.0.0">
|
||||
<label for="pub-desc">Description</label>
|
||||
<input id="pub-desc" placeholder="Short package summary">
|
||||
<label class="checkbox">
|
||||
<input id="pub-private" type="checkbox"> Private package
|
||||
</label>
|
||||
<label for="pub-file">Archive (.tar)</label>
|
||||
<input id="pub-file" type="file" required>
|
||||
<button type="submit" id="btn-publish-submit">Upload & Publish</button>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section id="view-tokens" class="panel" hidden>
|
||||
<h2>Scoped API Tokens</h2>
|
||||
<form id="token-form">
|
||||
<label for="tok-label">Token Label</label>
|
||||
<input id="tok-label" required placeholder="ci-publisher">
|
||||
<label><input type="checkbox" name="scope" value="read" checked> read</label>
|
||||
<label><input type="checkbox" name="scope" value="publish"> publish</label>
|
||||
<label><input type="checkbox" name="scope" value="admin"> admin</label>
|
||||
<button type="submit" id="btn-token-create">Create Token</button>
|
||||
</form>
|
||||
<div id="created-token-box" class="token-once" hidden></div>
|
||||
<div id="tokens-list"></div>
|
||||
</section>
|
||||
|
||||
<section id="view-admin" class="panel" hidden>
|
||||
<h2>Administration</h2>
|
||||
<div id="storage-stats" class="stats"></div>
|
||||
<h3>Users & Roles</h3>
|
||||
<form id="user-form">
|
||||
<label for="u-name">Username</label>
|
||||
<input id="u-name" required>
|
||||
<label for="u-pass">Password (min 6 chars)</label>
|
||||
<input id="u-pass" type="password" minlength="6" required>
|
||||
<label for="u-role">Role</label>
|
||||
<select id="u-role">
|
||||
<option value="reader">Reader</option>
|
||||
<option value="publisher">Publisher</option>
|
||||
<option value="admin">Admin</option>
|
||||
</select>
|
||||
<button type="submit" id="btn-user-create">Save User</button>
|
||||
</form>
|
||||
<div id="users-list"></div>
|
||||
<h3>Audit Log (Secret-Redacted)</h3>
|
||||
<div id="audit-list"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,99 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0f1218;
|
||||
--surface: #171c26;
|
||||
--border: #2b3344;
|
||||
--text: #e6ebf5;
|
||||
--muted: #9aa7bd;
|
||||
--accent: #5fa8ff;
|
||||
--danger: #f06a6a;
|
||||
--ok: #58d68d;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body {
|
||||
margin: 0;
|
||||
font-family: system-ui, -apple-system, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
line-height: 1.5;
|
||||
}
|
||||
.topbar {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
padding: 1rem 1.5rem;
|
||||
background: var(--surface);
|
||||
border-bottom: 1px solid var(--border);
|
||||
gap: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.brand { display: flex; align-items: center; gap: 0.75rem; }
|
||||
.brand h1 { margin: 0; font-size: 1.15rem; }
|
||||
.badge {
|
||||
font-size: 0.8rem;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border-radius: 999px;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--ok);
|
||||
}
|
||||
nav { display: flex; gap: 0.5rem; flex-wrap: wrap; }
|
||||
button {
|
||||
background: var(--surface);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 0.45rem 0.85rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover, button:focus-visible { border-color: var(--accent); outline: 2px solid var(--accent); }
|
||||
button.active { background: var(--accent); color: #09101c; border-color: var(--accent); }
|
||||
button:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||
main { max-width: 1000px; margin: 1.5rem auto; padding: 0 1rem; }
|
||||
.panel {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 1.25rem;
|
||||
}
|
||||
.toolbar { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
|
||||
input, select {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
width: 100%;
|
||||
margin-bottom: 0.75rem;
|
||||
}
|
||||
.toolbar input { margin-bottom: 0; flex: 1; }
|
||||
.grid { display: grid; gap: 0.75rem; }
|
||||
.card {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 0.85rem;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
.muted { color: var(--muted); font-size: 0.9rem; }
|
||||
.banner {
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: 8px;
|
||||
margin-bottom: 1rem;
|
||||
border: 1px solid var(--accent);
|
||||
background: #132238;
|
||||
}
|
||||
.banner.error { border-color: var(--danger); background: #2d1418; }
|
||||
.token-once {
|
||||
padding: 0.85rem;
|
||||
margin: 1rem 0;
|
||||
border: 1px solid var(--ok);
|
||||
border-radius: 8px;
|
||||
font-family: monospace;
|
||||
word-break: break-all;
|
||||
}
|
||||
.detail { margin-top: 1.25rem; border-top: 1px solid var(--border); padding-top: 1rem; }
|
||||
table { width: 100%; border-collapse: collapse; margin-top: 0.75rem; font-size: 0.9rem; }
|
||||
th, td { text-align: left; padding: 0.5rem; border-bottom: 1px solid var(--border); }
|
||||
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0,0,0,0); }
|
||||
Reference in new issue
Block a user