GITv

Add GITv: private Git hosting over OpenSSH with a web browser

Browse files

gitv handles SSH forced commands (list, create, delete, push and fetch, with push-to-create) and root administration of repositories and keys. gitv-web is a read-only browser for repositories, trees, files, commits and tags, with Markdown rendering and syntax highlighting. GITV_REPOS and GITV_KEYS point both at a local tree for development. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 10:57
Commit
8776577b34fd

8 files changed +1998−0

+2−0
@@ -0,0 +1,2 @@
/target
/dev
+982−0
@@ -0,0 +1,982 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "anstream"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is_terminal_polyfill",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
[[package]]
name = "anstyle-parse"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "3.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
dependencies = [
"anstyle",
"once_cell_polyfill",
"windows-sys",
]
[[package]]
name = "atomic-waker"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
[[package]]
name = "axum"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
dependencies = [
"axum-core",
"bytes",
"form_urlencoded",
"futures-util",
"http",
"http-body",
"http-body-util",
"hyper",
"hyper-util",
"itoa",
"matchit",
"memchr",
"mime",
"percent-encoding",
"pin-project-lite",
"serde_core",
"serde_json",
"serde_path_to_error",
"serde_urlencoded",
"sync_wrapper",
"tokio",
"tower",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "axum-core"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"http-body-util",
"mime",
"pin-project-lite",
"sync_wrapper",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "base64"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bincode"
version = "1.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1f45e9417d87227c7a56d22e471c6206462cba514c7590c09aff4cf6d1ddcad"
dependencies = [
"serde",
]
[[package]]
name = "bit-set"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
dependencies = [
"bit-vec",
]
[[package]]
name = "bit-vec"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
[[package]]
name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
[[package]]
name = "bytes"
version = "1.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "cfg_aliases"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"
[[package]]
name = "clap"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "844c5c0b65be192cb68d570cca1b21a6444431d24e39c084dc0336177015337c"
dependencies = [
"clap_builder",
"clap_derive",
]
[[package]]
name = "clap_builder"
version = "4.6.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d"
dependencies = [
"anstream",
"anstyle",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.6.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
[[package]]
name = "colorchoice"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "crc32fast"
version = "1.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
dependencies = [
"cfg-if",
]
[[package]]
name = "deranged"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "fancy-regex"
version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "998b056554fbe42e03ae0e152895cd1a7e1002aec800fdc6635d20270260c46f"
dependencies = [
"bit-set",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "flate2"
version = "1.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
dependencies = [
"crc32fast",
"miniz_oxide",
"zlib-rs",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "form_urlencoded"
version = "1.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afa489199eaffb1211795df1c6236ce1ad0d41a6fa45250add73e3b02420f06e"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-core"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
[[package]]
name = "futures-task"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
[[package]]
name = "futures-util"
version = "0.3.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"slab",
]
[[package]]
name = "gitv"
version = "0.1.0"
dependencies = [
"axum",
"base64",
"clap",
"html-escape",
"nix",
"pulldown-cmark",
"shlex",
"syntect",
"tokio",
]
[[package]]
name = "hashbrown"
version = "0.17.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "html-escape"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d45ed4d99334da2a2f221504e8ffc8ad09baf2a452b154465a976bfde697b004"
[[package]]
name = "http"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
dependencies = [
"bytes",
"itoa",
]
[[package]]
name = "http-body"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
dependencies = [
"bytes",
"http",
]
[[package]]
name = "http-body-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
dependencies = [
"bytes",
"futures-core",
"http",
"http-body",
"pin-project-lite",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "httpdate"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
[[package]]
name = "hyper"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"
dependencies = [
"atomic-waker",
"bytes",
"futures-core",
"http",
"http-body",
"httparse",
"httpdate",
"itoa",
"pin-project-lite",
"smallvec",
"tokio",
]
[[package]]
name = "hyper-util"
version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
dependencies = [
"bytes",
"http",
"http-body",
"hyper",
"pin-project-lite",
"tokio",
"tower-service",
]
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
]
[[package]]
name = "is_terminal_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
[[package]]
name = "itoa"
version = "1.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "linked-hash-map"
version = "0.5.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
[[package]]
name = "log"
version = "0.4.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c"
[[package]]
name = "matchit"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "mime"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1"
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "mio"
version = "1.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
dependencies = [
"libc",
"wasi",
"windows-sys",
]
[[package]]
name = "nix"
version = "0.32.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77730ed34f01f4990cb2ea67fec715ecebc6fab9a6396cf83c5529b13f581bdc"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "pin-project-lite"
version = "0.2.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752"
[[package]]
name = "plist"
version = "1.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d86a77b7d9cdebd9643c180c158748db7d894b24a3935ed4b5843e698ae086eb"
dependencies = [
"base64",
"indexmap",
"quick-xml",
"serde",
"time",
]
[[package]]
name = "powerfmt"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "pulldown-cmark"
version = "0.13.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b"
dependencies = [
"bitflags",
"memchr",
"pulldown-cmark-escape",
"unicase",
]
[[package]]
name = "pulldown-cmark-escape"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
[[package]]
name = "quick-xml"
version = "0.42.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
dependencies = [
"memchr",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex-automata"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
[[package]]
name = "ryu"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
[[package]]
name = "same-file"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
dependencies = [
"winapi-util",
]
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "serde_path_to_error"
version = "0.1.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
dependencies = [
"itoa",
"serde",
"serde_core",
]
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
"itoa",
"ryu",
"serde",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "slab"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "socket2"
version = "0.6.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "strsim"
version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "sync_wrapper"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
[[package]]
name = "syntect"
version = "5.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "656b45c05d95a5704399aeef6bd0ddec7b2b3531b7c9e900abbf7c4d2190c925"
dependencies = [
"bincode",
"fancy-regex",
"flate2",
"fnv",
"once_cell",
"plist",
"regex-syntax",
"serde",
"serde_derive",
"serde_json",
"thiserror",
"walkdir",
"yaml-rust",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "time"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
dependencies = [
"deranged",
"num-conv",
"powerfmt",
"serde_core",
"time-core",
"time-macros",
]
[[package]]
name = "time-core"
version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "time-macros"
version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
dependencies = [
"num-conv",
"time-core",
]
[[package]]
name = "tokio"
version = "1.54.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
dependencies = [
"libc",
"mio",
"pin-project-lite",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tower"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
dependencies = [
"futures-core",
"futures-util",
"pin-project-lite",
"sync_wrapper",
"tokio",
"tower-layer",
"tower-service",
"tracing",
]
[[package]]
name = "tower-layer"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
[[package]]
name = "tower-service"
version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracing"
version = "0.1.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
dependencies = [
"log",
"pin-project-lite",
"tracing-core",
]
[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
"once_cell",
]
[[package]]
name = "unicase"
version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "utf8parse"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "walkdir"
version = "2.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "winapi-util"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
"windows-sys",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "yaml-rust"
version = "0.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56c1936c4cc7a1c9ab21a1ebb602eb942ba868cbd44a99cb7cdc5892335e1c85"
dependencies = [
"linked-hash-map",
]
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+15−0
@@ -0,0 +1,15 @@
[package]
name = "gitv"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = "0.8.9"
base64 = "0.23.1"
clap = { version = "4.6.9", features = ["derive"] }
html-escape = "0.3.1"
nix = { version = "0.32.0", features = ["user", "fs"] }
pulldown-cmark = { version = "0.13.6", default-features = false, features = ["html"] }
shlex = "2.0.1"
syntect = { version = "5.3.0", default-features = false, features = ["default-fancy"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net"] }
+24−0
@@ -0,0 +1,24 @@
# GITv
Private Git hosting over OpenSSH, plus a read-only web browser.
- `gitv`: the SSH forced-command handler (`serve`) and the root admin CLI (`create`, `delete`, `add-key`)
- `gitv-web`: the read-only browser (repositories, tree, blob, raw, log, commit, tags), with Markdown rendering and syntax highlighting (`src/render.rs`)
## Run locally
Set `GITV_REPOS` (and optionally `GITV_KEYS`) to point at a local tree. When `GITV_REPOS` is set, admin commands run without root.
```sh
cargo build
export GITV_REPOS=$PWD/dev/repos GITV_KEYS=$PWD/dev/authorized_keys
mkdir -p dev/repos
./target/debug/gitv create um9i demo
./target/debug/gitv-web serve --port 8080 # http://127.0.0.1:8080
```
`dev/fake-ssh` stands in for ssh, so you can push and clone through `gitv serve` without an SSH server:
```sh
GIT_SSH_COMMAND=$PWD/dev/fake-ssh git push git@x:um9i/myrepo.git main
```
+416−0
@@ -0,0 +1,416 @@
//! Read-only web browser for GITv repositories, served on localhost behind Caddy.
use std::collections::HashMap;
use std::path::PathBuf;
use axum::extract::{Path, Query};
use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Redirect, Response};
use axum::{Router, routing::get};
use clap::{Parser, Subcommand};
use html_escape::{encode_double_quoted_attribute as attr, encode_text as esc};
use gitv::render;
use gitv::{HOST, git, repos_root, valid_name};
static STYLESHEET: std::sync::LazyLock<String> = std::sync::LazyLock::new(render::stylesheet);
const PAGE: usize = 50;
const RAW_LIMIT: usize = 50 << 20;
#[derive(Parser)]
#[command(about = "Read-only web browser for GITv repositories")]
struct Cli {
#[command(subcommand)]
action: Action,
}
#[derive(Subcommand)]
enum Action {
/// Serve the browser on localhost
Serve {
#[arg(long, default_value_t = 8080)]
port: u16,
},
}
type Q = HashMap<String, String>;
enum View {
Html(String),
Raw(Vec<u8>, &'static str),
Redirect(String),
Missing,
}
impl IntoResponse for View {
fn into_response(self) -> Response {
let headers = [
(header::CONTENT_SECURITY_POLICY, "default-src 'none'; style-src 'self'; img-src 'self'; base-uri 'none'; frame-ancestors 'none'"),
(header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
(header::REFERRER_POLICY, "no-referrer"),
(header::CACHE_CONTROL, "no-store"),
];
match self {
View::Html(body) => (headers, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response(),
View::Raw(data, kind) => (headers, [(header::CONTENT_TYPE, kind)], data).into_response(),
View::Redirect(to) => Redirect::to(&to).into_response(),
View::Missing => (StatusCode::NOT_FOUND, headers, [(header::CONTENT_TYPE, "text/html; charset=utf-8")],
page("Not found", "<h1>Nothing here</h1><p>That repository, branch, file or commit doesn’t exist, \
or the link is malformed.</p><p><a href=\"/\">Back to repositories</a></p>"))
.into_response(),
}
}
}
struct Repo {
owner: String,
name: String,
path: PathBuf,
}
impl Repo {
fn open(owner: &str, name: &str) -> Option<Repo> {
if !(valid_name(owner) && valid_name(name)) {
return None;
}
let path = repos_root().join(owner).join(format!("{name}.git"));
path.join("HEAD").is_file().then(|| Repo { owner: owner.into(), name: name.into(), path })
}
fn git(&self, args: &[&str]) -> Option<String> {
git(&self.path, args).ok().map(|out| String::from_utf8_lossy(&out).into_owned())
}
fn url(&self, view: &str, query: &[(&str, &str)]) -> String {
let query: Vec<String> = query
.iter()
.filter(|(_, v)| !v.is_empty())
.map(|(k, v)| format!("{k}={}", encode(v)))
.collect();
let base = format!("/{}/{}/{view}", self.owner, self.name);
if query.is_empty() { base } else { format!("{base}?{}", query.join("&")) }
}
fn default_ref(&self) -> String {
self.git(&["symbolic-ref", "--short", "HEAD"]).map_or("HEAD".into(), |s| s.trim().into())
}
/// The commit a ref names, rejecting anything that could read as an option or range.
fn resolve(&self, reference: &str) -> Option<String> {
let ok = (1..=200).contains(&reference.len())
&& !reference.starts_with('-')
&& !reference.contains("..")
&& reference.bytes().all(|b| b.is_ascii_alphanumeric() || b"._/-".contains(&b));
if !ok {
return None;
}
let spec = format!("{reference}^{{commit}}");
self.git(&["rev-parse", "--verify", "--quiet", "--end-of-options", &spec]).map(|s| s.trim().into())
}
/// (oid, subject, author, timestamp) of the newest commit on rev.
fn latest(&self, rev: &str) -> Option<[String; 4]> {
let out = self.git(&["log", "-1", "--format=%H%x1f%s%x1f%an%x1f%ct", rev, "--"])?;
let fields: Vec<&str> = out.trim_end().split('\x1f').collect();
<[&str; 4]>::try_from(fields).ok().map(|f| f.map(String::from))
}
/// Render a Markdown file from directory `dir`, linking repository paths at `reference`.
fn markdown(&self, source: &str, dir: &str, reference: &str) -> String {
render::markdown(source, dir, &|path, image| {
if image {
self.url("raw", &[("ref", reference), ("path", path)])
} else if path.is_empty() {
self.url("tree", &[("ref", reference)])
} else {
self.url("blob", &[("ref", reference), ("path", path)])
}
})
}
fn header(&self) -> String {
let r = |v| self.url(v, &[]);
format!(
"<h1><a href=\"/\">GITv</a> / {owner} / {name}</h1>\
<p>Clone: <code>git@{HOST}:{owner}/{name}.git</code></p>\
<nav><a href=\"{}\">Code</a> · <a href=\"{}\">Commits</a> · <a href=\"{}\">Tags</a></nav><hr>",
attr(&r("tree")), attr(&r("log")), attr(&r("tags")),
owner = esc(&self.owner), name = esc(&self.name),
)
}
}
fn encode(value: &str) -> String {
value
.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => (b as char).to_string(),
_ => format!("%{b:02X}"),
})
.collect()
}
/// A repository-relative path with no `..`, empty or absolute parts.
fn clean_path(value: &str) -> Option<String> {
let parts: Vec<&str> = value.split('/').filter(|p| !p.is_empty()).collect();
if parts.iter().any(|p| *p == "." || *p == ".." || p.contains('\0')) {
return None;
}
Some(parts.join("/"))
}
fn page(title: &str, body: &str) -> String {
format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
<title>{} · GITv</title><link rel=\"stylesheet\" href=\"/style.css\"></head><body>{body}</body></html>",
esc(title)
)
}
fn view_index() -> View {
let root = repos_root();
let mut rows = Vec::new();
for owner in sorted_dir(&root) {
for entry in sorted_dir(&root.join(&owner)) {
let Some(name) = entry.strip_suffix(".git") else { continue };
let Some(repo) = Repo::open(&owner, name) else { continue };
let head = repo.latest(&repo.default_ref());
let stamp: i64 = head.as_ref().and_then(|h| h[3].parse().ok()).unwrap_or(0);
rows.push((stamp, repo, head));
}
}
rows.sort_by(|a, b| b.0.cmp(&a.0));
let items: String = rows
.iter()
.map(|(_, repo, head)| {
let last = head.as_ref().map_or("No commits yet".into(), |h| esc(&h[1]).into_owned());
format!("<li><a href=\"{}\">{}/{}</a> — {last}</li>",
attr(&repo.url("tree", &[])), esc(&repo.owner), esc(&repo.name))
})
.collect();
let listing = if items.is_empty() {
format!("<p>No repositories yet. Push to a new name and GITv creates it:</p>\
<pre>git push git@{HOST}:um9i/my-project.git main</pre>")
} else {
format!("<ul>{items}</ul>")
};
View::Html(page("Repositories", &format!("<h1>GITv repositories ({})</h1>{listing}", rows.len())))
}
fn sorted_dir(path: &std::path::Path) -> Vec<String> {
let mut names: Vec<String> = std::fs::read_dir(path)
.into_iter()
.flatten()
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| !n.starts_with('.'))
.collect();
names.sort();
names
}
fn view_tree(repo: &Repo, q: &Q) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let path = clean_path(q.get("path").map_or("", String::as_str))?;
let mut body = repo.header();
let Some(commit) = repo.resolve(&reference) else {
// An empty repository has no commits to show yet.
if repo.git(&["for-each-ref", "--count=1", "refs/heads"]).is_some_and(|s| s.trim().is_empty()) {
body += "<p>This repository is empty. Push a branch to get started.</p>";
return Some(View::Html(page(&repo.name, &body)));
}
return None;
};
let spec = format!("{commit}:{path}");
let listing = repo.git(&["ls-tree", "-z", &spec])?;
body += &format!("<p>Ref: <b>{}</b> · Path: /{}</p>", esc(&reference), esc(&path));
if !path.is_empty() {
let parent = path.rsplit_once('/').map_or("", |(p, _)| p);
body += &format!("<p><a href=\"{}\">..</a></p>", attr(&repo.url("tree", &[("ref", &reference), ("path", parent)])));
}
let mut entries: Vec<(bool, String)> = listing
.split('\0')
.filter_map(|line| {
let (meta, name) = line.split_once('\t')?;
Some((meta.split(' ').nth(1)? == "tree", name.to_string()))
})
.collect();
entries.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
body += "<ul>";
for (is_dir, name) in &entries {
let full = if path.is_empty() { name.clone() } else { format!("{path}/{name}") };
let view = if *is_dir { "tree" } else { "blob" };
let href = repo.url(view, &[("ref", &reference), ("path", &full)]);
body += &format!("<li><a href=\"{}\">{}{}</a></li>", attr(&href), esc(name), if *is_dir { "/" } else { "" });
}
body += "</ul>";
let readme = entries.iter().find(|(d, n)| !d && n.to_ascii_lowercase().starts_with("readme"));
if let Some((_, readme)) = readme {
let full = if path.is_empty() { readme.clone() } else { format!("{path}/{readme}") };
if let Some(text) = repo.git(&["cat-file", "blob", &format!("{commit}:{full}")]) {
body += &format!("<h2>{}</h2>", esc(readme));
body += &if render::is_markdown(readme) {
format!("<article class=\"markdown\">{}</article>", repo.markdown(&text, &path, &reference))
} else {
format!("<pre class=\"code\">{}</pre>", render::highlight(readme, &text))
};
}
}
Some(View::Html(page(&repo.name, &body)))
}
fn view_blob(repo: &Repo, q: &Q, raw: bool) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let path = clean_path(q.get("path")?)?;
let commit = repo.resolve(&reference)?;
let spec = format!("{commit}:{path}");
// Markdown links can't tell files from directories, so a blob link to a directory lands here.
if repo.git(&["cat-file", "-t", &spec]).is_some_and(|t| t.trim() == "tree") {
return Some(View::Redirect(repo.url("tree", &[("ref", &reference), ("path", &path)])));
}
let data = git(&repo.path, &["cat-file", "blob", &spec]).ok()?;
let binary = data.iter().take(8000).any(|b| *b == 0);
if raw {
let kind = match path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).as_deref() {
Some("png") => "image/png",
Some("jpg" | "jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("webp") => "image/webp",
_ if binary => "application/octet-stream",
_ => "text/plain; charset=utf-8",
};
return Some(View::Raw(data.into_iter().take(RAW_LIMIT).collect(), kind));
}
let as_code = q.get("view").is_some_and(|v| v == "code");
let parent = path.rsplit_once('/').map_or("", |(p, _)| p);
let mut body = repo.header();
body += &format!(
"<p>Ref: <b>{}</b> · <a href=\"{}\">{}/</a>{} · {} bytes · <a href=\"{}\">raw</a></p>",
esc(&reference),
attr(&repo.url("tree", &[("ref", &reference), ("path", parent)])),
esc(parent),
esc(path.rsplit('/').next().unwrap_or(&path)),
data.len(),
attr(&repo.url("raw", &[("ref", &reference), ("path", &path)])),
);
let text = String::from_utf8_lossy(&data);
if binary {
body += "<p>Binary file not shown.</p>";
} else if render::is_markdown(&path) {
let toggle = |label: &str, view: &str| {
format!("<a href=\"{}\">{label}</a>", attr(&repo.url("blob", &[("ref", &reference), ("path", &path), ("view", view)])))
};
if as_code {
body += &format!("<p>{} · <b>Code</b></p><pre class=\"code\">{}</pre>",
toggle("Preview", ""), render::highlight(&path, &text));
} else {
body += &format!("<p><b>Preview</b> · {}</p><article class=\"markdown\">{}</article>",
toggle("Code", "code"), repo.markdown(&text, parent, &reference));
}
} else {
body += &format!("<pre class=\"code\">{}</pre>", render::highlight(&path, &text));
}
Some(View::Html(page(&path, &body)))
}
fn view_log(repo: &Repo, q: &Q) -> Option<View> {
let reference = q.get("ref").cloned().unwrap_or_else(|| repo.default_ref());
let number: usize = q.get("page").and_then(|p| p.parse().ok()).unwrap_or(0);
let commit = repo.resolve(&reference)?;
let out = repo.git(&[
"log", &format!("-n{}", PAGE + 1), &format!("--skip={}", number * PAGE),
"--format=%H%x1f%h%x1f%s%x1f%an%x1f%ad", "--date=short", &commit, "--",
])?;
let lines: Vec<&str> = out.lines().collect();
let mut body = repo.header() + &format!("<h2>Commits on {}</h2><ul>", esc(&reference));
for line in lines.iter().take(PAGE) {
let f: Vec<&str> = line.split('\x1f').collect();
if f.len() != 5 {
continue;
}
body += &format!("<li><a href=\"{}\"><code>{}</code></a> {} — {} on {}</li>",
attr(&repo.url("commit", &[("id", f[0])])), f[1], esc(f[2]), esc(f[3]), esc(f[4]));
}
body += "</ul><p>";
let page_str = |n: usize| n.to_string();
if number > 0 {
body += &format!("<a href=\"{}\">Newer</a> ", attr(&repo.url("log", &[("ref", &reference), ("page", &page_str(number - 1))])));
}
if lines.len() > PAGE {
body += &format!("<a href=\"{}\">Older</a>", attr(&repo.url("log", &[("ref", &reference), ("page", &page_str(number + 1))])));
}
body += "</p>";
Some(View::Html(page(&format!("Commits · {}", repo.name), &body)))
}
fn view_commit(repo: &Repo, q: &Q) -> Option<View> {
let id = q.get("id")?;
if !(4..=64).contains(&id.len()) || !id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
return None;
}
let commit = repo.resolve(id)?;
let show = repo.git(&["show", "--no-color", "--format=commit %H%nAuthor: %an <%ae>%nDate: %aD%n%n%B", "--patch", "--stat", &commit])?;
let body = repo.header() + &format!("<pre class=\"code\">{}</pre>", render::highlight("commit.diff", &show));
Some(View::Html(page(&format!("Commit {}", &commit[..12]), &body)))
}
fn view_tags(repo: &Repo) -> Option<View> {
let out = repo.git(&["for-each-ref", "--sort=-creatordate",
"--format=%(refname:short)%1f%(creatordate:short)%1f%(contents:subject)", "refs/tags"])?;
let mut body = repo.header() + "<h2>Tags</h2><ul>";
let mut count = 0;
for line in out.lines() {
let f: Vec<&str> = line.split('\x1f').collect();
if f.len() != 3 {
continue;
}
count += 1;
body += &format!("<li><a href=\"{}\">{}</a> {} {}</li>",
attr(&repo.url("tree", &[("ref", f[0])])), esc(f[0]), esc(f[1]), esc(f[2]));
}
if count == 0 {
body += "<li>No tags yet.</li>";
}
body += "</ul>";
Some(View::Html(page(&format!("Tags · {}", repo.name), &body)))
}
fn route(owner: &str, name: &str, view: Option<&str>, q: &Q) -> View {
let Some(repo) = Repo::open(owner, name) else { return View::Missing };
let result = match view {
None => Some(View::Redirect(repo.url("tree", &[]))),
Some("tree") => view_tree(&repo, q),
Some("blob") => view_blob(&repo, q, false),
Some("raw") => view_blob(&repo, q, true),
Some("log") => view_log(&repo, q),
Some("commit") => view_commit(&repo, q),
Some("tags") => view_tags(&repo),
Some(_) => None,
};
result.unwrap_or(View::Missing)
}
/// Git calls block, so every page renders on the blocking pool.
async fn blocking(f: impl FnOnce() -> View + Send + 'static) -> View {
tokio::task::spawn_blocking(f).await.unwrap_or(View::Missing)
}
#[tokio::main]
async fn main() {
let Action::Serve { port } = Cli::parse().action;
let app = Router::new()
.route("/", get(|| blocking(view_index)))
.route("/style.css", get(|| async {
([(header::CONTENT_TYPE, "text/css; charset=utf-8"), (header::CACHE_CONTROL, "max-age=3600")],
STYLESHEET.as_str())
}))
.route("/{owner}/{name}", get(|Path((o, n)): Path<(String, String)>, Query(q): Query<Q>|
blocking(move || route(&o, &n, None, &q))))
.route("/{owner}/{name}/{view}", get(|Path((o, n, v)): Path<(String, String, String)>, Query(q): Query<Q>|
blocking(move || route(&o, &n, Some(&v), &q))))
.fallback(|| async { View::Missing });
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.expect("bind port");
println!("gitv-web listening on http://127.0.0.1:{port} (repos: {})", repos_root().display());
axum::serve(listener, app).await.expect("server");
}
+292−0
@@ -0,0 +1,292 @@
//! Private Git hosting over OpenSSH and Git's native pack protocol.
use std::fs;
use std::io::Write;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitCode, Stdio};
use base64::Engine;
use clap::{Parser, Subcommand};
use gitv::{HOST, NAME_RULE, git, git_command, keys_path, repos_root, valid_name};
const HELP: &str = "Commands for your key, run as: ssh git@git.um9i.dev <command>
list list your repositories
create <name> create an empty repository
delete <name> --yes delete a repository permanently
Pushing to a repository that does not exist yet creates it.";
#[derive(Parser)]
#[command(about = "Private Git hosting over OpenSSH and Git's native pack protocol")]
struct Cli {
#[command(subcommand)]
action: Action,
}
#[derive(Subcommand)]
enum Action {
/// Create an empty repository (root)
Create { #[arg(value_parser = name)] owner: String, #[arg(value_parser = name)] name: String },
/// Delete a repository permanently (root)
Delete {
#[arg(value_parser = name)] owner: String,
#[arg(value_parser = name)] name: String,
/// Confirm permanent deletion
#[arg(long)] yes: bool,
},
/// Register an Ed25519 public key for an owner (root)
AddKey { #[arg(value_parser = name)] owner: String, public_key: PathBuf },
/// Handle one SSH request (forced command from authorized_keys)
Serve { #[arg(value_parser = name)] owner: String },
}
fn name(value: &str) -> Result<String, String> {
if valid_name(value) { Ok(value.to_string()) } else { Err(NAME_RULE.into()) }
}
fn check_name(value: &str) -> Result<&str, String> {
if valid_name(value) { Ok(value) } else { Err(NAME_RULE.into()) }
}
fn repo_path(owner: &str, name: &str) -> PathBuf {
repos_root().join(owner).join(format!("{name}.git"))
}
fn is_root() -> bool {
nix::unistd::geteuid().is_root()
}
/// Hand a path to the `git` account when running as root, so keys can manage it later.
fn chown_git(path: &Path) -> Result<(), String> {
if !is_root() {
return Ok(());
}
let user = nix::unistd::User::from_name("git")
.map_err(|e| e.to_string())?
.ok_or("no git account")?;
nix::unistd::chown(path, Some(user.uid), Some(user.gid)).map_err(|e| e.to_string())
}
fn owner_directory(owner: &str) -> Result<PathBuf, String> {
let directory = repos_root().join(owner);
fs::create_dir_all(&directory).map_err(|e| e.to_string())?;
chown_git(&directory)?;
Ok(directory)
}
fn create(owner: &str, name: &str, quiet: bool) -> Result<(), String> {
let directory = owner_directory(owner)?;
let repo = directory.join(format!("{name}.git"));
if repo.exists() {
return Err("repository already exists".into());
}
// Build in a hidden staging name, then rename, so a half-made repository never serves.
let staging = directory.join(format!(".create-{}-{name}", std::process::id()));
let status = Command::new("git")
.args(["init", "--quiet", "--bare", "--initial-branch=main"])
.arg(&staging)
.status()
.map_err(|e| e.to_string())?;
if !status.success() {
let _ = fs::remove_dir_all(&staging);
return Err("git init failed".into());
}
fs::set_permissions(&staging, fs::Permissions::from_mode(0o750)).map_err(|e| e.to_string())?;
if is_root() {
for entry in walk(&staging) {
chown_git(&entry)?;
}
}
if repo.exists() {
let _ = fs::remove_dir_all(&staging);
return Err("repository already exists".into());
}
fs::rename(&staging, &repo).map_err(|e| e.to_string())?;
if !quiet {
println!("git@{HOST}:{owner}/{name}.git");
}
Ok(())
}
fn walk(root: &Path) -> Vec<PathBuf> {
let mut found = vec![root.to_path_buf()];
if let Ok(entries) = fs::read_dir(root) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() && !path.is_symlink() {
found.extend(walk(&path));
} else {
found.push(path);
}
}
}
found
}
fn delete(owner: &str, name: &str) -> Result<(), String> {
let directory = repos_root().join(owner);
let repo = directory.join(format!("{name}.git"));
if !(repo.is_dir() && !repo.is_symlink() && repo.join("HEAD").is_file()) {
return Err("repository unavailable".into());
}
// A hidden name stops the repository serving at once, before the slow removal.
let staging = directory.join(format!(".delete-{}-{name}", std::process::id()));
fs::rename(&repo, &staging).map_err(|e| e.to_string())?;
fs::remove_dir_all(&staging).map_err(|e| e.to_string())?;
println!("deleted {owner}/{name}.git");
Ok(())
}
fn add_key(owner: &str, file: &Path) -> Result<(), String> {
let text = fs::read_to_string(file).map_err(|e| e.to_string())?;
let parts: Vec<&str> = text.split_whitespace().collect();
if parts.len() < 2 || parts[0] != "ssh-ed25519" {
return Err("expected an OpenSSH Ed25519 public key".into());
}
let engine = base64::engine::general_purpose::STANDARD;
let blob = engine.decode(parts[1]).map_err(|_| "invalid Ed25519 public key")?;
let mut header = 11u32.to_be_bytes().to_vec();
header.extend_from_slice(b"ssh-ed25519");
header.extend_from_slice(&32u32.to_be_bytes());
if blob.len() != 51 || blob[..19] != header[..] {
return Err("invalid Ed25519 public key".into());
}
let token = engine.encode(&blob);
let keys = keys_path();
let old = fs::read_to_string(&keys).unwrap_or_default();
if old.lines().any(|row| row.split_whitespace().last() == Some(token.as_str())) {
return Err("key already registered".into());
}
let line = format!("restrict,command=\"/usr/local/bin/gitv serve {owner}\" ssh-ed25519 {token}\n");
let temporary = keys.with_extension("tmp");
let mut out = fs::File::create(&temporary).map_err(|e| e.to_string())?;
out.write_all(format!("{old}{line}").as_bytes()).map_err(|e| e.to_string())?;
out.set_permissions(fs::Permissions::from_mode(0o644)).map_err(|e| e.to_string())?;
fs::rename(&temporary, &keys).map_err(|e| e.to_string())?;
owner_directory(owner)?;
Ok(())
}
/// Handle one SSH request from a key registered to owner.
fn serve(owner: &str, command: &str) -> Result<u8, String> {
let args = shlex::split(command).ok_or("unreadable command; run: ssh git@git.um9i.dev help")?;
let args: Vec<&str> = args.iter().map(String::as_str).collect();
match args.as_slice() {
[] | ["help"] => println!("{HELP}"),
[program @ ("git-upload-pack" | "git-receive-pack"), path] => return serve_git(owner, program, path),
["list"] => {
let mut names: Vec<String> = fs::read_dir(repos_root().join(owner))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| e.file_name().to_str()?.strip_suffix(".git").map(str::to_string))
.filter(|n| valid_name(n))
.collect();
names.sort();
for name in names {
println!("git@{HOST}:{owner}/{name}.git");
}
}
["create", name] => create(owner, check_name(name)?, false)?,
["delete", name, rest @ ..] => {
let name = check_name(name)?;
if rest != ["--yes"] {
return Err(format!("deleting {owner}/{name}.git is permanent; run: delete {name} --yes"));
}
delete(owner, name)?;
}
_ => return Err("unknown command; run: ssh git@git.um9i.dev help".into()),
}
Ok(0)
}
/// Parse `owner/name.git` (optionally with leading or trailing slash).
fn parse_request(path: &str) -> Option<(&str, &str)> {
let path = path.strip_prefix('/').unwrap_or(path);
let path = path.strip_suffix('/').unwrap_or(path);
let (owner, rest) = path.split_once('/')?;
let name = rest.strip_suffix(".git")?;
(valid_name(owner) && valid_name(name)).then_some((owner, name))
}
fn serve_git(owner: &str, program: &str, path: &str) -> Result<u8, String> {
let (requested, name) = parse_request(path).ok_or("repository unavailable")?;
if requested != owner {
return Err("repository unavailable".into());
}
let repo = repo_path(owner, name);
if !repo.is_dir() {
if program != "git-receive-pack" {
return Err("repository unavailable".into());
}
// Pushing to a new name creates it, so a fresh project needs no setup step.
create(owner, name, true)?;
eprintln!("gitv: created {owner}/{name}.git");
}
let status = Command::new(program)
.arg(&repo)
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("HOME", "/var/empty")
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.status()
.map_err(|e| e.to_string())?;
if program == "git-receive-pack" && status.success() {
fix_head(&repo)?;
}
Ok(status.code().unwrap_or(1) as u8)
}
/// Point HEAD at a pushed branch when its current target does not exist.
fn fix_head(repo: &Path) -> Result<(), String> {
if git(repo, &["rev-parse", "--verify", "--quiet", "HEAD"]).is_ok() {
return Ok(());
}
let out = git(repo, &["for-each-ref", "--format=%(refname)", "refs/heads"])?;
let heads: Vec<String> = String::from_utf8_lossy(&out).split_whitespace().map(str::to_string).collect();
let Some(first) = heads.first() else { return Ok(()) };
let choice = ["refs/heads/main", "refs/heads/master"]
.into_iter()
.find(|r| heads.iter().any(|h| h == r))
.unwrap_or(first);
let status = git_command(repo).args(["symbolic-ref", "HEAD", choice]).status().map_err(|e| e.to_string())?;
if !status.success() {
return Err("could not set the default branch".into());
}
eprintln!("gitv: default branch is now {}", choice.trim_start_matches("refs/heads/"));
Ok(())
}
fn run() -> Result<u8, String> {
let cli = Cli::parse();
if let Action::Serve { owner } = &cli.action {
return serve(owner, &std::env::var("SSH_ORIGINAL_COMMAND").unwrap_or_default());
}
// Locally (GITV_REPOS set) administration runs as yourself.
if !is_root() && !gitv::is_local() {
return Err("run repository and key administration as root".into());
}
match cli.action {
Action::Create { owner, name } => create(&owner, &name, false)?,
Action::Delete { owner, name, yes } => {
if !yes {
return Err(format!("deleting {owner}/{name}.git is permanent; pass --yes to confirm"));
}
delete(&owner, &name)?;
}
Action::AddKey { owner, public_key } => add_key(&owner, &public_key)?,
Action::Serve { .. } => unreachable!(),
}
Ok(0)
}
fn main() -> ExitCode {
match run() {
Ok(code) => ExitCode::from(code),
Err(error) => {
eprintln!("gitv: {error}");
ExitCode::FAILURE
}
}
}
+60−0
@@ -0,0 +1,60 @@
//! Shared pieces of GITv: configuration, name rules and read-only git access.
pub mod render;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub const HOST: &str = "git.um9i.dev";
/// Where bare repositories live: `<root>/<owner>/<name>.git`. `GITV_REPOS` overrides it for local runs.
pub fn repos_root() -> PathBuf {
std::env::var_os("GITV_REPOS").map_or_else(|| PathBuf::from("/srv/gitv/repos"), PathBuf::from)
}
/// The OpenSSH authorized_keys file that maps each key to an owner. `GITV_KEYS` overrides it.
pub fn keys_path() -> PathBuf {
std::env::var_os("GITV_KEYS").map_or_else(|| PathBuf::from("/etc/gitv/authorized_keys"), PathBuf::from)
}
/// True when running against a local tree instead of the server's real paths.
pub fn is_local() -> bool {
std::env::var_os("GITV_REPOS").is_some()
}
/// Owner and repository names: 1–63 of `[a-z0-9_-]`, starting with a letter or digit.
pub fn valid_name(value: &str) -> bool {
let bytes = value.as_bytes();
(1..=63).contains(&bytes.len())
&& (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
&& bytes.iter().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'_' || *b == b'-')
}
pub const NAME_RULE: &str = "use 1–63 lowercase letters, digits, hyphens or underscores";
/// A minimal environment for git so the server's user config never leaks in.
pub fn git_command(git_dir: &Path) -> Command {
let mut command = Command::new("git");
command
.env_clear()
.env("PATH", "/usr/bin:/bin")
.env("HOME", "/var/empty")
.env("GIT_CONFIG_NOSYSTEM", "1")
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("LC_ALL", "C.UTF-8")
.args(["-c", "safe.directory=*", "-c", "core.quotePath=false", "--git-dir"])
.arg(git_dir)
.stdin(Stdio::null());
command
}
/// Run a read-only git command and return stdout, or git's error message.
pub fn git(git_dir: &Path, args: &[&str]) -> Result<Vec<u8>, String> {
let output = git_command(git_dir).args(args).output().map_err(|e| format!("cannot run git: {e}"))?;
if output.status.success() {
Ok(output.stdout)
} else {
let message = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(if message.is_empty() { "git failed".into() } else { message })
}
}
+207−0
@@ -0,0 +1,207 @@
//! Syntax highlighting and Markdown rendering for the web browser.
//!
//! Highlighting emits CSS classes rather than inline styles, so the page's
//! `style-src 'self'` policy holds; [`stylesheet`] supplies the colours.
use std::sync::LazyLock;
use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd};
use syntect::highlighting::ThemeSet;
use syntect::html::{ClassStyle, ClassedHTMLGenerator, css_for_theme_with_class_style};
use syntect::parsing::{SyntaxReference, SyntaxSet};
use syntect::util::LinesWithEndings;
/// Files larger than this are shown as plain escaped text.
pub const HIGHLIGHT_LIMIT: usize = 512 << 10;
const CLASSES: ClassStyle = ClassStyle::SpacedPrefixed { prefix: "hl-" };
static SYNTAXES: LazyLock<SyntaxSet> = LazyLock::new(SyntaxSet::load_defaults_newlines);
/// Highlighting colours for light and dark schemes.
pub fn stylesheet() -> String {
let themes = ThemeSet::load_defaults();
let light = css_for_theme_with_class_style(&themes.themes["InspiredGitHub"], CLASSES).unwrap_or_default();
let dark = css_for_theme_with_class_style(&themes.themes["base16-ocean.dark"], CLASSES).unwrap_or_default();
format!(
":root{{color-scheme:light dark}}\n{light}\n@media (prefers-color-scheme:dark){{\n{dark}\n}}\n\
pre.code{{padding:8px 12px;overflow:auto}}\n\
.markdown table{{border-collapse:collapse}}\n\
.markdown th,.markdown td{{border:1px solid #8884;padding:4px 8px}}\n\
.markdown img{{max-width:100%}}\n"
)
}
/// The syntax for a file, by extension, whole file name, then shebang or modeline.
fn syntax_for(path: &str, first_line: &str) -> Option<&'static SyntaxReference> {
let file = path.rsplit('/').next().unwrap_or(path);
let ext = file.rsplit_once('.').map_or(file, |(_, ext)| ext);
SYNTAXES
.find_syntax_by_extension(ext)
.or_else(|| SYNTAXES.find_syntax_by_extension(file))
.or_else(|| SYNTAXES.find_syntax_by_first_line(first_line))
}
/// The syntax named by a Markdown fence such as ```rust or ```py.
fn syntax_for_fence(lang: &str) -> Option<&'static SyntaxReference> {
let lang = lang.split([',', ' ', '{']).next().unwrap_or("").trim();
if lang.is_empty() {
return None;
}
SYNTAXES.find_syntax_by_token(lang)
}
fn highlight_with(code: &str, syntax: Option<&'static SyntaxReference>) -> String {
let Some(syntax) = syntax.filter(|_| code.len() <= HIGHLIGHT_LIMIT) else {
return html_escape::encode_text(code).into_owned();
};
let mut generator = ClassedHTMLGenerator::new_with_class_style(syntax, &SYNTAXES, CLASSES);
for line in LinesWithEndings::from(code) {
if generator.parse_html_for_line_which_includes_newline(line).is_err() {
return html_escape::encode_text(code).into_owned();
}
}
generator.finalize()
}
/// A file's contents as highlighted HTML, ready to go inside `<pre>`.
pub fn highlight(path: &str, code: &str) -> String {
highlight_with(code, syntax_for(path, code.lines().next().unwrap_or("")))
}
/// True for files the browser renders as Markdown by default.
pub fn is_markdown(path: &str) -> bool {
let lower = path.to_ascii_lowercase();
[".md", ".markdown", ".mdown", ".mkd"].iter().any(|ext| lower.ends_with(ext))
}
/// Where a link or image in a Markdown file points.
pub enum Target {
/// Kept as written: web, mail and in-page links.
External(String),
/// A repository path, already normalised against the Markdown file's directory.
Repo(String),
/// Anything else (other schemes, paths escaping the repository): dropped.
Blocked,
}
/// Resolve a link written in a Markdown file that lives in `dir`.
pub fn resolve_link(dir: &str, target: &str) -> Target {
let lower = target.to_ascii_lowercase();
if lower.starts_with("http://") || lower.starts_with("https://") || lower.starts_with("mailto:") || target.starts_with('#') {
return Target::External(target.to_string());
}
let path = target.split(['#', '?']).next().unwrap_or("");
// A colon before any slash means a scheme (javascript:, data:, ...).
if path.split('/').next().is_some_and(|first| first.contains(':')) {
return Target::Blocked;
}
let mut parts: Vec<&str> = if path.starts_with('/') { Vec::new() } else { dir.split('/').filter(|p| !p.is_empty()).collect() };
for part in path.split('/') {
match part {
"" | "." => {}
".." => {
if parts.pop().is_none() {
return Target::Blocked;
}
}
part => parts.push(part),
}
}
Target::Repo(parts.join("/"))
}
/// Render Markdown to HTML. Raw HTML in the source is escaped, fenced code is highlighted, and
/// `link(path, is_image)` turns repository paths into URLs.
pub fn markdown(source: &str, dir: &str, link: &dyn Fn(&str, bool) -> String) -> String {
let options = Options::ENABLE_TABLES
| Options::ENABLE_STRIKETHROUGH
| Options::ENABLE_TASKLISTS
| Options::ENABLE_FOOTNOTES
| Options::ENABLE_HEADING_ATTRIBUTES;
let rewrite = |dest: CowStr<'_>, image: bool| -> CowStr<'static> {
match resolve_link(dir, &dest) {
Target::External(url) => url.into(),
Target::Repo(path) => link(&path, image).into(),
Target::Blocked => "#".into(),
}
};
let mut events = Vec::new();
let mut fence: Option<(Option<&'static SyntaxReference>, String)> = None;
for event in Parser::new_ext(source, options) {
if let Some((_, code)) = fence.as_mut() {
match event {
Event::Text(text) => code.push_str(&text),
Event::End(TagEnd::CodeBlock) => {
let (syntax, code) = fence.take().unwrap_or_default();
events.push(Event::Html(format!("<pre class=\"code\">{}</pre>\n", highlight_with(&code, syntax)).into()));
}
_ => {}
}
continue;
}
events.push(match event {
Event::Start(Tag::CodeBlock(kind)) => {
let syntax = match kind {
CodeBlockKind::Fenced(lang) => syntax_for_fence(&lang),
CodeBlockKind::Indented => None,
};
fence = Some((syntax, String::new()));
continue;
}
// Never pass the file's own HTML through: show it as text instead.
Event::Html(raw) | Event::InlineHtml(raw) => Event::Text(raw),
Event::Start(Tag::Link { link_type, dest_url, title, id }) => {
Event::Start(Tag::Link { link_type, dest_url: rewrite(dest_url, false), title, id })
}
Event::Start(Tag::Image { link_type, dest_url, title, id }) => {
Event::Start(Tag::Image { link_type, dest_url: rewrite(dest_url, true), title, id })
}
other => other,
});
}
let mut out = String::new();
pulldown_cmark::html::push_html(&mut out, events.into_iter());
out
}
#[cfg(test)]
mod tests {
use super::*;
fn link(path: &str, image: bool) -> String {
format!("/{}?path={path}", if image { "raw" } else { "blob" })
}
#[test]
fn escapes_raw_html() {
let html = markdown("hi <script>alert(1)</script>\n\n<div onclick=x>", "", &link);
assert!(!html.contains("<script"), "{html}");
assert!(!html.contains("<div"), "{html}");
}
#[test]
fn blocks_dangerous_links() {
let html = markdown("[x](javascript:alert(1)) [y](../../etc/passwd)", "docs", &link);
assert!(!html.contains("javascript:"), "{html}");
assert!(!html.contains("passwd"), "{html}");
}
#[test]
fn rewrites_relative_links_and_images() {
let html = markdown("[a](guide.md#top) [b](/src/lib.rs) ![c](../img/logo.png) [d](https://x.dev)", "docs", &link);
assert!(html.contains("href=\"/blob?path=docs/guide.md\""), "{html}");
assert!(html.contains("href=\"/blob?path=src/lib.rs\""), "{html}");
assert!(html.contains("src=\"/raw?path=img/logo.png\""), "{html}");
assert!(html.contains("href=\"https://x.dev\""), "{html}");
}
#[test]
fn highlights_fenced_code_and_files() {
let html = markdown("```rust\nfn main() {}\n```", "", &link);
assert!(html.contains("<pre class=\"code\">") && html.contains("hl-"), "{html}");
assert!(highlight("x.py", "def f(): pass\n").contains("hl-"));
assert!(highlight("run", "#!/bin/sh\necho hi\n").contains("hl-"));
assert_eq!(highlight("notes.unknownext", "<b>"), "&lt;b&gt;");
}
}