local archiver = require("archiver") local cmd = require("cmd") local file = require("file") local http = require("http") local json = require("json") local has_checksum, checksum = pcall(require, "checksum") local M = {} M.DEFAULT_URL = "https://code.cleyrop.tech" M.USER_AGENT = "mise-forge/0.1.0" M.MAX_PAGES = 100 local ARCHIVE_EXTENSIONS = { ".tar.gz", ".tgz", ".tar.xz", ".txz", ".tar.bz2", ".tbz2", ".tar.zst", ".tar", ".zip", } local function trim(s) if type(s) ~= "string" then return "" end return (s:gsub("^%s+", ""):gsub("%s+$", "")) end local function ends_with(str, suffix) return suffix == "" or str:sub(-#suffix) == suffix end local function starts_with(str, prefix) return str:sub(1, #prefix) == prefix end function M.shell_quote(str) return "'" .. tostring(str):gsub("'", "'\\''") .. "'" end function M.base_url(options) local raw = nil if type(options) == "table" and type(options.url) == "string" and trim(options.url) ~= "" then raw = trim(options.url) else local env_url = os.getenv("MISE_FORGE_URL") if type(env_url) == "string" and trim(env_url) ~= "" then raw = trim(env_url) else raw = M.DEFAULT_URL end end raw = raw:gsub("/+$", "") if not (starts_with(raw, "https://") or starts_with(raw, "http://")) then error("Invalid forge URL (must start with https:// or http://): " .. raw) end return raw end local function validate_segment(seg, label) if type(seg) ~= "string" or seg == "" then error("Invalid " .. label .. ": empty value") end if seg == "." or seg == ".." or seg:find("%.%.") then error("Invalid " .. label .. ": path traversal is not allowed (" .. seg .. ")") end if not seg:match("^[A-Za-z0-9._-]+$") then error("Invalid " .. label .. ": unsupported characters (" .. seg .. ")") end end function M.parse_tool(tool, options) if type(tool) ~= "string" or trim(tool) == "" then error("Tool name is required (expected forge: or forge:/)") end local parts = {} for part in tool:gmatch("[^/]+") do table.insert(parts, part) end if #parts == 0 or #parts > 2 or tool:find("//") or starts_with(tool, "/") or ends_with(tool, "/") then error("Invalid tool identifier '" .. tool .. "' (expected or /)") end local repo = parts[1] validate_segment(repo, "repository name") if repo == "api" then error("Repository name 'api' is reserved on the public forge") end local explicit_bin = false local bin = repo if #parts == 2 then bin = parts[2] explicit_bin = true elseif type(options) == "table" and type(options.bin) == "string" and trim(options.bin) ~= "" then bin = trim(options.bin) explicit_bin = true end validate_segment(bin, "binary name") return { repo = repo, bin = bin, explicit_bin = explicit_bin, } end function M.runtime_platform() local raw_os = string.lower(tostring((RUNTIME and RUNTIME.osType) or "")) local raw_arch = string.lower(tostring((RUNTIME and RUNTIME.archType) or "")) local os_map = { darwin = "darwin", macos = "darwin", osx = "darwin", linux = "linux", windows = "windows", win32 = "windows", } local arch_map = { amd64 = "amd64", x86_64 = "amd64", x64 = "amd64", arm64 = "arm64", aarch64 = "arm64", } local os_name = os_map[raw_os] if not os_name then error("Unsupported operating system: " .. tostring(RUNTIME and RUNTIME.osType)) end local arch_name = arch_map[raw_arch] if not arch_name then error("Unsupported CPU architecture: " .. tostring(RUNTIME and RUNTIME.archType)) end return os_name, arch_name end function M.http_headers(accept) local headers = { ["User-Agent"] = M.USER_AGENT, } if accept then headers["Accept"] = accept end local token = os.getenv("MISE_FORGE_TOKEN") if type(token) == "string" and trim(token) ~= "" then headers["Authorization"] = "Bearer " .. trim(token) end return headers end function M.resolve_url(base_url, target) if type(target) ~= "string" or trim(target) == "" then error("Missing URL in release metadata") end local url = trim(target) if starts_with(url, "/") then url = base_url .. url end if not (starts_with(url, "https://") or starts_with(url, "http://")) then error("Refusing non-HTTP(S) URL: " .. url) end return url end local function get_header_ci(headers, target_name) if type(headers) ~= "table" then return nil end local lower_target = string.lower(target_name) for k, v in pairs(headers) do if string.lower(tostring(k)) == lower_target then return v end end return nil end function M.parse_next_link(headers, base_url) local link = get_header_ci(headers, "link") if type(link) ~= "string" or link == "" then return nil end for entry in link:gmatch("[^,]+") do local url, params = entry:match("^%s*<([^>]+)>%s*;(.*)$") if url and params and params:match('rel%s*=%s*"?next"?') then return M.resolve_url(base_url, url) end end return nil end function M.fetch_json(url, allow_404) local resp, err = http.get({ url = url, headers = M.http_headers("application/json"), }) if err ~= nil then error("HTTP request failed for " .. url .. ": " .. tostring(err)) end if resp == nil then error("Empty HTTP response for " .. url) end if allow_404 and resp.status_code == 404 then return nil, resp.headers, 404 end if resp.status_code ~= 200 then error("HTTP " .. tostring(resp.status_code) .. " while fetching " .. url) end local ok, decoded = pcall(json.decode, resp.body) if not ok then error("Failed to decode JSON from " .. url .. ": " .. tostring(decoded)) end return decoded, resp.headers, resp.status_code end local function unwrap_list(decoded, key) if type(decoded) ~= "table" then return {} end if type(decoded[key]) == "table" then return decoded[key] end return decoded end function M.list_repos(base_url) local decoded = M.fetch_json(base_url .. "/api/v1/repos", false) return unwrap_list(decoded, "repos") end function M.list_releases(base_url, repo) local url = base_url .. "/api/v1/repos/" .. repo .. "/releases" local all = {} local seen_urls = {} local page = 0 while url do page = page + 1 if page > M.MAX_PAGES then error("Pagination limit exceeded while listing releases for " .. repo) end if seen_urls[url] then break end seen_urls[url] = true local decoded, headers, status = M.fetch_json(url, page == 1) if status == 404 then error("Repository '" .. repo .. "' was not found on " .. base_url) end local items = unwrap_list(decoded, "releases") for _, rel in ipairs(items) do table.insert(all, rel) end url = M.parse_next_link(headers, base_url) end return all end function M.is_placed_asset(asset) return type(asset) == "table" and type(asset.os) == "string" and asset.os ~= "" and type(asset.arch) == "string" and asset.arch ~= "" and type(asset.bin) == "string" and asset.bin ~= "" and type(asset.url) == "string" and asset.url ~= "" end function M.release_has_bin(release, spec) if type(release) ~= "table" or type(release.assets) ~= "table" then return false end local any_placed = false for _, asset in ipairs(release.assets) do if M.is_placed_asset(asset) then any_placed = true if asset.bin == spec.bin then return true end end end -- When the user did not specify an explicit /, keep releases with placed assets -- so repos whose binary name differs from the repo name still list versions. return (not spec.explicit_bin) and any_placed end function M.find_release(base_url, repo, version, options) if version == "latest" then local rel, _, status = M.fetch_json(base_url .. "/api/v1/repos/" .. repo .. "/releases/latest", true) if status == 404 or rel == nil then error("No published release found for repository '" .. repo .. "' on " .. base_url) end return rel end -- Fast path: direct immutable tag lookup ( or v). local candidates = {} if type(options) == "table" and type(options.tag_prefix) == "string" and options.tag_prefix ~= "" then table.insert(candidates, options.tag_prefix .. version) end if starts_with(version, "v") then table.insert(candidates, version) else table.insert(candidates, "v" .. version) table.insert(candidates, version) end local tried = {} for _, tag in ipairs(candidates) do if not tried[tag] then tried[tag] = true local rel, _, status = M.fetch_json(base_url .. "/api/v1/repos/" .. repo .. "/releases/" .. tag, true) if status == 200 and type(rel) == "table" then return rel end end end -- Fallback: scan paginated releases to handle prefixed tags (e.g. forge-v1.4.0). local releases = M.list_releases(base_url, repo) for _, rel in ipairs(releases) do if type(rel) == "table" and (rel.version == version or rel.tag == version) then return rel end end error("Release '" .. version .. "' not found for repository '" .. repo .. "' on " .. base_url) end function M.select_asset(release, spec, os_name, arch_name) if type(release.assets) ~= "table" then error("Release '" .. tostring(release.tag or release.version) .. "' has no assets") end local platform_matches = {} for _, asset in ipairs(release.assets) do if M.is_placed_asset(asset) and asset.os == os_name and asset.arch == arch_name then if asset.bin == spec.bin then return asset end table.insert(platform_matches, asset) end end if (not spec.explicit_bin) and #platform_matches == 1 then return platform_matches[1] end if #platform_matches > 1 then local names = {} for _, asset in ipairs(platform_matches) do table.insert(names, spec.repo .. "/" .. asset.bin) end table.sort(names) error( "Multiple binaries available in '" .. spec.repo .. "' for " .. os_name .. "/" .. arch_name .. ": " .. table.concat(names, ", ") .. ". Select one explicitly with forge:/." ) end error( "No asset found for '" .. spec.repo .. "' (bin=" .. spec.bin .. ") on " .. os_name .. "/" .. arch_name .. " in release " .. tostring(release.tag or release.version) ) end function M.is_archive(name) local lower = string.lower(tostring(name or "")) for _, ext in ipairs(ARCHIVE_EXTENSIONS) do if ends_with(lower, ext) then return true end end return false end local function compute_sha256_fallback(file_path, os_name) local quoted = M.shell_quote(file_path) if os_name == "windows" then local ok, out = pcall( cmd.exec, 'powershell -NoProfile -Command "(Get-FileHash -Algorithm SHA256 -Path ' .. quoted .. ').Hash.ToLower()"' ) if ok and type(out) == "string" then local digest = out:match("([0-9a-fA-F]+)") if digest and #digest == 64 then return string.lower(digest) end end error("Unable to compute SHA-256 checksum on Windows (PowerShell Get-FileHash failed)") end local probes = { "sha256sum " .. quoted, "shasum -a 256 " .. quoted, "openssl dgst -sha256 -r " .. quoted, } for _, probe in ipairs(probes) do local ok, out = pcall(cmd.exec, probe) if ok and type(out) == "string" then local digest = out:match("^%s*([0-9a-fA-F]+)") if digest and #digest == 64 then return string.lower(digest) end end end error("Unable to verify SHA-256 checksum: built-in checksum module unavailable and neither sha256sum, shasum, nor openssl was found") end function M.verify_sha256(file_path, expected_sha256, os_name) if type(expected_sha256) ~= "string" or not expected_sha256:match("^[0-9a-fA-F]+$") or #expected_sha256 ~= 64 then error("Refusing to install asset without a valid 64-hex sha256 digest in release metadata") end local expected = string.lower(expected_sha256) if has_checksum and type(checksum) == "table" and type(checksum.verify) == "function" then checksum.verify(file_path, "sha256:" .. expected) return end local actual = compute_sha256_fallback(file_path, os_name) if actual ~= expected then error("SHA-256 checksum mismatch for " .. file_path .. ": expected " .. expected .. ", got " .. actual) end end local function is_truthy(val) if val == true then return true end if type(val) ~= "string" then return false end local lower = string.lower(trim(val)) return lower == "1" or lower == "true" or lower == "yes" end function M.maybe_verify_cosign(base_url, release, asset, file_path, temp_dir, options) local enabled = (type(options) == "table" and is_truthy(options.verify_cosign)) or is_truthy(os.getenv("MISE_FORGE_VERIFY_COSIGN")) if not enabled then return end if type(asset.signature_url) ~= "string" or trim(asset.signature_url) == "" then error("Cosign verification requested, but asset has no signature_url") end if type(release.key_url) ~= "string" or trim(release.key_url) == "" then error("Cosign verification requested, but release has no key_url") end local sig_url = M.resolve_url(base_url, asset.signature_url) local key_url = M.resolve_url(base_url, release.key_url) local sig_path = file.join_path(temp_dir, "asset.sig") local key_path = file.join_path(temp_dir, "release.pub") http.download_file({ url = sig_url, headers = M.http_headers() }, sig_path) http.download_file({ url = key_url, headers = M.http_headers() }, key_path) local command if ends_with(string.lower(sig_url), ".bundle") then command = "cosign verify-blob --key " .. M.shell_quote(key_path) .. " --bundle " .. M.shell_quote(sig_path) .. " --insecure-ignore-tlog " .. M.shell_quote(file_path) else command = "cosign verify-blob --key " .. M.shell_quote(key_path) .. " --signature " .. M.shell_quote(sig_path) .. " --insecure-ignore-tlog " .. M.shell_quote(file_path) end local ok, out = pcall(cmd.exec, command) if not ok then error("Cosign verification failed: " .. tostring(out)) end end local function make_executable(path, os_name) if os_name == "windows" then return end if type(file.chmod) == "function" then local ok = pcall(file.chmod, path, 493) -- 0755 if ok then return end end cmd.exec("chmod +x " .. M.shell_quote(path)) end local function find_extracted_binary(extract_dir, target_bin, os_name) local direct = file.join_path(extract_dir, target_bin) if file.exists(direct) then return direct, "root" end local in_bin = file.join_path(extract_dir, "bin", target_bin) if file.exists(in_bin) then return in_bin, "bin" end -- Search nested directories (e.g. single top-level folder inside tarball) if os_name == "windows" then local ok, out = pcall( cmd.exec, 'powershell -NoProfile -Command "Get-ChildItem -Path ' .. M.shell_quote(extract_dir) .. " -Recurse -File -Filter " .. M.shell_quote(target_bin) .. ' | Select-Object -First 1 -ExpandProperty FullName"' ) if ok and type(out) == "string" and trim(out) ~= "" then return trim(out), "nested" end else local ok, out = pcall( cmd.exec, "find " .. M.shell_quote(extract_dir) .. " -maxdepth 4 -type f -name " .. M.shell_quote(target_bin) .. " | head -n 1" ) if ok and type(out) == "string" and trim(out) ~= "" then return trim(out), "nested" end end return nil, nil end function M.mkdir_p(path, os_name) if type(file.mkdir) == "function" then file.mkdir(path) return end if os_name == "windows" then cmd.exec( 'powershell -NoProfile -Command "New-Item -ItemType Directory -Force -Path ' .. M.shell_quote(path) .. ' | Out-Null"' ) else cmd.exec("mkdir -p " .. M.shell_quote(path)) end end function M.remove_rf(path, os_name) if not file.exists(path) then return end if type(file.remove) == "function" then file.remove(path) return end if os_name == "windows" then cmd.exec( 'powershell -NoProfile -Command "Remove-Item -Recurse -Force -Path ' .. M.shell_quote(path) .. '"' ) else cmd.exec("rm -rf " .. M.shell_quote(path)) end end function M.move_path(src, dest, os_name) if type(file.move) == "function" then file.move(src, dest) return end local ok = os.rename(src, dest) if ok then return end if os_name == "windows" then cmd.exec( 'powershell -NoProfile -Command "Move-Item -Force -Path ' .. M.shell_quote(src) .. " -Destination " .. M.shell_quote(dest) .. '"' ) else cmd.exec("mv -f " .. M.shell_quote(src) .. " " .. M.shell_quote(dest)) end end function M.install_asset(downloaded_path, asset, install_path, download_path, os_name) local bin_dir = file.join_path(install_path, "bin") M.mkdir_p(bin_dir, os_name) local target_bin = asset.bin if os_name == "windows" and not ends_with(string.lower(target_bin), ".exe") then target_bin = target_bin .. ".exe" end local dest_bin = file.join_path(bin_dir, target_bin) local asset_name = asset.name or asset.bin if M.is_archive(asset_name) then local extract_dir = file.join_path(download_path, "extract") M.remove_rf(extract_dir, os_name) archiver.decompress(downloaded_path, extract_dir) local found_path, layout = find_extracted_binary(extract_dir, target_bin, os_name) if not found_path then error("Archive '" .. asset_name .. "' did not contain expected binary '" .. target_bin .. "'") end if layout == "bin" then -- Preserve sibling binaries shipped inside the archive's bin/ directory. local src_bin_dir = file.join_path(extract_dir, "bin") M.remove_rf(bin_dir, os_name) M.move_path(src_bin_dir, bin_dir, os_name) make_executable(dest_bin, os_name) else M.move_path(found_path, dest_bin, os_name) make_executable(dest_bin, os_name) end M.remove_rf(extract_dir, os_name) else M.move_path(downloaded_path, dest_bin, os_name) make_executable(dest_bin, os_name) end return dest_bin end return M