forgeFRENBrowse the repositories

miselibforge.lua

6b43a505698341ce02e15c97ca3d37e17537fa47

At commit 6b43a50

666 lines · 19.9 KiBLuaRaw
  1. local archiver = require("archiver")
  2. local cmd = require("cmd")
  3. local file = require("file")
  4. local http = require("http")
  5. local json = require("json")
  6. local has_checksum, checksum = pcall(require, "checksum")
  7. local M = {}
  8. M.DEFAULT_URL = "https://code.cleyrop.tech"
  9. M.USER_AGENT = "mise-forge/0.1.0"
  10. M.MAX_PAGES = 100
  11. local ARCHIVE_EXTENSIONS = {
  12. ".tar.gz",
  13. ".tgz",
  14. ".tar.xz",
  15. ".txz",
  16. ".tar.bz2",
  17. ".tbz2",
  18. ".tar.zst",
  19. ".tar",
  20. ".zip",
  21. }
  22. local function trim(s)
  23. if type(s) ~= "string" then
  24. return ""
  25. end
  26. return (s:gsub("^%s+", ""):gsub("%s+$", ""))
  27. end
  28. local function ends_with(str, suffix)
  29. return suffix == "" or str:sub(-#suffix) == suffix
  30. end
  31. local function starts_with(str, prefix)
  32. return str:sub(1, #prefix) == prefix
  33. end
  34. function M.shell_quote(str)
  35. return "'" .. tostring(str):gsub("'", "'\\''") .. "'"
  36. end
  37. function M.base_url(options)
  38. local raw = nil
  39. if type(options) == "table" and type(options.url) == "string" and trim(options.url) ~= "" then
  40. raw = trim(options.url)
  41. else
  42. local env_url = os.getenv("MISE_FORGE_URL")
  43. if type(env_url) == "string" and trim(env_url) ~= "" then
  44. raw = trim(env_url)
  45. else
  46. raw = M.DEFAULT_URL
  47. end
  48. end
  49. raw = raw:gsub("/+$", "")
  50. if not (starts_with(raw, "https://") or starts_with(raw, "http://")) then
  51. error("Invalid forge URL (must start with https:// or http://): " .. raw)
  52. end
  53. return raw
  54. end
  55. local function validate_segment(seg, label)
  56. if type(seg) ~= "string" or seg == "" then
  57. error("Invalid " .. label .. ": empty value")
  58. end
  59. if seg == "." or seg == ".." or seg:find("%.%.") then
  60. error("Invalid " .. label .. ": path traversal is not allowed (" .. seg .. ")")
  61. end
  62. if not seg:match("^[A-Za-z0-9._-]+$") then
  63. error("Invalid " .. label .. ": unsupported characters (" .. seg .. ")")
  64. end
  65. end
  66. function M.parse_tool(tool, options)
  67. if type(tool) ~= "string" or trim(tool) == "" then
  68. error("Tool name is required (expected forge:<repo> or forge:<repo>/<bin>)")
  69. end
  70. local parts = {}
  71. for part in tool:gmatch("[^/]+") do
  72. table.insert(parts, part)
  73. end
  74. if #parts == 0 or #parts > 2 or tool:find("//") or starts_with(tool, "/") or ends_with(tool, "/") then
  75. error("Invalid tool identifier '" .. tool .. "' (expected <repo> or <repo>/<bin>)")
  76. end
  77. local repo = parts[1]
  78. validate_segment(repo, "repository name")
  79. if repo == "api" then
  80. error("Repository name 'api' is reserved on the public forge")
  81. end
  82. local explicit_bin = false
  83. local bin = repo
  84. if #parts == 2 then
  85. bin = parts[2]
  86. explicit_bin = true
  87. elseif type(options) == "table" and type(options.bin) == "string" and trim(options.bin) ~= "" then
  88. bin = trim(options.bin)
  89. explicit_bin = true
  90. end
  91. validate_segment(bin, "binary name")
  92. return {
  93. repo = repo,
  94. bin = bin,
  95. explicit_bin = explicit_bin,
  96. }
  97. end
  98. function M.runtime_platform()
  99. local raw_os = string.lower(tostring((RUNTIME and RUNTIME.osType) or ""))
  100. local raw_arch = string.lower(tostring((RUNTIME and RUNTIME.archType) or ""))
  101. local os_map = {
  102. darwin = "darwin",
  103. macos = "darwin",
  104. osx = "darwin",
  105. linux = "linux",
  106. windows = "windows",
  107. win32 = "windows",
  108. }
  109. local arch_map = {
  110. amd64 = "amd64",
  111. x86_64 = "amd64",
  112. x64 = "amd64",
  113. arm64 = "arm64",
  114. aarch64 = "arm64",
  115. }
  116. local os_name = os_map[raw_os]
  117. if not os_name then
  118. error("Unsupported operating system: " .. tostring(RUNTIME and RUNTIME.osType))
  119. end
  120. local arch_name = arch_map[raw_arch]
  121. if not arch_name then
  122. error("Unsupported CPU architecture: " .. tostring(RUNTIME and RUNTIME.archType))
  123. end
  124. return os_name, arch_name
  125. end
  126. function M.http_headers(accept)
  127. local headers = {
  128. ["User-Agent"] = M.USER_AGENT,
  129. }
  130. if accept then
  131. headers["Accept"] = accept
  132. end
  133. local token = os.getenv("MISE_FORGE_TOKEN")
  134. if type(token) == "string" and trim(token) ~= "" then
  135. headers["Authorization"] = "Bearer " .. trim(token)
  136. end
  137. return headers
  138. end
  139. function M.resolve_url(base_url, target)
  140. if type(target) ~= "string" or trim(target) == "" then
  141. error("Missing URL in release metadata")
  142. end
  143. local url = trim(target)
  144. if starts_with(url, "/") then
  145. url = base_url .. url
  146. end
  147. if not (starts_with(url, "https://") or starts_with(url, "http://")) then
  148. error("Refusing non-HTTP(S) URL: " .. url)
  149. end
  150. return url
  151. end
  152. local function get_header_ci(headers, target_name)
  153. if type(headers) ~= "table" then
  154. return nil
  155. end
  156. local lower_target = string.lower(target_name)
  157. for k, v in pairs(headers) do
  158. if string.lower(tostring(k)) == lower_target then
  159. return v
  160. end
  161. end
  162. return nil
  163. end
  164. function M.parse_next_link(headers, base_url)
  165. local link = get_header_ci(headers, "link")
  166. if type(link) ~= "string" or link == "" then
  167. return nil
  168. end
  169. for entry in link:gmatch("[^,]+") do
  170. local url, params = entry:match("^%s*<([^>]+)>%s*;(.*)$")
  171. if url and params and params:match('rel%s*=%s*"?next"?') then
  172. return M.resolve_url(base_url, url)
  173. end
  174. end
  175. return nil
  176. end
  177. function M.fetch_json(url, allow_404)
  178. local resp, err = http.get({
  179. url = url,
  180. headers = M.http_headers("application/json"),
  181. })
  182. if err ~= nil then
  183. error("HTTP request failed for " .. url .. ": " .. tostring(err))
  184. end
  185. if resp == nil then
  186. error("Empty HTTP response for " .. url)
  187. end
  188. if allow_404 and resp.status_code == 404 then
  189. return nil, resp.headers, 404
  190. end
  191. if resp.status_code ~= 200 then
  192. error("HTTP " .. tostring(resp.status_code) .. " while fetching " .. url)
  193. end
  194. local ok, decoded = pcall(json.decode, resp.body)
  195. if not ok then
  196. error("Failed to decode JSON from " .. url .. ": " .. tostring(decoded))
  197. end
  198. return decoded, resp.headers, resp.status_code
  199. end
  200. local function unwrap_list(decoded, key)
  201. if type(decoded) ~= "table" then
  202. return {}
  203. end
  204. if type(decoded[key]) == "table" then
  205. return decoded[key]
  206. end
  207. return decoded
  208. end
  209. function M.list_repos(base_url)
  210. local decoded = M.fetch_json(base_url .. "/api/v1/repos", false)
  211. return unwrap_list(decoded, "repos")
  212. end
  213. function M.list_releases(base_url, repo)
  214. local url = base_url .. "/api/v1/repos/" .. repo .. "/releases"
  215. local all = {}
  216. local seen_urls = {}
  217. local page = 0
  218. while url do
  219. page = page + 1
  220. if page > M.MAX_PAGES then
  221. error("Pagination limit exceeded while listing releases for " .. repo)
  222. end
  223. if seen_urls[url] then
  224. break
  225. end
  226. seen_urls[url] = true
  227. local decoded, headers, status = M.fetch_json(url, page == 1)
  228. if status == 404 then
  229. error("Repository '" .. repo .. "' was not found on " .. base_url)
  230. end
  231. local items = unwrap_list(decoded, "releases")
  232. for _, rel in ipairs(items) do
  233. table.insert(all, rel)
  234. end
  235. url = M.parse_next_link(headers, base_url)
  236. end
  237. return all
  238. end
  239. function M.is_placed_asset(asset)
  240. return type(asset) == "table"
  241. and type(asset.os) == "string" and asset.os ~= ""
  242. and type(asset.arch) == "string" and asset.arch ~= ""
  243. and type(asset.bin) == "string" and asset.bin ~= ""
  244. and type(asset.url) == "string" and asset.url ~= ""
  245. end
  246. function M.release_has_bin(release, spec)
  247. if type(release) ~= "table" or type(release.assets) ~= "table" then
  248. return false
  249. end
  250. local any_placed = false
  251. for _, asset in ipairs(release.assets) do
  252. if M.is_placed_asset(asset) then
  253. any_placed = true
  254. if asset.bin == spec.bin then
  255. return true
  256. end
  257. end
  258. end
  259. -- When the user did not specify an explicit /<bin>, keep releases with placed assets
  260. -- so repos whose binary name differs from the repo name still list versions.
  261. return (not spec.explicit_bin) and any_placed
  262. end
  263. function M.find_release(base_url, repo, version, options)
  264. if version == "latest" then
  265. local rel, _, status = M.fetch_json(base_url .. "/api/v1/repos/" .. repo .. "/releases/latest", true)
  266. if status == 404 or rel == nil then
  267. error("No published release found for repository '" .. repo .. "' on " .. base_url)
  268. end
  269. return rel
  270. end
  271. -- Fast path: direct immutable tag lookup (<tag_prefix><version> or v<version>).
  272. local candidates = {}
  273. if type(options) == "table" and type(options.tag_prefix) == "string" and options.tag_prefix ~= "" then
  274. table.insert(candidates, options.tag_prefix .. version)
  275. end
  276. if starts_with(version, "v") then
  277. table.insert(candidates, version)
  278. else
  279. table.insert(candidates, "v" .. version)
  280. table.insert(candidates, version)
  281. end
  282. local tried = {}
  283. for _, tag in ipairs(candidates) do
  284. if not tried[tag] then
  285. tried[tag] = true
  286. local rel, _, status = M.fetch_json(base_url .. "/api/v1/repos/" .. repo .. "/releases/" .. tag, true)
  287. if status == 200 and type(rel) == "table" then
  288. return rel
  289. end
  290. end
  291. end
  292. -- Fallback: scan paginated releases to handle prefixed tags (e.g. forge-v1.4.0).
  293. local releases = M.list_releases(base_url, repo)
  294. for _, rel in ipairs(releases) do
  295. if type(rel) == "table" and (rel.version == version or rel.tag == version) then
  296. return rel
  297. end
  298. end
  299. error("Release '" .. version .. "' not found for repository '" .. repo .. "' on " .. base_url)
  300. end
  301. function M.select_asset(release, spec, os_name, arch_name)
  302. if type(release.assets) ~= "table" then
  303. error("Release '" .. tostring(release.tag or release.version) .. "' has no assets")
  304. end
  305. local platform_matches = {}
  306. for _, asset in ipairs(release.assets) do
  307. if M.is_placed_asset(asset) and asset.os == os_name and asset.arch == arch_name then
  308. if asset.bin == spec.bin then
  309. return asset
  310. end
  311. table.insert(platform_matches, asset)
  312. end
  313. end
  314. if (not spec.explicit_bin) and #platform_matches == 1 then
  315. return platform_matches[1]
  316. end
  317. if #platform_matches > 1 then
  318. local names = {}
  319. for _, asset in ipairs(platform_matches) do
  320. table.insert(names, spec.repo .. "/" .. asset.bin)
  321. end
  322. table.sort(names)
  323. error(
  324. "Multiple binaries available in '"
  325. .. spec.repo
  326. .. "' for "
  327. .. os_name
  328. .. "/"
  329. .. arch_name
  330. .. ": "
  331. .. table.concat(names, ", ")
  332. .. ". Select one explicitly with forge:<repo>/<bin>."
  333. )
  334. end
  335. error(
  336. "No asset found for '"
  337. .. spec.repo
  338. .. "' (bin="
  339. .. spec.bin
  340. .. ") on "
  341. .. os_name
  342. .. "/"
  343. .. arch_name
  344. .. " in release "
  345. .. tostring(release.tag or release.version)
  346. )
  347. end
  348. function M.is_archive(name)
  349. local lower = string.lower(tostring(name or ""))
  350. for _, ext in ipairs(ARCHIVE_EXTENSIONS) do
  351. if ends_with(lower, ext) then
  352. return true
  353. end
  354. end
  355. return false
  356. end
  357. local function compute_sha256_fallback(file_path, os_name)
  358. local quoted = M.shell_quote(file_path)
  359. if os_name == "windows" then
  360. local ok, out = pcall(
  361. cmd.exec,
  362. 'powershell -NoProfile -Command "(Get-FileHash -Algorithm SHA256 -Path '
  363. .. quoted
  364. .. ').Hash.ToLower()"'
  365. )
  366. if ok and type(out) == "string" then
  367. local digest = out:match("([0-9a-fA-F]+)")
  368. if digest and #digest == 64 then
  369. return string.lower(digest)
  370. end
  371. end
  372. error("Unable to compute SHA-256 checksum on Windows (PowerShell Get-FileHash failed)")
  373. end
  374. local probes = {
  375. "sha256sum " .. quoted,
  376. "shasum -a 256 " .. quoted,
  377. "openssl dgst -sha256 -r " .. quoted,
  378. }
  379. for _, probe in ipairs(probes) do
  380. local ok, out = pcall(cmd.exec, probe)
  381. if ok and type(out) == "string" then
  382. local digest = out:match("^%s*([0-9a-fA-F]+)")
  383. if digest and #digest == 64 then
  384. return string.lower(digest)
  385. end
  386. end
  387. end
  388. error("Unable to verify SHA-256 checksum: built-in checksum module unavailable and neither sha256sum, shasum, nor openssl was found")
  389. end
  390. function M.verify_sha256(file_path, expected_sha256, os_name)
  391. if type(expected_sha256) ~= "string" or not expected_sha256:match("^[0-9a-fA-F]+$") or #expected_sha256 ~= 64 then
  392. error("Refusing to install asset without a valid 64-hex sha256 digest in release metadata")
  393. end
  394. local expected = string.lower(expected_sha256)
  395. if has_checksum and type(checksum) == "table" and type(checksum.verify) == "function" then
  396. checksum.verify(file_path, "sha256:" .. expected)
  397. return
  398. end
  399. local actual = compute_sha256_fallback(file_path, os_name)
  400. if actual ~= expected then
  401. error("SHA-256 checksum mismatch for " .. file_path .. ": expected " .. expected .. ", got " .. actual)
  402. end
  403. end
  404. local function is_truthy(val)
  405. if val == true then
  406. return true
  407. end
  408. if type(val) ~= "string" then
  409. return false
  410. end
  411. local lower = string.lower(trim(val))
  412. return lower == "1" or lower == "true" or lower == "yes"
  413. end
  414. function M.maybe_verify_cosign(base_url, release, asset, file_path, temp_dir, options)
  415. local enabled = (type(options) == "table" and is_truthy(options.verify_cosign))
  416. or is_truthy(os.getenv("MISE_FORGE_VERIFY_COSIGN"))
  417. if not enabled then
  418. return
  419. end
  420. if type(asset.signature_url) ~= "string" or trim(asset.signature_url) == "" then
  421. error("Cosign verification requested, but asset has no signature_url")
  422. end
  423. if type(release.key_url) ~= "string" or trim(release.key_url) == "" then
  424. error("Cosign verification requested, but release has no key_url")
  425. end
  426. local sig_url = M.resolve_url(base_url, asset.signature_url)
  427. local key_url = M.resolve_url(base_url, release.key_url)
  428. local sig_path = file.join_path(temp_dir, "asset.sig")
  429. local key_path = file.join_path(temp_dir, "release.pub")
  430. http.download_file({ url = sig_url, headers = M.http_headers() }, sig_path)
  431. http.download_file({ url = key_url, headers = M.http_headers() }, key_path)
  432. local command
  433. if ends_with(string.lower(sig_url), ".bundle") then
  434. command = "cosign verify-blob --key "
  435. .. M.shell_quote(key_path)
  436. .. " --bundle "
  437. .. M.shell_quote(sig_path)
  438. .. " --insecure-ignore-tlog "
  439. .. M.shell_quote(file_path)
  440. else
  441. command = "cosign verify-blob --key "
  442. .. M.shell_quote(key_path)
  443. .. " --signature "
  444. .. M.shell_quote(sig_path)
  445. .. " --insecure-ignore-tlog "
  446. .. M.shell_quote(file_path)
  447. end
  448. local ok, out = pcall(cmd.exec, command)
  449. if not ok then
  450. error("Cosign verification failed: " .. tostring(out))
  451. end
  452. end
  453. local function make_executable(path, os_name)
  454. if os_name == "windows" then
  455. return
  456. end
  457. if type(file.chmod) == "function" then
  458. local ok = pcall(file.chmod, path, 493) -- 0755
  459. if ok then
  460. return
  461. end
  462. end
  463. cmd.exec("chmod +x " .. M.shell_quote(path))
  464. end
  465. local function find_extracted_binary(extract_dir, target_bin, os_name)
  466. local direct = file.join_path(extract_dir, target_bin)
  467. if file.exists(direct) then
  468. return direct, "root"
  469. end
  470. local in_bin = file.join_path(extract_dir, "bin", target_bin)
  471. if file.exists(in_bin) then
  472. return in_bin, "bin"
  473. end
  474. -- Search nested directories (e.g. single top-level folder inside tarball)
  475. if os_name == "windows" then
  476. local ok, out = pcall(
  477. cmd.exec,
  478. 'powershell -NoProfile -Command "Get-ChildItem -Path '
  479. .. M.shell_quote(extract_dir)
  480. .. " -Recurse -File -Filter "
  481. .. M.shell_quote(target_bin)
  482. .. ' | Select-Object -First 1 -ExpandProperty FullName"'
  483. )
  484. if ok and type(out) == "string" and trim(out) ~= "" then
  485. return trim(out), "nested"
  486. end
  487. else
  488. local ok, out = pcall(
  489. cmd.exec,
  490. "find "
  491. .. M.shell_quote(extract_dir)
  492. .. " -maxdepth 4 -type f -name "
  493. .. M.shell_quote(target_bin)
  494. .. " | head -n 1"
  495. )
  496. if ok and type(out) == "string" and trim(out) ~= "" then
  497. return trim(out), "nested"
  498. end
  499. end
  500. return nil, nil
  501. end
  502. function M.mkdir_p(path, os_name)
  503. if type(file.mkdir) == "function" then
  504. file.mkdir(path)
  505. return
  506. end
  507. if os_name == "windows" then
  508. cmd.exec(
  509. 'powershell -NoProfile -Command "New-Item -ItemType Directory -Force -Path '
  510. .. M.shell_quote(path)
  511. .. ' | Out-Null"'
  512. )
  513. else
  514. cmd.exec("mkdir -p " .. M.shell_quote(path))
  515. end
  516. end
  517. function M.remove_rf(path, os_name)
  518. if not file.exists(path) then
  519. return
  520. end
  521. if type(file.remove) == "function" then
  522. file.remove(path)
  523. return
  524. end
  525. if os_name == "windows" then
  526. cmd.exec(
  527. 'powershell -NoProfile -Command "Remove-Item -Recurse -Force -Path '
  528. .. M.shell_quote(path)
  529. .. '"'
  530. )
  531. else
  532. cmd.exec("rm -rf " .. M.shell_quote(path))
  533. end
  534. end
  535. function M.move_path(src, dest, os_name)
  536. if type(file.move) == "function" then
  537. file.move(src, dest)
  538. return
  539. end
  540. local ok = os.rename(src, dest)
  541. if ok then
  542. return
  543. end
  544. if os_name == "windows" then
  545. cmd.exec(
  546. 'powershell -NoProfile -Command "Move-Item -Force -Path '
  547. .. M.shell_quote(src)
  548. .. " -Destination "
  549. .. M.shell_quote(dest)
  550. .. '"'
  551. )
  552. else
  553. cmd.exec("mv -f " .. M.shell_quote(src) .. " " .. M.shell_quote(dest))
  554. end
  555. end
  556. function M.install_asset(downloaded_path, asset, install_path, download_path, os_name)
  557. local bin_dir = file.join_path(install_path, "bin")
  558. M.mkdir_p(bin_dir, os_name)
  559. local target_bin = asset.bin
  560. if os_name == "windows" and not ends_with(string.lower(target_bin), ".exe") then
  561. target_bin = target_bin .. ".exe"
  562. end
  563. local dest_bin = file.join_path(bin_dir, target_bin)
  564. local asset_name = asset.name or asset.bin
  565. if M.is_archive(asset_name) then
  566. local extract_dir = file.join_path(download_path, "extract")
  567. M.remove_rf(extract_dir, os_name)
  568. archiver.decompress(downloaded_path, extract_dir)
  569. local found_path, layout = find_extracted_binary(extract_dir, target_bin, os_name)
  570. if not found_path then
  571. error("Archive '" .. asset_name .. "' did not contain expected binary '" .. target_bin .. "'")
  572. end
  573. if layout == "bin" then
  574. -- Preserve sibling binaries shipped inside the archive's bin/ directory.
  575. local src_bin_dir = file.join_path(extract_dir, "bin")
  576. M.remove_rf(bin_dir, os_name)
  577. M.move_path(src_bin_dir, bin_dir, os_name)
  578. make_executable(dest_bin, os_name)
  579. else
  580. M.move_path(found_path, dest_bin, os_name)
  581. make_executable(dest_bin, os_name)
  582. end
  583. M.remove_rf(extract_dir, os_name)
  584. else
  585. M.move_path(downloaded_path, dest_bin, os_name)
  586. make_executable(dest_bin, os_name)
  587. end
  588. return dest_bin
  589. end
  590. return M