# Host verification checks: detects trailing-slash relative link traps # in rendered sites and verifies HTTP response headers for non-HTML assets. # # Run with: # Rscript hosting-check.R # Rscript hosting-check.R --site _site # Rscript hosting-check.R --url https://example.web.app/posts/slug/scripts/demo.R #' Scan a rendered directory for relative links vulnerable to trailing-slash stripping #' #' In static site hosting, directory pages served as `/index.html` often have #' the `.html` extension stripped by clean URL rules. If the host serves the page #' at `/dir` without a trailing slash, RFC 3986 path resolution strips `dir` as a #' file component and resolves relative links against the parent directory. #' This function finds all relative child links within directory index pages. #' #' @param site_dir Path to the rendered site directory (default "_site"). #' @return A data frame with columns: page, target, resolved_path, exists. find_relative_directory_links <- function(site_dir = "_site") { if (!dir.exists(site_dir)) { return(data.frame( page = character(), target = character(), resolved_path = character(), exists = logical(), stringsAsFactors = FALSE )) } all_indices <- list.files( site_dir, pattern = "^index\\.html$", recursive = TRUE, full.names = FALSE ) # Only inspect index.html files located inside subdirectories sub_indices <- all_indices[dirname(all_indices) != "."] if (length(sub_indices) == 0L) { return(data.frame( page = character(), target = character(), resolved_path = character(), exists = logical(), stringsAsFactors = FALSE )) } results <- list() for (sub_index in sub_indices) { full_index_path <- file.path(site_dir, sub_index) lines <- readLines(full_index_path, warn = FALSE) page_dir <- dirname(sub_index) # Extract href and src attribute values href_matches <- regmatches( lines, gregexpr('(?:href|src)=["\']([^"\']+)["\']', lines, perl = TRUE) ) targets <- character() for (m in href_matches) { if (length(m) > 0L) { cleaned <- sub('^(?:href|src)=["\']', "", m) cleaned <- sub('["\']$', "", cleaned) targets <- c(targets, cleaned) } } targets <- unique(targets) # Filter out anchors, query-only, root-relative, parent-relative, and URI schemes is_scheme <- grepl("^[a-zA-Z][a-zA-Z0-9+.-]*:", targets) is_root_rel <- startsWith(targets, "/") is_anchor <- startsWith(targets, "#") is_query <- startsWith(targets, "?") is_parent_rel <- startsWith(targets, "../") is_blank <- targets == "" child_relative <- targets[ !is_scheme & !is_root_rel & !is_anchor & !is_query & !is_parent_rel & !is_blank ] for (target in child_relative) { # Strip anchor or query string for disk path check disk_target <- sub("[?#].*$", "", target) resolved_rel <- file.path(page_dir, disk_target) target_exists <- file.exists(file.path(site_dir, resolved_rel)) results[[length(results) + 1L]] <- list( page = sub_index, target = target, resolved_path = resolved_rel, exists = target_exists ) } } if (length(results) == 0L) { return(data.frame( page = character(), target = character(), resolved_path = character(), exists = logical(), stringsAsFactors = FALSE )) } do.call(rbind, lapply(results, as.data.frame, stringsAsFactors = FALSE)) } #' Parse raw HTTP response headers #' #' Parses raw header lines returned by curl into structured status and header fields. #' Correctly handles redirect chains (e.g. 301 followed by 200). #' #' @param raw_headers Character vector of header lines, or a single newline-delimited string. #' @return A list with status_code, protocol, headers (named vector), redirects, and chain. parse_http_headers <- function(raw_headers) { if (length(raw_headers) == 1L && grepl("[\r\n]", raw_headers)) { lines <- strsplit(raw_headers, "\r?\n")[[1]] } else { lines <- as.character(raw_headers) } lines <- trimws(lines) lines <- lines[lines != ""] if (length(lines) == 0L) { return(list( status_code = NA_integer_, protocol = NA_character_, headers = character(), redirects = list(), chain = integer() )) } # Identify HTTP status lines (e.g. "HTTP/1.1 301 Moved Permanently" or "HTTP/2 200") status_indices <- grep("^HTTP/[0-9.]+ +[0-9]{3}", lines) if (length(status_indices) == 0L) { return(list( status_code = NA_integer_, protocol = NA_character_, headers = character(), redirects = list(), chain = integer() )) } responses <- list() for (i in seq_along(status_indices)) { start_idx <- status_indices[i] end_idx <- if (i < length(status_indices)) { status_indices[i + 1L] - 1L } else { length(lines) } block_lines <- lines[start_idx:end_idx] status_line <- block_lines[1] status_match <- regexec( "^([A-Za-z0-9/.]+) +([0-9]{3})(?: +(.*))?$", status_line ) status_parts <- regmatches(status_line, status_match)[[1]] proto <- if (length(status_parts) >= 2L) status_parts[2] else NA_character_ code <- if (length(status_parts) >= 3L) { as.integer(status_parts[3]) } else { NA_integer_ } header_lines <- block_lines[-1] parsed_headers <- character() for (h_line in header_lines) { sep_idx <- regexpr(":", h_line, fixed = TRUE) if (sep_idx > 0L) { key <- tolower(trimws(substr(h_line, 1L, sep_idx - 1L))) val <- trimws(substr(h_line, sep_idx + 1L, nchar(h_line))) parsed_headers[key] <- val } } responses[[length(responses) + 1L]] <- list( protocol = proto, status_code = code, headers = parsed_headers ) } final_resp <- responses[[length(responses)]] chain <- vapply(responses, function(r) r$status_code, integer(1)) redirects <- list() if (length(responses) > 1L) { for (j in seq_len(length(responses) - 1L)) { redirects[[j]] <- list( status_code = responses[[j]]$status_code, location = unname(responses[[j]]$headers["location"]) ) } } list( status_code = final_resp$status_code, protocol = final_resp$protocol, headers = final_resp$headers, redirects = redirects, chain = chain ) } #' Check HTTP headers for MIME type misclassifications #' #' Flags responses where non-HTML assets (.R, .sh, .yml, extensionless scripts) #' are served as text/html when compressed or requested with browser headers. #' #' @param raw_headers Character vector of header lines or string. #' @param url_path Optional URL or path to infer expected file type. #' @return A list with valid (logical), status_code, content_type, content_encoding, nosniff, and issue. check_content_type <- function(raw_headers, url_path = "") { parsed <- parse_http_headers(raw_headers) if (is.na(parsed$status_code)) { return(list( valid = FALSE, status_code = NA_integer_, content_type = NA_character_, content_encoding = NA_character_, nosniff = FALSE, issue = "Could not parse HTTP response headers" )) } ct <- unname(parsed$headers["content-type"]) if (is.na(ct)) { ct <- "missing" } ce <- unname(parsed$headers["content-encoding"]) nosniff_hdr <- unname(parsed$headers["x-content-type-options"]) nosniff <- !is.na(nosniff_hdr) && tolower(nosniff_hdr) == "nosniff" # Detect non-HTML target from url_path clean_path <- sub("[?#].*$", "", url_path) is_non_html <- grepl( "\\.(r|sh|bash|yml|yaml|json|csv|tsv|txt|md|qmd|rmd)$", clean_path, ignore.case = TRUE ) || grepl("/commit-msg$", clean_path) is_served_as_html <- grepl("text/html", ct, ignore.case = TRUE) issue <- "" valid <- TRUE if (is_non_html && is_served_as_html) { valid <- FALSE issue <- sprintf( "Non-HTML asset (%s) was served as '%s'", basename(clean_path), ct ) } list( valid = valid, status_code = parsed$status_code, content_type = ct, content_encoding = ce, nosniff = nosniff, issue = issue ) } # Standalone execution if (sys.nframe() == 0L) { args <- commandArgs(trailingOnly = TRUE) if ("--help" %in% args || "-h" %in% args) { cat("Usage:\n") cat( " Rscript hosting-check.R # Run offline verification demo\n" ) cat( " Rscript hosting-check.R --site # Scan directory index pages for relative links\n" ) cat( " Rscript hosting-check.R --url # Inspect HTTP headers for target URL\n" ) } else if ("--site" %in% args) { site_idx <- which(args == "--site") + 1L site_dir <- if (site_idx <= length(args)) args[site_idx] else "_site" cat("Scanning rendered directory:", site_dir, "\n") findings <- find_relative_directory_links(site_dir) if (nrow(findings) == 0L) { cat("No relative child links found in directory index pages.\n") } else { cat(sprintf( "Found %d relative link(s) vulnerable to trailing slash removal:\n", nrow(findings) )) print(findings) } } else if ("--url" %in% args) { url_idx <- which(args == "--url") + 1L if (url_idx <= length(args)) { target_url <- args[url_idx] cat("Inspecting headers for:", target_url, "\n") curl_args <- c( "-sI", "-H", "Accept-Encoding: gzip, br", "-H", "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "--", target_url ) raw_output <- tryCatch( system2("curl", curl_args, stdout = TRUE, stderr = FALSE), error = function(e) character() ) res <- check_content_type(raw_output, url_path = target_url) cat("Status Code: ", res$status_code, "\n") cat("Content-Type: ", res$content_type, "\n") cat( "Content-Encoding:", ifelse(is.na(res$content_encoding), "none", res$content_encoding), "\n" ) cat("Nosniff: ", ifelse(res$nosniff, "yes", "no"), "\n") cat("Valid MIME: ", ifelse(res$valid, "PASS", "FAIL"), "\n") if (nzchar(res$issue)) { cat("Issue: ", res$issue, "\n") } } else { cat("Error: --url requires a target URL argument.\n") } } else { cat("=======================================================\n") cat("Running offline hosting-check demonstration\n") cat("=======================================================\n\n") cat("Step 1: Header parsing with browser compression headers\n") sample_compressed_bug <- paste( "HTTP/2 200", "content-type: text/html; charset=UTF-8", "content-encoding: gzip", sep = "\n" ) res_bug <- check_content_type( sample_compressed_bug, url_path = "scripts/ars-demo.R" ) cat("Bug reproduction (unconfigured CDN response):\n") cat(" Asset: scripts/ars-demo.R\n") cat(" Valid: ", res_bug$valid, "\n") cat(" Type: ", res_bug$content_type, "\n") cat(" Issue: ", res_bug$issue, "\n\n") sample_fixed <- paste( "HTTP/2 200", "content-type: text/plain; charset=utf-8", "content-encoding: gzip", "x-content-type-options: nosniff", sep = "\n" ) res_fixed <- check_content_type( sample_fixed, url_path = "scripts/ars-demo.R" ) cat("Fixed configuration (explicit headers):\n") cat(" Asset: scripts/ars-demo.R\n") cat(" Valid: ", res_fixed$valid, "\n") cat(" Type: ", res_fixed$content_type, "\n") cat(" Nosniff:", res_fixed$nosniff, "\n") } }