const std = @import("std");
const wap = @import("wap");
const env = @import("../utilities/env.zig");
const runtime = @import("../runtime.zig");
const log = @import("../logging.zig");
const max_file_size = 32 * 1024 * 1024;
const placeholder = "/PREFECT_UI_SERVE_BASE_REPLACE_PLACEHOLDER";
pub fn tryServe(req: *wap.Request, res: *wap.Response) !bool {
if (req.method != .GET and req.method != .HEAD) return false;
if (isApiPath(req.path)) return false;
if (try isUiSettingsRequest(req.arena, req.path)) return false;
const root = staticDir() orelse return false;
if (root.len == 0) return false;
if (!(try pathTargetsServeBase(req.arena, req.path))) return false;
const io = runtime.appIo();
var dir = std.Io.Dir.cwd().openDir(io, root, .{}) catch |err| {
log.warn("ui", "PREFECT_UI_STATIC_DIR={s} is not readable: {}", .{ root, err });
return false;
};
defer dir.close(io);
const lookup_path = stripServeBase(req.arena, req.path) catch req.path;
const requested_path = relPath(lookup_path) catch {
return sendStaticNotFound(req, res);
};
if (try serveFile(io, req, res, &dir, requested_path, false)) return true;
if (isStaticAssetPath(requested_path)) return sendStaticNotFound(req, res);
return serveIndex(io, req, res, &dir);
}
fn staticDir() ?[]const u8 {
const enabled = env.getenv("PREFECT_SERVER_UI_ENABLED") orelse env.getenv("PREFECT_UI_ENABLED") orelse "true";
if (std.ascii.eqlIgnoreCase(enabled, "false") or std.mem.eql(u8, enabled, "0")) return null;
return env.getenv("PREFECT_SERVER_UI_STATIC_DIRECTORY") orelse env.getenv("PREFECT_UI_STATIC_DIRECTORY") orelse env.getenv("PREFECT_UI_STATIC_DIR") orelse env.getenv("PREFECT_SERVER_UI_STATIC_DIR");
}
fn serveBase() []const u8 {
const raw = env.getenv("PREFECT_UI_SERVE_BASE") orelse env.getenv("PREFECT_SERVER_UI_SERVE_BASE") orelse "/";
return raw;
}
fn normalizeServeBase(alloc: std.mem.Allocator, raw: []const u8) ![]const u8 {
const trimmed = std.mem.trim(u8, raw, " \t\r\n");
if (trimmed.len == 0 or std.mem.eql(u8, trimmed, "/")) return "/";
var end = trimmed.len;
while (end > 1 and trimmed[end - 1] == '/') end -= 1;
const normalized = trimmed[0..end];
return if (normalized[0] == '/') normalized else try std.fmt.allocPrint(alloc, "/{s}", .{normalized});
}
fn replacementServeBase(alloc: std.mem.Allocator) ![]const u8 {
const normalized = try normalizeServeBase(alloc, serveBase());
return if (std.mem.eql(u8, normalized, "/")) "" else normalized;
}
fn stripServeBase(alloc: std.mem.Allocator, path: []const u8) ![]const u8 {
const normalized = try normalizeServeBase(alloc, serveBase());
if (std.mem.eql(u8, normalized, "/")) return path;
if (std.mem.eql(u8, path, normalized)) return "/";
if (std.mem.startsWith(u8, path, normalized) and path.len > normalized.len and path[normalized.len] == '/') {
return path[normalized.len..];
}
return path;
}
fn pathTargetsServeBase(alloc: std.mem.Allocator, path: []const u8) !bool {
const normalized = try normalizeServeBase(alloc, serveBase());
if (std.mem.eql(u8, normalized, "/")) return true;
if (std.mem.eql(u8, path, normalized)) return true;
return std.mem.startsWith(u8, path, normalized) and path.len > normalized.len and path[normalized.len] == '/';
}
pub fn isUiSettingsRequest(alloc: std.mem.Allocator, path: []const u8) !bool {
return isUiSettingsPath(try stripServeBase(alloc, path));
}
fn isApiPath(path: []const u8) bool {
return std.mem.eql(u8, path, "/api") or std.mem.startsWith(u8, path, "/api/");
}
fn isUiSettingsPath(path: []const u8) bool {
return std.mem.eql(u8, path, "/ui-settings");
}
fn relPath(path: []const u8) ![]const u8 {
if (path.len == 0 or std.mem.eql(u8, path, "/")) return "index.html";
if (std.mem.indexOfScalar(u8, path, '\\') != null) return error.InvalidPath;
if (std.mem.indexOfScalar(u8, path, 0) != null) return error.InvalidPath;
const stripped = std.mem.trimStart(u8, path, "/");
var parts = std.mem.splitScalar(u8, stripped, '/');
while (parts.next()) |part| {
if (std.mem.eql(u8, part, "..")) return error.InvalidPath;
}
return stripped;
}
fn serveIndex(io: std.Io, req: *wap.Request, res: *wap.Response, dir: *std.Io.Dir) !bool {
return serveFile(io, req, res, dir, "index.html", true);
}
fn sendStaticNotFound(req: *wap.Request, res: *wap.Response) !bool {
_ = res.setStatus(.not_found)
.setHeader("content-type", "text/plain; charset=utf-8")
.setHeader("cache-control", "no-cache");
if (req.method == .HEAD) {
try res.sendBody("");
} else {
try res.sendBody("not found");
}
return true;
}
fn isStaticAssetPath(path: []const u8) bool {
if (std.mem.startsWith(u8, path, "assets/")) return true;
if (std.mem.startsWith(u8, path, "ico/")) return true;
const basename = std.fs.path.basename(path);
return std.mem.eql(u8, basename, "favicon.ico") or
std.mem.eql(u8, basename, "manifest.json") or
std.mem.eql(u8, basename, "robots.txt") or
std.mem.eql(u8, basename, "site.webmanifest") or
std.mem.eql(u8, basename, "asset-manifest.json");
}
fn serveFile(io: std.Io, req: *wap.Request, res: *wap.Response, dir: *std.Io.Dir, path: []const u8, is_index: bool) !bool {
var file = dir.openFile(io, path, .{ .mode = .read_only, .allow_directory = false, .resolve_beneath = true }) catch |err| switch (err) {
error.FileNotFound, error.IsDir, error.NotDir => return false,
else => return err,
};
defer file.close(io);
const stat = try file.stat(io);
if (stat.kind != .file) return false;
if (stat.size > max_file_size) return error.FileTooLarge;
const size: usize = std.math.cast(usize, stat.size) orelse return error.FileTooLarge;
const body = try req.arena.alloc(u8, size);
const n = try file.readPositionalAll(io, body, 0);
const bytes = body[0..n];
const ctype = contentType(path);
const response_body = if (shouldRewritePlaceholders(path))
try rewritePlaceholders(req.arena, bytes)
else
bytes;
_ = res.setStatus(.ok)
.setHeader("content-type", ctype)
.setHeader("cache-control", if (is_index) "no-cache" else cacheControl(path));
if (req.method == .HEAD) {
try res.sendBody("");
} else {
try res.sendBody(response_body);
}
return true;
}
fn shouldRewritePlaceholders(path: []const u8) bool {
const ext = std.fs.path.extension(path);
return std.ascii.eqlIgnoreCase(ext, ".html") or
std.ascii.eqlIgnoreCase(ext, ".js") or
std.ascii.eqlIgnoreCase(ext, ".mjs") or
std.ascii.eqlIgnoreCase(ext, ".css") or
std.ascii.eqlIgnoreCase(ext, ".json") or
std.ascii.eqlIgnoreCase(ext, ".svg") or
std.ascii.eqlIgnoreCase(ext, ".map") or
std.ascii.eqlIgnoreCase(ext, ".txt");
}
fn rewritePlaceholders(alloc: std.mem.Allocator, body: []const u8) ![]const u8 {
if (std.mem.indexOf(u8, body, placeholder) == null) return body;
const replacement = try replacementServeBase(alloc);
return rewritePlaceholdersWithBase(alloc, body, replacement);
}
fn rewritePlaceholdersWithBase(alloc: std.mem.Allocator, body: []const u8, replacement: []const u8) ![]const u8 {
return std.mem.replaceOwned(u8, alloc, body, placeholder, replacement);
}
fn cacheControl(path: []const u8) []const u8 {
if (std.mem.startsWith(u8, path, "assets/")) {
return "public, max-age=31536000, immutable";
}
return "no-cache";
}
fn contentType(path: []const u8) []const u8 {
const ext = std.fs.path.extension(path);
if (std.ascii.eqlIgnoreCase(ext, ".html")) return "text/html; charset=utf-8";
if (std.ascii.eqlIgnoreCase(ext, ".js")) return "text/javascript; charset=utf-8";
if (std.ascii.eqlIgnoreCase(ext, ".mjs")) return "text/javascript; charset=utf-8";
if (std.ascii.eqlIgnoreCase(ext, ".css")) return "text/css; charset=utf-8";
if (std.ascii.eqlIgnoreCase(ext, ".json")) return "application/json";
if (std.ascii.eqlIgnoreCase(ext, ".svg")) return "image/svg+xml";
if (std.ascii.eqlIgnoreCase(ext, ".png")) return "image/png";
if (std.ascii.eqlIgnoreCase(ext, ".jpg")) return "image/jpeg";
if (std.ascii.eqlIgnoreCase(ext, ".jpeg")) return "image/jpeg";
if (std.ascii.eqlIgnoreCase(ext, ".gif")) return "image/gif";
if (std.ascii.eqlIgnoreCase(ext, ".webp")) return "image/webp";
if (std.ascii.eqlIgnoreCase(ext, ".ico")) return "image/x-icon";
if (std.ascii.eqlIgnoreCase(ext, ".woff")) return "font/woff";
if (std.ascii.eqlIgnoreCase(ext, ".woff2")) return "font/woff2";
if (std.ascii.eqlIgnoreCase(ext, ".map")) return "application/json";
if (std.ascii.eqlIgnoreCase(ext, ".txt")) return "text/plain; charset=utf-8";
return "application/octet-stream";
}
test "relPath rejects traversal" {
try std.testing.expectError(error.InvalidPath, relPath("/../index.html"));
try std.testing.expectError(error.InvalidPath, relPath("/assets/../app.js"));
try std.testing.expectError(error.InvalidPath, relPath("/assets\\app.js"));
}
test "relPath maps root and strips leading slash" {
try std.testing.expectEqualStrings("index.html", try relPath("/"));
try std.testing.expectEqualStrings("runs/flow-run/abc", try relPath("/runs/flow-run/abc"));
}
test "static asset paths do not use SPA fallback" {
try std.testing.expect(isStaticAssetPath("assets/app.js"));
try std.testing.expect(isStaticAssetPath("ico/favicon.svg"));
try std.testing.expect(isStaticAssetPath("favicon.ico"));
try std.testing.expect(!isStaticAssetPath("dashboard"));
try std.testing.expect(!isStaticAssetPath("runs/flow-run/abc"));
}
test "ui settings bypasses SPA fallback" {
try std.testing.expect(try isUiSettingsRequest(std.testing.allocator, "/ui-settings"));
try std.testing.expect(!try isUiSettingsRequest(std.testing.allocator, "/api/ui-settings"));
}
test "normalizeServeBase follows python shape" {
try std.testing.expectEqualStrings("/", try normalizeServeBase(std.testing.allocator, ""));
try std.testing.expectEqualStrings("/", try normalizeServeBase(std.testing.allocator, "/"));
const prefect = try normalizeServeBase(std.testing.allocator, "prefect/");
defer std.testing.allocator.free(prefect);
try std.testing.expectEqualStrings("/prefect", prefect);
try std.testing.expectEqualStrings("/prefect/v2", try normalizeServeBase(std.testing.allocator, "/prefect/v2/"));
}
test "rewritePlaceholders removes root placeholder" {
const alloc = std.testing.allocator;
const rewritten = try rewritePlaceholdersWithBase(alloc, "", "");
defer alloc.free(rewritten);
try std.testing.expectEqualStrings("", rewritten);
}
test "rewritePlaceholders inserts non-root serve base" {
const alloc = std.testing.allocator;
const rewritten = try rewritePlaceholdersWithBase(alloc, "import('/PREFECT_UI_SERVE_BASE_REPLACE_PLACEHOLDER/assets/chunk.js')", "/prefect");
defer alloc.free(rewritten);
try std.testing.expectEqualStrings("import('/prefect/assets/chunk.js')", rewritten);
}