navid/veinsforge / commit

339ac252df9a

Navid M <navidmomtahen@gmail.com> · 2026-11-26

Browse files at this commit · Download source

all: init
--- /dev/null+++ b/.gitignore@@ -0,0 +1,3 @@+/data/+/veinsforge+*.test--- /dev/null+++ b/DEPLOY.md@@ -0,0 +1,175 @@+# Deploying veinsforge++veinsforge is a single Go binary plus the `vn` binary. It supervises its own+`vn serve` process for the native protocol, manages SQLite migrations, and+writes `.veins/access` policies from database permissions.++## 1. Build++```sh+cd frontend+CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o veinsforge ./cmd/veinsforge+```++`modernc.org/sqlite` is pure Go, so the service builds without CGO. Put the+built binary and a recent `vn` binary on the server:++```sh+install -m 0755 veinsforge /usr/local/bin/veinsforge+install -m 0755 vn /usr/local/bin/vn+```++## 2. Service account and directories++```sh+useradd --system --home-dir /var/lib/veinsforge --shell /usr/sbin/nologin veinsforge+install -d -o veinsforge -g veinsforge -m 0700 /var/lib/veinsforge /etc/veinsforge+install -m 0644 deploy/veinsforge.service /etc/systemd/system/veinsforge.service+install -m 0600 deploy/veinsforge.env.example /etc/veinsforge/veinsforge.env+```++Edit `/etc/veinsforge/veinsforge.env`. A typical IONOS setup behind Caddy:++```ini+VEINSFORGE_ADDR=127.0.0.1:8080+VEINSFORGE_DATA=/var/lib/veinsforge+VEINSFORGE_BASE_URL=https://forge.example.com+VEINSFORGE_VN_BIN=/usr/local/bin/vn+VEINSFORGE_NATIVE_LISTEN=0.0.0.0:7419+VEINSFORGE_NATIVE_HOST=forge.example.com+VEINSFORGE_TRUSTED_PROXIES=127.0.0.1/32,::1/128+```++`VEINSFORGE_NATIVE_LISTEN=127.0.0.1:7419` (the default) keeps the native+protocol local-only. Set it to `0.0.0.0:7419` only when you actually want+clients outside the machine to clone and push.++## 3. Create the first administrator++Do this before exposing the web port. The first signup also becomes an+administrator, so on a fresh public host an unauthenticated visitor could take+that role.++```sh+sudo -u veinsforge /usr/local/bin/veinsforge create-admin \+  -data /var/lib/veinsforge \+  -username admin \+  -password 'use-a-long-random-password'+```++Alternatively set `VEINSFORGE_ADMIN_USER` and `VEINSFORGE_ADMIN_PASSWORD` in+the environment file for the first start. After the account exists, remove the+password from the environment file.++## 4. TLS in front of the web UI++Use Caddy (or nginx) for public HTTPS. Caddy obtains and renews certificates+automatically:++```caddyfile+forge.example.com {+	encode zstd gzip+	header {+		Strict-Transport-Security "max-age=31536000; includeSubDomains"+		X-Content-Type-Options "nosniff"+	}+	reverse_proxy 127.0.0.1:8080+}+```++Set `VEINSFORGE_BASE_URL=https://forge.example.com`. The app then marks session+and CSRF cookies `Secure` and trusts `X-Forwarded-For` only from the proxies+listed in `VEINSFORGE_TRUSTED_PROXIES`.++## 5. Native protocol TLS++On first start, if `VEINSFORGE_NATIVE_CERT` / `VEINSFORGE_NATIVE_KEY` do not+exist, the service generates a self-signed certificate in+`$VEINSFORGE_DATA/native/` and prints its SHA-256 pin. The repository page shows+the pin; clients can clone with:++```sh+vn clone veins://forge.example.com:7419/owner/repo -key:your-key -pin:<pin>+```++If you already have a publicly trusted certificate, point+`VEINSFORGE_NATIVE_CERT` and `VEINSFORGE_NATIVE_KEY` at it. Clients can then+omit `-pin`. Restart the service after changing certificates.++The native server authenticates every push with the Ed25519 keys registered in+the web UI. Public repositories also allow anonymous read. Private repositories+only include keys for users/teams with access.++## 6. Firewall and basic DDoS posture++The web application has per-IP token buckets, auth/write-specific limits,+concurrent-request caps, connection limits, body limits, and HTTP timeouts.+That is not a substitute for a network firewall or a provider-level DDoS+filter.++Example nftables policy for a VPS (adjust the interface name):++```nft+table inet filter {+	chain input {+		type filter hook input priority 0; policy drop;+		ct state established,related accept+		iif lo accept+		ip protocol icmp accept+		ip6 nexthdr icmpv6 accept+		tcp dport 22 accept+		tcp dport { 80, 443 } accept+		# Native veins protocol. Rate-limit new connections.+		tcp dport 7419 ct state new limit rate 20/second burst 40 packets accept+		tcp dport 7419 ct state new drop+	}+}+```++Keep SSH behind key authentication. Consider `fail2ban` on repeated+`429`/`403` responses and on `vn serve` authentication failures, and keep the+host and `vn` binary patched.++## 7. systemd++```sh+systemctl daemon-reload+systemctl enable --now veinsforge+journalctl -u veinsforge -f+```++The unit uses `ProtectSystem=strict`; the only writable path is+`/var/lib/veinsforge`, which contains:++- `veinsforge.db` — SQLite (WAL mode)+- `repos/` — served veins repositories+- `cache/browse/` — disposable read-only checkouts+- `attachments/`, `avatars/` — filesystem assets+- `home/` — the service Ed25519 key used for cache/merge operations+- `native/` — generated native TLS certificate/key and pin++## 8. Backups++Back up SQLite with the online backup command, then copy object storage and+filesystem assets:++```sh+sqlite3 /var/lib/veinsforge/veinsforge.db \+  ".backup '/var/backups/veinsforge-$(date +%F).db'"+tar -C /var/lib/veinsforge -czf /var/backups/veinsforge-data-$(date +%F).tar.gz \+  repos attachments avatars home native+```++The browse cache is disposable and should not be backed up. Test restores on a+separate host before relying on them.++## 9. Operational notes++- Registration is open by default after the first administrator exists. An+  administrator can close it in **Admin → Site settings**.+- Access files are regenerated from SQLite periodically and after permission or+  key changes. Do not edit `.veins/access` by hand on a served repository.+- The app runs one `vn serve` supervisor process. Do not start a second native+  server on the same port.+- SQLite uses WAL with a 5 second busy timeout. Keep the data directory on local+  disk, not a network filesystem.--- /dev/null+++ b/cmd/veinsforge/main.go@@ -0,0 +1,307 @@+package main++import (+	"context"+	"errors"+	"flag"+	"fmt"+	"io"+	"log"+	"net"+	"net/http"+	"os"+	"os/signal"+	"path/filepath"+	"sync"+	"syscall"+	"time"++	"veinsforge/internal/auth"+	"veinsforge/internal/config"+	"veinsforge/internal/data"+	"veinsforge/internal/vn"+	"veinsforge/internal/web"+)++const version = "0.1.0"++func main() {+	log.SetFlags(log.LstdFlags | log.LUTC)+	if len(os.Args) < 2 {+		runServer(nil)+		return+	}+	switch os.Args[1] {+	case "serve":+		runServer(os.Args[2:])+	case "create-admin":+		createAdmin(os.Args[2:])+	case "version", "-version", "--version":+		fmt.Println("veinsforge", version)+	case "help", "-h", "--help":+		usage()+	default:+		fmt.Fprintf(os.Stderr, "unknown command: %s\n", os.Args[1])+		usage()+		os.Exit(2)+	}+}++func usage() {+	fmt.Print(`veinsforge - a forge for veins repositories++usage:+  veinsforge serve [flags]+  veinsforge create-admin -username <name> -password <password>+  veinsforge version++environment:+  VEINSFORGE_ADDR, VEINSFORGE_DATA, VEINSFORGE_BASE_URL, VEINSFORGE_VN_BIN,+  VEINSFORGE_NATIVE_LISTEN, VEINSFORGE_NATIVE_HOST, VEINSFORGE_NATIVE_CERT,+  VEINSFORGE_NATIVE_KEY, VEINSFORGE_TRUSTED_PROXIES, VEINSFORGE_ADMIN_USER,+  VEINSFORGE_ADMIN_PASSWORD+`)+}++func serveFlags(args []string) (config.Config, error) {+	fs := flag.NewFlagSet("serve", flag.ContinueOnError)+	fs.SetOutput(os.Stderr)+	addr := fs.String("addr", "", "HTTP listen address")+	dataDir := fs.String("data", "", "data directory")+	baseURL := fs.String("base-url", "", "public base URL")+	vnBin := fs.String("vn-bin", "", "path to the vn binary")+	nativeListen := fs.String("native-listen", "", "native protocol listen address (empty or off disables it)")+	nativeHost := fs.String("native-host", "", "advertised native protocol host")+	nativeCert := fs.String("native-cert", "", "native TLS certificate")+	nativeKey := fs.String("native-key", "", "native TLS key")+	if err := fs.Parse(args); err != nil {+		return config.Config{}, err+	}+	return config.Load(map[string]string{+		"addr": *addr, "data": *dataDir, "base-url": *baseURL, "vn-bin": *vnBin,+		"native-listen": *nativeListen, "native-host": *nativeHost,+		"native-cert": *nativeCert, "native-key": *nativeKey,+	})+}++func setupLogger(cfg config.Config) (*log.Logger, io.Closer, error) {+	logPath := filepath.Join(cfg.LogDir, "veinsforge.log")+	f, err := os.OpenFile(logPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)+	if err != nil {+		return log.New(os.Stdout, "", log.LstdFlags|log.LUTC), nil, nil+	}+	return log.New(io.MultiWriter(os.Stdout, f), "", log.LstdFlags|log.LUTC), f, nil+}++func runServer(args []string) {+	cfg, err := serveFlags(args)+	if err != nil {+		if errors.Is(err, flag.ErrHelp) {+			return+		}+		log.Fatalf("config: %v", err)+	}+	if err := cfg.EnsureDirs(); err != nil {+		log.Fatalf("directories: %v", err)+	}+	logger, closer, err := setupLogger(cfg)+	if err != nil {+		log.Fatalf("logger: %v", err)+	}+	if closer != nil {+		defer closer.Close()+	}++	store, err := data.Open(cfg.DBPath)+	if err != nil {+		logger.Fatalf("database: %v", err)+	}+	defer store.Close()+	if err := store.BootstrapSettings(context.Background(), cfg.RegistrationOpen); err != nil {+		logger.Fatalf("settings: %v", err)+	}+	if err := bootstrapAdmin(context.Background(), store, cfg, logger); err != nil {+		logger.Fatalf("bootstrap admin: %v", err)+	}++	runner := vn.NewRunner(cfg.VNBin, cfg.VNHome, cfg.RepoRoot, cfg.CacheDir, logger)+	if err := runner.EnsureKey(context.Background()); err != nil {+		logger.Fatalf("service key: %v", err)+	}+	logger.Printf("service key %s (%s)", runner.KeyPublic, runner.KeyFinger)++	native := vn.NewNativeServer(cfg.VNBin, cfg.VNHome, cfg.NativeListen, cfg.NativeAddress(), cfg.RepoRoot, cfg.NativeCert, cfg.NativeKey, cfg.NativeHost, logger)+	ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)+	defer cancel()+	if err := native.Start(ctx); err != nil {+		logger.Printf("native server disabled: %v", err)+	}++	app, err := web.New(cfg, store, runner, native, logger)+	if err != nil {+		logger.Fatalf("web: %v", err)+	}+	app.StartBackground(ctx)++	srv := &http.Server{+		Addr:              cfg.Addr,+		Handler:           app.Handler(),+		ReadHeaderTimeout: cfg.ReadHeaderTimeout,+		ReadTimeout:       cfg.ReadTimeout,+		WriteTimeout:      cfg.WriteTimeout,+		IdleTimeout:       cfg.IdleTimeout,+		MaxHeaderBytes:    16 << 10,+		ErrorLog:          logger,+		ConnState:         connectionLimiter(cfg.MaxConcurrent * 2),+	}+	ln, err := net.Listen("tcp", cfg.Addr)+	if err != nil {+		logger.Fatalf("listen %s: %v", cfg.Addr, err)+	}+	logger.Printf("veinsforge %s listening on %s", version, cfg.Addr)+	logger.Printf("public URL: %s", cfg.BaseURL)+	if cfg.NativeListen != "" && cfg.NativeListen != "off" && native.Fingerprint != "" {+		logger.Printf("native protocol: %s (TLS pin %s)", cfg.NativeAddress(), native.Fingerprint)+	}+	go func() {+		if err := srv.Serve(ln); err != nil && !errors.Is(err, http.ErrServerClosed) {+			logger.Printf("http server: %v", err)+			cancel()+		}+	}()+	<-ctx.Done()+	shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second)+	defer shutdownCancel()+	_ = srv.Shutdown(shutdownCtx)+	logger.Printf("shutting down")+}++func bootstrapAdmin(ctx context.Context, store *data.Store, cfg config.Config, logger *log.Logger) error {+	if cfg.AdminUser == "" {+		if n, _ := store.CountUsers(ctx); n == 0 {+			logger.Printf("no users exist yet; create one with: veinsforge create-admin -username admin -password '...'")+		}+		return nil+	}+	if cfg.AdminPassword == "" {+		logger.Printf("VEINSFORGE_ADMIN_USER is set but VEINSFORGE_ADMIN_PASSWORD is empty")+		return nil+	}+	if err := auth.ValidHandle(cfg.AdminUser); err != nil {+		return err+	}+	if err := auth.ValidatePassword(cfg.AdminPassword); err != nil {+		return err+	}+	if existing, err := store.GetUserByUsername(ctx, cfg.AdminUser); err == nil {+		if !existing.IsAdmin {+			return store.SetUserAdmin(ctx, existing.ID, true)+		}+		return nil+	}+	hash, err := auth.HashPassword(cfg.AdminPassword)+	if err != nil {+		return err+	}+	user, err := store.CreateUser(ctx, cfg.AdminUser, cfg.AdminUser, "", hash, "", true)+	if err != nil {+		return err+	}+	logger.Printf("created bootstrap administrator %s (id %d)", user.Username, user.ID)+	return nil+}++func createAdmin(args []string) {+	fs := flag.NewFlagSet("create-admin", flag.ContinueOnError)+	fs.SetOutput(os.Stderr)+	username := fs.String("username", "", "admin username")+	password := fs.String("password", "", "admin password")+	dataDir := fs.String("data", "", "data directory")+	if err := fs.Parse(args); err != nil {+		return+	}+	if *username == "" {+		*username = os.Getenv("VEINSFORGE_ADMIN_USER")+	}+	if *password == "" {+		*password = os.Getenv("VEINSFORGE_ADMIN_PASSWORD")+	}+	if *username == "" || *password == "" {+		fmt.Fprintln(os.Stderr, "username and password are required")+		os.Exit(2)+	}+	cfg, err := config.Load(map[string]string{"data": *dataDir})+	if err != nil {+		fmt.Fprintln(os.Stderr, err)+		os.Exit(1)+	}+	if err := cfg.EnsureDirs(); err != nil {+		fmt.Fprintln(os.Stderr, err)+		os.Exit(1)+	}+	store, err := data.Open(cfg.DBPath)+	if err != nil {+		fmt.Fprintln(os.Stderr, err)+		os.Exit(1)+	}+	defer store.Close()+	ctx := context.Background()+	if err := auth.ValidHandle(*username); err != nil {+		fmt.Fprintln(os.Stderr, err)+		os.Exit(1)+	}+	if err := auth.ValidatePassword(*password); err != nil {+		fmt.Fprintln(os.Stderr, err)+		os.Exit(1)+	}+	hash, err := auth.HashPassword(*password)+	if err != nil {+		fmt.Fprintln(os.Stderr, err)+		os.Exit(1)+	}+	if existing, err := store.GetUserByUsername(ctx, *username); err == nil {+		if err := store.UpdateUserPassword(ctx, existing.ID, hash); err != nil {+			fmt.Fprintln(os.Stderr, err)+			os.Exit(1)+		}+		if err := store.SetUserAdmin(ctx, existing.ID, true); err != nil {+			fmt.Fprintln(os.Stderr, err)+			os.Exit(1)+		}+		if err := store.SetUserActive(ctx, existing.ID, true); err != nil {+			fmt.Fprintln(os.Stderr, err)+			os.Exit(1)+		}+		store.DeleteUserSessions(ctx, existing.ID)+		fmt.Printf("updated administrator %s\n", existing.Username)+		return+	}+	user, err := store.CreateUser(ctx, *username, *username, "", hash, "", true)+	if err != nil {+		fmt.Fprintln(os.Stderr, err)+		os.Exit(1)+	}+	fmt.Printf("created administrator %s (id %d)\n", user.Username, user.ID)+}++func connectionLimiter(max int) func(net.Conn, http.ConnState) {+	if max < 16 {+		max = 16+	}+	var mu sync.Mutex+	open := make(map[net.Conn]bool)+	return func(conn net.Conn, state http.ConnState) {+		mu.Lock()+		defer mu.Unlock()+		switch state {+		case http.StateNew:+			if len(open) >= max {+				_ = conn.Close()+				return+			}+			open[conn] = true+		case http.StateClosed, http.StateHijacked:+			delete(open, conn)+		}+	}+}--- /dev/null+++ b/deploy/Caddyfile@@ -0,0 +1,8 @@+forge.example.com {+	encode zstd gzip+	header {+		Strict-Transport-Security "max-age=31536000; includeSubDomains"+		X-Content-Type-Options "nosniff"+	}+	reverse_proxy 127.0.0.1:8080+}--- /dev/null+++ b/deploy/veinsforge.env.example@@ -0,0 +1,20 @@+# Bind the web UI to localhost and put Caddy/nginx in front for public HTTPS.+VEINSFORGE_ADDR=127.0.0.1:8080+VEINSFORGE_DATA=/var/lib/veinsforge+VEINSFORGE_BASE_URL=https://forge.example.com+VEINSFORGE_VN_BIN=/usr/local/bin/vn++# Native protocol. Use 0.0.0.0:7419 only if external clients need it.+VEINSFORGE_NATIVE_LISTEN=0.0.0.0:7419+VEINSFORGE_NATIVE_HOST=forge.example.com++# Trust X-Forwarded-For only from the local reverse proxy.+VEINSFORGE_TRUSTED_PROXIES=127.0.0.1/32,::1/128++# Optional: use a publicly trusted certificate instead of the generated one.+# VEINSFORGE_NATIVE_CERT=/etc/letsencrypt/live/forge.example.com/fullchain.pem+# VEINSFORGE_NATIVE_KEY=/etc/letsencrypt/live/forge.example.com/privkey.pem++# Bootstrap the first administrator (remove the password after first start).+# VEINSFORGE_ADMIN_USER=admin+# VEINSFORGE_ADMIN_PASSWORD=replace-with-a-long-random-password--- /dev/null+++ b/deploy/veinsforge.service@@ -0,0 +1,27 @@+[Unit]+Description=veinsforge+Documentation=file:///usr/local/share/veinsforge/DEPLOY.md+After=network-online.target+Wants=network-online.target++[Service]+Type=simple+User=veinsforge+Group=veinsforge+EnvironmentFile=/etc/veinsforge/veinsforge.env+ExecStart=/usr/local/bin/veinsforge serve+Restart=on-failure+RestartSec=3+TimeoutStopSec=20+LimitNOFILE=65535+NoNewPrivileges=true+PrivateTmp=true+ProtectHome=true+ProtectSystem=strict+ReadWritePaths=/var/lib/veinsforge+StateDirectory=veinsforge+ConfigurationDirectory=veinsforge+UMask=0077++[Install]+WantedBy=multi-user.target--- /dev/null+++ b/go.mod@@ -0,0 +1,23 @@+module veinsforge++go 1.25++require (+	github.com/yuin/goldmark v1.7.4+	github.com/zeebo/blake3 v0.2.4+	golang.org/x/crypto v0.33.0+	modernc.org/sqlite v1.34.5+)++require (+	github.com/dustin/go-humanize v1.0.1 // indirect+	github.com/google/uuid v1.6.0 // indirect+	github.com/klauspost/cpuid/v2 v2.0.12 // indirect+	github.com/mattn/go-isatty v0.0.20 // indirect+	github.com/ncruces/go-strftime v0.1.9 // indirect+	github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect+	golang.org/x/sys v0.30.0 // indirect+	modernc.org/libc v1.55.3 // indirect+	modernc.org/mathutil v1.6.0 // indirect+	modernc.org/memory v1.8.0 // indirect+)--- /dev/null+++ b/go.sum@@ -0,0 +1,55 @@+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=+github.com/klauspost/cpuid/v2 v2.0.12 h1:p9dKCg8i4gmOxtv35DvrYoWqYzQrvEVdjQ762Y0OqZE=+github.com/klauspost/cpuid/v2 v2.0.12/go.mod h1:g2LTdtYhdyuGPqyWyv7qRAmj1WBqxuObKfj5c0PQa7c=+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=+github.com/yuin/goldmark v1.7.4 h1:BDXOHExt+A7gwPCJgPIIq7ENvceR7we7rOS9TNoLZeg=+github.com/yuin/goldmark v1.7.4/go.mod h1:uzxRWxtg69N339t3louHJ7+O03ezfj6PlliRlaOzY1E=+github.com/zeebo/assert v1.1.0 h1:hU1L1vLTHsnO8x8c9KAR5GmM5QscxHg5RNU5z5qbUWY=+github.com/zeebo/assert v1.1.0/go.mod h1:Pq9JiuJQpG8JLJdtkwrJESF0Foym2/D9XMU5ciN/wJ0=+github.com/zeebo/blake3 v0.2.4 h1:KYQPkhpRtcqh0ssGYcKLG1JYvddkEA8QwCM/yBqhaZI=+github.com/zeebo/blake3 v0.2.4/go.mod h1:7eeQ6d2iXWRGF6npfaxl2CU+xy2Fjo2gxeyZGCRUjcE=+github.com/zeebo/pcg v1.0.1 h1:lyqfGeWiv4ahac6ttHs+I5hwtH/+1mrhlCtVNQM2kHo=+github.com/zeebo/pcg v1.0.1/go.mod h1:09F0S9iiKrwn9rlI5yjLkmrug154/YRW6KnnXVDM/l4=+golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus=+golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M=+golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=+golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=+golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=+golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=+golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=+golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=+modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=+modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=+modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=+modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=+modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=+modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=+modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=+modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=+modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=+modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=+modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=+modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=+modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=+modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=+modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=+modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=+modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=+modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=+modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g=+modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE=+modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=+modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=--- /dev/null+++ b/internal/auth/keys.go@@ -0,0 +1,43 @@+package auth++import (+	"encoding/base32"+	"encoding/base64"+	"errors"+	"strings"++	"github.com/zeebo/blake3"+)++var b32 = base32.StdEncoding.WithPadding(base32.NoPadding)++// ParsePublicKey validates a veins Ed25519 public key and returns the canonical+// text form plus the raw 32-byte key and its veins fingerprint.+func ParsePublicKey(text string) (canonical string, raw []byte, fingerprint string, err error) {+	text = strings.TrimSpace(text)+	if !strings.HasPrefix(text, "ed25519:") {+		return "", nil, "", errors.New("key must start with ed25519:")+	}+	encoded := strings.TrimPrefix(text, "ed25519:")+	raw, err = base64.RawURLEncoding.DecodeString(strings.TrimRight(encoded, "="))+	if err != nil || len(raw) != 32 {+		return "", nil, "", errors.New("invalid Ed25519 public key")+	}+	canonical = "ed25519:" + base64.RawURLEncoding.EncodeToString(raw)+	return canonical, raw, Fingerprint(raw), nil+}++// Fingerprint matches veins: BLAKE3("veins/key/1" || public_key), first 16+// bytes, lowercase unpadded base32 (26 characters).+func Fingerprint(publicKey []byte) string {+	h := blake3.New()+	_, _ = h.Write([]byte("veins/key/1\x00"))+	_, _ = h.Write(publicKey)+	sum := h.Sum(nil)+	return b32.EncodeToString(sum[:16])+}++func ValidKeyName(name string) bool {+	name = strings.TrimSpace(name)+	return len(name) > 0 && len(name) <= 64 && !strings.ContainsAny(name, "\r\n\x00")+}--- /dev/null+++ b/internal/auth/keys_test.go@@ -0,0 +1,28 @@+package auth++import "testing"++func TestParsePublicKeyAndFingerprint(t *testing.T) {+	const key = "ed25519:vl99ipKRQSi1hHY_c2-3ewa3WY6rGLWgnzvQPd29hpw"+	canonical, raw, fingerprint, err := ParsePublicKey(key)+	if err != nil {+		t.Fatal(err)+	}+	if canonical != key {+		t.Fatalf("canonical key = %q, want %q", canonical, key)+	}+	if len(raw) != 32 {+		t.Fatalf("raw key length = %d", len(raw))+	}+	if fingerprint != "GCQWILDZKFUIUVJWQKUPYV2K3Y" {+		t.Fatalf("fingerprint = %q", fingerprint)+	}+}++func TestParsePublicKeyRejectsInvalid(t *testing.T) {+	for _, input := range []string{"", "ssh-ed25519 foo", "ed25519:not-base64", "ed25519:AAAA"} {+		if _, _, _, err := ParsePublicKey(input); err == nil {+			t.Fatalf("accepted invalid key %q", input)+		}+	}+}--- /dev/null+++ b/internal/auth/password.go@@ -0,0 +1,108 @@+package auth++import (+	"crypto/rand"+	"crypto/sha256"+	"crypto/subtle"+	"encoding/base64"+	"encoding/hex"+	"errors"+	"fmt"+	"strconv"+	"strings"++	"golang.org/x/crypto/argon2"+)++const (+	argonMemory      = 64 * 1024+	argonIterations  = 3+	argonParallelism = 2+	argonKeyLen      = 32+	argonSaltLen     = 16+)++var ErrInvalidHash = errors.New("invalid password hash")++// HashPassword derives an Argon2id password hash in the standard PHC format.+func HashPassword(password string) (string, error) {+	salt := make([]byte, argonSaltLen)+	if _, err := rand.Read(salt); err != nil {+		return "", err+	}+	key := argon2.IDKey([]byte(password), salt, argonIterations, argonMemory, argonParallelism, argonKeyLen)+	return fmt.Sprintf("$argon2id$v=19$m=%d,t=%d,p=%d$%s$%s",+		argonMemory, argonIterations, argonParallelism,+		base64.RawStdEncoding.EncodeToString(salt),+		base64.RawStdEncoding.EncodeToString(key)), nil+}++// VerifyPassword checks a password against a PHC-formatted Argon2id hash.+func VerifyPassword(encoded, password string) bool {+	parts := strings.Split(encoded, "$")+	if len(parts) != 6 || parts[1] != "argon2id" || parts[2] != "v=19" {+		return false+	}+	var memory uint32+	var iterations uint32+	var parallelism uint8+	for _, field := range strings.Split(parts[3], ",") {+		kv := strings.SplitN(field, "=", 2)+		if len(kv) != 2 {+			return false+		}+		n, err := strconv.ParseUint(kv[1], 10, 32)+		if err != nil {+			return false+		}+		switch kv[0] {+		case "m":+			memory = uint32(n)+		case "t":+			iterations = uint32(n)+		case "p":+			parallelism = uint8(n)+		}+	}+	if memory == 0 || iterations == 0 || parallelism == 0 {+		return false+	}+	salt, err := base64.RawStdEncoding.DecodeString(parts[4])+	if err != nil {+		return false+	}+	want, err := base64.RawStdEncoding.DecodeString(parts[5])+	if err != nil {+		return false+	}+	got := argon2.IDKey([]byte(password), salt, iterations, memory, parallelism, uint32(len(want)))+	return subtle.ConstantTimeCompare(got, want) == 1+}++// ValidatePassword applies strict bounds so hashing cannot be used as a DoS.+func ValidatePassword(password string) error {+	if len(password) < 10 {+		return errors.New("password must be at least 10 characters")+	}+	if len(password) > 256 {+		return errors.New("password must be at most 256 bytes")+	}+	return nil+}++func RandomToken(bytesLen int) (string, error) {+	b := make([]byte, bytesLen)+	if _, err := rand.Read(b); err != nil {+		return "", err+	}+	return base64.RawURLEncoding.EncodeToString(b), nil+}++func HashToken(token string) string {+	sum := sha256.Sum256([]byte(token))+	return hex.EncodeToString(sum[:])+}++func ConstantTimeEqual(a, b string) bool {+	return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1+}--- /dev/null+++ b/internal/auth/password_test.go@@ -0,0 +1,31 @@+package auth++import "testing"++func TestPasswordHashRoundTrip(t *testing.T) {+	hash, err := HashPassword("correct horse battery staple")+	if err != nil {+		t.Fatal(err)+	}+	if !VerifyPassword(hash, "correct horse battery staple") {+		t.Fatal("valid password was rejected")+	}+	if VerifyPassword(hash, "wrong password") {+		t.Fatal("invalid password was accepted")+	}+	if VerifyPassword("not-a-hash", "anything") {+		t.Fatal("malformed hash was accepted")+	}+}++func TestPasswordPolicy(t *testing.T) {+	if err := ValidatePassword("short"); err == nil {+		t.Fatal("short password accepted")+	}+	if err := ValidatePassword("this password is long enough"); err != nil {+		t.Fatal(err)+	}+	if err := ValidatePassword(string(make([]byte, 257))); err == nil {+		t.Fatal("overlong password accepted")+	}+}--- /dev/null+++ b/internal/auth/validate.go@@ -0,0 +1,118 @@+package auth++import (+	"errors"+	"net/mail"+	"regexp"+	"strings"+)++var (+	handleRE = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]{1,30}[a-zA-Z0-9]$`)+	repoRE   = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,99}$`)+)++// Reserved handles would collide with application routes or impersonate the+// service. The namespace is shared by users and organisations.+var reserved = map[string]bool{+	"api": true, "assets": true, "attachments": true, "avatars": true,+	"explore": true, "favicon.ico": true, "healthz": true, "login": true, "logout": true,+	"new": true, "orgs": true, "robots.txt": true, "settings": true, "signup": true,+	"static": true, "u": true, "veins": true, "veinsforge": true, "root": true,+	"system": true, "support": true, "help": true, "about": true, "search": true,+}++func ValidHandle(name string) error {+	if !handleRE.MatchString(name) {+		return errors.New("names must be 3-32 characters and use letters, digits, hyphens or underscores")+	}+	lower := strings.ToLower(name)+	if reserved[lower] {+		return errors.New("that name is reserved")+	}+	if strings.HasPrefix(lower, "org-") {+		return errors.New("that name is reserved")+	}+	return nil+}++func ValidRepoName(name string) error {+	if !repoRE.MatchString(name) || name == "." || name == ".." || strings.HasPrefix(name, ".veins") {+		return errors.New("repository names must start with a letter or digit and use letters, digits, dots, hyphens or underscores")+	}+	return nil+}++func ValidEmail(email string) error {+	if email == "" {+		return nil+	}+	addr, err := mail.ParseAddress(email)+	if err != nil || addr.Address != email || len(email) > 254 {+		return errors.New("invalid email address")+	}+	return nil+}++func ValidRevision(rev string) error {+	if rev == "" {+		return errors.New("revision is required")+	}+	if len(rev) > 200 {+		return errors.New("revision is too long")+	}+	if strings.HasPrefix(rev, "-") || strings.ContainsAny(rev, "\x00\r\n") {+		return errors.New("invalid revision")+	}+	for _, part := range strings.Split(rev, "/") {+		if part == ".." {+			return errors.New("invalid revision")+		}+	}+	for _, r := range rev {+		if r < 32 || r == 127 {+			return errors.New("invalid revision")+		}+	}+	return nil+}++func ValidBranchName(name string) error {+	name = strings.TrimSpace(name)+	if name == "" || len(name) > 200 {+		return errors.New("invalid branch name")+	}+	if strings.HasPrefix(name, "-") || strings.HasPrefix(name, "/") || strings.HasSuffix(name, "/") {+		return errors.New("invalid branch name")+	}+	if strings.Contains(name, "..") || strings.ContainsAny(name, "\x00\r\n\\") {+		return errors.New("invalid branch name")+	}+	return nil+}++func ValidRepoPath(p string) error {+	if p == "" {+		return nil+	}+	if len(p) > 1024 || strings.HasPrefix(p, "/") || strings.ContainsAny(p, "\x00\r\\") {+		return errors.New("invalid path")+	}+	for _, part := range strings.Split(p, "/") {+		if part == "" || part == "." || part == ".." {+			return errors.New("invalid path")+		}+	}+	if strings.HasPrefix(p, ".veins/") || p == ".veins" {+		return errors.New("invalid path")+	}+	return nil+}++func CleanOneLine(s string, max int) string {+	s = strings.TrimSpace(strings.ReplaceAll(strings.ReplaceAll(s, "\r", " "), "\n", " "))+	if len(s) > max {+		s = s[:max]+	}+	return s+}--- /dev/null+++ b/internal/auth/validate_test.go@@ -0,0 +1,49 @@+package auth++import "testing"++func TestHandlesAndRepositoryNames(t *testing.T) {+	for _, name := range []string{"navid", "a_b-c", "abc"} {+		if err := ValidHandle(name); err != nil {+			t.Errorf("ValidHandle(%q): %v", name, err)+		}+	}+	for _, name := range []string{"ab", "-abc", "abc-", "a b", "login", "static", "org-acme", ".."} {+		if err := ValidHandle(name); err == nil {+			t.Errorf("ValidHandle(%q) accepted", name)+		}+	}+	for _, name := range []string{"repo", "my.repo", "a-b_c", "x"} {+		if err := ValidRepoName(name); err != nil {+			t.Errorf("ValidRepoName(%q): %v", name, err)+		}+	}+	for _, name := range []string{"", ".hidden", "..", "a/b", ".veins"} {+		if err := ValidRepoName(name); err == nil {+			t.Errorf("ValidRepoName(%q) accepted", name)+		}+	}+}++func TestPathsAndRevisions(t *testing.T) {+	for _, p := range []string{"", "README.md", "src/main.go", "a/b/c"} {+		if err := ValidRepoPath(p); err != nil {+			t.Errorf("ValidRepoPath(%q): %v", p, err)+		}+	}+	for _, p := range []string{"/etc/passwd", "../secret", "a/../b", "a//b", ".veins/config", "a\\b"} {+		if err := ValidRepoPath(p); err == nil {+			t.Errorf("ValidRepoPath(%q) accepted", p)+		}+	}+	for _, rev := range []string{"main", "feature/x", "abc123", "@"} {+		if err := ValidRevision(rev); err != nil {+			t.Errorf("ValidRevision(%q): %v", rev, err)+		}+	}+	for _, rev := range []string{"", "-main", "bad\nrev", "a/../b", "../main"} {+		if err := ValidRevision(rev); err == nil {+			t.Errorf("ValidRevision(%q) accepted", rev)+		}+	}+}--- /dev/null+++ b/internal/config/config.go@@ -0,0 +1,244 @@+package config++import (+	"fmt"+	"net"+	"net/url"+	"os"+	"path/filepath"+	"strconv"+	"strings"+	"time"+)++// Config holds the runtime configuration for veinsforge.+type Config struct {+	Addr              string+	DataDir           string+	DBPath            string+	RepoRoot          string+	CacheDir          string+	AttachmentDir     string+	AvatarDir         string+	LogDir            string+	VNHome            string+	VNBin             string+	NativeListen      string+	NativeHost        string+	NativeCert        string+	NativeKey         string+	BaseURL           string+	TrustedProxies    []string+	SecureCookies     bool+	SessionTTL        time.Duration+	MaxUploadBytes    int64+	MaxAvatarBytes    int64+	ReadHeaderTimeout time.Duration+	ReadTimeout       time.Duration+	WriteTimeout      time.Duration+	IdleTimeout       time.Duration+	MaxConcurrent     int+	RateLimitPerSec   float64+	RateLimitBurst    int+	AuthLimitPerMin   int+	WriteLimitPerMin  int+	RegistrationOpen  bool+	AdminUser         string+	AdminPassword     string+}++// Load reads the environment, applies defaults, and normalizes paths. The+// optional command-line flags in overrides take precedence.+func Load(overrides map[string]string) (Config, error) {+	c := Config{+		Addr:              env("VEINSFORGE_ADDR", "127.0.0.1:8080"),+		DataDir:           env("VEINSFORGE_DATA", "./data"),+		VNBin:             env("VEINSFORGE_VN_BIN", "vn"),+		NativeListen:      env("VEINSFORGE_NATIVE_LISTEN", "127.0.0.1:7419"),+		NativeHost:        env("VEINSFORGE_NATIVE_HOST", ""),+		NativeCert:        os.Getenv("VEINSFORGE_NATIVE_CERT"),+		NativeKey:         os.Getenv("VEINSFORGE_NATIVE_KEY"),+		BaseURL:           env("VEINSFORGE_BASE_URL", "http://127.0.0.1:8080"),+		TrustedProxies:    splitCSV(env("VEINSFORGE_TRUSTED_PROXIES", "127.0.0.1/32,::1/128")),+		SessionTTL:        time.Duration(envInt("VEINSFORGE_SESSION_DAYS", 30)) * 24 * time.Hour,+		MaxUploadBytes:    int64(envInt("VEINSFORGE_MAX_UPLOAD_MB", 10)) << 20,+		MaxAvatarBytes:    int64(envInt("VEINSFORGE_MAX_AVATAR_MB", 2)) << 20,+		ReadHeaderTimeout: time.Duration(envInt("VEINSFORGE_READ_HEADER_SECONDS", 5)) * time.Second,+		ReadTimeout:       time.Duration(envInt("VEINSFORGE_READ_SECONDS", 60)) * time.Second,+		WriteTimeout:      time.Duration(envInt("VEINSFORGE_WRITE_SECONDS", 60)) * time.Second,+		IdleTimeout:       time.Duration(envInt("VEINSFORGE_IDLE_SECONDS", 90)) * time.Second,+		MaxConcurrent:     envInt("VEINSFORGE_MAX_CONCURRENT", 256),+		RateLimitPerSec:   envFloat("VEINSFORGE_RATE_PER_SECOND", 25),+		RateLimitBurst:    envInt("VEINSFORGE_RATE_BURST", 60),+		AuthLimitPerMin:   envInt("VEINSFORGE_AUTH_PER_MINUTE", 12),+		WriteLimitPerMin:  envInt("VEINSFORGE_WRITE_PER_MINUTE", 40),+		RegistrationOpen:  envBool("VEINSFORGE_REGISTRATION_OPEN", true),+		AdminUser:         os.Getenv("VEINSFORGE_ADMIN_USER"),+		AdminPassword:     os.Getenv("VEINSFORGE_ADMIN_PASSWORD"),+	}+	for k, v := range overrides {+		if v == "" {+			continue+		}+		switch k {+		case "addr":+			c.Addr = v+		case "data":+			c.DataDir = v+		case "base-url":+			c.BaseURL = v+		case "vn-bin":+			c.VNBin = v+		case "native-listen":+			c.NativeListen = v+		case "native-host":+			c.NativeHost = v+		case "native-cert":+			c.NativeCert = v+		case "native-key":+			c.NativeKey = v+		}+	}+	if err := c.finalize(); err != nil {+		return Config{}, err+	}+	return c, nil+}++func (c *Config) finalize() error {+	abs, err := filepath.Abs(c.DataDir)+	if err != nil {+		return err+	}+	c.DataDir = abs+	c.DBPath = filepath.Join(abs, "veinsforge.db")+	c.RepoRoot = filepath.Join(abs, "repos")+	c.CacheDir = filepath.Join(abs, "cache")+	c.AttachmentDir = filepath.Join(abs, "attachments")+	c.AvatarDir = filepath.Join(abs, "avatars")+	c.LogDir = filepath.Join(abs, "logs")+	c.VNHome = filepath.Join(abs, "home")+	if c.NativeCert == "" {+		c.NativeCert = filepath.Join(abs, "native", "tls.crt")+	}+	if c.NativeKey == "" {+		c.NativeKey = filepath.Join(abs, "native", "tls.key")+	}+	if c.SessionTTL <= 0 {+		c.SessionTTL = 30 * 24 * time.Hour+	}+	if c.NativeHost == "" {+		if u, err := url.Parse(c.BaseURL); err == nil && u.Hostname() != "" {+			c.NativeHost = u.Hostname()+		} else {+			c.NativeHost = "localhost"+		}+	}+	c.SecureCookies = strings.HasPrefix(strings.ToLower(c.BaseURL), "https://")+	if v, ok := os.LookupEnv("VEINSFORGE_SECURE_COOKIES"); ok {+		c.SecureCookies = envBoolValue(v, c.SecureCookies)+	}+	if c.MaxConcurrent < 16 {+		c.MaxConcurrent = 16+	}+	if c.RateLimitPerSec <= 0 {+		c.RateLimitPerSec = 25+	}+	if c.RateLimitBurst <= 0 {+		c.RateLimitBurst = 60+	}+	return nil+}++// EnsureDirs creates the service data directories with restrictive modes.+func (c Config) EnsureDirs() error {+	dirs := []string{+		c.DataDir, c.RepoRoot, c.CacheDir, c.AttachmentDir, c.AvatarDir,+		c.LogDir, c.VNHome, filepath.Dir(c.NativeCert),+		filepath.Join(c.VNHome, ".config", "veins", "keys"),+	}+	for _, d := range dirs {+		if err := os.MkdirAll(d, 0o700); err != nil {+			return fmt.Errorf("create %s: %w", d, err)+		}+	}+	return nil+}++// NativeAddress returns the advertised host:port for the native protocol.+func (c Config) NativeAddress() string {+	listen := c.NativeListen+	host, port, err := net.SplitHostPort(listen)+	if err != nil {+		return listen+	}+	if host == "" || host == "0.0.0.0" || host == "::" {+		host = c.NativeHost+	}+	return net.JoinHostPort(host, port)+}++// NativeURL returns the clone URL for a repository.+func (c Config) NativeURL(owner, name string) string {+	return fmt.Sprintf("veins://%s/%s/%s", c.NativeAddress(), owner, name)+}++func env(key, def string) string {+	if v, ok := os.LookupEnv(key); ok && strings.TrimSpace(v) != "" {+		return strings.TrimSpace(v)+	}+	return def+}++func envInt(key string, def int) int {+	v, ok := os.LookupEnv(key)+	if !ok || strings.TrimSpace(v) == "" {+		return def+	}+	n, err := strconv.Atoi(strings.TrimSpace(v))+	if err != nil {+		return def+	}+	return n+}++func envFloat(key string, def float64) float64 {+	v, ok := os.LookupEnv(key)+	if !ok || strings.TrimSpace(v) == "" {+		return def+	}+	n, err := strconv.ParseFloat(strings.TrimSpace(v), 64)+	if err != nil {+		return def+	}+	return n+}++func envBool(key string, def bool) bool {+	v, ok := os.LookupEnv(key)+	if !ok {+		return def+	}+	return envBoolValue(v, def)+}++func envBoolValue(v string, def bool) bool {+	switch strings.ToLower(strings.TrimSpace(v)) {+	case "1", "true", "yes", "on":+		return true+	case "0", "false", "no", "off":+		return false+	default:+		return def+	}+}++func splitCSV(s string) []string {+	var out []string+	for _, part := range strings.Split(s, ",") {+		if p := strings.TrimSpace(part); p != "" {+			out = append(out, p)+		}+	}+	return out+}--- /dev/null+++ b/internal/data/data_test.go@@ -0,0 +1,148 @@+package data++import (+	"context"+	"path/filepath"+	"testing"+)++func TestStoreWALAndCoreRecords(t *testing.T) {+	ctx := context.Background()+	s, err := Open(filepath.Join(t.TempDir(), "test.db"))+	if err != nil {+		t.Fatal(err)+	}+	defer s.Close()++	var mode string+	if err := s.DB().QueryRowContext(ctx, `PRAGMA journal_mode`).Scan(&mode); err != nil {+		t.Fatal(err)+	}+	if mode != "wal" {+		t.Fatalf("journal_mode = %q, want wal", mode)+	}+	var fk int+	if err := s.DB().QueryRowContext(ctx, `PRAGMA foreign_keys`).Scan(&fk); err != nil {+		t.Fatal(err)+	}+	if fk != 1 {+		t.Fatalf("foreign_keys = %d", fk)+	}++	u, err := s.CreateUser(ctx, "alice", "Alice", "", "$argon2id$fake", "127.0.0.1", false)+	if err != nil {+		t.Fatal(err)+	}+	repo, err := s.CreateRepo(ctx, "user", u.ID, u.Username, "demo", "Demo", "description", "public")+	if err != nil {+		t.Fatal(err)+	}+	perms, err := s.Permissions(ctx, repo, u)+	if err != nil {+		t.Fatal(err)+	}+	if !perms.CanAdmin || !perms.CanWrite || !perms.CanView {+		t.Fatalf("owner permissions = %+v", perms)+	}+	anon, err := s.Permissions(ctx, repo, nil)+	if err != nil {+		t.Fatal(err)+	}+	if !anon.CanView || anon.CanWrite {+		t.Fatalf("anonymous permissions = %+v", anon)+	}++	issue1, err := s.CreateIssue(ctx, repo.ID, u.ID, "one", "body", "127.0.0.1")+	if err != nil {+		t.Fatal(err)+	}+	issue2, err := s.CreateIssue(ctx, repo.ID, u.ID, "two", "body", "127.0.0.1")+	if err != nil {+		t.Fatal(err)+	}+	if issue1.Number != 1 || issue2.Number != 2 {+		t.Fatalf("issue numbers = %d, %d", issue1.Number, issue2.Number)+	}+	if _, err := s.AddComment(ctx, repo.ID, "issue", issue1.ID, u.ID, "hello", "127.0.0.1"); err != nil {+		t.Fatal(err)+	}+	if _, err := s.AddComment(ctx, repo.ID, "issue", issue1.ID, u.ID, "again", "127.0.0.1"); err != nil {+		t.Fatal(err)+	}+	got, err := s.GetIssue(ctx, repo.ID, 1)+	if err != nil {+		t.Fatal(err)+	}+	if got.CommentCount != 2 {+		t.Fatalf("comment count = %d", got.CommentCount)+	}++	added, err := s.ToggleStar(ctx, repo.ID, u.ID)+	if err != nil || !added {+		t.Fatalf("star add = %v, %v", added, err)+	}+	if !s.IsStarred(ctx, repo.ID, u.ID) {+		t.Fatal("star not recorded")+	}+	added, err = s.ToggleStar(ctx, repo.ID, u.ID)+	if err != nil || added {+		t.Fatalf("star remove = %v, %v", added, err)+	}++	access, err := s.AccessUsers(ctx, repo)+	if err != nil {+		t.Fatal(err)+	}+	if len(access) != 1 || access[0].UserID != u.ID || access[0].Role != "write" {+		t.Fatalf("access = %+v", access)+	}+}++func TestPrivateRepositoryVisibility(t *testing.T) {+	ctx := context.Background()+	s, err := Open(filepath.Join(t.TempDir(), "test.db"))+	if err != nil {+		t.Fatal(err)+	}+	defer s.Close()+	owner, _ := s.CreateUser(ctx, "owner", "Owner", "", "x", "", false)+	other, _ := s.CreateUser(ctx, "other", "Other", "", "x", "", false)+	repo, err := s.CreateRepo(ctx, "user", owner.ID, owner.Username, "private", "", "", "private")+	if err != nil {+		t.Fatal(err)+	}+	perms, _ := s.Permissions(ctx, repo, other)+	if perms.CanView {+		t.Fatal("unrelated user can view a private repository")+	}+	if err := s.SetCollaborator(ctx, repo.ID, other.ID, "read"); err != nil {+		t.Fatal(err)+	}+	perms, _ = s.Permissions(ctx, repo, other)+	if !perms.CanView || perms.CanWrite {+		t.Fatalf("collaborator permissions = %+v", perms)+	}+}++func TestCreateUserAutoAdminOnlyFirst(t *testing.T) {+	ctx := context.Background()+	s, err := Open(filepath.Join(t.TempDir(), "test.db"))+	if err != nil {+		t.Fatal(err)+	}+	defer s.Close()+	first, err := s.CreateUserAutoAdmin(ctx, "first", "First", "", "x", "")+	if err != nil {+		t.Fatal(err)+	}+	second, err := s.CreateUserAutoAdmin(ctx, "second", "Second", "", "x", "")+	if err != nil {+		t.Fatal(err)+	}+	if !first.IsAdmin {+		t.Fatal("first user is not an administrator")+	}+	if second.IsAdmin {+		t.Fatal("second user became an administrator")+	}+}--- /dev/null+++ b/internal/data/db.go@@ -0,0 +1,178 @@+package data++import (+	"context"+	"database/sql"+	_ "embed"+	"errors"+	"fmt"+	"os"+	"path/filepath"+	"strconv"+	"strings"+	"time"++	_ "modernc.org/sqlite"+)++//go:embed schema.sql+var schemaSQL string++// Store is the SQLite-backed application database.+type Store struct {+	db *sql.DB+}++// Open opens the database, applies the SQLite WAL pragmas, and runs migrations.+func Open(path string) (*Store, error) {+	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+		return nil, err+	}+	dsn := fmt.Sprintf("file:%s?_txlock=immediate&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(1)&_pragma=synchronous(NORMAL)&_pragma=temp_store(MEMORY)", path)+	db, err := sql.Open("sqlite", dsn)+	if err != nil {+		return nil, err+	}+	db.SetMaxOpenConns(8)+	db.SetMaxIdleConns(4)+	db.SetConnMaxLifetime(time.Hour)+	if err := db.Ping(); err != nil {+		db.Close()+		return nil, err+	}+	s := &Store{db: db}+	if err := s.migrate(); err != nil {+		db.Close()+		return nil, err+	}+	return s, nil+}++func (s *Store) Close() error { return s.db.Close() }+func (s *Store) DB() *sql.DB  { return s.db }++func (s *Store) migrate() error {+	if _, err := s.db.Exec(schemaSQL); err != nil {+		return fmt.Errorf("apply schema: %w", err)+	}+	now := time.Now().Unix()+	defaults := map[string]string{+		"site_name":         "veinsforge",+		"site_description":  "A brutalist forge for veins repositories.",+		"registration_open": "true",+	}+	for k, v := range defaults {+		if _, err := s.db.Exec(`INSERT INTO settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO NOTHING`, k, v); err != nil {+			return err+		}+	}+	_, _ = s.db.Exec(`INSERT INTO schema_migrations(version, applied_at) VALUES(1, ?) ON CONFLICT(version) DO NOTHING`, now)+	return nil+}++func (s *Store) Setting(ctx context.Context, key, def string) string {+	var v string+	err := s.db.QueryRowContext(ctx, `SELECT value FROM settings WHERE key = ?`, key).Scan(&v)+	if err != nil {+		return def+	}+	return v+}++func (s *Store) SetSetting(ctx context.Context, key, value string) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value`, key, value)+	return err+}++func (s *Store) BootstrapSettings(ctx context.Context, registrationOpen bool) error {+	if !registrationOpen {+		return s.SetSetting(ctx, "registration_open", "false")+	}+	return nil+}++// Stats is the site-wide landing page summary.+type Stats struct {+	Users       int64+	Repos       int64+	PublicRepos int64+	Issues      int64+	Stars       int64+}++func (s *Store) SiteStats(ctx context.Context) (Stats, error) {+	var st Stats+	err := s.db.QueryRowContext(ctx, `+		SELECT+			(SELECT COUNT(*) FROM users WHERE is_active = 1),+			(SELECT COUNT(*) FROM repos),+			(SELECT COUNT(*) FROM repos WHERE visibility = 'public' AND archived = 0),+			(SELECT COUNT(*) FROM issues WHERE state = 'open'),+			(SELECT COUNT(*) FROM stars)`).+		Scan(&st.Users, &st.Repos, &st.PublicRepos, &st.Issues, &st.Stars)+	return st, err+}++func unix(t time.Time) int64 { return t.UTC().Unix() }+func fromUnix(v int64) time.Time {+	if v == 0 {+		return time.Time{}+	}+	return time.Unix(v, 0).UTC()+}+func nullTime(v sql.NullInt64) *time.Time {+	if !v.Valid {+		return nil+	}+	t := fromUnix(v.Int64)+	return &t+}+func nullInt64Ptr(v sql.NullInt64) *int64 {+	if !v.Valid {+		return nil+	}+	n := v.Int64+	return &n+}+func boolInt(v bool) int {+	if v {+		return 1+	}+	return 0+}+func intBool(v int) bool { return v != 0 }++func isUnique(err error) bool {+	if err == nil {+		return false+	}+	msg := strings.ToLower(err.Error())+	return strings.Contains(msg, "unique constraint") || strings.Contains(msg, "constraint failed")+}++var ErrNotFound = errors.New("not found")+var ErrConflict = errors.New("conflict")++// Pagination validates a page and page size from query-style input.+func Pagination(pageStr, sizeStr string) (page, size, offset int) {+	page, _ = strconv.Atoi(pageStr)+	if page < 1 {+		page = 1+	}+	size, _ = strconv.Atoi(sizeStr)+	if size < 1 {+		size = 25+	}+	if size > 100 {+		size = 100+	}+	offset = (page - 1) * size+	return+}++func OrDefault(v, def string) string {+	if strings.TrimSpace(v) == "" {+		return def+	}+	return v+}--- /dev/null+++ b/internal/data/extra.go@@ -0,0 +1,195 @@+package data++import (+	"context"+	"database/sql"+	"time"+)++type Attachment struct {+	ID          string+	RepoID      int64+	UploaderID  int64+	SubjectType string+	SubjectID   int64+	Filename    string+	StoredName  string+	MIME        string+	Size        int64+	CreatedAt   time.Time+}++func (s *Store) CreateAttachment(ctx context.Context, a *Attachment) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO attachments(id, repo_id, uploader_id, subject_type, subject_id,+		filename, stored_name, mime, size, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+		a.ID, a.RepoID, a.UploaderID, a.SubjectType, a.SubjectID, a.Filename, a.StoredName, a.MIME, a.Size, unix(time.Now()))+	return err+}++func (s *Store) GetAttachment(ctx context.Context, id string) (*Attachment, error) {+	var a Attachment+	var created int64+	err := s.db.QueryRowContext(ctx, `SELECT id, repo_id, uploader_id, subject_type, subject_id, filename,+		stored_name, mime, size, created_at FROM attachments WHERE id = ?`, id).+		Scan(&a.ID, &a.RepoID, &a.UploaderID, &a.SubjectType, &a.SubjectID, &a.Filename, &a.StoredName, &a.MIME, &a.Size, &created)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	if err != nil {+		return nil, err+	}+	a.CreatedAt = fromUnix(created)+	return &a, nil+}++func (s *Store) ListAttachments(ctx context.Context, subjectType string, subjectID int64) ([]*Attachment, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT id, repo_id, uploader_id, subject_type, subject_id, filename,+		stored_name, mime, size, created_at FROM attachments+		WHERE subject_type = ? AND subject_id = ? ORDER BY created_at`, subjectType, subjectID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Attachment+	for rows.Next() {+		var a Attachment+		var created int64+		if err := rows.Scan(&a.ID, &a.RepoID, &a.UploaderID, &a.SubjectType, &a.SubjectID, &a.Filename,+			&a.StoredName, &a.MIME, &a.Size, &created); err != nil {+			return nil, err+		}+		a.CreatedAt = fromUnix(created)+		out = append(out, &a)+	}+	return out, rows.Err()+}++type Webhook struct {+	ID             int64+	RepoID         int64+	URL            string+	Secret         string+	Events         string+	Active         bool+	CreatedBy      int64+	CreatedAt      time.Time+	LastStatus     int+	LastDeliveryAt *time.Time+	Failures       int+}++func (s *Store) ListWebhooks(ctx context.Context, repoID int64) ([]*Webhook, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT id, repo_id, url, secret, events, active, created_by, created_at,+		last_status, last_delivery_at, failures FROM webhooks WHERE repo_id = ? ORDER BY id`, repoID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Webhook+	for rows.Next() {+		var w Webhook+		var active int+		var created int64+		var last sql.NullInt64+		if err := rows.Scan(&w.ID, &w.RepoID, &w.URL, &w.Secret, &w.Events, &active, &w.CreatedBy, &created,+			&w.LastStatus, &last, &w.Failures); err != nil {+			return nil, err+		}+		w.Active = intBool(active)+		w.CreatedAt = fromUnix(created)+		w.LastDeliveryAt = nullTime(last)+		out = append(out, &w)+	}+	return out, rows.Err()+}++func (s *Store) CreateWebhook(ctx context.Context, repoID, createdBy int64, url, secret, events string) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO webhooks(repo_id, url, secret, events, created_by, created_at)+		VALUES(?, ?, ?, ?, ?, ?)`, repoID, url, secret, events, createdBy, unix(time.Now()))+	return err+}++func (s *Store) DeleteWebhook(ctx context.Context, repoID, id int64) error {+	res, err := s.db.ExecContext(ctx, `DELETE FROM webhooks WHERE id = ? AND repo_id = ?`, id, repoID)+	if err != nil {+		return err+	}+	n, _ := res.RowsAffected()+	if n == 0 {+		return ErrNotFound+	}+	return nil+}++func (s *Store) RecordWebhookDelivery(ctx context.Context, id int64, status int, ok bool) {+	now := unix(time.Now())+	if ok {+		_, _ = s.db.ExecContext(ctx, `UPDATE webhooks SET last_status = ?, last_delivery_at = ?, failures = 0 WHERE id = ?`, status, now, id)+		return+	}+	_, _ = s.db.ExecContext(ctx, `UPDATE webhooks SET last_status = ?, last_delivery_at = ?, failures = failures + 1 WHERE id = ?`, status, now, id)+}++type AuditEntry struct {+	ID        int64+	UserID    *int64+	Username  string+	IP        string+	Action    string+	Detail    string+	UserAgent string+	CreatedAt time.Time+}++func (s *Store) RecordAudit(ctx context.Context, userID *int64, username, ip, action, detail, ua string) {+	var uid any+	if userID != nil {+		uid = *userID+	}+	_, _ = s.db.ExecContext(ctx, `INSERT INTO audit_log(user_id, username, ip, action, detail, user_agent, created_at)+		VALUES(?, ?, ?, ?, ?, ?, ?)`, uid, username, ip, action, detail, ua, unix(time.Now()))+}++func (s *Store) ListAudit(ctx context.Context, offset, limit int) ([]*AuditEntry, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT id, user_id, username, ip, action, detail, user_agent, created_at+		FROM audit_log ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?`, limit, offset)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*AuditEntry+	for rows.Next() {+		var e AuditEntry+		var uid sql.NullInt64+		var created int64+		if err := rows.Scan(&e.ID, &uid, &e.Username, &e.IP, &e.Action, &e.Detail, &e.UserAgent, &created); err != nil {+			return nil, err+		}+		e.UserID = nullInt64Ptr(uid)+		e.CreatedAt = fromUnix(created)+		out = append(out, &e)+	}+	return out, rows.Err()+}++func (s *Store) CountAudit(ctx context.Context) (int64, error) {+	var n int64+	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM audit_log`).Scan(&n)+	return n, err+}++func (s *Store) CountRepos(ctx context.Context) (int64, error) {+	var n int64+	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM repos`).Scan(&n)+	return n, err+}++func (s *Store) ListAllRepos(ctx context.Context, offset, limit int) ([]*Repo, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT `+repoColumns+` FROM repos ORDER BY updated_at DESC LIMIT ? OFFSET ?`, limit, offset)+	return s.scanRepos(rows, err)+}++func (s *Store) AllRepos(ctx context.Context) ([]*Repo, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT `+repoColumns+` FROM repos ORDER BY id`)+	return s.scanRepos(rows, err)+}--- /dev/null+++ b/internal/data/issues.go@@ -0,0 +1,363 @@+package data++import (+	"context"+	"database/sql"+	"time"+)++type Issue struct {+	ID            int64+	RepoID        int64+	Number        int64+	AuthorID      int64+	AuthorName    string+	AuthorDisplay string+	AuthorAvatar  string+	Title         string+	Body          string+	State         string+	IP            string+	CreatedAt     time.Time+	UpdatedAt     time.Time+	ClosedAt      *time.Time+	ClosedBy      *int64+	CommentCount  int64+}++type Pull struct {+	ID            int64+	RepoID        int64+	Number        int64+	AuthorID      int64+	AuthorName    string+	AuthorDisplay string+	AuthorAvatar  string+	Title         string+	Body          string+	BaseBranch    string+	HeadBranch    string+	BaseCommit    string+	HeadCommit    string+	State         string+	MergeCommit   string+	IP            string+	CreatedAt     time.Time+	UpdatedAt     time.Time+	MergedAt      *time.Time+	MergedBy      *int64+	ClosedAt      *time.Time+	ClosedBy      *int64+	CommentCount  int64+}++type Comment struct {+	ID            int64+	RepoID        int64+	SubjectType   string+	SubjectID     int64+	AuthorID      int64+	AuthorName    string+	AuthorDisplay string+	AuthorAvatar  string+	Body          string+	IP            string+	CreatedAt     time.Time+	UpdatedAt     time.Time+}++const issueColumns = `i.id, i.repo_id, i.number, i.author_id, u.username, u.display_name, u.avatar_file,+	i.title, i.body, i.state, i.ip, i.created_at, i.updated_at, i.closed_at, i.closed_by,+	(SELECT COUNT(*) FROM comments c WHERE c.subject_type = 'issue' AND c.subject_id = i.id)`++func scanIssue(sc interface{ Scan(...any) error }) (*Issue, error) {+	var i Issue+	var created, updated int64+	var closed sql.NullInt64+	var closedBy sql.NullInt64+	err := sc.Scan(&i.ID, &i.RepoID, &i.Number, &i.AuthorID, &i.AuthorName, &i.AuthorDisplay, &i.AuthorAvatar,+		&i.Title, &i.Body, &i.State, &i.IP, &created, &updated, &closed, &closedBy, &i.CommentCount)+	if err != nil {+		return nil, err+	}+	i.CreatedAt = fromUnix(created)+	i.UpdatedAt = fromUnix(updated)+	i.ClosedAt = nullTime(closed)+	i.ClosedBy = nullInt64Ptr(closedBy)+	return &i, nil+}++func (s *Store) CreateIssue(ctx context.Context, repoID, authorID int64, title, body, ip string) (*Issue, error) {+	now := unix(time.Now())+	tx, err := s.db.BeginTx(ctx, nil)+	if err != nil {+		return nil, err+	}+	defer tx.Rollback()+	if _, err := tx.ExecContext(ctx, `UPDATE repos SET next_issue_number = next_issue_number + 1, updated_at = ? WHERE id = ?`, now, repoID); err != nil {+		return nil, err+	}+	var number int64+	if err := tx.QueryRowContext(ctx, `SELECT next_issue_number - 1 FROM repos WHERE id = ?`, repoID).Scan(&number); err != nil {+		return nil, err+	}+	res, err := tx.ExecContext(ctx, `INSERT INTO issues(repo_id, number, author_id, title, body, ip, created_at, updated_at)+		VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, repoID, number, authorID, title, body, ip, now, now)+	if err != nil {+		return nil, err+	}+	id, _ := res.LastInsertId()+	if err := tx.Commit(); err != nil {+		return nil, err+	}+	return s.GetIssueByID(ctx, id)+}++func (s *Store) GetIssueByID(ctx context.Context, id int64) (*Issue, error) {+	row := s.db.QueryRowContext(ctx, `SELECT `+issueColumns+` FROM issues i JOIN users u ON u.id = i.author_id WHERE i.id = ?`, id)+	i, err := scanIssue(row)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	return i, err+}++func (s *Store) GetIssue(ctx context.Context, repoID, number int64) (*Issue, error) {+	row := s.db.QueryRowContext(ctx, `SELECT `+issueColumns+` FROM issues i JOIN users u ON u.id = i.author_id+		WHERE i.repo_id = ? AND i.number = ?`, repoID, number)+	i, err := scanIssue(row)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	return i, err+}++func (s *Store) ListIssues(ctx context.Context, repoID int64, state string, offset, limit int) ([]*Issue, error) {+	query := `SELECT ` + issueColumns + ` FROM issues i JOIN users u ON u.id = i.author_id WHERE i.repo_id = ?`+	args := []any{repoID}+	if state == "open" || state == "closed" {+		query += ` AND i.state = ?`+		args = append(args, state)+	}+	query += ` ORDER BY i.state = 'open' DESC, i.updated_at DESC LIMIT ? OFFSET ?`+	args = append(args, limit, offset)+	rows, err := s.db.QueryContext(ctx, query, args...)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Issue+	for rows.Next() {+		i, err := scanIssue(rows)+		if err != nil {+			return nil, err+		}+		out = append(out, i)+	}+	return out, rows.Err()+}++func (s *Store) CountIssues(ctx context.Context, repoID int64, state string) (int64, error) {+	query := `SELECT COUNT(*) FROM issues WHERE repo_id = ?`+	args := []any{repoID}+	if state == "open" || state == "closed" {+		query += ` AND state = ?`+		args = append(args, state)+	}+	var n int64+	err := s.db.QueryRowContext(ctx, query, args...).Scan(&n)+	return n, err+}++func (s *Store) SetIssueState(ctx context.Context, id int64, state string, by int64) error {+	now := unix(time.Now())+	if state == "closed" {+		_, err := s.db.ExecContext(ctx, `UPDATE issues SET state = 'closed', updated_at = ?, closed_at = ?, closed_by = ? WHERE id = ?`, now, now, by, id)+		return err+	}+	_, err := s.db.ExecContext(ctx, `UPDATE issues SET state = 'open', updated_at = ?, closed_at = NULL, closed_by = NULL WHERE id = ?`, now, id)+	return err+}++const pullColumns = `p.id, p.repo_id, p.number, p.author_id, u.username, u.display_name, u.avatar_file,+	p.title, p.body, p.base_branch, p.head_branch, p.base_commit, p.head_commit, p.state, p.merge_commit,+	p.ip, p.created_at, p.updated_at, p.merged_at, p.merged_by, p.closed_at, p.closed_by,+	(SELECT COUNT(*) FROM comments c WHERE c.subject_type = 'pull' AND c.subject_id = p.id)`++func scanPull(sc interface{ Scan(...any) error }) (*Pull, error) {+	var p Pull+	var created, updated int64+	var mergedAt, mergedBy, closedAt, closedBy sql.NullInt64+	err := sc.Scan(&p.ID, &p.RepoID, &p.Number, &p.AuthorID, &p.AuthorName, &p.AuthorDisplay, &p.AuthorAvatar,+		&p.Title, &p.Body, &p.BaseBranch, &p.HeadBranch, &p.BaseCommit, &p.HeadCommit, &p.State, &p.MergeCommit,+		&p.IP, &created, &updated, &mergedAt, &mergedBy, &closedAt, &closedBy, &p.CommentCount)+	if err != nil {+		return nil, err+	}+	p.CreatedAt = fromUnix(created)+	p.UpdatedAt = fromUnix(updated)+	p.MergedAt = nullTime(mergedAt)+	p.MergedBy = nullInt64Ptr(mergedBy)+	p.ClosedAt = nullTime(closedAt)+	p.ClosedBy = nullInt64Ptr(closedBy)+	return &p, nil+}++func (s *Store) CreatePull(ctx context.Context, repoID, authorID int64, title, body, base, head, baseCommit, headCommit, ip string) (*Pull, error) {+	now := unix(time.Now())+	tx, err := s.db.BeginTx(ctx, nil)+	if err != nil {+		return nil, err+	}+	defer tx.Rollback()+	if _, err := tx.ExecContext(ctx, `UPDATE repos SET next_pr_number = next_pr_number + 1, updated_at = ? WHERE id = ?`, now, repoID); err != nil {+		return nil, err+	}+	var number int64+	if err := tx.QueryRowContext(ctx, `SELECT next_pr_number - 1 FROM repos WHERE id = ?`, repoID).Scan(&number); err != nil {+		return nil, err+	}+	res, err := tx.ExecContext(ctx, `INSERT INTO pulls(repo_id, number, author_id, title, body, base_branch, head_branch,+		base_commit, head_commit, ip, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,+		repoID, number, authorID, title, body, base, head, baseCommit, headCommit, ip, now, now)+	if err != nil {+		return nil, err+	}+	id, _ := res.LastInsertId()+	if err := tx.Commit(); err != nil {+		return nil, err+	}+	return s.GetPullByID(ctx, id)+}++func (s *Store) GetPullByID(ctx context.Context, id int64) (*Pull, error) {+	row := s.db.QueryRowContext(ctx, `SELECT `+pullColumns+` FROM pulls p JOIN users u ON u.id = p.author_id WHERE p.id = ?`, id)+	p, err := scanPull(row)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	return p, err+}++func (s *Store) GetPull(ctx context.Context, repoID, number int64) (*Pull, error) {+	row := s.db.QueryRowContext(ctx, `SELECT `+pullColumns+` FROM pulls p JOIN users u ON u.id = p.author_id+		WHERE p.repo_id = ? AND p.number = ?`, repoID, number)+	p, err := scanPull(row)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	return p, err+}++func (s *Store) ListPulls(ctx context.Context, repoID int64, state string, offset, limit int) ([]*Pull, error) {+	query := `SELECT ` + pullColumns + ` FROM pulls p JOIN users u ON u.id = p.author_id WHERE p.repo_id = ?`+	args := []any{repoID}+	if state == "open" || state == "closed" || state == "merged" {+		query += ` AND p.state = ?`+		args = append(args, state)+	}+	query += ` ORDER BY p.state = 'open' DESC, p.updated_at DESC LIMIT ? OFFSET ?`+	args = append(args, limit, offset)+	rows, err := s.db.QueryContext(ctx, query, args...)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Pull+	for rows.Next() {+		p, err := scanPull(rows)+		if err != nil {+			return nil, err+		}+		out = append(out, p)+	}+	return out, rows.Err()+}++func (s *Store) CountPulls(ctx context.Context, repoID int64, state string) (int64, error) {+	query := `SELECT COUNT(*) FROM pulls WHERE repo_id = ?`+	args := []any{repoID}+	if state == "open" || state == "closed" || state == "merged" {+		query += ` AND state = ?`+		args = append(args, state)+	}+	var n int64+	err := s.db.QueryRowContext(ctx, query, args...).Scan(&n)+	return n, err+}++func (s *Store) SetPullState(ctx context.Context, id int64, state string, by int64) error {+	now := unix(time.Now())+	switch state {+	case "closed":+		_, err := s.db.ExecContext(ctx, `UPDATE pulls SET state = 'closed', updated_at = ?, closed_at = ?, closed_by = ? WHERE id = ?`, now, now, by, id)+		return err+	case "open":+		_, err := s.db.ExecContext(ctx, `UPDATE pulls SET state = 'open', updated_at = ?, closed_at = NULL, closed_by = NULL, merged_at = NULL, merged_by = NULL, merge_commit = '' WHERE id = ?`, now, id)+		return err+	}+	return nil+}++func (s *Store) MarkPullMerged(ctx context.Context, id int64, mergeCommit string, by int64) error {+	now := unix(time.Now())+	_, err := s.db.ExecContext(ctx, `UPDATE pulls SET state = 'merged', merge_commit = ?, merged_at = ?, merged_by = ?, updated_at = ? WHERE id = ?`,+		mergeCommit, now, by, now, id)+	return err+}++func (s *Store) AddComment(ctx context.Context, repoID int64, subjectType string, subjectID, authorID int64, body, ip string) (*Comment, error) {+	now := unix(time.Now())+	res, err := s.db.ExecContext(ctx, `INSERT INTO comments(repo_id, subject_type, subject_id, author_id, body, ip, created_at, updated_at)+		VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, repoID, subjectType, subjectID, authorID, body, ip, now, now)+	if err != nil {+		return nil, err+	}+	id, _ := res.LastInsertId()+	return s.GetComment(ctx, id)+}++func (s *Store) GetComment(ctx context.Context, id int64) (*Comment, error) {+	var c Comment+	var created, updated int64+	err := s.db.QueryRowContext(ctx, `+		SELECT c.id, c.repo_id, c.subject_type, c.subject_id, c.author_id, u.username, u.display_name, u.avatar_file,+			c.body, c.ip, c.created_at, c.updated_at+		FROM comments c JOIN users u ON u.id = c.author_id WHERE c.id = ?`, id).+		Scan(&c.ID, &c.RepoID, &c.SubjectType, &c.SubjectID, &c.AuthorID, &c.AuthorName, &c.AuthorDisplay,+			&c.AuthorAvatar, &c.Body, &c.IP, &created, &updated)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	if err != nil {+		return nil, err+	}+	c.CreatedAt = fromUnix(created)+	c.UpdatedAt = fromUnix(updated)+	return &c, nil+}++func (s *Store) ListComments(ctx context.Context, subjectType string, subjectID int64) ([]*Comment, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT c.id, c.repo_id, c.subject_type, c.subject_id, c.author_id, u.username, u.display_name, u.avatar_file,+			c.body, c.ip, c.created_at, c.updated_at+		FROM comments c JOIN users u ON u.id = c.author_id+		WHERE c.subject_type = ? AND c.subject_id = ? ORDER BY c.created_at, c.id`, subjectType, subjectID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Comment+	for rows.Next() {+		var c Comment+		var created, updated int64+		if err := rows.Scan(&c.ID, &c.RepoID, &c.SubjectType, &c.SubjectID, &c.AuthorID, &c.AuthorName,+			&c.AuthorDisplay, &c.AuthorAvatar, &c.Body, &c.IP, &created, &updated); err != nil {+			return nil, err+		}+		c.CreatedAt = fromUnix(created)+		c.UpdatedAt = fromUnix(updated)+		out = append(out, &c)+	}+	return out, rows.Err()+}--- /dev/null+++ b/internal/data/orgs.go@@ -0,0 +1,284 @@+package data++import (+	"context"+	"database/sql"+	"time"+)++type Org struct {+	ID          int64+	Name        string+	DisplayName string+	Description string+	AvatarFile  string+	OwnerID     int64+	CreatedAt   time.Time+	UpdatedAt   time.Time+	MemberCount int64+	RepoCount   int64+}++type OrgMember struct {+	OrgID       int64+	UserID      int64+	Username    string+	DisplayName string+	AvatarFile  string+	Role        string+	CreatedAt   time.Time+}++type Team struct {+	ID          int64+	OrgID       int64+	Name        string+	Description string+	CreatedAt   time.Time+	MemberCount int64+}++type TeamMember struct {+	TeamID      int64+	UserID      int64+	Username    string+	DisplayName string+	AvatarFile  string+	CreatedAt   time.Time+}++func (s *Store) CreateOrg(ctx context.Context, name, display, description string, ownerID int64) (*Org, error) {+	now := unix(time.Now())+	tx, err := s.db.BeginTx(ctx, nil)+	if err != nil {+		return nil, err+	}+	defer tx.Rollback()+	res, err := tx.ExecContext(ctx, `INSERT INTO orgs(name, display_name, description, owner_id, created_at, updated_at)+		VALUES(?, ?, ?, ?, ?, ?)`, name, display, description, ownerID, now, now)+	if err != nil {+		if isUnique(err) {+			return nil, ErrConflict+		}+		return nil, err+	}+	id, _ := res.LastInsertId()+	if _, err := tx.ExecContext(ctx, `INSERT INTO org_members(org_id, user_id, role, created_at) VALUES(?, ?, 'owner', ?)`, id, ownerID, now); err != nil {+		return nil, err+	}+	if err := tx.Commit(); err != nil {+		return nil, err+	}+	return s.GetOrgByID(ctx, id)+}++func (s *Store) GetOrgByID(ctx context.Context, id int64) (*Org, error) {+	return s.scanOrg(s.db.QueryRowContext(ctx, `+		SELECT o.id, o.name, o.display_name, o.description, o.avatar_file, o.owner_id, o.created_at, o.updated_at,+			(SELECT COUNT(*) FROM org_members m WHERE m.org_id = o.id),+			(SELECT COUNT(*) FROM repos r WHERE r.owner_type = 'org' AND r.owner_id = o.id)+		FROM orgs o WHERE o.id = ?`, id))+}++func (s *Store) GetOrgByName(ctx context.Context, name string) (*Org, error) {+	return s.scanOrg(s.db.QueryRowContext(ctx, `+		SELECT o.id, o.name, o.display_name, o.description, o.avatar_file, o.owner_id, o.created_at, o.updated_at,+			(SELECT COUNT(*) FROM org_members m WHERE m.org_id = o.id),+			(SELECT COUNT(*) FROM repos r WHERE r.owner_type = 'org' AND r.owner_id = o.id)+		FROM orgs o WHERE o.name = ? COLLATE NOCASE`, name))+}++func (s *Store) scanOrg(row *sql.Row) (*Org, error) {+	var o Org+	var created, updated int64+	err := row.Scan(&o.ID, &o.Name, &o.DisplayName, &o.Description, &o.AvatarFile, &o.OwnerID, &created, &updated, &o.MemberCount, &o.RepoCount)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	if err != nil {+		return nil, err+	}+	o.CreatedAt = fromUnix(created)+	o.UpdatedAt = fromUnix(updated)+	return &o, nil+}++func (s *Store) UpdateOrg(ctx context.Context, id int64, display, description string) error {+	_, err := s.db.ExecContext(ctx, `UPDATE orgs SET display_name = ?, description = ?, updated_at = ? WHERE id = ?`,+		display, description, unix(time.Now()), id)+	return err+}++func (s *Store) OrgRole(ctx context.Context, orgID, userID int64) (string, error) {+	var role string+	err := s.db.QueryRowContext(ctx, `SELECT role FROM org_members WHERE org_id = ? AND user_id = ?`, orgID, userID).Scan(&role)+	if err == sql.ErrNoRows {+		return "", nil+	}+	return role, err+}++func (s *Store) ListOrgMembers(ctx context.Context, orgID int64) ([]*OrgMember, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT m.org_id, m.user_id, u.username, u.display_name, u.avatar_file, m.role, m.created_at+		FROM org_members m JOIN users u ON u.id = m.user_id+		WHERE m.org_id = ? ORDER BY+			CASE m.role WHEN 'owner' THEN 0 WHEN 'admin' THEN 1 ELSE 2 END,+			u.username COLLATE NOCASE`, orgID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*OrgMember+	for rows.Next() {+		var m OrgMember+		var created int64+		if err := rows.Scan(&m.OrgID, &m.UserID, &m.Username, &m.DisplayName, &m.AvatarFile, &m.Role, &created); err != nil {+			return nil, err+		}+		m.CreatedAt = fromUnix(created)+		out = append(out, &m)+	}+	return out, rows.Err()+}++func (s *Store) AddOrgMember(ctx context.Context, orgID, userID int64, role string) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO org_members(org_id, user_id, role, created_at) VALUES(?, ?, ?, ?)+		ON CONFLICT(org_id, user_id) DO UPDATE SET role = excluded.role`, orgID, userID, role, unix(time.Now()))+	if err != nil && isUnique(err) {+		return ErrConflict+	}+	return err+}++func (s *Store) RemoveOrgMember(ctx context.Context, orgID, userID int64) error {+	var owners int+	_ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM org_members WHERE org_id = ? AND role = 'owner'`, orgID).Scan(&owners)+	var isOwner int+	_ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM org_members WHERE org_id = ? AND user_id = ? AND role = 'owner'`, orgID, userID).Scan(&isOwner)+	if isOwner == 1 && owners <= 1 {+		return ErrConflict+	}+	_, err := s.db.ExecContext(ctx, `DELETE FROM org_members WHERE org_id = ? AND user_id = ?`, orgID, userID)+	return err+}++func (s *Store) ListTeams(ctx context.Context, orgID int64) ([]*Team, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT t.id, t.org_id, t.name, t.description, t.created_at,+			(SELECT COUNT(*) FROM team_members tm WHERE tm.team_id = t.id)+		FROM teams t WHERE t.org_id = ? ORDER BY t.name COLLATE NOCASE`, orgID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Team+	for rows.Next() {+		var t Team+		var created int64+		if err := rows.Scan(&t.ID, &t.OrgID, &t.Name, &t.Description, &created, &t.MemberCount); err != nil {+			return nil, err+		}+		t.CreatedAt = fromUnix(created)+		out = append(out, &t)+	}+	return out, rows.Err()+}++func (s *Store) GetTeam(ctx context.Context, orgID, teamID int64) (*Team, error) {+	var t Team+	var created int64+	err := s.db.QueryRowContext(ctx, `SELECT id, org_id, name, description, created_at FROM teams WHERE id = ? AND org_id = ?`, teamID, orgID).+		Scan(&t.ID, &t.OrgID, &t.Name, &t.Description, &created)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	if err != nil {+		return nil, err+	}+	t.CreatedAt = fromUnix(created)+	return &t, nil+}++func (s *Store) CreateTeam(ctx context.Context, orgID int64, name, description string) (*Team, error) {+	res, err := s.db.ExecContext(ctx, `INSERT INTO teams(org_id, name, description, created_at) VALUES(?, ?, ?, ?)`,+		orgID, name, description, unix(time.Now()))+	if err != nil {+		if isUnique(err) {+			return nil, ErrConflict+		}+		return nil, err+	}+	id, _ := res.LastInsertId()+	return s.GetTeam(ctx, orgID, id)+}++func (s *Store) DeleteTeam(ctx context.Context, orgID, teamID int64) error {+	res, err := s.db.ExecContext(ctx, `DELETE FROM teams WHERE id = ? AND org_id = ?`, teamID, orgID)+	if err != nil {+		return err+	}+	n, _ := res.RowsAffected()+	if n == 0 {+		return ErrNotFound+	}+	return nil+}++func (s *Store) ListTeamMembers(ctx context.Context, teamID int64) ([]*TeamMember, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT tm.team_id, tm.user_id, u.username, u.display_name, u.avatar_file, tm.created_at+		FROM team_members tm JOIN users u ON u.id = tm.user_id+		WHERE tm.team_id = ? ORDER BY u.username COLLATE NOCASE`, teamID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*TeamMember+	for rows.Next() {+		var m TeamMember+		var created int64+		if err := rows.Scan(&m.TeamID, &m.UserID, &m.Username, &m.DisplayName, &m.AvatarFile, &created); err != nil {+			return nil, err+		}+		m.CreatedAt = fromUnix(created)+		out = append(out, &m)+	}+	return out, rows.Err()+}++func (s *Store) AddTeamMember(ctx context.Context, teamID, userID int64) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO team_members(team_id, user_id, created_at) VALUES(?, ?, ?)+		ON CONFLICT(team_id, user_id) DO NOTHING`, teamID, userID, unix(time.Now()))+	return err+}++func (s *Store) RemoveTeamMember(ctx context.Context, teamID, userID int64) error {+	_, err := s.db.ExecContext(ctx, `DELETE FROM team_members WHERE team_id = ? AND user_id = ?`, teamID, userID)+	return err+}++func (s *Store) ListUserOrgs(ctx context.Context, userID int64) ([]*Org, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT o.id, o.name, o.display_name, o.description, o.avatar_file, o.owner_id, o.created_at, o.updated_at,+			(SELECT COUNT(*) FROM org_members m2 WHERE m2.org_id = o.id),+			(SELECT COUNT(*) FROM repos r WHERE r.owner_type = 'org' AND r.owner_id = o.id)+		FROM orgs o JOIN org_members m ON m.org_id = o.id+		WHERE m.user_id = ? ORDER BY o.name COLLATE NOCASE`, userID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Org+	for rows.Next() {+		var o Org+		var created, updated int64+		if err := rows.Scan(&o.ID, &o.Name, &o.DisplayName, &o.Description, &o.AvatarFile, &o.OwnerID, &created, &updated, &o.MemberCount, &o.RepoCount); err != nil {+			return nil, err+		}+		o.CreatedAt = fromUnix(created)+		o.UpdatedAt = fromUnix(updated)+		out = append(out, &o)+	}+	return out, rows.Err()+}--- /dev/null+++ b/internal/data/repos.go@@ -0,0 +1,533 @@+package data++import (+	"context"+	"database/sql"+	"time"+)++type Repo struct {+	ID            int64+	OwnerType     string+	OwnerID       int64+	OwnerName     string+	Name          string+	DisplayName   string+	Description   string+	Visibility    string+	DefaultBranch string+	Archived      bool+	NextIssue     int64+	NextPR        int64+	CreatedAt     time.Time+	UpdatedAt     time.Time+	Stars         int64+	IsStarred     bool+}++type Collaborator struct {+	RepoID      int64+	UserID      int64+	Username    string+	DisplayName string+	AvatarFile  string+	Role        string+	CreatedAt   time.Time+}++type RepoTeam struct {+	RepoID     int64+	TeamID     int64+	TeamName   string+	OrgName    string+	Permission string+	CreatedAt  time.Time+}++type AccessUser struct {+	UserID int64+	Role   string+}++type Permissions struct {+	Role      string+	CanView   bool+	CanWrite  bool+	CanAdmin  bool+	Anonymous bool+}++const repoColumns = `id, owner_type, owner_id, owner_name, name, display_name, description,+	visibility, default_branch, archived, next_issue_number, next_pr_number, created_at, updated_at`++func scanRepo(sc interface{ Scan(...any) error }) (*Repo, error) {+	var r Repo+	var archived int+	var created, updated int64+	err := sc.Scan(&r.ID, &r.OwnerType, &r.OwnerID, &r.OwnerName, &r.Name, &r.DisplayName,+		&r.Description, &r.Visibility, &r.DefaultBranch, &archived, &r.NextIssue, &r.NextPR,+		&created, &updated)+	if err != nil {+		return nil, err+	}+	r.Archived = intBool(archived)+	r.CreatedAt = fromUnix(created)+	r.UpdatedAt = fromUnix(updated)+	return &r, nil+}++func (s *Store) CreateRepo(ctx context.Context, ownerType string, ownerID int64, ownerName, name, display, description, visibility string) (*Repo, error) {+	now := unix(time.Now())+	res, err := s.db.ExecContext(ctx, `INSERT INTO repos(owner_type, owner_id, owner_name, name, display_name, description, visibility, default_branch, created_at, updated_at)+		VALUES(?, ?, ?, ?, ?, ?, ?, 'main', ?, ?)`, ownerType, ownerID, ownerName, name, display, description, visibility, now, now)+	if err != nil {+		if isUnique(err) {+			return nil, ErrConflict+		}+		return nil, err+	}+	id, _ := res.LastInsertId()+	return s.GetRepoByID(ctx, id)+}++func (s *Store) GetRepoByID(ctx context.Context, id int64) (*Repo, error) {+	r, err := scanRepo(s.db.QueryRowContext(ctx, `SELECT `+repoColumns+` FROM repos WHERE id = ?`, id))+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	if err != nil {+		return nil, err+	}+	_ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM stars WHERE repo_id = ?`, id).Scan(&r.Stars)+	return r, nil+}++func (s *Store) GetRepo(ctx context.Context, owner, name string) (*Repo, error) {+	r, err := scanRepo(s.db.QueryRowContext(ctx, `SELECT `+repoColumns+` FROM repos WHERE owner_name = ? COLLATE NOCASE AND name = ? COLLATE NOCASE`, owner, name))+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	if err != nil {+		return nil, err+	}+	_ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM stars WHERE repo_id = ?`, r.ID).Scan(&r.Stars)+	return r, nil+}++func (s *Store) UpdateRepo(ctx context.Context, id int64, display, description, visibility, defaultBranch string, archived bool) error {+	_, err := s.db.ExecContext(ctx, `UPDATE repos SET display_name = ?, description = ?, visibility = ?, default_branch = ?, archived = ?, updated_at = ? WHERE id = ?`,+		display, description, visibility, defaultBranch, boolInt(archived), unix(time.Now()), id)+	return err+}++func (s *Store) TouchRepo(ctx context.Context, id int64) {+	_, _ = s.db.ExecContext(ctx, `UPDATE repos SET updated_at = ? WHERE id = ?`, unix(time.Now()), id)+}++func (s *Store) DeleteRepo(ctx context.Context, id int64) error {+	_, err := s.db.ExecContext(ctx, `DELETE FROM repos WHERE id = ?`, id)+	return err+}++func (s *Store) ListPublicRepos(ctx context.Context, q string, offset, limit int) ([]*Repo, error) {+	pattern := "%" + q + "%"+	rows, err := s.db.QueryContext(ctx, `SELECT `+repoColumns+` FROM repos+		WHERE visibility = 'public' AND archived = 0 AND (name LIKE ? OR owner_name LIKE ? OR description LIKE ?)+		ORDER BY updated_at DESC LIMIT ? OFFSET ?`, pattern, pattern, pattern, limit, offset)+	return s.scanRepos(rows, err)+}++func (s *Store) CountPublicRepos(ctx context.Context, q string) (int64, error) {+	pattern := "%" + q + "%"+	var n int64+	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM repos+		WHERE visibility = 'public' AND archived = 0 AND (name LIKE ? OR owner_name LIKE ? OR description LIKE ?)`,+		pattern, pattern, pattern).Scan(&n)+	return n, err+}++func (s *Store) ListOwnerRepos(ctx context.Context, ownerType string, ownerID int64, includePrivate bool) ([]*Repo, error) {+	query := `SELECT ` + repoColumns + ` FROM repos WHERE owner_type = ? AND owner_id = ?`+	if !includePrivate {+		query += ` AND visibility = 'public'`+	}+	query += ` ORDER BY updated_at DESC`+	rows, err := s.db.QueryContext(ctx, query, ownerType, ownerID)+	return s.scanRepos(rows, err)+}++func (s *Store) ListStarredRepos(ctx context.Context, userID int64, includePrivate bool) ([]*Repo, error) {+	query := `SELECT r.id, r.owner_type, r.owner_id, r.owner_name, r.name, r.display_name,+		r.description, r.visibility, r.default_branch, r.archived, r.next_issue_number, r.next_pr_number, r.created_at, r.updated_at+		FROM repos r JOIN stars st ON st.repo_id = r.id WHERE st.user_id = ?`+	if !includePrivate {+		query += ` AND r.visibility = 'public'`+	}+	query += ` ORDER BY st.created_at DESC`+	rows, err := s.db.QueryContext(ctx, query, userID)+	return s.scanRepos(rows, err)+}++func (s *Store) ListAccessibleRepos(ctx context.Context, userID int64, offset, limit int) ([]*Repo, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT DISTINCT `+prefixColumns("r")+` FROM repos r+		LEFT JOIN repo_collaborators c ON c.repo_id = r.id AND c.user_id = ?+		LEFT JOIN repo_teams rt ON rt.repo_id = r.id+		LEFT JOIN team_members tm ON tm.team_id = rt.team_id AND tm.user_id = ?+		WHERE r.visibility = 'public'+		   OR (r.owner_type = 'user' AND r.owner_id = ?)+		   OR (r.owner_type = 'org' AND r.owner_id IN (SELECT org_id FROM org_members WHERE user_id = ?))+		   OR c.user_id IS NOT NULL OR tm.user_id IS NOT NULL+		ORDER BY r.updated_at DESC LIMIT ? OFFSET ?`, userID, userID, userID, userID, limit, offset)+	return s.scanRepos(rows, err)+}++func prefixColumns(alias string) string {+	if alias == "" {+		return repoColumns+	}+	cols := []string{"id", "owner_type", "owner_id", "owner_name", "name", "display_name",+		"description", "visibility", "default_branch", "archived", "next_issue_number",+		"next_pr_number", "created_at", "updated_at"}+	out := ""+	for i, c := range cols {+		if i > 0 {+			out += ", "+		}+		out += alias + "." + c+	}+	return out+}++func (s *Store) scanRepos(rows *sql.Rows, err error) ([]*Repo, error) {+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Repo+	for rows.Next() {+		r, err := scanRepo(rows)+		if err != nil {+			return nil, err+		}+		out = append(out, r)+	}+	return out, rows.Err()+}++func (s *Store) StarCount(ctx context.Context, repoID int64) (int64, error) {+	var n int64+	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM stars WHERE repo_id = ?`, repoID).Scan(&n)+	return n, err+}++func (s *Store) IsStarred(ctx context.Context, repoID, userID int64) bool {+	var n int+	_ = s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM stars WHERE repo_id = ? AND user_id = ?`, repoID, userID).Scan(&n)+	return n > 0+}++func (s *Store) ToggleStar(ctx context.Context, repoID, userID int64) (bool, error) {+	now := unix(time.Now())+	res, err := s.db.ExecContext(ctx, `DELETE FROM stars WHERE repo_id = ? AND user_id = ?`, repoID, userID)+	if err != nil {+		return false, err+	}+	n, _ := res.RowsAffected()+	if n > 0 {+		return false, nil+	}+	_, err = s.db.ExecContext(ctx, `INSERT INTO stars(repo_id, user_id, created_at) VALUES(?, ?, ?)`, repoID, userID, now)+	return err == nil, err+}++func (s *Store) ListStargazers(ctx context.Context, repoID int64, limit int) ([]*User, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT `+prefixUserColumns("u")+` FROM users u JOIN stars st ON st.user_id = u.id+		WHERE st.repo_id = ? ORDER BY st.created_at DESC LIMIT ?`, repoID, limit)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*User+	for rows.Next() {+		u, err := scanUser(rows)+		if err != nil {+			return nil, err+		}+		out = append(out, u)+	}+	return out, rows.Err()+}++func prefixUserColumns(alias string) string {+	cols := []string{"id", "username", "display_name", "email", "password_hash", "bio", "avatar_file",+		"is_admin", "is_active", "signup_ip", "last_ip", "created_at", "updated_at", "last_login_at"}+	out := ""+	for i, c := range cols {+		if i > 0 {+			out += ", "+		}+		out += alias + "." + c+	}+	return out+}++func roleRank(role string) int {+	switch role {+	case "admin":+		return 3+	case "write":+		return 2+	case "read":+		return 1+	default:+		return 0+	}+}++// Permissions computes the effective web permissions for a repository.+func (s *Store) Permissions(ctx context.Context, repo *Repo, user *User) (Permissions, error) {+	p := Permissions{Role: "", Anonymous: user == nil}+	if repo.Visibility == "public" {+		p.Role = "read"+		p.CanView = true+	}+	if user == nil {+		return p, nil+	}+	if user.IsAdmin {+		p.Role = "admin"+		p.CanView, p.CanWrite, p.CanAdmin = true, true, true+		return p, nil+	}+	role := ""+	if repo.OwnerType == "user" && repo.OwnerID == user.ID {+		role = "admin"+	}+	if repo.OwnerType == "org" {+		var orgRole string+		_ = s.db.QueryRowContext(ctx, `SELECT role FROM org_members WHERE org_id = ? AND user_id = ?`, repo.OwnerID, user.ID).Scan(&orgRole)+		if orgRole == "owner" || orgRole == "admin" {+			role = "admin"+		}+	}+	var direct string+	_ = s.db.QueryRowContext(ctx, `SELECT role FROM repo_collaborators WHERE repo_id = ? AND user_id = ?`, repo.ID, user.ID).Scan(&direct)+	if roleRank(direct) > roleRank(role) {+		role = direct+	}+	rows, err := s.db.QueryContext(ctx, `+		SELECT rt.permission FROM repo_teams rt JOIN team_members tm ON tm.team_id = rt.team_id+		WHERE rt.repo_id = ? AND tm.user_id = ?`, repo.ID, user.ID)+	if err != nil {+		return p, err+	}+	for rows.Next() {+		var perm string+		if err := rows.Scan(&perm); err != nil {+			rows.Close()+			return p, err+		}+		if roleRank(perm) > roleRank(role) {+			role = perm+		}+	}+	rows.Close()+	if roleRank(role) > roleRank(p.Role) {+		p.Role = role+	}+	p.CanView = role != ""+	p.CanWrite = roleRank(role) >= 2+	p.CanAdmin = roleRank(role) >= 3+	return p, nil+}++func (s *Store) ListCollaborators(ctx context.Context, repoID int64) ([]*Collaborator, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT c.repo_id, c.user_id, u.username, u.display_name, u.avatar_file, c.role, c.created_at+		FROM repo_collaborators c JOIN users u ON u.id = c.user_id+		WHERE c.repo_id = ? ORDER BY u.username COLLATE NOCASE`, repoID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Collaborator+	for rows.Next() {+		var c Collaborator+		var created int64+		if err := rows.Scan(&c.RepoID, &c.UserID, &c.Username, &c.DisplayName, &c.AvatarFile, &c.Role, &created); err != nil {+			return nil, err+		}+		c.CreatedAt = fromUnix(created)+		out = append(out, &c)+	}+	return out, rows.Err()+}++func (s *Store) SetCollaborator(ctx context.Context, repoID, userID int64, role string) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO repo_collaborators(repo_id, user_id, role, created_at) VALUES(?, ?, ?, ?)+		ON CONFLICT(repo_id, user_id) DO UPDATE SET role = excluded.role`, repoID, userID, role, unix(time.Now()))+	return err+}++func (s *Store) RemoveCollaborator(ctx context.Context, repoID, userID int64) error {+	_, err := s.db.ExecContext(ctx, `DELETE FROM repo_collaborators WHERE repo_id = ? AND user_id = ?`, repoID, userID)+	return err+}++func (s *Store) ListRepoTeams(ctx context.Context, repoID int64) ([]*RepoTeam, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT rt.repo_id, rt.team_id, t.name, o.name, rt.permission, rt.created_at+		FROM repo_teams rt JOIN teams t ON t.id = rt.team_id JOIN orgs o ON o.id = t.org_id+		WHERE rt.repo_id = ? ORDER BY o.name, t.name`, repoID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*RepoTeam+	for rows.Next() {+		var t RepoTeam+		var created int64+		if err := rows.Scan(&t.RepoID, &t.TeamID, &t.TeamName, &t.OrgName, &t.Permission, &created); err != nil {+			return nil, err+		}+		t.CreatedAt = fromUnix(created)+		out = append(out, &t)+	}+	return out, rows.Err()+}++func (s *Store) SetRepoTeam(ctx context.Context, repoID, teamID int64, permission string) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO repo_teams(repo_id, team_id, permission, created_at) VALUES(?, ?, ?, ?)+		ON CONFLICT(repo_id, team_id) DO UPDATE SET permission = excluded.permission`, repoID, teamID, permission, unix(time.Now()))+	return err+}++func (s *Store) RemoveRepoTeam(ctx context.Context, repoID, teamID int64) error {+	_, err := s.db.ExecContext(ctx, `DELETE FROM repo_teams WHERE repo_id = ? AND team_id = ?`, repoID, teamID)+	return err+}++// AccessUsers computes the union of users and roles that should be written into+// the served repository's .veins/access file.+func (s *Store) AccessUsers(ctx context.Context, repo *Repo) ([]AccessUser, error) {+	roles := map[int64]string{}+	set := func(id int64, role string) {+		if id == 0 || role == "" {+			return+		}+		if roleRank(role) > roleRank(roles[id]) {+			roles[id] = role+		}+	}+	// Site administrators retain write access for support and moderation.+	rows, err := s.db.QueryContext(ctx, `SELECT id FROM users WHERE is_active = 1 AND is_admin = 1`)+	if err != nil {+		return nil, err+	}+	for rows.Next() {+		var id int64+		if err := rows.Scan(&id); err != nil {+			rows.Close()+			return nil, err+		}+		set(id, "write")+	}+	rows.Close()+	if repo.OwnerType == "user" {+		set(repo.OwnerID, "write")+	} else {+		rows, err = s.db.QueryContext(ctx, `SELECT user_id, role FROM org_members WHERE org_id = ? AND role IN ('owner', 'admin')`, repo.OwnerID)+		if err != nil {+			return nil, err+		}+		for rows.Next() {+			var id int64+			var role string+			if err := rows.Scan(&id, &role); err != nil {+				rows.Close()+				return nil, err+			}+			set(id, "write")+		}+		rows.Close()+	}+	rows, err = s.db.QueryContext(ctx, `SELECT user_id, role FROM repo_collaborators WHERE repo_id = ?`, repo.ID)+	if err != nil {+		return nil, err+	}+	for rows.Next() {+		var id int64+		var role string+		if err := rows.Scan(&id, &role); err != nil {+			rows.Close()+			return nil, err+		}+		set(id, role)+	}+	rows.Close()+	rows, err = s.db.QueryContext(ctx, `+		SELECT tm.user_id, rt.permission FROM repo_teams rt+		JOIN team_members tm ON tm.team_id = rt.team_id WHERE rt.repo_id = ?`, repo.ID)+	if err != nil {+		return nil, err+	}+	for rows.Next() {+		var id int64+		var role string+		if err := rows.Scan(&id, &role); err != nil {+			rows.Close()+			return nil, err+		}+		set(id, role)+	}+	rows.Close()+	out := make([]AccessUser, 0, len(roles))+	for id, role := range roles {+		out = append(out, AccessUser{UserID: id, Role: role})+	}+	return out, nil+}++type Activity struct {+	ID        int64+	RepoID    int64+	ActorID   *int64+	ActorName string+	Kind      string+	Detail    string+	CreatedAt time.Time+}++func (s *Store) AddActivity(ctx context.Context, repoID int64, actorID *int64, kind, detail string) {+	var a any+	if actorID != nil {+		a = *actorID+	}+	_, _ = s.db.ExecContext(ctx, `INSERT INTO repo_activity(repo_id, actor_id, kind, detail, created_at) VALUES(?, ?, ?, ?, ?)`,+		repoID, a, kind, detail, unix(time.Now()))+}++func (s *Store) ListActivity(ctx context.Context, repoID int64, limit int) ([]*Activity, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT a.id, a.repo_id, a.actor_id, COALESCE(u.username, ''), a.kind, a.detail, a.created_at+		FROM repo_activity a LEFT JOIN users u ON u.id = a.actor_id+		WHERE a.repo_id = ? ORDER BY a.created_at DESC, a.id DESC LIMIT ?`, repoID, limit)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*Activity+	for rows.Next() {+		var a Activity+		var actor sql.NullInt64+		var created int64+		if err := rows.Scan(&a.ID, &a.RepoID, &actor, &a.ActorName, &a.Kind, &a.Detail, &created); err != nil {+			return nil, err+		}+		a.ActorID = nullInt64Ptr(actor)+		a.CreatedAt = fromUnix(created)+		out = append(out, &a)+	}+	return out, rows.Err()+}--- /dev/null+++ b/internal/data/schema.sql@@ -0,0 +1,251 @@+PRAGMA foreign_keys = ON;++CREATE TABLE IF NOT EXISTS schema_migrations (+    version    INTEGER PRIMARY KEY,+    applied_at INTEGER NOT NULL+);++CREATE TABLE IF NOT EXISTS settings (+    key   TEXT PRIMARY KEY,+    value TEXT NOT NULL+);++CREATE TABLE IF NOT EXISTS users (+    id            INTEGER PRIMARY KEY AUTOINCREMENT,+    username      TEXT NOT NULL UNIQUE COLLATE NOCASE,+    display_name  TEXT NOT NULL DEFAULT '',+    email         TEXT NOT NULL DEFAULT '',+    password_hash TEXT NOT NULL,+    bio           TEXT NOT NULL DEFAULT '',+    avatar_file   TEXT NOT NULL DEFAULT '',+    is_admin      INTEGER NOT NULL DEFAULT 0,+    is_active     INTEGER NOT NULL DEFAULT 1,+    signup_ip     TEXT NOT NULL DEFAULT '',+    last_ip       TEXT NOT NULL DEFAULT '',+    created_at    INTEGER NOT NULL,+    updated_at    INTEGER NOT NULL,+    last_login_at INTEGER+);++CREATE TABLE IF NOT EXISTS sessions (+    id           TEXT PRIMARY KEY,+    user_id      INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    csrf         TEXT NOT NULL,+    ip           TEXT NOT NULL DEFAULT '',+    user_agent   TEXT NOT NULL DEFAULT '',+    created_at   INTEGER NOT NULL,+    last_seen_at INTEGER NOT NULL,+    expires_at   INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);+CREATE INDEX IF NOT EXISTS idx_sessions_expires ON sessions(expires_at);++CREATE TABLE IF NOT EXISTS ssh_keys (+    id          INTEGER PRIMARY KEY AUTOINCREMENT,+    user_id     INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    name        TEXT NOT NULL,+    public_key  TEXT NOT NULL,+    fingerprint TEXT NOT NULL,+    created_at  INTEGER NOT NULL,+    last_used_at INTEGER,+    UNIQUE(user_id, fingerprint)+);+CREATE UNIQUE INDEX IF NOT EXISTS idx_ssh_keys_fingerprint ON ssh_keys(fingerprint);++CREATE TABLE IF NOT EXISTS login_attempts (+    id         INTEGER PRIMARY KEY AUTOINCREMENT,+    username   TEXT NOT NULL DEFAULT '',+    ip         TEXT NOT NULL DEFAULT '',+    success    INTEGER NOT NULL DEFAULT 0,+    created_at INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_login_attempts_ip ON login_attempts(ip, created_at);+CREATE INDEX IF NOT EXISTS idx_login_attempts_user ON login_attempts(username, created_at);++CREATE TABLE IF NOT EXISTS orgs (+    id           INTEGER PRIMARY KEY AUTOINCREMENT,+    name         TEXT NOT NULL UNIQUE COLLATE NOCASE,+    display_name TEXT NOT NULL DEFAULT '',+    description  TEXT NOT NULL DEFAULT '',+    avatar_file  TEXT NOT NULL DEFAULT '',+    owner_id     INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    created_at   INTEGER NOT NULL,+    updated_at   INTEGER NOT NULL+);++CREATE TABLE IF NOT EXISTS org_members (+    org_id     INTEGER NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+    user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    role       TEXT NOT NULL CHECK (role IN ('owner', 'admin', 'member')),+    created_at INTEGER NOT NULL,+    PRIMARY KEY (org_id, user_id)+);+CREATE INDEX IF NOT EXISTS idx_org_members_user ON org_members(user_id);++CREATE TABLE IF NOT EXISTS teams (+    id          INTEGER PRIMARY KEY AUTOINCREMENT,+    org_id      INTEGER NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,+    name        TEXT NOT NULL COLLATE NOCASE,+    description TEXT NOT NULL DEFAULT '',+    created_at  INTEGER NOT NULL,+    UNIQUE (org_id, name)+);++CREATE TABLE IF NOT EXISTS team_members (+    team_id    INTEGER NOT NULL REFERENCES teams(id) ON DELETE CASCADE,+    user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    created_at INTEGER NOT NULL,+    PRIMARY KEY (team_id, user_id)+);+CREATE INDEX IF NOT EXISTS idx_team_members_user ON team_members(user_id);++CREATE TABLE IF NOT EXISTS repos (+    id                INTEGER PRIMARY KEY AUTOINCREMENT,+    owner_type        TEXT NOT NULL CHECK (owner_type IN ('user', 'org')),+    owner_id          INTEGER NOT NULL,+    owner_name        TEXT NOT NULL,+    name              TEXT NOT NULL,+    display_name      TEXT NOT NULL DEFAULT '',+    description       TEXT NOT NULL DEFAULT '',+    visibility        TEXT NOT NULL DEFAULT 'public' CHECK (visibility IN ('public', 'private')),+    default_branch    TEXT NOT NULL DEFAULT 'main',+    archived          INTEGER NOT NULL DEFAULT 0,+    next_issue_number INTEGER NOT NULL DEFAULT 1,+    next_pr_number    INTEGER NOT NULL DEFAULT 1,+    created_at        INTEGER NOT NULL,+    updated_at        INTEGER NOT NULL,+    UNIQUE (owner_name, name)+);+CREATE INDEX IF NOT EXISTS idx_repos_owner ON repos(owner_type, owner_id);+CREATE INDEX IF NOT EXISTS idx_repos_public ON repos(visibility, updated_at);++CREATE TABLE IF NOT EXISTS repo_collaborators (+    repo_id    INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    role       TEXT NOT NULL CHECK (role IN ('read', 'write', 'admin')),+    created_at INTEGER NOT NULL,+    PRIMARY KEY (repo_id, user_id)+);+CREATE INDEX IF NOT EXISTS idx_repo_collaborators_user ON repo_collaborators(user_id);++CREATE TABLE IF NOT EXISTS repo_teams (+    repo_id    INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    team_id    INTEGER NOT NULL REFERENCES teams(id) ON DELETE CASCADE,+    permission TEXT NOT NULL CHECK (permission IN ('read', 'write', 'admin')),+    created_at INTEGER NOT NULL,+    PRIMARY KEY (repo_id, team_id)+);++CREATE TABLE IF NOT EXISTS stars (+    user_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    repo_id    INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    created_at INTEGER NOT NULL,+    PRIMARY KEY (user_id, repo_id)+);+CREATE INDEX IF NOT EXISTS idx_stars_repo ON stars(repo_id);++CREATE TABLE IF NOT EXISTS issues (+    id         INTEGER PRIMARY KEY AUTOINCREMENT,+    repo_id    INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    number     INTEGER NOT NULL,+    author_id  INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    title      TEXT NOT NULL,+    body       TEXT NOT NULL DEFAULT '',+    state      TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'closed')),+    ip         TEXT NOT NULL DEFAULT '',+    created_at INTEGER NOT NULL,+    updated_at INTEGER NOT NULL,+    closed_at  INTEGER,+    closed_by  INTEGER REFERENCES users(id) ON DELETE SET NULL,+    UNIQUE (repo_id, number)+);+CREATE INDEX IF NOT EXISTS idx_issues_repo ON issues(repo_id, state, updated_at);++CREATE TABLE IF NOT EXISTS pulls (+    id           INTEGER PRIMARY KEY AUTOINCREMENT,+    repo_id      INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    number       INTEGER NOT NULL,+    author_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    title        TEXT NOT NULL,+    body         TEXT NOT NULL DEFAULT '',+    base_branch  TEXT NOT NULL,+    head_branch  TEXT NOT NULL,+    base_commit  TEXT NOT NULL DEFAULT '',+    head_commit  TEXT NOT NULL DEFAULT '',+    state        TEXT NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'closed', 'merged')),+    merge_commit TEXT NOT NULL DEFAULT '',+    ip           TEXT NOT NULL DEFAULT '',+    created_at   INTEGER NOT NULL,+    updated_at   INTEGER NOT NULL,+    merged_at    INTEGER,+    merged_by    INTEGER REFERENCES users(id) ON DELETE SET NULL,+    closed_at    INTEGER,+    closed_by    INTEGER REFERENCES users(id) ON DELETE SET NULL,+    UNIQUE (repo_id, number)+);+CREATE INDEX IF NOT EXISTS idx_pulls_repo ON pulls(repo_id, state, updated_at);++CREATE TABLE IF NOT EXISTS comments (+    id           INTEGER PRIMARY KEY AUTOINCREMENT,+    repo_id      INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    subject_type TEXT NOT NULL CHECK (subject_type IN ('issue', 'pull')),+    subject_id   INTEGER NOT NULL,+    author_id    INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    body         TEXT NOT NULL,+    ip           TEXT NOT NULL DEFAULT '',+    created_at   INTEGER NOT NULL,+    updated_at   INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_comments_subject ON comments(subject_type, subject_id, created_at);++CREATE TABLE IF NOT EXISTS attachments (+    id           TEXT PRIMARY KEY,+    repo_id      INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    uploader_id  INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    subject_type TEXT NOT NULL CHECK (subject_type IN ('issue', 'pull', 'comment', 'repo')),+    subject_id   INTEGER NOT NULL DEFAULT 0,+    filename     TEXT NOT NULL,+    stored_name  TEXT NOT NULL,+    mime         TEXT NOT NULL,+    size         INTEGER NOT NULL,+    created_at   INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_attachments_subject ON attachments(subject_type, subject_id);++CREATE TABLE IF NOT EXISTS webhooks (+    id               INTEGER PRIMARY KEY AUTOINCREMENT,+    repo_id          INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    url              TEXT NOT NULL,+    secret           TEXT NOT NULL,+    events           TEXT NOT NULL,+    active           INTEGER NOT NULL DEFAULT 1,+    created_by       INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+    created_at       INTEGER NOT NULL,+    last_status      INTEGER NOT NULL DEFAULT 0,+    last_delivery_at INTEGER,+    failures         INTEGER NOT NULL DEFAULT 0+);+CREATE INDEX IF NOT EXISTS idx_webhooks_repo ON webhooks(repo_id);++CREATE TABLE IF NOT EXISTS repo_activity (+    id         INTEGER PRIMARY KEY AUTOINCREMENT,+    repo_id    INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,+    actor_id   INTEGER REFERENCES users(id) ON DELETE SET NULL,+    kind       TEXT NOT NULL,+    detail     TEXT NOT NULL DEFAULT '',+    created_at INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_activity_repo ON repo_activity(repo_id, created_at);++CREATE TABLE IF NOT EXISTS audit_log (+    id         INTEGER PRIMARY KEY AUTOINCREMENT,+    user_id    INTEGER,+    username   TEXT NOT NULL DEFAULT '',+    ip         TEXT NOT NULL DEFAULT '',+    action     TEXT NOT NULL,+    detail     TEXT NOT NULL DEFAULT '',+    user_agent TEXT NOT NULL DEFAULT '',+    created_at INTEGER NOT NULL+);+CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_log(created_at);+CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log(user_id, created_at);--- /dev/null+++ b/internal/data/users.go@@ -0,0 +1,350 @@+package data++import (+	"context"+	"database/sql"+	"strings"+	"time"+)++type User struct {+	ID           int64+	Username     string+	DisplayName  string+	Email        string+	PasswordHash string+	Bio          string+	AvatarFile   string+	IsAdmin      bool+	IsActive     bool+	SignupIP     string+	LastIP       string+	CreatedAt    time.Time+	UpdatedAt    time.Time+	LastLoginAt  *time.Time+}++func scanUser(sc interface{ Scan(...any) error }) (*User, error) {+	var u User+	var admin, active int+	var created, updated int64+	var last sql.NullInt64+	err := sc.Scan(&u.ID, &u.Username, &u.DisplayName, &u.Email, &u.PasswordHash,+		&u.Bio, &u.AvatarFile, &admin, &active, &u.SignupIP, &u.LastIP,+		&created, &updated, &last)+	if err != nil {+		return nil, err+	}+	u.IsAdmin = intBool(admin)+	u.IsActive = intBool(active)+	u.CreatedAt = fromUnix(created)+	u.UpdatedAt = fromUnix(updated)+	u.LastLoginAt = nullTime(last)+	return &u, nil+}++const userColumns = `id, username, display_name, email, password_hash, bio, avatar_file,+	is_admin, is_active, signup_ip, last_ip, created_at, updated_at, last_login_at`++func (s *Store) CreateUser(ctx context.Context, username, displayName, email, passwordHash, ip string, admin bool) (*User, error) {+	now := time.Now()+	res, err := s.db.ExecContext(ctx, `+		INSERT INTO users(username, display_name, email, password_hash, signup_ip, last_ip, is_admin, created_at, updated_at)+		VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`,+		username, displayName, email, passwordHash, ip, ip, boolInt(admin), unix(now), unix(now))+	if err != nil {+		if isUnique(err) {+			return nil, ErrConflict+		}+		return nil, err+	}+	id, _ := res.LastInsertId()+	return s.GetUserByID(ctx, id)+}++// CreateUserAutoAdmin atomically creates a user and makes the very first+// account an administrator. The transaction prevents a signup race from+// producing two administrators.+func (s *Store) CreateUserAutoAdmin(ctx context.Context, username, displayName, email, passwordHash, ip string) (*User, error) {+	now := time.Now()+	tx, err := s.db.BeginTx(ctx, nil)+	if err != nil {+		return nil, err+	}+	defer tx.Rollback()+	var count int64+	if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&count); err != nil {+		return nil, err+	}+	admin := count == 0+	res, err := tx.ExecContext(ctx, `+		INSERT INTO users(username, display_name, email, password_hash, signup_ip, last_ip, is_admin, created_at, updated_at)+		VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`,+		username, displayName, email, passwordHash, ip, ip, boolInt(admin), unix(now), unix(now))+	if err != nil {+		if isUnique(err) {+			return nil, ErrConflict+		}+		return nil, err+	}+	id, _ := res.LastInsertId()+	if err := tx.Commit(); err != nil {+		return nil, err+	}+	return s.GetUserByID(ctx, id)+}++func (s *Store) GetUserByID(ctx context.Context, id int64) (*User, error) {+	row := s.db.QueryRowContext(ctx, `SELECT `+userColumns+` FROM users WHERE id = ?`, id)+	u, err := scanUser(row)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	return u, err+}++func (s *Store) GetUserByUsername(ctx context.Context, username string) (*User, error) {+	row := s.db.QueryRowContext(ctx, `SELECT `+userColumns+` FROM users WHERE username = ? COLLATE NOCASE`, username)+	u, err := scanUser(row)+	if err == sql.ErrNoRows {+		return nil, ErrNotFound+	}+	return u, err+}++func (s *Store) CountUsers(ctx context.Context) (int64, error) {+	var n int64+	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM users`).Scan(&n)+	return n, err+}++func (s *Store) UpdateUserProfile(ctx context.Context, id int64, displayName, email, bio string) error {+	_, err := s.db.ExecContext(ctx, `UPDATE users SET display_name = ?, email = ?, bio = ?, updated_at = ? WHERE id = ?`,+		displayName, email, bio, unix(time.Now()), id)+	return err+}++func (s *Store) UpdateUserPassword(ctx context.Context, id int64, hash string) error {+	_, err := s.db.ExecContext(ctx, `UPDATE users SET password_hash = ?, updated_at = ? WHERE id = ?`, hash, unix(time.Now()), id)+	return err+}++func (s *Store) SetUserAvatar(ctx context.Context, id int64, file string) error {+	_, err := s.db.ExecContext(ctx, `UPDATE users SET avatar_file = ?, updated_at = ? WHERE id = ?`, file, unix(time.Now()), id)+	return err+}++func (s *Store) SetUserActive(ctx context.Context, id int64, active bool) error {+	_, err := s.db.ExecContext(ctx, `UPDATE users SET is_active = ?, updated_at = ? WHERE id = ?`, boolInt(active), unix(time.Now()), id)+	if !active {+		_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, id)+	}+	return err+}++func (s *Store) SetUserAdmin(ctx context.Context, id int64, admin bool) error {+	_, err := s.db.ExecContext(ctx, `UPDATE users SET is_admin = ?, updated_at = ? WHERE id = ?`, boolInt(admin), unix(time.Now()), id)+	return err+}++func (s *Store) RecordLogin(ctx context.Context, id int64, ip string) error {+	now := unix(time.Now())+	_, err := s.db.ExecContext(ctx, `UPDATE users SET last_login_at = ?, last_ip = ?, updated_at = ? WHERE id = ?`, now, ip, now, id)+	return err+}++func (s *Store) ListUsers(ctx context.Context, offset, limit int) ([]*User, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT `+userColumns+` FROM users ORDER BY username COLLATE NOCASE LIMIT ? OFFSET ?`, limit, offset)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*User+	for rows.Next() {+		u, err := scanUser(rows)+		if err != nil {+			return nil, err+		}+		out = append(out, u)+	}+	return out, rows.Err()+}++func (s *Store) RecordLoginAttempt(ctx context.Context, username, ip string, success bool) {+	_, _ = s.db.ExecContext(ctx, `INSERT INTO login_attempts(username, ip, success, created_at) VALUES(?, ?, ?, ?)`,+		username, ip, boolInt(success), unix(time.Now()))+}++func (s *Store) RecentFailures(ctx context.Context, username, ip string, since time.Time) (int, error) {+	var n int+	err := s.db.QueryRowContext(ctx, `+		SELECT COUNT(*) FROM login_attempts+		WHERE success = 0 AND created_at >= ? AND ip = ?`,+		unix(since), ip).Scan(&n)+	return n, err+}++func (s *Store) ClearLoginFailures(ctx context.Context, ip string) {+	_, _ = s.db.ExecContext(ctx, `DELETE FROM login_attempts WHERE ip = ? AND success = 0`, ip)+}++func (s *Store) CountRecentAttempts(ctx context.Context, ip string, since time.Time) (int, error) {+	var n int+	err := s.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM login_attempts WHERE ip = ? AND created_at >= ?`, ip, unix(since)).Scan(&n)+	return n, err+}++func (s *Store) CleanupLoginAttempts(ctx context.Context, before time.Time) {+	_, _ = s.db.ExecContext(ctx, `DELETE FROM login_attempts WHERE created_at < ?`, unix(before))+}++type SSHKey struct {+	ID          int64+	UserID      int64+	Name        string+	PublicKey   string+	Fingerprint string+	CreatedAt   time.Time+	LastUsedAt  *time.Time+}++func (s *Store) ListSSHKeys(ctx context.Context, userID int64) ([]*SSHKey, error) {+	rows, err := s.db.QueryContext(ctx, `SELECT id, user_id, name, public_key, fingerprint, created_at, last_used_at FROM ssh_keys WHERE user_id = ? ORDER BY created_at`, userID)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*SSHKey+	for rows.Next() {+		var k SSHKey+		var created int64+		var last sql.NullInt64+		if err := rows.Scan(&k.ID, &k.UserID, &k.Name, &k.PublicKey, &k.Fingerprint, &created, &last); err != nil {+			return nil, err+		}+		k.CreatedAt = fromUnix(created)+		k.LastUsedAt = nullTime(last)+		out = append(out, &k)+	}+	return out, rows.Err()+}++func (s *Store) AddSSHKey(ctx context.Context, userID int64, name, publicKey, fingerprint string) error {+	_, err := s.db.ExecContext(ctx, `INSERT INTO ssh_keys(user_id, name, public_key, fingerprint, created_at) VALUES(?, ?, ?, ?, ?)`,+		userID, name, publicKey, fingerprint, unix(time.Now()))+	if err != nil {+		if isUnique(err) {+			return ErrConflict+		}+		return err+	}+	return nil+}++func (s *Store) DeleteSSHKey(ctx context.Context, userID, keyID int64) error {+	res, err := s.db.ExecContext(ctx, `DELETE FROM ssh_keys WHERE id = ? AND user_id = ?`, keyID, userID)+	if err != nil {+		return err+	}+	n, _ := res.RowsAffected()+	if n == 0 {+		return ErrNotFound+	}+	return nil+}++func (s *Store) AllActiveSSHKeys(ctx context.Context) ([]*SSHKey, error) {+	rows, err := s.db.QueryContext(ctx, `+		SELECT k.id, k.user_id, k.name, k.public_key, k.fingerprint, k.created_at, k.last_used_at+		FROM ssh_keys k JOIN users u ON u.id = k.user_id+		WHERE u.is_active = 1 ORDER BY k.user_id, k.id`)+	if err != nil {+		return nil, err+	}+	defer rows.Close()+	var out []*SSHKey+	for rows.Next() {+		var k SSHKey+		var created int64+		var last sql.NullInt64+		if err := rows.Scan(&k.ID, &k.UserID, &k.Name, &k.PublicKey, &k.Fingerprint, &created, &last); err != nil {+			return nil, err+		}+		k.CreatedAt = fromUnix(created)+		k.LastUsedAt = nullTime(last)+		out = append(out, &k)+	}+	return out, rows.Err()+}++type Session struct {+	ID         string+	UserID     int64+	CSRF       string+	IP         string+	UserAgent  string+	CreatedAt  time.Time+	LastSeenAt time.Time+	ExpiresAt  time.Time+	User       *User+}++func (s *Store) CreateSession(ctx context.Context, id string, userID int64, csrf, ip, ua string, expires time.Time) error {+	now := time.Now()+	_, err := s.db.ExecContext(ctx, `INSERT INTO sessions(id, user_id, csrf, ip, user_agent, created_at, last_seen_at, expires_at)+		VALUES(?, ?, ?, ?, ?, ?, ?, ?)`, id, userID, csrf, ip, ua, unix(now), unix(now), unix(expires))+	return err+}++func (s *Store) GetSession(ctx context.Context, id string) (*Session, error) {+	row := s.db.QueryRowContext(ctx, `+		SELECT id, user_id, csrf, ip, user_agent, created_at, last_seen_at, expires_at+		FROM sessions WHERE id = ? AND expires_at > ?`, id, unix(time.Now()))+	var sess Session+	var created, seen, expires int64+	if err := row.Scan(&sess.ID, &sess.UserID, &sess.CSRF, &sess.IP, &sess.UserAgent, &created, &seen, &expires); err != nil {+		if err == sql.ErrNoRows {+			return nil, ErrNotFound+		}+		return nil, err+	}+	sess.CreatedAt = fromUnix(created)+	sess.LastSeenAt = fromUnix(seen)+	sess.ExpiresAt = fromUnix(expires)+	u, err := s.GetUserByID(ctx, sess.UserID)+	if err != nil {+		return nil, err+	}+	if !u.IsActive {+		return nil, ErrNotFound+	}+	sess.User = u+	return &sess, nil+}++func (s *Store) TouchSession(ctx context.Context, id string) {+	_, _ = s.db.ExecContext(ctx, `UPDATE sessions SET last_seen_at = ? WHERE id = ?`, unix(time.Now()), id)+}++func (s *Store) DeleteSession(ctx context.Context, id string) {+	_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE id = ?`, id)+}++func (s *Store) DeleteUserSessions(ctx context.Context, userID int64) {+	_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE user_id = ?`, userID)+}++func (s *Store) CleanupSessions(ctx context.Context) {+	_, _ = s.db.ExecContext(ctx, `DELETE FROM sessions WHERE expires_at <= ?`, unix(time.Now()))+}++// UsernameAvailable checks the shared user/org namespace used in URLs.+func (s *Store) UsernameAvailable(ctx context.Context, username string) (bool, error) {+	var n int+	err := s.db.QueryRowContext(ctx, `+		SELECT (SELECT COUNT(*) FROM users WHERE username = ? COLLATE NOCASE)+		     + (SELECT COUNT(*) FROM orgs WHERE name = ? COLLATE NOCASE)`, username, username).Scan(&n)+	return n == 0, err+}++func NormalizeHandle(name string) string { return strings.TrimSpace(name) }--- /dev/null+++ b/internal/vn/access.go@@ -0,0 +1,83 @@+package vn++import (+	"errors"+	"os"+	"path/filepath"+	"sort"+	"strings"+)++type AccessEntry struct {+	PublicKey string+	Name      string+	Role      string+}++// WriteAccess writes a veins .veins/access policy. The service key always+// retains write access so the forge can refresh caches and merge pull requests.+func (r *Runner) WriteAccess(central string, anonymous bool, entries []AccessEntry) error {+	if !pathWithin(r.RepoRoot, central) {+		return errors.New("access file path is outside the repository root")+	}+	all := append([]AccessEntry{}, entries...)+	if r.KeyPublic != "" {+		all = append(all, AccessEntry{PublicKey: r.KeyPublic, Name: r.KeyName, Role: "write"})+	}+	best := make(map[string]AccessEntry)+	for _, e := range all {+		e.PublicKey = strings.TrimSpace(e.PublicKey)+		e.Name = strings.TrimSpace(e.Name)+		if !strings.HasPrefix(e.PublicKey, "ed25519:") {+			continue+		}+		if e.Role == "admin" {+			e.Role = "write"+		}+		if e.Role != "write" && e.Role != "read" {+			e.Role = "read"+		}+		if len(e.Name) > 64 || strings.ContainsAny(e.Name, " \t\r\n\x00") {+			e.Name = ""+		}+		if old, ok := best[e.PublicKey]; !ok || (e.Role == "write" && old.Role == "read") {+			best[e.PublicKey] = e+		}+	}+	list := make([]AccessEntry, 0, len(best))+	for _, e := range best {+		list = append(list, e)+	}+	sort.Slice(list, func(i, j int) bool {+		if list[i].Name == list[j].Name {+			return list[i].PublicKey < list[j].PublicKey+		}+		return list[i].Name < list[j].Name+	})+	var b strings.Builder+	b.WriteString("# veins access policy\n")+	if anonymous {+		b.WriteString("anonymous read\n")+	}+	for _, e := range list {+		b.WriteString("allow ")+		b.WriteString(e.Role)+		b.WriteByte(' ')+		b.WriteString(e.PublicKey)+		if e.Name != "" {+			b.WriteByte(' ')+			b.WriteString(e.Name)+		}+		b.WriteByte('\n')+	}+	dir := filepath.Join(central, ".veins")+	if err := os.MkdirAll(dir, 0o700); err != nil {+		return err+	}+	final := filepath.Join(dir, "access")+	tmp := final + ".tmp"+	if err := os.WriteFile(tmp, []byte(b.String()), 0o600); err != nil {+		return err+	}+	return os.Rename(tmp, final)+}--- /dev/null+++ b/internal/vn/access_test.go@@ -0,0 +1,53 @@+package vn++import (+	"os"+	"path/filepath"+	"strings"+	"testing"+)++func TestWriteAccessIsCanonicalAndDeduplicated(t *testing.T) {+	root := t.TempDir()+	central := filepath.Join(root, "owner", "repo")+	if err := os.MkdirAll(filepath.Join(central, ".veins"), 0o700); err != nil {+		t.Fatal(err)+	}+	r := &Runner{RepoRoot: root, KeyName: "veinsforge", KeyPublic: "ed25519:service"}+	entries := []AccessEntry{+		{PublicKey: "ed25519:z", Name: "zoe", Role: "read"},+		{PublicKey: "ed25519:a", Name: "alice", Role: "admin"},+		{PublicKey: "ed25519:service", Name: "veinsforge", Role: "read"},+		{PublicKey: "ed25519:a", Name: "alice", Role: "read"},+	}+	if err := r.WriteAccess(central, true, entries); err != nil {+		t.Fatal(err)+	}+	data, err := os.ReadFile(filepath.Join(central, ".veins", "access"))+	if err != nil {+		t.Fatal(err)+	}+	text := string(data)+	if !strings.Contains(text, "anonymous read\n") {+		t.Fatalf("missing anonymous read:\n%s", text)+	}+	if strings.Count(text, "ed25519:a") != 1 {+		t.Fatalf("duplicate key was written:\n%s", text)+	}+	if !strings.Contains(text, "allow write ed25519:a alice") {+		t.Fatalf("admin was not mapped to write:\n%s", text)+	}+	if !strings.Contains(text, "allow write ed25519:service veinsforge") {+		t.Fatalf("service key did not retain write:\n%s", text)+	}+	if strings.Index(text, "alice") > strings.Index(text, "zoe") {+		t.Fatalf("entries are not sorted:\n%s", text)+	}+}++func TestWriteAccessRejectsOutsidePath(t *testing.T) {+	r := &Runner{RepoRoot: t.TempDir(), KeyName: "veinsforge"}+	if err := r.WriteAccess("/tmp", true, nil); err == nil {+		t.Fatal("accepted a path outside the repository root")+	}+}--- /dev/null+++ b/internal/vn/browse.go@@ -0,0 +1,305 @@+package vn++import (+	"context"+	"errors"+	"io"+	"os"+	"path/filepath"+	"sort"+	"strings"+	"time"+)++var ErrTooLarge = errors.New("file is too large to display")++type FileData struct {+	Data       []byte+	Size       int64+	IsSymlink  bool+	LinkTarget string+	ModTime    time.Time+}++func (r *Runner) EnsureBrowse(ctx context.Context, repoID int64, central string) (string, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	return r.ensureBrowseLocked(ctx, repoID, central)+}++func (r *Runner) ensureBrowseLocked(ctx context.Context, repoID int64, central string) (string, error) {+	path := r.BrowsePath(repoID)+	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+		return "", err+	}+	if !r.RepoExists(path) {+		if _, err := r.runOK(ctx, filepath.Dir(path), nil, "init", path); err != nil {+			return "", err+		}+		_ = os.Chmod(path, 0o700)+	}+	if err := r.ensureRemoteConfig(path, central); err != nil {+		return "", err+	}+	head := currentHead(central)+	if head == "" {+		return path, nil+	}+	r.mu.Lock()+	last := r.fetchAt[repoID]+	seen := r.fetchHead[repoID]+	r.mu.Unlock()+	if head == seen && time.Since(last) < 30*time.Second {+		return path, nil+	}+	if _, errOut, err := r.runLong(ctx, path, nil, "fetch", "origin"); err != nil {+		if r.Logger != nil {+			r.Logger.Printf("vn fetch for repo %d failed: %v: %s", repoID, err, truncate(string(errOut), 1024))+		}+		// Back off for a short while instead of re-running a failing fetch on+		// every page request.+	}+	r.mu.Lock()+	r.fetchAt[repoID] = time.Now()+	r.fetchHead[repoID] = head+	r.mu.Unlock()+	return path, nil+}++func (r *Runner) ensureRemoteConfig(repoPath, central string) error {+	cfgPath := filepath.Join(repoPath, ".veins", "config")+	data, _ := os.ReadFile(cfgPath)+	var kept []string+	for _, line := range strings.Split(string(data), "\n") {+		trimmed := strings.TrimSpace(line)+		if strings.HasPrefix(trimmed, "remote.origin.url =") ||+			strings.HasPrefix(trimmed, "remote.origin.key =") ||+			strings.HasPrefix(trimmed, "promisor =") {+			continue+		}+		kept = append(kept, line)+	}+	body := strings.TrimRight(strings.Join(kept, "\n"), "\n")+	if body != "" {+		body += "\n"+	}+	body += "remote.origin.url = file://" + filepath.Clean(central) + "\n"+	body += "remote.origin.key = " + r.KeyName + "\n"+	body += "promisor = origin\n"+	tmp := cfgPath + ".tmp"+	if err := os.WriteFile(tmp, []byte(body), 0o600); err != nil {+		return err+	}+	return os.Rename(tmp, cfgPath)+}++func currentHead(central string) string {+	entries, err := os.ReadDir(filepath.Join(central, ".veins", "op-heads"))+	if err != nil || len(entries) == 0 {+		return ""+	}+	names := make([]string, 0, len(entries))+	for _, e := range entries {+		names = append(names, e.Name())+	}+	sort.Strings(names)+	return strings.Join(names, ",")+}++func (r *Runner) Invalidate(repoID int64) {+	r.mu.Lock()+	delete(r.fetchAt, repoID)+	delete(r.currentRev, repoID)+	r.mu.Unlock()+}++func (r *Runner) Resolve(ctx context.Context, repoID int64, central, rev string) (string, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	path, err := r.ensureBrowseLocked(ctx, repoID, central)+	if err != nil {+		return "", err+	}+	return r.resolveLocked(ctx, path, rev)+}++func (r *Runner) resolveLocked(ctx context.Context, browsePath, rev string) (string, error) {+	out, err := r.runOK(ctx, browsePath, nil, "hash", "-rev", rev)+	if err != nil {+		return "", err+	}+	return strings.TrimSpace(string(out)), nil+}++func (r *Runner) CommitHash(ctx context.Context, repoID int64, central, rev string) (string, error) {+	return r.Resolve(ctx, repoID, central, rev)+}++func (r *Runner) Branches(ctx context.Context, repoID int64, central string) ([]Branch, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	path, err := r.ensureBrowseLocked(ctx, repoID, central)+	if err != nil {+		return nil, err+	}+	if currentHead(central) == "" {+		return nil, nil+	}+	out, _, err := r.run(ctx, path, nil, "bmk", "ls", "-no-col-titles")+	if err != nil {+		if strings.Contains(strings.ToLower(string(out)), "no bookmarks") {+			return nil, nil+		}+		return nil, err+	}+	return ParseBranches(string(out)), nil+}++func (r *Runner) Log(ctx context.Context, repoID int64, central, rev string, max int) ([]Commit, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	path, err := r.ensureBrowseLocked(ctx, repoID, central)+	if err != nil {+		return nil, err+	}+	args := []string{"log", "-no-col-titles"}+	if rev != "" {+		args = append(args, "-rev", rev)+	}+	out, err := r.runOK(ctx, path, nil, args...)+	if err != nil {+		return nil, err+	}+	return ParseLog(string(out), max), nil+}++func (r *Runner) Show(ctx context.Context, repoID int64, central, rev string) (*CommitDetail, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	path, err := r.ensureBrowseLocked(ctx, repoID, central)+	if err != nil {+		return nil, err+	}+	out, err := r.runOK(ctx, path, nil, "show", rev)+	if err != nil {+		return nil, err+	}+	d := ParseShow(string(out))+	return &d, nil+}++func (r *Runner) Diff(ctx context.Context, repoID int64, central, from, to string) (string, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	path, err := r.ensureBrowseLocked(ctx, repoID, central)+	if err != nil {+		return "", err+	}+	out, _, err := r.run(ctx, path, nil, "diff", from, to)+	if err != nil {+		return "", err+	}+	return string(out), nil+}++func (r *Runner) ListFiles(ctx context.Context, repoID int64, central, rev string) ([]string, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	path, err := r.ensureBrowseLocked(ctx, repoID, central)+	if err != nil {+		return nil, err+	}+	out, err := r.runOK(ctx, path, nil, "ls", "-plain", rev)+	if err != nil {+		return nil, err+	}+	var files []string+	for _, line := range strings.Split(string(out), "\n") {+		line = strings.TrimSpace(line)+		if line == "" {+			continue+		}+		files = append(files, line)+	}+	return files, nil+}++func (r *Runner) ReadFile(ctx context.Context, repoID int64, central, rev, rel string, max int64) (*FileData, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()+	path, err := r.ensureBrowseLocked(ctx, repoID, central)+	if err != nil {+		return nil, err+	}+	hash, err := r.resolveLocked(ctx, path, rev)+	if err != nil {+		return nil, err+	}+	r.mu.Lock()+	checkedOut := r.currentRev[repoID]+	r.mu.Unlock()+	if checkedOut != hash {+		if _, err := r.runOK(ctx, path, nil, "co", hash); err != nil {+			return nil, err+		}+		r.mu.Lock()+		r.currentRev[repoID] = hash+		r.mu.Unlock()+	}+	return safeRead(path, rel, max)+}++func safeRead(root, rel string, max int64) (*FileData, error) {+	rel = filepath.FromSlash(rel)+	clean := filepath.Clean(rel)+	if clean == "." || filepath.IsAbs(clean) || clean == ".." ||+		strings.HasPrefix(clean, ".."+string(filepath.Separator)) ||+		clean == ".veins" || strings.HasPrefix(clean, ".veins"+string(filepath.Separator)) {+		return nil, errors.New("invalid path")+	}+	full := filepath.Join(root, clean)+	if !pathWithin(root, full) {+		return nil, errors.New("invalid path")+	}+	info, err := os.Lstat(full)+	if err != nil {+		return nil, err+	}+	if info.IsDir() {+		return nil, errors.New("path is a directory")+	}+	if info.Mode()&os.ModeSymlink != 0 {+		target, err := os.Readlink(full)+		if err != nil {+			return nil, err+		}+		return &FileData{Data: []byte(target), Size: int64(len(target)), IsSymlink: true, LinkTarget: target, ModTime: info.ModTime()}, nil+	}+	if !info.Mode().IsRegular() {+		return nil, errors.New("not a regular file")+	}+	if info.Size() > max {+		return nil, ErrTooLarge+	}+	f, err := os.Open(full)+	if err != nil {+		return nil, err+	}+	defer f.Close()+	data, err := io.ReadAll(io.LimitReader(f, max+1))+	if err != nil {+		return nil, err+	}+	if int64(len(data)) > max {+		return nil, ErrTooLarge+	}+	return &FileData{Data: data, Size: info.Size(), ModTime: info.ModTime()}, nil+}--- /dev/null+++ b/internal/vn/merge.go@@ -0,0 +1,82 @@+package vn++import (+	"context"+	"crypto/rand"+	"encoding/hex"+	"errors"+	"fmt"+	"os"+	"path/filepath"+	"strings"+)++type MergeResult struct {+	CommitHash string+	Conflicts  []string+}++// MergePull performs a server-side merge in a temporary clone and pushes the+// updated base bookmark back to the central repository. If the merge produces+// conflicts, nothing is pushed.+func (r *Runner) MergePull(ctx context.Context, repoID int64, central, base, head, message, authorName, authorEmail string) (*MergeResult, error) {+	lock := r.repoLock(central)+	lock.Lock()+	defer lock.Unlock()++	tmpParent := filepath.Join(r.CacheDir, "tmp")+	if err := os.MkdirAll(tmpParent, 0o700); err != nil {+		return nil, err+	}+	tmp := filepath.Join(tmpParent, randomName())+	defer os.RemoveAll(tmp)+	env := []string{"GIT_AUTHOR_NAME=" + authorName, "GIT_AUTHOR_EMAIL=" + authorEmail}+	if _, errOut, err := r.runLong(ctx, tmpParent, env, "clone", "file://"+filepath.Clean(central), tmp, "-blobs:all", "-key:"+r.KeyName); err != nil {+		return nil, fmt.Errorf("clone for merge: %w (%s)", err, truncate(string(errOut), 300))+	}+	if err := r.ensureRemoteConfig(tmp, central); err != nil {+		return nil, err+	}+	if _, err := r.runOK(ctx, tmp, env, "co", base); err != nil {+		return nil, fmt.Errorf("checkout base %s: %w", base, err)+	}+	if _, errOut, err := r.run(ctx, tmp, env, "merge", head); err != nil {+		return nil, fmt.Errorf("merge %s: %w (%s)", head, err, truncate(string(errOut), 300))+	}+	out, errOut, err := r.run(ctx, tmp, env, "xs")+	if err != nil {+		return nil, fmt.Errorf("read conflicts: %w", err)+	}+	conflicts := ParseConflicts(string(out) + "\n" + string(errOut))+	if len(conflicts) > 0 {+		return &MergeResult{Conflicts: conflicts}, nil+	}+	if message != "" {+		if _, errOut, err := r.run(ctx, tmp, env, "amend", "@", "-m", message); err != nil {+			return nil, fmt.Errorf("amend merge commit: %w (%s)", err, truncate(string(errOut), 300))+		}+	}+	hashOut, err := r.runOK(ctx, tmp, env, "hash", "-rev", "@")+	if err != nil {+		return nil, fmt.Errorf("read merge commit: %w", err)+	}+	mergeHash := strings.TrimSpace(string(hashOut))+	if _, err := r.runOK(ctx, tmp, env, "bmk", "set", base); err != nil {+		return nil, fmt.Errorf("move bookmark %s: %w", base, err)+	}+	if _, errOut, err := r.runLong(ctx, tmp, env, "push", "origin", base); err != nil {+		return nil, fmt.Errorf("push merge: %w (%s)", err, truncate(string(errOut), 300))+	}+	r.Invalidate(repoID)+	return &MergeResult{CommitHash: mergeHash}, nil+}++func randomName() string {+	b := make([]byte, 12)+	if _, err := rand.Read(b); err != nil {+		return fmt.Sprintf("merge-%d", os.Getpid())+	}+	return hex.EncodeToString(b)+}++var ErrMergeConflicts = errors.New("merge has conflicts")--- /dev/null+++ b/internal/vn/parse.go@@ -0,0 +1,157 @@+package vn++import (+	"regexp"+	"strings"+	"time"+)++type Commit struct {+	Hash      string+	ShortHash string+	ChangeID  string+	Date      time.Time+	Author    string+	Message   string+	Current   bool+}++type CommitDetail struct {+	Hash      string+	ChangeID  string+	Author    string+	Email     string+	Date      time.Time+	Parents   []string+	Bookmarks []string+	Message   string+	Diff      string+}++type Branch struct {+	Name      string+	Hash      string+	ShortHash string+	ChangeID  string+	Current   bool+}++var logLineRE = regexp.MustCompile(`^\s*(@?)\s*([0-9a-f]{12})\s+(\S+)\s+(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\s+(.*)$`)+var doubleSpaceRE = regexp.MustCompile(`\s{2,}`)++// ParseLog parses `vn log -no-col-titles`.+func ParseLog(out string, max int) []Commit {+	var commits []Commit+	for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") {+		if strings.TrimSpace(line) == "" {+			continue+		}+		m := logLineRE.FindStringSubmatch(line)+		if m == nil {+			continue+		}+		date, _ := time.ParseInLocation("2006-01-02 15:04:05", m[4], time.UTC)+		author := ""+		message := strings.TrimSpace(m[5])+		if parts := doubleSpaceRE.Split(message, 2); len(parts) == 2 {+			author = strings.TrimSpace(parts[0])+			message = strings.TrimSpace(parts[1])+		} else {+			author = message+			message = ""+		}+		commits = append(commits, Commit{+			Hash:      m[2],+			ShortHash: m[2],+			ChangeID:  m[3],+			Date:      date,+			Author:    author,+			Message:   message,+			Current:   m[1] == "@",+		})+		if max > 0 && len(commits) >= max {+			break+		}+	}+	return commits+}++// ParseShow parses `vn show <rev>` into metadata, message and unified diff.+func ParseShow(out string) CommitDetail {+	var d CommitDetail+	text := strings.ReplaceAll(out, "\r\n", "\n")+	diffIndex := strings.Index(text, "\n--- ")+	headerText := text+	if diffIndex >= 0 {+		headerText = text[:diffIndex]+		d.Diff = strings.TrimLeft(text[diffIndex+1:], "\n")+	}+	lines := strings.Split(headerText, "\n")+	messageStart := 0+	for i, line := range lines {+		trimmed := strings.TrimSpace(line)+		switch {+		case strings.HasPrefix(trimmed, "commit "):+			d.Hash = strings.TrimSpace(strings.TrimPrefix(trimmed, "commit "))+		case strings.HasPrefix(trimmed, "change "):+			d.ChangeID = strings.TrimSpace(strings.TrimPrefix(trimmed, "change "))+		case strings.HasPrefix(trimmed, "author "):+			author := strings.TrimSpace(strings.TrimPrefix(trimmed, "author "))+			if lt := strings.LastIndex(author, "<"); lt >= 0 {+				d.Author = strings.TrimSpace(author[:lt])+				d.Email = strings.Trim(strings.TrimSpace(author[lt:]), "<>")+			} else {+				d.Author = author+			}+		case strings.HasPrefix(trimmed, "date "):+			date, _ := time.ParseInLocation("2006-01-02 15:04:05", strings.TrimSpace(strings.TrimPrefix(trimmed, "date ")), time.UTC)+			d.Date = date+		case strings.HasPrefix(trimmed, "parents "):+			for _, p := range strings.Fields(strings.TrimSpace(strings.TrimPrefix(trimmed, "parents "))) {+				if p != "<none>" {+					d.Parents = append(d.Parents, p)+				}+			}+		case strings.HasPrefix(trimmed, "bookmarks "):+			d.Bookmarks = strings.Fields(strings.TrimSpace(strings.TrimPrefix(trimmed, "bookmarks ")))+		}+		if trimmed == "" && messageStart == 0 && i > 0 {+			messageStart = i + 1+			break+		}+	}+	if messageStart > 0 && messageStart <= len(lines) {+		d.Message = strings.TrimSpace(strings.Join(lines[messageStart:], "\n"))+	}+	return d+}++// ParseBranches parses `vn bmk ls -no-col-titles`.+func ParseBranches(out string) []Branch {+	var branches []Branch+	for _, line := range strings.Split(strings.TrimRight(out, "\n"), "\n") {+		fields := strings.Fields(line)+		if len(fields) < 3 {+			continue+		}+		b := Branch{Name: fields[0], Hash: fields[1], ShortHash: fields[1], ChangeID: fields[2]}+		if len(fields) >= 4 && fields[len(fields)-1] == "@" {+			b.Current = true+		}+		branches = append(branches, b)+	}+	return branches+}++// ParseConflicts interprets `vn xs` output. An empty result means no conflicts.+func ParseConflicts(out string) []string {+	var paths []string+	for _, line := range strings.Split(out, "\n") {+		line = strings.TrimSpace(line)+		if line == "" || strings.HasPrefix(line, "info:") {+			continue+		}+		paths = append(paths, line)+	}+	return paths+}--- /dev/null+++ b/internal/vn/parse_test.go@@ -0,0 +1,81 @@+package vn++import "testing"++func TestParseLog(t *testing.T) {+	text := `  c5b8994084ba  6z2z    2026-11-26 21:53:12  t       <unset> [main]+  26bb37b955b1  fa3e    2026-11-26 21:53:12  t       third (divergent)+@ c47aa877c1e9  o7rn    2026-11-26 21:53:10  A Very Long Author Name  Merge pull request #1: thing+  4a79ee834a67  276x    2026-11-26 21:53:10  t       initial commit+`+	commits := ParseLog(text, 0)+	if len(commits) != 4 {+		t.Fatalf("got %d commits", len(commits))+	}+	if commits[0].Hash != "c5b8994084ba" || commits[0].Author != "t" || commits[0].Message != "<unset> [main]" {+		t.Fatalf("unexpected first commit: %+v", commits[0])+	}+	if !commits[2].Current {+		t.Fatal("expected current marker")+	}+	if commits[2].Author != "A Very Long Author Name" {+		t.Fatalf("author = %q", commits[2].Author)+	}+	if commits[2].Message != "Merge pull request #1: thing" {+		t.Fatalf("message = %q", commits[2].Message)+	}+	if commits[0].Date.Year() != 2026 {+		t.Fatalf("date = %v", commits[0].Date)+	}+	if got := ParseLog(text, 2); len(got) != 2 {+		t.Fatalf("limit returned %d", len(got))+	}+}++func TestParseShow(t *testing.T) {+	text := `commit   4a79ee834a678bbc839bef8cbee761c130a34171ecd7672d302575469838317b+change   276xmffexvvc5pkwauzaj5p4xe+author   Test User <test@example.com>+date     2026-11-26 21:53:10+parents  555c8880e98c+bookmarks [feat]++Add feature file++--- /dev/null++++ b/b.txt+@@ -0,0 +1,1 @@++b+`+	d := ParseShow(text)+	if d.Hash != "4a79ee834a678bbc839bef8cbee761c130a34171ecd7672d302575469838317b" {+		t.Fatalf("hash = %q", d.Hash)+	}+	if d.Author != "Test User" || d.Email != "test@example.com" {+		t.Fatalf("author = %q email = %q", d.Author, d.Email)+	}+	if len(d.Parents) != 1 || d.Parents[0] != "555c8880e98c" {+		t.Fatalf("parents = %v", d.Parents)+	}+	if d.Message != "Add feature file" {+		t.Fatalf("message = %q", d.Message)+	}+	if d.Diff == "" {+		t.Fatal("diff was not split")+	}+}++func TestParseBranchesAndConflicts(t *testing.T) {+	branches := ParseBranches("feat      4a79ee834a67  276xmffe  \nmain      b4f9a770b344  fa3elkzy  @\n")+	if len(branches) != 2 || branches[0].Name != "feat" || !branches[1].Current {+		t.Fatalf("branches = %+v", branches)+	}+	conflicts := ParseConflicts("info: no conflicts\n")+	if len(conflicts) != 0 {+		t.Fatalf("unexpected conflicts: %v", conflicts)+	}+	conflicts = ParseConflicts("a.txt\nb/c.txt\n")+	if len(conflicts) != 2 {+		t.Fatalf("conflicts = %v", conflicts)+	}+}--- /dev/null+++ b/internal/vn/runner.go@@ -0,0 +1,265 @@+package vn++import (+	"bytes"+	"context"+	"errors"+	"fmt"+	"io"+	"log"+	"os"+	"os/exec"+	"path/filepath"+	"sort"+	"strings"+	"sync"+	"time"+)++// Runner wraps the vn binary. Every command is executed without a shell, with+// a private HOME, a timeout, and a bounded output buffer.+type Runner struct {+	Bin        string+	Home       string+	RepoRoot   string+	CacheDir   string+	KeyName    string+	KeyPublic  string+	KeyFinger  string+	Logger     *log.Logger+	CommandTTL time.Duration++	mu         sync.Mutex+	repoLocks  map[string]*sync.Mutex+	fetchAt    map[int64]time.Time+	fetchHead  map[int64]string+	currentRev map[int64]string+}++type CommandError struct {+	Args   []string+	Stderr string+	Err    error+}++func (e *CommandError) Error() string {+	msg := strings.TrimSpace(e.Stderr)+	if msg == "" {+		msg = e.Err.Error()+	}+	return msg+}++func (e *CommandError) Unwrap() error { return e.Err }++func NewRunner(bin, home, repoRoot, cacheDir string, logger *log.Logger) *Runner {+	return &Runner{+		Bin:        bin,+		Home:       home,+		RepoRoot:   repoRoot,+		CacheDir:   cacheDir,+		KeyName:    "veinsforge",+		Logger:     logger,+		CommandTTL: 30 * time.Second,+		repoLocks:  make(map[string]*sync.Mutex),+		fetchAt:    make(map[int64]time.Time),+		fetchHead:  make(map[int64]string),+		currentRev: make(map[int64]string),+	}+}++// EnsureKey creates and loads the service key used for local clone/merge work.+func (r *Runner) EnsureKey(ctx context.Context) error {+	keyPath := filepath.Join(r.Home, ".config", "veins", "keys", r.KeyName+".key")+	if _, err := os.Stat(keyPath); err != nil {+		if !errors.Is(err, os.ErrNotExist) {+			return err+		}+		if _, _, err := r.run(ctx, r.Home, nil, "key", "generate", r.KeyName); err != nil {+			return fmt.Errorf("generate service key: %w", err)+		}+	}+	if err := os.Chmod(keyPath, 0o600); err != nil && !errors.Is(err, os.ErrNotExist) {+		return err+	}+	out, _, err := r.run(ctx, r.Home, nil, "key", "show", r.KeyName)+	if err != nil {+		return fmt.Errorf("read service key: %w", err)+	}+	for _, line := range strings.Split(string(out), "\n") {+		line = strings.TrimSpace(line)+		if strings.HasPrefix(line, "public key:") {+			r.KeyPublic = strings.TrimSpace(strings.TrimPrefix(line, "public key:"))+		}+		if strings.HasPrefix(line, "fingerprint:") {+			r.KeyFinger = strings.TrimSpace(strings.TrimPrefix(line, "fingerprint:"))+		}+	}+	if r.KeyPublic == "" {+		return errors.New("service key has no public key")+	}+	return nil+}++func (r *Runner) repoLock(key string) *sync.Mutex {+	r.mu.Lock()+	defer r.mu.Unlock()+	if r.repoLocks[key] == nil {+		r.repoLocks[key] = &sync.Mutex{}+	}+	return r.repoLocks[key]+}++func (r *Runner) run(ctx context.Context, dir string, extraEnv []string, args ...string) ([]byte, []byte, error) {+	timeout := r.CommandTTL+	if timeout <= 0 {+		timeout = 30 * time.Second+	}+	return r.runWithTimeout(ctx, dir, extraEnv, timeout, args...)+}++func (r *Runner) runWithTimeout(ctx context.Context, dir string, extraEnv []string, timeout time.Duration, args ...string) ([]byte, []byte, error) {+	if r.Bin == "" {+		return nil, nil, errors.New("vn binary is not configured")+	}+	if timeout <= 0 {+		timeout = 30 * time.Second+	}+	cctx, cancel := context.WithTimeout(ctx, timeout)+	defer cancel()+	cmd := exec.CommandContext(cctx, r.Bin, args...)+	cmd.Dir = dir+	env := append([]string{}, os.Environ()...)+	env = append(env,+		"HOME="+r.Home,+		"XDG_CONFIG_HOME="+filepath.Join(r.Home, ".config"),+		"GIT_AUTHOR_NAME=veinsforge",+		"GIT_AUTHOR_EMAIL=veinsforge@localhost",+		"GIT_TERMINAL_PROMPT=0",+	)+	env = append(env, extraEnv...)+	cmd.Env = env+	var stdout, stderr limitedBuffer+	cmd.Stdout = &stdout+	cmd.Stderr = &stderr+	err := cmd.Run()+	out := stdout.Bytes()+	errOut := stderr.Bytes()+	if err != nil {+		if cctx.Err() == context.DeadlineExceeded {+			err = fmt.Errorf("command timed out")+		}+		if r.Logger != nil {+			r.Logger.Printf("vn %s failed: %v: %s", strings.Join(args, " "), err, truncate(string(errOut), 1024))+		}+		return out, errOut, &CommandError{Args: args, Stderr: string(errOut), Err: err}+	}+	return out, errOut, nil+}++func (r *Runner) runLong(ctx context.Context, dir string, extraEnv []string, args ...string) ([]byte, []byte, error) {+	return r.runWithTimeout(ctx, dir, extraEnv, 5*time.Minute, args...)+}++// runOK is run with a fallback that includes stdout in the error text.+func (r *Runner) runOK(ctx context.Context, dir string, extraEnv []string, args ...string) ([]byte, error) {+	out, errOut, err := r.run(ctx, dir, extraEnv, args...)+	if err != nil {+		if len(bytes.TrimSpace(errOut)) == 0 && len(bytes.TrimSpace(out)) > 0 {+			return nil, &CommandError{Args: args, Stderr: string(out), Err: err}+		}+		return nil, err+	}+	return out, nil+}++func (r *Runner) RepoPath(owner, name string) string {+	return filepath.Join(r.RepoRoot, owner, name)+}++func (r *Runner) BrowsePath(repoID int64) string {+	return filepath.Join(r.CacheDir, "browse", fmt.Sprintf("%d", repoID))+}++func (r *Runner) CreateRepo(ctx context.Context, owner, name string) (string, error) {+	path := r.RepoPath(owner, name)+	if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {+		return "", err+	}+	if _, err := r.runOK(ctx, filepath.Dir(path), nil, "init", path); err != nil {+		return "", err+	}+	_ = os.Chmod(path, 0o700)+	return path, nil+}++func (r *Runner) RepoExists(path string) bool {+	_, err := os.Stat(filepath.Join(path, ".veins", "format"))+	return err == nil+}++func (r *Runner) RemoveRepo(ctx context.Context, owner, name string, repoID int64) error {+	path := r.RepoPath(owner, name)+	if !pathWithin(r.RepoRoot, path) {+		return errors.New("refusing to remove path outside repository root")+	}+	if err := os.RemoveAll(path); err != nil {+		return err+	}+	browse := r.BrowsePath(repoID)+	if pathWithin(filepath.Join(r.CacheDir, "browse"), browse) {+		_ = os.RemoveAll(browse)+	}+	r.mu.Lock()+	delete(r.fetchAt, repoID)+	delete(r.fetchHead, repoID)+	delete(r.currentRev, repoID)+	r.mu.Unlock()+	return nil+}++func pathWithin(root, child string) bool {+	rel, err := filepath.Rel(root, child)+	return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator))+}++type limitedBuffer struct {+	buf bytes.Buffer+	max int+}++func (b *limitedBuffer) Write(p []byte) (int, error) {+	if b.max == 0 {+		b.max = 16 << 20+	}+	remaining := b.max - b.buf.Len()+	if remaining <= 0 {+		return len(p), nil+	}+	if len(p) > remaining {+		b.buf.Write(p[:remaining])+	} else {+		b.buf.Write(p)+	}+	return len(p), nil+}++func (b *limitedBuffer) Bytes() []byte { return b.buf.Bytes() }++func truncate(s string, n int) string {+	if len(s) <= n {+		return s+	}+	return s[:n] + "..."+}++func sortedKeys[V any](m map[string]V) []string {+	out := make([]string, 0, len(m))+	for k := range m {+		out = append(out, k)+	}+	sort.Strings(out)+	return out+}++var _ io.Writer = (*limitedBuffer)(nil)--- /dev/null+++ b/internal/vn/serve.go@@ -0,0 +1,212 @@+package vn++import (+	"context"+	"crypto/ed25519"+	"crypto/rand"+	"crypto/sha256"+	"crypto/x509"+	"crypto/x509/pkix"+	"encoding/hex"+	"encoding/pem"+	"fmt"+	"log"+	"math/big"+	"net"+	"os"+	"os/exec"+	"path/filepath"+	"strings"+	"sync"+	"time"+)++type NativeServer struct {+	Bin         string+	Home        string+	Listen      string+	Address     string+	RepoRoot    string+	CertPath    string+	KeyPath     string+	Host        string+	Logger      *log.Logger+	Fingerprint string++	mu      sync.Mutex+	running bool+	lastErr string+}++func NewNativeServer(bin, home, listen, address, repoRoot, certPath, keyPath, host string, logger *log.Logger) *NativeServer {+	return &NativeServer{+		Bin: bin, Home: home, Listen: listen, Address: address, RepoRoot: repoRoot,+		CertPath: certPath, KeyPath: keyPath, Host: host, Logger: logger,+	}+}++// Start ensures a TLS certificate and supervises `vn serve`.+func (n *NativeServer) Start(ctx context.Context) error {+	if n.Listen == "" || n.Listen == "off" {+		return nil+	}+	fp, err := ensureCertificate(n.CertPath, n.KeyPath, n.Host)+	if err != nil {+		return err+	}+	n.Fingerprint = fp+	go n.loop(ctx)+	return nil+}++func (n *NativeServer) loop(ctx context.Context) {+	backoff := time.Second+	for {+		if ctx.Err() != nil {+			return+		}+		cmd := exec.CommandContext(ctx, n.Bin, "serve",+			"-listen", n.Listen,+			"-root", n.RepoRoot,+			"-tls-cert", n.CertPath,+			"-tls-key", n.KeyPath,+		)+		cmd.Env = append(os.Environ(), "HOME="+n.Home, "XDG_CONFIG_HOME="+filepath.Join(n.Home, ".config"))+		if n.Logger != nil {+			cmd.Stdout = logWriter{n.Logger, "vn-serve: "}+			cmd.Stderr = logWriter{n.Logger, "vn-serve: "}+		}+		if err := cmd.Start(); err != nil {+			n.setStatus(false, err.Error())+			if !sleepContext(ctx, backoff) {+				return+			}+			backoff = minDuration(backoff*2, 30*time.Second)+			continue+		}+		n.setStatus(true, "")+		if n.Logger != nil {+			n.Logger.Printf("native server listening on %s (pin %s)", n.Listen, n.Fingerprint)+		}+		err := cmd.Wait()+		n.setStatus(false, "")+		if ctx.Err() != nil {+			return+		}+		if err != nil && n.Logger != nil {+			n.Logger.Printf("native server exited: %v; restarting", err)+		}+		if !sleepContext(ctx, backoff) {+			return+		}+		backoff = minDuration(backoff*2, 30*time.Second)+	}+}++func (n *NativeServer) setStatus(running bool, lastErr string) {+	n.mu.Lock()+	n.running = running+	n.lastErr = lastErr+	n.mu.Unlock()+}++func (n *NativeServer) Status() (bool, string, string, string) {+	n.mu.Lock()+	defer n.mu.Unlock()+	return n.running, n.lastErr, n.Fingerprint, n.Address+}++func sleepContext(ctx context.Context, d time.Duration) bool {+	t := time.NewTimer(d)+	defer t.Stop()+	select {+	case <-ctx.Done():+		return false+	case <-t.C:+		return true+	}+}++func minDuration(a, b time.Duration) time.Duration {+	if a < b {+		return a+	}+	return b+}++type logWriter struct {+	l      *log.Logger+	prefix string+}++func (w logWriter) Write(p []byte) (int, error) {+	for _, line := range strings.Split(strings.TrimRight(string(p), "\n"), "\n") {+		if line != "" {+			w.l.Printf("%s%s", w.prefix, line)+		}+	}+	return len(p), nil+}++func ensureCertificate(certPath, keyPath, host string) (string, error) {+	if cert, err := loadCertificate(certPath); err == nil {+		if _, err := os.Stat(keyPath); err == nil {+			sum := sha256.Sum256(cert.Raw)+			return hex.EncodeToString(sum[:]), nil+		}+	}+	if err := os.MkdirAll(filepath.Dir(certPath), 0o700); err != nil {+		return "", err+	}+	pub, priv, err := ed25519.GenerateKey(rand.Reader)+	if err != nil {+		return "", err+	}+	serial, err := rand.Int(rand.Reader, new(big.Int).Lsh(big.NewInt(1), 128))+	if err != nil {+		return "", err+	}+	tmpl := &x509.Certificate{+		SerialNumber: serial,+		Subject:      pkix.Name{CommonName: "veinsforge native"},+		NotBefore:    time.Now().Add(-time.Hour),+		NotAfter:     time.Now().AddDate(10, 0, 0),+		KeyUsage:     x509.KeyUsageDigitalSignature,+		ExtKeyUsage:  []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},+		DNSNames:     []string{"localhost", host},+		IPAddresses:  []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},+	}+	if ip := net.ParseIP(host); ip != nil {+		tmpl.IPAddresses = append(tmpl.IPAddresses, ip)+	}+	der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, priv)+	if err != nil {+		return "", err+	}+	certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})+	keyDER, err := x509.MarshalPKCS8PrivateKey(priv)+	if err != nil {+		return "", err+	}+	keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})+	if err := os.WriteFile(certPath, certPEM, 0o644); err != nil {+		return "", err+	}+	if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil {+		return "", err+	}+	sum := sha256.Sum256(der)+	return hex.EncodeToString(sum[:]), nil+}++func loadCertificate(path string) (*x509.Certificate, error) {+	data, err := os.ReadFile(path)+	if err != nil {+		return nil, err+	}+	block, _ := pem.Decode(data)+	if block == nil {+		return nil, fmt.Errorf("invalid certificate")+	}+	return x509.ParseCertificate(block.Bytes)+}--- /dev/null+++ b/internal/web/access.go@@ -0,0 +1,107 @@+package web++import (+	"context"+	"time"++	"veinsforge/internal/data"+	"veinsforge/internal/vn"+)++// syncRepoAccess regenerates .veins/access from SQLite permissions.+func (s *Server) syncRepoAccess(ctx context.Context, repo *data.Repo) error {+	s.accessMu.Lock()+	defer s.accessMu.Unlock()+	users, err := s.data.AccessUsers(ctx, repo)+	if err != nil {+		return err+	}+	keys, err := s.data.AllActiveSSHKeys(ctx)+	if err != nil {+		return err+	}+	byUser := make(map[int64][]*data.SSHKey)+	for _, k := range keys {+		byUser[k.UserID] = append(byUser[k.UserID], k)+	}+	var entries []vn.AccessEntry+	userNames := make(map[int64]string)+	for _, au := range users {+		if u, err := s.data.GetUserByID(ctx, au.UserID); err == nil {+			userNames[au.UserID] = u.Username+		}+	}+	for _, au := range users {+		name := userNames[au.UserID]+		role := au.Role+		if repo.Archived && role != "read" {+			role = "read"+		}+		for _, k := range byUser[au.UserID] {+			entries = append(entries, vn.AccessEntry{PublicKey: k.PublicKey, Name: name, Role: role})+		}+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	return s.vn.WriteAccess(central, repo.Visibility == "public", entries)+}++func (s *Server) syncRepoAccessByID(ctx context.Context, repoID int64) error {+	repo, err := s.data.GetRepoByID(ctx, repoID)+	if err != nil {+		return err+	}+	return s.syncRepoAccess(ctx, repo)+}++func (s *Server) syncOrgAccess(ctx context.Context, orgID int64) error {+	org, err := s.data.GetOrgByID(ctx, orgID)+	if err != nil {+		return err+	}+	repos, err := s.data.ListOwnerRepos(ctx, "org", orgID, true)+	if err != nil {+		return err+	}+	for _, repo := range repos {+		if err := s.syncRepoAccess(ctx, repo); err != nil {+			return err+		}+	}+	_ = org+	return nil+}++func (s *Server) syncAllAccess(ctx context.Context) error {+	repos, err := s.data.AllRepos(ctx)+	if err != nil {+		return err+	}+	for _, repo := range repos {+		if err := s.syncRepoAccess(ctx, repo); err != nil {+			return err+		}+	}+	return nil+}++// StartBackground runs periodic housekeeping and access reconciliation.+func (s *Server) StartBackground(ctx context.Context) {+	go func() {+		ticker := time.NewTicker(2 * time.Minute)+		defer ticker.Stop()+		for {+			select {+			case <-ctx.Done():+				return+			case <-ticker.C:+				s.data.CleanupSessions(ctx)+				s.data.CleanupLoginAttempts(ctx, time.Now().Add(-7*24*time.Hour))+				sctx, cancel := context.WithTimeout(ctx, 90*time.Second)+				if err := s.syncAllAccess(sctx); err != nil {+					s.logger.Printf("periodic access sync: %v", err)+				}+				cancel()+			}+		}+	}()+}--- /dev/null+++ b/internal/web/admin_handlers.go@@ -0,0 +1,234 @@+package web++import (+	"errors"+	"net/http"+	"strconv"+	"strings"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++func (s *Server) adminPage(w http.ResponseWriter, r *http.Request) {+	u := s.requireAdmin(w, r)+	if u == nil {+		return+	}+	stats, _ := s.data.SiteStats(r.Context())+	audit, _ := s.data.ListAudit(r.Context(), 0, 20)+	running, lastErr, pin, address := "", "", "", ""+	if s.native != nil {+		ok, e, p, a := s.native.Status()+		if ok {+			running = "running"+		}+		lastErr, pin, address = e, p, a+	}+	page := s.page(r, "Admin")+	page.Data = map[string]any{+		"Stats": stats, "Audit": audit, "NativeState": running,+		"NativeError": lastErr, "NativePin": pin, "NativeAddress": address,+		"RegistrationOpen": s.registrationOpen(r.Context()),+	}+	s.render(w, r, http.StatusOK, "admin", page)+}++func (s *Server) adminUsers(w http.ResponseWriter, r *http.Request) {+	if s.requireAdmin(w, r) == nil {+		return+	}+	pageNo, size, offset := data.Pagination(r.URL.Query().Get("page"), "50")+	users, _ := s.data.ListUsers(r.Context(), offset, size)+	count, _ := s.data.CountUsers(r.Context())+	page := s.page(r, "Users · Admin")+	page.Data = map[string]any{"Users": users, "Count": count, "Page": pageNo, "HasNext": int64(offset+size) < count}+	s.render(w, r, http.StatusOK, "admin", page)+}++func (s *Server) adminUserCreate(w http.ResponseWriter, r *http.Request) {+	admin := s.requireAdmin(w, r)+	if admin == nil {+		return+	}+	username := strings.TrimSpace(r.FormValue("username"))+	display := auth.CleanOneLine(r.FormValue("display_name"), 80)+	email := strings.TrimSpace(r.FormValue("email"))+	password := r.FormValue("password")+	if err := auth.ValidHandle(username); err != nil {+		redirect(w, r, "/admin/users", "", err.Error())+		return+	}+	if display == "" {+		display = username+	}+	if err := auth.ValidEmail(email); err != nil {+		redirect(w, r, "/admin/users", "", err.Error())+		return+	}+	if err := auth.ValidatePassword(password); err != nil {+		redirect(w, r, "/admin/users", "", err.Error())+		return+	}+	hash, err := s.hashPassword(password)+	if err != nil {+		redirect(w, r, "/admin/users", "", "Could not hash the password.")+		return+	}+	isAdmin := r.FormValue("is_admin") == "on"+	target, err := s.data.CreateUser(r.Context(), username, display, email, hash, ipFrom(r), isAdmin)+	if err != nil {+		if errors.Is(err, data.ErrConflict) {+			redirect(w, r, "/admin/users", "", "That username is taken.")+		} else {+			redirect(w, r, "/admin/users", "", "Could not create the user.")+		}+		return+	}+	s.data.RecordAudit(r.Context(), &admin.ID, admin.Username, ipFrom(r), "admin.user.create", target.Username, r.UserAgent())+	redirect(w, r, "/admin/users", "User created.", "")+}++func (s *Server) adminUserActive(w http.ResponseWriter, r *http.Request) {+	admin := s.requireAdmin(w, r)+	if admin == nil {+		return+	}+	id, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid user.")+		return+	}+	if id == admin.ID {+		redirect(w, r, "/admin/users", "", "You cannot deactivate your own account.")+		return+	}+	target, err := s.data.GetUserByID(r.Context(), id)+	if err != nil {+		redirect(w, r, "/admin/users", "", "User not found.")+		return+	}+	active := !target.IsActive+	if err := s.data.SetUserActive(r.Context(), id, active); err != nil {+		redirect(w, r, "/admin/users", "", "Could not update the user.")+		return+	}+	s.data.RecordAudit(r.Context(), &admin.ID, admin.Username, ipFrom(r), "admin.user.active", target.Username+" "+strconv.FormatBool(active), r.UserAgent())+	s.syncAllAccessAsync()+	redirect(w, r, "/admin/users", "User updated.", "")+}++func (s *Server) adminUserAdmin(w http.ResponseWriter, r *http.Request) {+	admin := s.requireAdmin(w, r)+	if admin == nil {+		return+	}+	id, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid user.")+		return+	}+	if id == admin.ID {+		redirect(w, r, "/admin/users", "", "You cannot change your own administrator flag.")+		return+	}+	target, err := s.data.GetUserByID(r.Context(), id)+	if err != nil {+		redirect(w, r, "/admin/users", "", "User not found.")+		return+	}+	makeAdmin := !target.IsAdmin+	if err := s.data.SetUserAdmin(r.Context(), id, makeAdmin); err != nil {+		redirect(w, r, "/admin/users", "", "Could not update the user.")+		return+	}+	s.data.RecordAudit(r.Context(), &admin.ID, admin.Username, ipFrom(r), "admin.user.admin", target.Username+" "+strconv.FormatBool(makeAdmin), r.UserAgent())+	redirect(w, r, "/admin/users", "User updated.", "")+}++func (s *Server) adminUserPassword(w http.ResponseWriter, r *http.Request) {+	admin := s.requireAdmin(w, r)+	if admin == nil {+		return+	}+	id, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid user.")+		return+	}+	target, err := s.data.GetUserByID(r.Context(), id)+	if err != nil {+		redirect(w, r, "/admin/users", "", "User not found.")+		return+	}+	password := r.FormValue("password")+	if err := auth.ValidatePassword(password); err != nil {+		redirect(w, r, "/admin/users", "", err.Error())+		return+	}+	hash, err := s.hashPassword(password)+	if err != nil {+		redirect(w, r, "/admin/users", "", "Could not hash the password.")+		return+	}+	if err := s.data.UpdateUserPassword(r.Context(), id, hash); err != nil {+		redirect(w, r, "/admin/users", "", "Could not update the password.")+		return+	}+	s.data.DeleteUserSessions(r.Context(), id)+	s.data.RecordAudit(r.Context(), &admin.ID, admin.Username, ipFrom(r), "admin.user.password", target.Username, r.UserAgent())+	redirect(w, r, "/admin/users", "Password reset. Existing sessions were signed out.", "")+}++func (s *Server) adminRepos(w http.ResponseWriter, r *http.Request) {+	if s.requireAdmin(w, r) == nil {+		return+	}+	pageNo, size, offset := data.Pagination(r.URL.Query().Get("page"), "50")+	repos, _ := s.data.ListAllRepos(r.Context(), offset, size)+	count, _ := s.data.CountRepos(r.Context())+	page := s.page(r, "Repositories · Admin")+	page.Data = map[string]any{"Repos": repos, "Count": count, "Page": pageNo, "HasNext": int64(offset+size) < count}+	s.render(w, r, http.StatusOK, "admin", page)+}++func (s *Server) adminAudit(w http.ResponseWriter, r *http.Request) {+	if s.requireAdmin(w, r) == nil {+		return+	}+	pageNo, size, offset := data.Pagination(r.URL.Query().Get("page"), "100")+	entries, _ := s.data.ListAudit(r.Context(), offset, size)+	count, _ := s.data.CountAudit(r.Context())+	page := s.page(r, "Audit log · Admin")+	page.Data = map[string]any{"Audit": entries, "Count": count, "Page": pageNo, "HasNext": int64(offset+size) < count}+	s.render(w, r, http.StatusOK, "admin", page)+}++func (s *Server) adminSettings(w http.ResponseWriter, r *http.Request) {+	admin := s.requireAdmin(w, r)+	if admin == nil {+		return+	}+	name := auth.CleanOneLine(r.FormValue("site_name"), 60)+	description := auth.CleanOneLine(r.FormValue("site_description"), 240)+	registration := r.FormValue("registration_open") == "on"+	if name == "" {+		name = "veinsforge"+	}+	if err := s.data.SetSetting(r.Context(), "site_name", name); err != nil {+		redirect(w, r, "/admin", "", "Could not save settings.")+		return+	}+	if err := s.data.SetSetting(r.Context(), "site_description", description); err != nil {+		redirect(w, r, "/admin", "", "Could not save settings.")+		return+	}+	if err := s.data.SetSetting(r.Context(), "registration_open", strconv.FormatBool(registration)); err != nil {+		redirect(w, r, "/admin", "", "Could not save settings.")+		return+	}+	s.siteName = name+	s.siteDesc = description+	s.data.RecordAudit(r.Context(), &admin.ID, admin.Username, ipFrom(r), "admin.settings", "", r.UserAgent())+	redirect(w, r, "/admin", "Site settings saved.", "")+}--- /dev/null+++ b/internal/web/attachments.go@@ -0,0 +1,199 @@+package web++import (+	"io"+	"mime"+	"net/http"+	"os"+	"path/filepath"+	"strconv"+	"strings"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++func (s *Server) handleAttachmentUpload(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !perms.CanView || repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "Cannot attach files here.")+		return+	}+	subjectType := r.FormValue("subject_type")+	subjectID, ok := parseID(r.FormValue("subject_id"))+	if !ok || (subjectType != "issue" && subjectType != "pull") {+		s.renderError(w, r, http.StatusBadRequest, "Invalid attachment target.")+		return+	}+	if subjectType == "issue" {+		issue, err := s.data.GetIssueByID(r.Context(), subjectID)+		if err != nil || issue.RepoID != repo.ID {+			s.renderError(w, r, http.StatusNotFound, "Issue not found.")+			return+		}+	} else {+		pull, err := s.data.GetPullByID(r.Context(), subjectID)+		if err != nil || pull.RepoID != repo.ID {+			s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+			return+		}+	}+	file, header, err := r.FormFile("file")+	if err != nil {+		redirect(w, r, repoURL(repo), "", "Choose a file to upload.")+		return+	}+	defer file.Close()+	dataBytes, err := io.ReadAll(io.LimitReader(file, s.cfg.MaxUploadBytes+1))+	if err != nil || int64(len(dataBytes)) > s.cfg.MaxUploadBytes {+		redirect(w, r, repoURL(repo), "", "Attachment is too large.")+		return+	}+	if len(dataBytes) == 0 {+		redirect(w, r, repoURL(repo), "", "Attachment is empty.")+		return+	}+	filename := sanitizeFilename(header.Filename)+	if filename == "" {+		filename = "attachment"+	}+	mimeType := http.DetectContentType(dataBytes[:minInt(len(dataBytes), 512)])+	ext := filepath.Ext(filename)+	if strings.EqualFold(ext, ".svg") || strings.Contains(strings.ToLower(mimeType), "svg") || strings.Contains(strings.ToLower(mimeType), "html") {+		mimeType = "application/octet-stream"+	}+	id, err := auth.RandomToken(18)+	if err != nil {+		redirect(w, r, repoURL(repo), "", "Could not store the attachment.")+		return+	}+	stored := id+	if safeExt := cleanExt(ext); safeExt != "" {+		stored += safeExt+	}+	dir := filepath.Join(s.cfg.AttachmentDir, strconv.FormatInt(repo.ID, 10))+	if err := os.MkdirAll(dir, 0o700); err != nil {+		redirect(w, r, repoURL(repo), "", "Could not store the attachment.")+		return+	}+	if err := os.WriteFile(filepath.Join(dir, stored), dataBytes, 0o600); err != nil {+		redirect(w, r, repoURL(repo), "", "Could not store the attachment.")+		return+	}+	att := &data.Attachment{+		ID: id, RepoID: repo.ID, UploaderID: u.ID, SubjectType: subjectType, SubjectID: subjectID,+		Filename: filename, StoredName: stored, MIME: mimeType, Size: int64(len(dataBytes)),+	}+	if err := s.data.CreateAttachment(r.Context(), att); err != nil {+		_ = os.Remove(filepath.Join(dir, stored))+		redirect(w, r, repoURL(repo), "", "Could not save the attachment record.")+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "attachment.create", repo.OwnerName+"/"+repo.Name+" "+filename, r.UserAgent())+	target := repoURL(repo) + "/issues"+	if subjectType == "pull" {+		target = repoURL(repo) + "/pulls"+	}+	// Redirect back to the concrete subject.+	if subjectType == "issue" {+		if issue, err := s.data.GetIssueByID(r.Context(), subjectID); err == nil {+			target = issueURL(repo, issue.Number)+		}+	} else {+		if pull, err := s.data.GetPullByID(r.Context(), subjectID); err == nil {+			target = pullURL(repo, pull.Number)+		}+	}+	redirect(w, r, target, "Attachment uploaded.", "")+}++func (s *Server) attachmentGet(w http.ResponseWriter, r *http.Request) {+	att, err := s.data.GetAttachment(r.Context(), r.PathValue("id"))+	if err != nil {+		http.NotFound(w, r)+		return+	}+	repo, err := s.data.GetRepoByID(r.Context(), att.RepoID)+	if err != nil {+		http.NotFound(w, r)+		return+	}+	perms, err := s.data.Permissions(r.Context(), repo, userFrom(r))+	if err != nil || !perms.CanView {+		http.NotFound(w, r)+		return+	}+	file := filepath.Join(s.cfg.AttachmentDir, strconv.FormatInt(repo.ID, 10), filepath.Base(att.StoredName))+	f, err := os.Open(file)+	if err != nil {+		http.NotFound(w, r)+		return+	}+	defer f.Close()+	stat, err := f.Stat()+	if err != nil {+		http.NotFound(w, r)+		return+	}+	name := sanitizeFilename(att.Filename)+	if name == "" {+		name = "attachment"+	}+	mimeType := att.MIME+	disposition := "attachment"+	if isSafeImage(mimeType) {+		disposition = "inline"+	} else if !strings.HasPrefix(mimeType, "text/") && mimeType != "application/pdf" {+		mimeType = "application/octet-stream"+	}+	w.Header().Set("Content-Type", mimeType)+	w.Header().Set("X-Content-Type-Options", "nosniff")+	w.Header().Set("Content-Disposition", mime.FormatMediaType(disposition, map[string]string{"filename": name}))+	w.Header().Set("Cache-Control", "private, max-age=300")+	http.ServeContent(w, r, name, stat.ModTime(), f)+}++func sanitizeFilename(name string) string {+	name = filepath.Base(strings.ReplaceAll(name, "\\", "/"))+	name = strings.Map(func(r rune) rune {+		if r < 32 || r == 127 || r == '"' || r == '\'' || r == '\n' || r == '\r' {+			return -1+		}+		return r+	}, name)+	name = strings.TrimSpace(name)+	if len(name) > 200 {+		name = name[:200]+	}+	if name == "." || name == ".." {+		return ""+	}+	return name+}++func cleanExt(ext string) string {+	if len(ext) < 2 || len(ext) > 12 {+		return ""+	}+	ext = strings.ToLower(ext)+	for _, r := range ext[1:] {+		if (r < 'a' || r > 'z') && (r < '0' || r > '9') {+			return ""+		}+	}+	return ext+}++func minInt(a, b int) int {+	if a < b {+		return a+	}+	return b+}--- /dev/null+++ b/internal/web/auth_handlers.go@@ -0,0 +1,383 @@+package web++import (+	"context"+	"errors"+	"net/http"+	"strconv"+	"strings"+	"time"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++func (s *Server) registrationOpen(ctx context.Context) bool {+	return strings.EqualFold(s.data.Setting(ctx, "registration_open", "true"), "true")+}++func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {+	if userFrom(r) != nil {+		http.Redirect(w, r, "/", http.StatusSeeOther)+		return+	}+	page := s.page(r, "Sign in")+	page.Data = map[string]any{"Next": r.URL.Query().Get("next")}+	s.render(w, r, http.StatusOK, "login", page)+}++func (s *Server) loginPost(w http.ResponseWriter, r *http.Request) {+	if userFrom(r) != nil {+		http.Redirect(w, r, "/", http.StatusSeeOther)+		return+	}+	username := strings.TrimSpace(r.FormValue("username"))+	password := r.FormValue("password")+	next := safeNext(r.FormValue("next"))+	ip := ipFrom(r)+	if username == "" || password == "" || len(password) > 256 {+		s.renderLoginFailure(w, r, http.StatusUnauthorized, "Invalid username or password.", username, next)+		return+	}+	failures, _ := s.data.RecentFailures(r.Context(), username, ip, time.Now().Add(-15*time.Minute))+	if failures >= 8 {+		s.renderLoginFailure(w, r, http.StatusTooManyRequests, "Too many failed attempts. Try again in a few minutes.", username, next)+		return+	}+	user, err := s.data.GetUserByUsername(r.Context(), username)+	if err != nil || !user.IsActive {+		_ = s.verifyPassword(s.dummyHash, password)+		s.data.RecordLoginAttempt(r.Context(), username, ip, false)+		s.data.RecordAudit(r.Context(), nil, username, ip, "login.failed", "", r.UserAgent())+		s.renderLoginFailure(w, r, http.StatusUnauthorized, "Invalid username or password.", username, next)+		return+	}+	if !s.verifyPassword(user.PasswordHash, password) {+		s.data.RecordLoginAttempt(r.Context(), username, ip, false)+		s.data.RecordAudit(r.Context(), &user.ID, user.Username, ip, "login.failed", "", r.UserAgent())+		s.renderLoginFailure(w, r, http.StatusUnauthorized, "Invalid username or password.", username, next)+		return+	}+	s.data.RecordLoginAttempt(r.Context(), username, ip, true)+	s.data.ClearLoginFailures(r.Context(), ip)+	if err := s.startSession(w, r, user); err != nil {+		s.logger.Printf("start session for %s: %v", user.Username, err)+		s.renderLoginFailure(w, r, http.StatusInternalServerError, "Could not start a session.", username, next)+		return+	}+	s.data.RecordAudit(r.Context(), &user.ID, user.Username, ip, "login", "", r.UserAgent())+	if next == "" {+		next = "/"+	}+	http.Redirect(w, r, next, http.StatusSeeOther)+}++func (s *Server) renderLoginFailure(w http.ResponseWriter, r *http.Request, status int, msg, username, next string) {+	page := s.page(r, "Sign in")+	page.Error = msg+	page.Data = map[string]any{"Username": username, "Next": next}+	s.render(w, r, status, "login", page)+}++func (s *Server) signupPage(w http.ResponseWriter, r *http.Request) {+	if userFrom(r) != nil {+		http.Redirect(w, r, "/", http.StatusSeeOther)+		return+	}+	if !s.registrationOpen(r.Context()) {+		s.renderError(w, r, http.StatusForbidden, "Registration is closed.")+		return+	}+	page := s.page(r, "Create account")+	page.Data = map[string]any{}+	s.render(w, r, http.StatusOK, "signup", page)+}++func (s *Server) signupPost(w http.ResponseWriter, r *http.Request) {+	if userFrom(r) != nil {+		http.Redirect(w, r, "/", http.StatusSeeOther)+		return+	}+	if !s.registrationOpen(r.Context()) {+		s.renderError(w, r, http.StatusForbidden, "Registration is closed.")+		return+	}+	username := strings.TrimSpace(r.FormValue("username"))+	display := auth.CleanOneLine(r.FormValue("display_name"), 80)+	email := strings.TrimSpace(r.FormValue("email"))+	password := r.FormValue("password")+	confirm := r.FormValue("confirm")+	ip := ipFrom(r)++	page := s.page(r, "Create account")+	page.Data = map[string]any{"Username": username, "DisplayName": display, "Email": email}++	fail := func(msg string) {+		page.Error = msg+		s.render(w, r, http.StatusBadRequest, "signup", page)+	}+	if err := auth.ValidHandle(username); err != nil {+		fail(err.Error())+		return+	}+	if display == "" {+		display = username+	}+	if err := auth.ValidEmail(email); err != nil {+		fail(err.Error())+		return+	}+	if err := auth.ValidatePassword(password); err != nil {+		fail(err.Error())+		return+	}+	if password != confirm {+		fail("Passwords do not match.")+		return+	}+	available, err := s.data.UsernameAvailable(r.Context(), username)+	if err != nil {+		fail("Could not check that name. Try again.")+		return+	}+	if !available {+		fail("That username or organisation name is already taken.")+		return+	}+	hash, err := s.hashPassword(password)+	if err != nil {+		fail("Could not hash the password.")+		return+	}+	user, err := s.data.CreateUserAutoAdmin(r.Context(), username, display, email, hash, ip)+	if err != nil {+		if errors.Is(err, data.ErrConflict) {+			fail("That username or organisation name is already taken.")+		} else {+			s.logger.Printf("create user: %v", err)+			fail("Could not create the account.")+		}+		return+	}+	if err := s.startSession(w, r, user); err != nil {+		s.logger.Printf("start session for %s: %v", user.Username, err)+		fail("Account created, but the session could not start. Sign in instead.")+		return+	}+	s.data.RecordAudit(r.Context(), &user.ID, user.Username, ip, "signup", "", r.UserAgent())+	http.Redirect(w, r, "/", http.StatusSeeOther)+}++func (s *Server) startSession(w http.ResponseWriter, r *http.Request, user *data.User) error {+	if old := sessionFrom(r); old != nil {+		s.data.DeleteSession(context.Background(), old.ID)+	}+	token, err := auth.RandomToken(32)+	if err != nil {+		return err+	}+	csrf, err := auth.RandomToken(32)+	if err != nil {+		return err+	}+	expires := time.Now().Add(s.cfg.SessionTTL)+	if err := s.data.CreateSession(r.Context(), auth.HashToken(token), user.ID, csrf, ipFrom(r), truncateString(r.UserAgent(), 300), expires); err != nil {+		return err+	}+	s.data.RecordLogin(r.Context(), user.ID, ipFrom(r))+	s.setSessionCookie(w, token)+	return nil+}++func (s *Server) logout(w http.ResponseWriter, r *http.Request) {+	if sess := sessionFrom(r); sess != nil {+		s.data.DeleteSession(r.Context(), sess.ID)+	}+	s.clearSessionCookie(w)+	if u := userFrom(r); u != nil {+		s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "logout", "", r.UserAgent())+	}+	http.Redirect(w, r, "/", http.StatusSeeOther)+}++func (s *Server) userSettings(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	keys, err := s.data.ListSSHKeys(r.Context(), u.ID)+	if err != nil {+		s.renderError(w, r, http.StatusInternalServerError, "Could not load SSH keys.")+		return+	}+	page := s.page(r, "Settings")+	page.Data = map[string]any{+		"Keys":      keys,+		"HasAvatar": u.AvatarFile != "",+		"Admin":     u.IsAdmin,+	}+	s.render(w, r, http.StatusOK, "settings_user", page)+}++func (s *Server) userProfilePost(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	display := auth.CleanOneLine(r.FormValue("display_name"), 80)+	email := strings.TrimSpace(r.FormValue("email"))+	bio := strings.TrimSpace(r.FormValue("bio"))+	if len(bio) > 2000 {+		redirect(w, r, "/settings", "", "Bio is too long.")+		return+	}+	if display == "" {+		display = u.Username+	}+	if err := auth.ValidEmail(email); err != nil {+		redirect(w, r, "/settings", "", err.Error())+		return+	}+	if err := s.data.UpdateUserProfile(r.Context(), u.ID, display, email, bio); err != nil {+		redirect(w, r, "/settings", "", "Could not save profile.")+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "profile.update", "", r.UserAgent())+	redirect(w, r, "/settings", "Profile updated.", "")+}++func (s *Server) userPasswordPost(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	current := r.FormValue("current")+	password := r.FormValue("password")+	confirm := r.FormValue("confirm")+	if !s.verifyPassword(u.PasswordHash, current) {+		redirect(w, r, "/settings", "", "Current password is incorrect.")+		return+	}+	if err := auth.ValidatePassword(password); err != nil {+		redirect(w, r, "/settings", "", err.Error())+		return+	}+	if password != confirm {+		redirect(w, r, "/settings", "", "Passwords do not match.")+		return+	}+	hash, err := s.hashPassword(password)+	if err != nil {+		redirect(w, r, "/settings", "", "Could not hash the password.")+		return+	}+	if err := s.data.UpdateUserPassword(r.Context(), u.ID, hash); err != nil {+		redirect(w, r, "/settings", "", "Could not update the password.")+		return+	}+	s.data.DeleteUserSessions(r.Context(), u.ID)+	if err := s.startSession(w, r, u); err != nil {+		s.logger.Printf("restart session after password change: %v", err)+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "password.change", "", r.UserAgent())+	redirect(w, r, "/settings", "Password changed. Other sessions were signed out.", "")+}++func (s *Server) userKeyAdd(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	name := auth.CleanOneLine(r.FormValue("name"), 64)+	rawKey := strings.TrimSpace(r.FormValue("public_key"))+	if !auth.ValidKeyName(name) {+		redirect(w, r, "/settings", "", "Key name is required (max 64 characters).")+		return+	}+	canonical, _, fingerprint, err := auth.ParsePublicKey(rawKey)+	if err != nil {+		redirect(w, r, "/settings", "", err.Error())+		return+	}+	if err := s.data.AddSSHKey(r.Context(), u.ID, name, canonical, fingerprint); err != nil {+		if errors.Is(err, data.ErrConflict) {+			redirect(w, r, "/settings", "", "That key is already registered.")+		} else {+			redirect(w, r, "/settings", "", "Could not add the key.")+		}+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "key.add", fingerprint, r.UserAgent())+	s.syncAllAccessAsync()+	redirect(w, r, "/settings", "SSH key added. New clone sessions will see it immediately.", "")+}++func (s *Server) userKeyDelete(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	id, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid key.")+		return+	}+	if err := s.data.DeleteSSHKey(r.Context(), u.ID, id); err != nil {+		redirect(w, r, "/settings", "", "Could not remove that key.")+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "key.remove", strconv.FormatInt(id, 10), r.UserAgent())+	s.syncAllAccessAsync()+	redirect(w, r, "/settings", "SSH key removed.", "")+}++func (s *Server) userPage(w http.ResponseWriter, r *http.Request) {+	username := r.PathValue("username")+	u, err := s.data.GetUserByUsername(r.Context(), username)+	if err != nil || !u.IsActive {+		s.renderError(w, r, http.StatusNotFound, "User not found.")+		return+	}+	repos, _ := s.data.ListOwnerRepos(r.Context(), "user", u.ID, u.ID == userID(userFrom(r)))+	orgs, _ := s.data.ListUserOrgs(r.Context(), u.ID)+	starred, _ := s.data.ListStarredRepos(r.Context(), u.ID, userFrom(r) != nil && userFrom(r).ID == u.ID)+	page := s.page(r, u.Username)+	page.Data = map[string]any{+		"Profile": u,+		"Repos":   repos,+		"Orgs":    orgs,+		"Starred": starred,+		"Self":    userFrom(r) != nil && userFrom(r).ID == u.ID,+	}+	s.render(w, r, http.StatusOK, "user", page)+}++func userID(u *data.User) int64 {+	if u == nil {+		return 0+	}+	return u.ID+}++func safeNext(next string) string {+	if next == "" {+		return ""+	}+	if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.Contains(next, "\\") {+		return ""+	}+	if strings.HasPrefix(next, "/login") || strings.HasPrefix(next, "/signup") {+		return ""+	}+	return next+}++func (s *Server) syncAllAccessAsync() {+	go func() {+		ctx, cancel := backgroundWithTimeout(2 * time.Minute)+		defer cancel()+		if err := s.syncAllAccess(ctx); err != nil {+			s.logger.Printf("sync all access: %v", err)+		}+	}()+}--- /dev/null+++ b/internal/web/avatar.go@@ -0,0 +1,146 @@+package web++import (+	"bytes"+	"crypto/sha256"+	"fmt"+	"html"+	"image"+	_ "image/gif"+	_ "image/jpeg"+	"image/png"+	"io"+	"net/http"+	"os"+	"path/filepath"+	"strconv"+	"strings"+)++func (s *Server) userAvatar(w http.ResponseWriter, r *http.Request) {+	name := r.PathValue("username")+	if strings.HasPrefix(name, "org-") {+		orgName := strings.TrimPrefix(name, "org-")+		org, err := s.data.GetOrgByName(r.Context(), orgName)+		if err != nil {+			s.renderAvatarPlaceholder(w, orgName)+			return+		}+		s.renderAvatarPlaceholder(w, org.DisplayName)+		return+	}+	u, err := s.data.GetUserByUsername(r.Context(), name)+	if err != nil || !u.IsActive {+		s.renderAvatarPlaceholder(w, name)+		return+	}+	if u.AvatarFile != "" {+		file := filepath.Join(s.cfg.AvatarDir, filepath.Base(u.AvatarFile))+		if f, err := os.Open(file); err == nil {+			defer f.Close()+			w.Header().Set("Content-Type", "image/png")+			w.Header().Set("Cache-Control", "public, max-age=300")+			w.Header().Set("X-Content-Type-Options", "nosniff")+			http.ServeContent(w, r, "avatar.png", u.UpdatedAt, f)+			return+		}+	}+	display := u.DisplayName+	if display == "" {+		display = u.Username+	}+	s.renderAvatarPlaceholder(w, display)+}++func (s *Server) renderAvatarPlaceholder(w http.ResponseWriter, name string) {+	initials := initials(name)+	hash := sha256.Sum256([]byte(strings.ToLower(name)))+	palette := []string{"#0b1b34", "#111827", "#3a0d12", "#1f2937", "#450a0a", "#0f172a"}+	bg := palette[int(hash[0])%len(palette)]+	accent := "#e5383b"+	if hash[1]%3 == 0 {+		accent = "#d7e3f4"+	}+	svg := fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128" role="img" aria-label="%s">+<rect width="128" height="128" fill="%s"/>+<rect x="8" y="8" width="112" height="112" fill="none" stroke="%s" stroke-width="2"/>+<text x="64" y="79" text-anchor="middle" font-family="ui-monospace,monospace" font-size="44" font-weight="700" fill="%s">%s</text>+</svg>`, html.EscapeString(name), bg, accent, accent, html.EscapeString(initials))+	w.Header().Set("Content-Type", "image/svg+xml")+	w.Header().Set("Cache-Control", "public, max-age=300")+	w.Header().Set("X-Content-Type-Options", "nosniff")+	w.Header().Set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'")+	_, _ = w.Write([]byte(svg))+}++func (s *Server) userAvatarPost(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	file, header, err := r.FormFile("avatar")+	if err != nil {+		redirect(w, r, "/settings", "", "Choose an image to upload.")+		return+	}+	defer file.Close()+	_ = header+	raw, err := io.ReadAll(io.LimitReader(file, s.cfg.MaxAvatarBytes+1))+	if err != nil || int64(len(raw)) > s.cfg.MaxAvatarBytes {+		redirect(w, r, "/settings", "", "Avatar is too large.")+		return+	}+	cfg, _, err := image.DecodeConfig(bytes.NewReader(raw))+	if err != nil {+		redirect(w, r, "/settings", "", "Avatar must be a PNG, JPEG or GIF image.")+		return+	}+	if cfg.Width > 4096 || cfg.Height > 4096 || cfg.Width*cfg.Height > 16_000_000 {+		redirect(w, r, "/settings", "", "Avatar dimensions are too large.")+		return+	}+	img, _, err := image.Decode(bytes.NewReader(raw))+	if err != nil {+		redirect(w, r, "/settings", "", "Avatar must be a PNG, JPEG or GIF image.")+		return+	}+	if err := os.MkdirAll(s.cfg.AvatarDir, 0o700); err != nil {+		redirect(w, r, "/settings", "", "Could not save the avatar.")+		return+	}+	name := strconv.FormatInt(u.ID, 10) + ".png"+	final := filepath.Join(s.cfg.AvatarDir, name)+	tmp := final + ".tmp"+	f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600)+	if err != nil {+		redirect(w, r, "/settings", "", "Could not save the avatar.")+		return+	}+	if err := png.Encode(f, img); err != nil {+		f.Close()+		os.Remove(tmp)+		redirect(w, r, "/settings", "", "Could not encode the avatar.")+		return+	}+	_ = f.Close()+	if err := os.Rename(tmp, final); err != nil {+		redirect(w, r, "/settings", "", "Could not save the avatar.")+		return+	}+	_ = s.data.SetUserAvatar(r.Context(), u.ID, name)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "avatar.update", "", r.UserAgent())+	redirect(w, r, "/settings", "Avatar updated.", "")+}++func (s *Server) userAvatarDelete(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if u.AvatarFile != "" {+		_ = os.Remove(filepath.Join(s.cfg.AvatarDir, filepath.Base(u.AvatarFile)))+	}+	_ = s.data.SetUserAvatar(r.Context(), u.ID, "")+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "avatar.delete", "", r.UserAgent())+	redirect(w, r, "/settings", "Avatar removed.", "")+}--- /dev/null+++ b/internal/web/helpers.go@@ -0,0 +1,326 @@+package web++import (+	"bytes"+	"context"+	"encoding/base64"+	"fmt"+	"net/http"+	"net/url"+	"path"+	"path/filepath"+	"sort"+	"strconv"+	"strings"+	"time"+	"unicode/utf8"++	"veinsforge/internal/data"+)++type ctxKey int++const (+	userKey ctxKey = iota+	sessionKey+	csrfKey+	ipKey+)++type requestSession struct {+	ID   string+	CSRF string+}++func userFrom(r *http.Request) *data.User {+	u, _ := r.Context().Value(userKey).(*data.User)+	return u+}++func sessionFrom(r *http.Request) *requestSession {+	s, _ := r.Context().Value(sessionKey).(*requestSession)+	return s+}++func csrfFrom(r *http.Request) string {+	if r == nil {+		return ""+	}+	s, _ := r.Context().Value(csrfKey).(string)+	return s+}++func ipFrom(r *http.Request) string {+	ip, _ := r.Context().Value(ipKey).(string)+	return ip+}++func parseID(s string) (int64, bool) {+	n, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64)+	return n, err == nil && n > 0+}++func redirect(w http.ResponseWriter, r *http.Request, target, notice, errMsg string) {+	if !strings.HasPrefix(target, "/") || strings.HasPrefix(target, "//") {+		target = "/"+	}+	u, err := url.Parse(target)+	if err != nil {+		u = &url.URL{Path: "/"}+	}+	q := u.Query()+	if notice != "" {+		q.Set("notice", notice)+	}+	if errMsg != "" {+		q.Set("error", errMsg)+	}+	u.RawQuery = q.Encode()+	http.Redirect(w, r, u.String(), http.StatusSeeOther)+}++func repoURL(repo *data.Repo) string {+	if repo == nil {+		return "/"+	}+	return "/" + url.PathEscape(repo.OwnerName) + "/" + url.PathEscape(repo.Name)+}++func ownerURL(repo *data.Repo) string {+	if repo == nil {+		return "/"+	}+	if repo.OwnerType == "org" {+		return "/orgs/" + url.PathEscape(repo.OwnerName)+	}+	return "/u/" + url.PathEscape(repo.OwnerName)+}++func issueURL(repo *data.Repo, n int64) string {+	return repoURL(repo) + "/issues/" + strconv.FormatInt(n, 10)+}++func pullURL(repo *data.Repo, n int64) string {+	return repoURL(repo) + "/pulls/" + strconv.FormatInt(n, 10)+}++func commitURL(repo *data.Repo, rev string) string {+	return repoURL(repo) + "/commit/" + revPath(rev)+}++func treeURL(repo *data.Repo, rev, p string) string {+	base := repoURL(repo) + "/tree/" + revPath(rev)+	if p != "" {+		base += "/" + escapePath(p)+	}+	return base+}++func blobURL(repo *data.Repo, rev, p string) string {+	return repoURL(repo) + "/blob/" + revPath(rev) + "/" + escapePath(p)+}++func rawURL(repo *data.Repo, rev, p string) string {+	return repoURL(repo) + "/raw/" + revPath(rev) + "/" + escapePath(p)+}++// revPath keeps slash-containing bookmark names inside a single URL segment.+func revPath(rev string) string {+	if rev == "" {+		return ""+	}+	if !strings.ContainsAny(rev, "/?#%") {+		return url.PathEscape(rev)+	}+	return "~" + base64.RawURLEncoding.EncodeToString([]byte(rev))+}++func decodeRevPath(token string) string {+	if strings.HasPrefix(token, "~") {+		if decoded, err := base64.RawURLEncoding.DecodeString(token[1:]); err == nil {+			return string(decoded)+		}+	}+	return token+}++func escapePath(p string) string {+	parts := strings.Split(strings.TrimLeft(path.Clean("/"+p), "/"), "/")+	for i, part := range parts {+		parts[i] = url.PathEscape(part)+	}+	return strings.Join(parts, "/")+}++func avatarURL(username string) string {+	return "/avatars/" + url.PathEscape(username)+}++func orgAvatarURL(name string) string {+	return "/avatars/org-" + url.PathEscape(name)+}++type TreeEntry struct {+	Name  string+	Path  string+	IsDir bool+}++func buildTree(files []string, prefix string) []TreeEntry {+	prefix = strings.TrimSuffix(prefix, "/")+	seen := make(map[string]bool)+	for _, f := range files {+		if prefix != "" {+			if !strings.HasPrefix(f, prefix+"/") {+				continue+			}+			f = strings.TrimPrefix(f, prefix+"/")+		}+		if f == "" {+			continue+		}+		parts := strings.SplitN(f, "/", 2)+		name := parts[0]+		full := name+		if prefix != "" {+			full = prefix + "/" + name+		}+		if len(parts) == 2 {+			seen["d:"+name] = true+			seen["p:"+name] = true+			_ = full+		} else {+			seen["f:"+name] = true+			seen["p:"+name] = true+		}+	}+	var dirs, regular []TreeEntry+	for k := range seen {+		if !strings.HasPrefix(k, "p:") {+			continue+		}+		name := strings.TrimPrefix(k, "p:")+		if name == "" {+			continue+		}+		full := name+		if prefix != "" {+			full = prefix + "/" + name+		}+		e := TreeEntry{Name: name, Path: full, IsDir: seen["d:"+name]}+		if e.IsDir {+			dirs = append(dirs, e)+		} else {+			regular = append(regular, e)+		}+	}+	sort.Slice(dirs, func(i, j int) bool { return strings.ToLower(dirs[i].Name) < strings.ToLower(dirs[j].Name) })+	sort.Slice(regular, func(i, j int) bool { return strings.ToLower(regular[i].Name) < strings.ToLower(regular[j].Name) })+	return append(dirs, regular...)+}++type CodeLine struct {+	Number int+	Text   string+}++type DiffLine struct {+	Text  string+	Class string+}++func splitCode(data []byte) ([]CodeLine, bool, bool) {+	if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) {+		return nil, true, false+	}+	text := string(data)+	truncated := false+	lines := strings.Split(text, "\n")+	if len(lines) > 5000 {+		lines = lines[:5000]+		truncated = true+	}+	out := make([]CodeLine, 0, len(lines))+	for i, line := range lines {+		out = append(out, CodeLine{Number: i + 1, Text: strings.TrimSuffix(line, "\r")})+	}+	return out, false, truncated+}++func splitDiff(diff string) []DiffLine {+	if diff == "" {+		return nil+	}+	diff = strings.TrimSuffix(diff, "\n")+	var out []DiffLine+	for _, line := range strings.Split(diff, "\n") {+		class := ""+		switch {+		case strings.HasPrefix(line, "+++") || strings.HasPrefix(line, "---"):+			class = "diff-file"+		case strings.HasPrefix(line, "@@"):+			class = "diff-hunk"+		case strings.HasPrefix(line, "+"):+			class = "diff-add"+		case strings.HasPrefix(line, "-"):+			class = "diff-del"+		case strings.HasPrefix(line, "diff "), strings.HasPrefix(line, "index "):+			class = "diff-meta"+		}+		out = append(out, DiffLine{Text: line, Class: class})+	}+	return out+}++func humanSize(n int64) string {+	const unit = 1024+	if n < unit {+		return fmt.Sprintf("%d B", n)+	}+	div, exp := int64(unit), 0+	for n/div >= unit && exp < 4 {+		div *= unit+		exp+++	}+	return fmt.Sprintf("%.1f %ciB", float64(n)/float64(div), "KMGTPE"[exp])+}++func mimeFor(name string) string {+	ext := strings.ToLower(filepath.Ext(name))+	switch ext {+	case ".md", ".markdown", ".txt", ".sx", ".c", ".h", ".go", ".rs", ".py", ".js", ".ts", ".css", ".html", ".json", ".toml", ".yaml", ".yml", ".sh", ".mod", ".lock":+		return "text/plain; charset=utf-8"+	case ".png":+		return "image/png"+	case ".jpg", ".jpeg":+		return "image/jpeg"+	case ".gif":+		return "image/gif"+	case ".webp":+		return "image/webp"+	case ".svg":+		return "image/svg+xml"+	case ".pdf":+		return "application/pdf"+	case ".zip":+		return "application/zip"+	default:+		return "application/octet-stream"+	}+}++func isSafeImage(mime string) bool {+	switch mime {+	case "image/png", "image/jpeg", "image/gif", "image/webp":+		return true+	}+	return false+}++func (s *Server) setting(name, def string, r *http.Request) string {+	return s.data.Setting(r.Context(), name, def)+}++func backgroundWithTimeout(d time.Duration) (context.Context, context.CancelFunc) {+	return context.WithTimeout(context.Background(), d)+}--- /dev/null+++ b/internal/web/helpers_test.go@@ -0,0 +1,56 @@+package web++import "testing"++func TestBuildTree(t *testing.T) {+	files := []string{"README.md", "src/main.go", "src/util/a.go", "src/util/b.go", "z.txt"}+	tree := buildTree(files, "")+	if len(tree) != 3 || !tree[0].IsDir || tree[0].Name != "src" {+		t.Fatalf("root tree = %+v", tree)+	}+	sub := buildTree(files, "src")+	if len(sub) != 2 || sub[0].Name != "util" || sub[1].Name != "main.go" {+		t.Fatalf("src tree = %+v", sub)+	}+	deep := buildTree(files, "src/util")+	if len(deep) != 2 || deep[0].IsDir {+		t.Fatalf("util tree = %+v", deep)+	}+}++func TestSplitDiffClasses(t *testing.T) {+	lines := splitDiff("--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n context\n")+	want := []string{"diff-file", "diff-file", "diff-hunk", "diff-del", "diff-add", ""}+	if len(lines) != len(want) {+		t.Fatalf("got %d lines", len(lines))+	}+	for i := range want {+		if lines[i].Class != want[i] {+			t.Fatalf("line %d class = %q, want %q", i, lines[i].Class, want[i])+		}+	}+}++func TestRevPathKeepsSlashesInsideOneSegment(t *testing.T) {+	for _, rev := range []string{"main", "feature/slash", "a?b", "a%b"} {+		token := revPath(rev)+		if token == "" {+			t.Fatalf("empty token for %q", rev)+		}+		if containsSlash(token) {+			t.Fatalf("token %q still contains a slash", token)+		}+		if got := decodeRevPath(token); got != rev {+			t.Fatalf("decode(%q) = %q, want %q", token, got, rev)+		}+	}+}++func containsSlash(s string) bool {+	for _, r := range s {+		if r == '/' {+			return true+		}+	}+	return false+}--- /dev/null+++ b/internal/web/home_handlers.go@@ -0,0 +1,43 @@+package web++import (+	"net/http"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++func (s *Server) home(w http.ResponseWriter, r *http.Request) {+	stats, _ := s.data.SiteStats(r.Context())+	repos, _ := s.data.ListPublicRepos(r.Context(), "", 0, 9)+	page := s.page(r, "Forge for veins")+	dataMap := map[string]any{+		"Stats": stats,+		"Repos": repos,+	}+	if u := userFrom(r); u != nil {+		own, _ := s.data.ListOwnerRepos(r.Context(), "user", u.ID, true)+		orgs, _ := s.data.ListUserOrgs(r.Context(), u.ID)+		dataMap["UserRepos"] = own+		dataMap["UserOrgs"] = orgs+	}+	page.Data = dataMap+	s.render(w, r, http.StatusOK, "home", page)+}++func (s *Server) explore(w http.ResponseWriter, r *http.Request) {+	q := auth.CleanOneLine(r.URL.Query().Get("q"), 100)+	pageNo, size, offset := data.Pagination(r.URL.Query().Get("page"), "24")+	repos, err := s.data.ListPublicRepos(r.Context(), q, offset, size)+	if err != nil {+		s.renderError(w, r, http.StatusInternalServerError, "Could not search repositories.")+		return+	}+	count, _ := s.data.CountPublicRepos(r.Context(), q)+	page := s.page(r, "Explore")+	page.Data = map[string]any{+		"Repos": repos, "Query": q, "Count": count,+		"Page": pageNo, "HasNext": int64(offset+size) < count,+	}+	s.render(w, r, http.StatusOK, "explore", page)+}--- /dev/null+++ b/internal/web/issues_handlers.go@@ -0,0 +1,208 @@+package web++import (+	"html/template"+	"net/http"+	"strconv"+	"strings"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++type commentView struct {+	*data.Comment+	BodyHTML template.HTML+}++func (s *Server) repoIssues(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	state := r.URL.Query().Get("state")+	if state != "open" && state != "closed" && state != "all" {+		state = "open"+	}+	pageNo, size, offset := data.Pagination(r.URL.Query().Get("page"), "25")+	issues, err := s.data.ListIssues(r.Context(), repo.ID, state, offset, size)+	if err != nil {+		s.renderError(w, r, http.StatusInternalServerError, "Could not load issues.")+		return+	}+	openCount, _ := s.data.CountIssues(r.Context(), repo.ID, "open")+	closedCount, _ := s.data.CountIssues(r.Context(), repo.ID, "closed")+	total := openCount + closedCount+	switch state {+	case "open":+		total = openCount+	case "closed":+		total = closedCount+	}+	page := s.page(r, "Issues · "+repo.OwnerName+"/"+repo.Name)+	page.Data = map[string]any{+		"Repo": repo, "Perms": perms, "Issues": issues, "State": state,+		"OpenCount": openCount, "ClosedCount": closedCount, "Total": total,+		"Page": pageNo, "HasNext": int64(offset+size) < total,+	}+	s.render(w, r, http.StatusOK, "issues", page)+}++func (s *Server) repoIssueNew(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if s.requireUser(w, r) == nil {+		return+	}+	if repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "This repository is archived.")+		return+	}+	page := s.page(r, "New issue · "+repo.OwnerName+"/"+repo.Name)+	page.Data = map[string]any{"Repo": repo, "Perms": perms}+	s.render(w, r, http.StatusOK, "issue_new", page)+}++func (s *Server) repoIssueCreate(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !perms.CanView || repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "Cannot create an issue here.")+		return+	}+	title := auth.CleanOneLine(r.FormValue("title"), 256)+	body := strings.TrimSpace(r.FormValue("body"))+	if title == "" {+		redirect(w, r, repoURL(repo)+"/issues/new", "", "Title is required.")+		return+	}+	if len(body) > 64<<10 {+		redirect(w, r, repoURL(repo)+"/issues/new", "", "Issue body is too long.")+		return+	}+	issue, err := s.data.CreateIssue(r.Context(), repo.ID, u.ID, title, body, ipFrom(r))+	if err != nil {+		redirect(w, r, repoURL(repo)+"/issues/new", "", "Could not create the issue.")+		return+	}+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "issue.open", "#"+strconv.FormatInt(issue.Number, 10)+" "+title)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "issue.create", repo.OwnerName+"/"+repo.Name+"#"+strconv.FormatInt(issue.Number, 10), r.UserAgent())+	s.dispatchWebhook(repo, u, "issue", map[string]any{"action": "opened", "number": issue.Number, "title": title})+	redirect(w, r, issueURL(repo, issue.Number), "Issue opened.", "")+}++func (s *Server) repoIssue(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	number, ok := parseID(r.PathValue("number"))+	if !ok {+		s.renderError(w, r, http.StatusNotFound, "Issue not found.")+		return+	}+	issue, err := s.data.GetIssue(r.Context(), repo.ID, number)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Issue not found.")+		return+	}+	comments, _ := s.data.ListComments(r.Context(), "issue", issue.ID)+	attachments, _ := s.data.ListAttachments(r.Context(), "issue", issue.ID)+	views := make([]commentView, 0, len(comments))+	for _, c := range comments {+		views = append(views, commentView{Comment: c, BodyHTML: RenderMarkdown(c.Body)})+	}+	u := userFrom(r)+	canClose := u != nil && (u.ID == issue.AuthorID || perms.CanWrite)+	page := s.page(r, "#"+strconv.FormatInt(number, 10)+" "+issue.Title)+	page.Data = map[string]any{+		"Repo": repo, "Perms": perms, "Issue": issue, "Comments": views,+		"BodyHTML": RenderMarkdown(issue.Body), "Attachments": attachments,+		"CanClose": canClose, "CanComment": u != nil && !repo.Archived,+		"Number": number,+	}+	s.render(w, r, http.StatusOK, "issue", page)+}++func (s *Server) repoIssueComment(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !perms.CanView || repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "Cannot comment here.")+		return+	}+	number, ok := parseID(r.PathValue("number"))+	if !ok {+		s.renderError(w, r, http.StatusNotFound, "Issue not found.")+		return+	}+	issue, err := s.data.GetIssue(r.Context(), repo.ID, number)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Issue not found.")+		return+	}+	body := strings.TrimSpace(r.FormValue("body"))+	if body == "" || len(body) > 64<<10 {+		redirect(w, r, issueURL(repo, number), "", "Comment is empty or too long.")+		return+	}+	if _, err := s.data.AddComment(r.Context(), repo.ID, "issue", issue.ID, u.ID, body, ipFrom(r)); err != nil {+		redirect(w, r, issueURL(repo, number), "", "Could not add the comment.")+		return+	}+	_, _ = s.data.DB().ExecContext(r.Context(), `UPDATE issues SET updated_at = strftime('%s','now') WHERE id = ?`, issue.ID)+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "issue.comment", "#"+strconv.FormatInt(number, 10))+	s.dispatchWebhook(repo, u, "comment", map[string]any{"action": "created", "issue": number})+	redirect(w, r, issueURL(repo, number)+"#comments", "Comment added.", "")+}++func (s *Server) repoIssueState(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	number, ok := parseID(r.PathValue("number"))+	if !ok {+		s.renderError(w, r, http.StatusNotFound, "Issue not found.")+		return+	}+	issue, err := s.data.GetIssue(r.Context(), repo.ID, number)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Issue not found.")+		return+	}+	if u.ID != issue.AuthorID && !perms.CanWrite {+		s.renderError(w, r, http.StatusForbidden, "You cannot change this issue.")+		return+	}+	state := r.FormValue("state")+	if state != "open" && state != "closed" {+		redirect(w, r, issueURL(repo, number), "", "Invalid state.")+		return+	}+	if err := s.data.SetIssueState(r.Context(), issue.ID, state, u.ID); err != nil {+		redirect(w, r, issueURL(repo, number), "", "Could not update the issue.")+		return+	}+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "issue."+state, "#"+strconv.FormatInt(number, 10))+	s.dispatchWebhook(repo, u, "issue", map[string]any{"action": state, "number": number, "title": issue.Title})+	redirect(w, r, issueURL(repo, number), "Issue "+state+".", "")+}--- /dev/null+++ b/internal/web/markdown.go@@ -0,0 +1,105 @@+package web++import (+	"bytes"+	"html"+	"html/template"+	"net/url"+	"path"+	"regexp"+	"strings"++	"github.com/yuin/goldmark"+	"github.com/yuin/goldmark/extension"+	"github.com/yuin/goldmark/parser"++	"veinsforge/internal/data"+)++var md = goldmark.New(+	goldmark.WithExtensions(extension.GFM),+	goldmark.WithParserOptions(parser.WithAutoHeadingID()),+)++var attrRE = regexp.MustCompile(`(?i)\b(href|src)="([^"]*)"`)++func RenderMarkdown(input string) template.HTML {+	var buf bytes.Buffer+	if err := md.Convert([]byte(input), &buf); err != nil {+		return template.HTML("<p>Unable to render markdown.</p>")+	}+	return template.HTML(buf.String())+}++func RenderRepoMarkdown(input string, repo *data.Repo, rev, dir string) template.HTML {+	var buf bytes.Buffer+	if err := md.Convert([]byte(input), &buf); err != nil {+		return template.HTML("<p>Unable to render markdown.</p>")+	}+	out := attrRE.ReplaceAllStringFunc(buf.String(), func(match string) string {+		sub := attrRE.FindStringSubmatch(match)+		if len(sub) != 3 {+			return match+		}+		attr := strings.ToLower(sub[1])+		raw := html.UnescapeString(sub[2])+		rewritten := rewriteRepoLink(raw, repo, rev, dir, attr == "src")+		if rewritten == raw {+			return match+		}+		return sub[1] + `="` + html.EscapeString(rewritten) + `"`+	})+	return template.HTML(out)+}++func rewriteRepoLink(raw string, repo *data.Repo, rev, dir string, image bool) string {+	if raw == "" || strings.HasPrefix(raw, "#") || strings.HasPrefix(raw, "/") ||+		strings.HasPrefix(raw, "//") || strings.HasPrefix(raw, "data:") {+		return raw+	}+	lower := strings.ToLower(raw)+	for _, scheme := range []string{"http://", "https://", "mailto:", "tel:"} {+		if strings.HasPrefix(lower, scheme) {+			return raw+		}+	}+	u, err := url.Parse(raw)+	if err != nil {+		return raw+	}+	rel := u.Path+	if rel == "" {+		return raw+	}+	if strings.HasPrefix(rel, "/") {+		return raw+	}+	target := path.Clean(path.Join(dir, rel))+	if target == ".." || strings.HasPrefix(target, "../") {+		return raw+	}+	var built string+	if image {+		built = rawURL(repo, rev, target)+	} else {+		built = blobURL(repo, rev, target)+	}+	if u.RawQuery != "" {+		built += "?" + u.RawQuery+	}+	if u.Fragment != "" {+		built += "#" + u.Fragment+	}+	return built+}++func firstReadme(files []string) string {+	for _, want := range []string{"readme.md", "readme.markdown", "readme", "readme.txt"} {+		for _, f := range files {+			if strings.EqualFold(f, want) {+				return f+			}+		}+	}+	return ""+}--- /dev/null+++ b/internal/web/markdown_test.go@@ -0,0 +1,32 @@+package web++import (+	"strings"+	"testing"++	"veinsforge/internal/data"+)++func TestMarkdownEscapesRawHTML(t *testing.T) {+	out := string(RenderMarkdown("<script>alert(1)</script>\n\n**safe**"))+	if strings.Contains(strings.ToLower(out), "<script") {+		t.Fatalf("raw script survived: %s", out)+	}+	if !strings.Contains(out, "<strong>safe</strong>") {+		t.Fatalf("markdown formatting missing: %s", out)+	}+}++func TestRepoMarkdownRewritesRelativeLinks(t *testing.T) {+	repo := &data.Repo{OwnerName: "alice", Name: "demo"}+	out := string(RenderRepoMarkdown("[doc](docs/a.md) ![img](images/a.png) [web](https://example.com/x)", repo, "main", "sub"))+	if !strings.Contains(out, `href="/alice/demo/blob/main/sub/docs/a.md"`) {+		t.Fatalf("blob link not rewritten: %s", out)+	}+	if !strings.Contains(out, `src="/alice/demo/raw/main/sub/images/a.png"`) {+		t.Fatalf("image link not rewritten: %s", out)+	}+	if !strings.Contains(out, `href="https://example.com/x"`) {+		t.Fatalf("external link changed: %s", out)+	}+}--- /dev/null+++ b/internal/web/middleware.go@@ -0,0 +1,279 @@+package web++import (+	"context"+	"crypto/subtle"+	"fmt"+	"net"+	"net/http"+	"net/url"+	"strings"+	"time"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++const (+	sessionCookie = "veinsforge_session"+	csrfCookie    = "veinsforge_csrf"+)++func (s *Server) recover(next http.Handler) http.Handler {+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		defer func() {+			if rec := recover(); rec != nil {+				s.logger.Printf("panic serving %s %s: %v", r.Method, r.URL.Path, rec)+				s.renderError(w, r, http.StatusInternalServerError, "Internal server error.")+			}+		}()+		next.ServeHTTP(w, r)+	})+}++func (s *Server) security(next http.Handler) http.Handler {+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		h := w.Header()+		h.Set("X-Content-Type-Options", "nosniff")+		h.Set("X-Frame-Options", "DENY")+		h.Set("Referrer-Policy", "strict-origin-when-cross-origin")+		h.Set("Permissions-Policy", "geolocation=(), camera=(), microphone=()")+		h.Set("Content-Security-Policy", "default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'")+		if s.cfg.SecureCookies {+			h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")+		}+		next.ServeHTTP(w, r)+	})+}++func (s *Server) limit(next http.Handler) http.Handler {+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		ip := s.clientIP(r)+		r = r.WithContext(context.WithValue(r.Context(), ipKey, ip))++		class := "general"+		switch {+		case r.Method != http.MethodGet && r.Method != http.MethodHead:+			class = "write"+		}+		if r.URL.Path == "/login" || r.URL.Path == "/signup" {+			class = "auth"+		}+		if !s.limiter.Allow(ip, class) {+			w.Header().Set("Retry-After", "60")+			s.renderError(w, r, http.StatusTooManyRequests, "Too many requests. Slow down.")+			return+		}+		select {+		case s.sem <- struct{}{}:+			defer func() { <-s.sem }()+		default:+			w.Header().Set("Retry-After", "5")+			s.renderError(w, r, http.StatusServiceUnavailable, "The forge is busy. Try again shortly.")+			return+		}+		if r.Method != http.MethodGet && r.Method != http.MethodHead && r.Method != http.MethodPost {+			w.Header().Set("Allow", "GET, HEAD, POST")+			s.renderError(w, r, http.StatusMethodNotAllowed, "Method not allowed.")+			return+		}+		if len(r.URL.Path) > 2048 {+			s.renderError(w, r, http.StatusRequestURITooLong, "Request path is too long.")+			return+		}+		r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes+(2<<20))+		next.ServeHTTP(w, r)+	})+}++func (s *Server) loadSession(next http.Handler) http.Handler {+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		cookie, err := r.Cookie(sessionCookie)+		if err == nil && cookie.Value != "" {+			sess, err := s.data.GetSession(r.Context(), auth.HashToken(cookie.Value))+			if err == nil {+				r = r.WithContext(context.WithValue(r.Context(), userKey, sess.User))+				r = r.WithContext(context.WithValue(r.Context(), sessionKey, &requestSession{ID: sess.ID, CSRF: sess.CSRF}))+				if time.Since(sess.LastSeenAt) > time.Hour {+					s.data.TouchSession(context.Background(), sess.ID)+				}+			} else {+				s.clearSessionCookie(w)+			}+		}+		next.ServeHTTP(w, r)+	})+}++func (s *Server) withCSRF(next http.Handler) http.Handler {+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		sess := sessionFrom(r)+		var expected string+		if sess != nil {+			expected = sess.CSRF+		} else if c, err := r.Cookie(csrfCookie); err == nil {+			expected = c.Value+		}+		if r.Method == http.MethodGet || r.Method == http.MethodHead {+			if expected == "" {+				token, err := auth.RandomToken(32)+				if err == nil {+					expected = token+					http.SetCookie(w, &http.Cookie{+						Name:     csrfCookie,+						Value:    token,+						Path:     "/",+						HttpOnly: true,+						Secure:   s.cfg.SecureCookies,+						SameSite: http.SameSiteLaxMode,+						MaxAge:   7 * 24 * 3600,+					})+				}+			}+			r = r.WithContext(context.WithValue(r.Context(), csrfKey, expected))+			next.ServeHTTP(w, r)+			return+		}+		if r.Method != http.MethodPost {+			next.ServeHTTP(w, r)+			return+		}+		if expected == "" {+			s.renderError(w, r, http.StatusForbidden, "Missing CSRF token. Reload the page and try again.")+			return+		}+		contentType := r.Header.Get("Content-Type")+		if strings.HasPrefix(contentType, "multipart/form-data") {+			if err := r.ParseMultipartForm(1 << 20); err != nil {+				s.renderError(w, r, http.StatusBadRequest, "Upload is too large or malformed.")+				return+			}+			if r.MultipartForm != nil {+				defer r.MultipartForm.RemoveAll()+			}+		} else if err := r.ParseForm(); err != nil {+			s.renderError(w, r, http.StatusBadRequest, "Malformed form body.")+			return+		}+		got := r.FormValue("csrf")+		if subtle.ConstantTimeCompare([]byte(got), []byte(expected)) != 1 {+			s.renderError(w, r, http.StatusForbidden, "Invalid CSRF token. Reload the page and try again.")+			return+		}+		r = r.WithContext(context.WithValue(r.Context(), csrfKey, expected))+		next.ServeHTTP(w, r)+	})+}++func (s *Server) clientIP(r *http.Request) string {+	remote := r.RemoteAddr+	if host, _, err := net.SplitHostPort(remote); err == nil {+		remote = host+	}+	ip := net.ParseIP(remote)+	if ip == nil {+		return truncateString(remote, 64)+	}+	if !s.isTrusted(ip) {+		return ip.String()+	}+	xff := r.Header.Get("X-Forwarded-For")+	if xff != "" {+		parts := strings.Split(xff, ",")+		for i := len(parts) - 1; i >= 0; i-- {+			candidate := strings.TrimSpace(parts[i])+			parsed := net.ParseIP(candidate)+			if parsed == nil {+				continue+			}+			if s.isTrusted(parsed) {+				continue+			}+			return parsed.String()+		}+	}+	if real := strings.TrimSpace(r.Header.Get("X-Real-IP")); real != "" {+		if parsed := net.ParseIP(real); parsed != nil {+			return parsed.String()+		}+	}+	return ip.String()+}++func (s *Server) isTrusted(ip net.IP) bool {+	for _, block := range s.trusted {+		if block.Contains(ip) {+			return true+		}+	}+	return false+}++func (s *Server) setSessionCookie(w http.ResponseWriter, token string) {+	http.SetCookie(w, &http.Cookie{+		Name:     sessionCookie,+		Value:    token,+		Path:     "/",+		HttpOnly: true,+		Secure:   s.cfg.SecureCookies,+		SameSite: http.SameSiteLaxMode,+		MaxAge:   int(s.cfg.SessionTTL.Seconds()),+		Expires:  time.Now().Add(s.cfg.SessionTTL),+	})+}++func (s *Server) clearSessionCookie(w http.ResponseWriter) {+	http.SetCookie(w, &http.Cookie{+		Name:     sessionCookie,+		Value:    "",+		Path:     "/",+		HttpOnly: true,+		Secure:   s.cfg.SecureCookies,+		SameSite: http.SameSiteLaxMode,+		MaxAge:   -1,+		Expires:  time.Unix(1, 0),+	})+}++func (s *Server) requireUser(w http.ResponseWriter, r *http.Request) *data.User {+	u := userFrom(r)+	if u == nil {+		next := url.QueryEscape(r.URL.RequestURI())+		http.Redirect(w, r, "/login?next="+next, http.StatusSeeOther)+		return nil+	}+	return u+}++func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) *data.User {+	u := s.requireUser(w, r)+	if u == nil {+		return nil+	}+	if !u.IsAdmin {+		s.renderError(w, r, http.StatusForbidden, "Administrator access required.")+		return nil+	}+	return u+}++func truncateString(s string, n int) string {+	if len(s) <= n {+		return s+	}+	return s[:n]+}++func sameOriginReferer(r *http.Request) bool {+	ref := r.Referer()+	if ref == "" {+		return true+	}+	u, err := url.Parse(ref)+	if err != nil {+		return false+	}+	return u.Host == "" || u.Host == r.Host+}++var _ = fmt.Sprintf--- /dev/null+++ b/internal/web/org_handlers.go@@ -0,0 +1,352 @@+package web++import (+	"errors"+	"net/http"+	"strings"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++func (s *Server) newOrgPage(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	page := s.page(r, "New organisation")+	page.Data = map[string]any{}+	s.render(w, r, http.StatusOK, "org_new", page)+}++func (s *Server) newOrgPost(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	name := strings.TrimSpace(r.FormValue("name"))+	display := auth.CleanOneLine(r.FormValue("display_name"), 80)+	description := strings.TrimSpace(r.FormValue("description"))+	if err := auth.ValidHandle(name); err != nil {+		redirect(w, r, "/orgs/new", "", err.Error())+		return+	}+	if display == "" {+		display = name+	}+	if len(description) > 2000 {+		redirect(w, r, "/orgs/new", "", "Description is too long.")+		return+	}+	available, err := s.data.UsernameAvailable(r.Context(), name)+	if err != nil || !available {+		redirect(w, r, "/orgs/new", "", "That name is already taken.")+		return+	}+	org, err := s.data.CreateOrg(r.Context(), name, display, description, u.ID)+	if err != nil {+		if errors.Is(err, data.ErrConflict) {+			redirect(w, r, "/orgs/new", "", "That name is already taken.")+		} else {+			redirect(w, r, "/orgs/new", "", "Could not create the organisation.")+		}+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "org.create", org.Name, r.UserAgent())+	redirect(w, r, "/orgs/"+org.Name, "Organisation created.", "")+}++func (s *Server) getOrg(w http.ResponseWriter, r *http.Request) (*data.Org, bool) {+	org, err := s.data.GetOrgByName(r.Context(), r.PathValue("org"))+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Organisation not found.")+		return nil, false+	}+	return org, true+}++func (s *Server) orgCanAdmin(r *http.Request, org *data.Org, u *data.User) bool {+	if u == nil {+		return false+	}+	if u.IsAdmin {+		return true+	}+	role, _ := s.data.OrgRole(r.Context(), org.ID, u.ID)+	return role == "owner" || role == "admin"+}++func (s *Server) orgPage(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := userFrom(r)+	role := ""+	if u != nil {+		role, _ = s.data.OrgRole(r.Context(), org.ID, u.ID)+	}+	member := role != ""+	repos, _ := s.data.ListOwnerRepos(r.Context(), "org", org.ID, member)+	members, _ := s.data.ListOrgMembers(r.Context(), org.ID)+	teams, _ := s.data.ListTeams(r.Context(), org.ID)+	page := s.page(r, org.Name)+	page.Data = map[string]any{+		"Org": org, "Repos": repos, "Members": members, "Teams": teams,+		"Member": member, "Role": role, "CanAdmin": s.orgCanAdmin(r, org, u),+	}+	s.render(w, r, http.StatusOK, "org", page)+}++func (s *Server) orgSettings(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	members, _ := s.data.ListOrgMembers(r.Context(), org.ID)+	teams, _ := s.data.ListTeams(r.Context(), org.ID)+	type teamWithMembers struct {+		Team    *data.Team+		Members []*data.TeamMember+	}+	var teamViews []teamWithMembers+	for _, t := range teams {+		m, _ := s.data.ListTeamMembers(r.Context(), t.ID)+		teamViews = append(teamViews, teamWithMembers{Team: t, Members: m})+	}+	page := s.page(r, "Settings · "+org.Name)+	page.Data = map[string]any{"Org": org, "Members": members, "Teams": teamViews}+	s.render(w, r, http.StatusOK, "org_settings", page)+}++func (s *Server) orgSettingsPost(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	display := auth.CleanOneLine(r.FormValue("display_name"), 80)+	description := strings.TrimSpace(r.FormValue("description"))+	if display == "" {+		display = org.Name+	}+	if len(description) > 2000 {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Description is too long.")+		return+	}+	if err := s.data.UpdateOrg(r.Context(), org.ID, display, description); err != nil {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Could not save organisation settings.")+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "org.settings", org.Name, r.UserAgent())+	redirect(w, r, "/orgs/"+org.Name+"/settings", "Organisation updated.", "")+}++func (s *Server) orgMemberAdd(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	username := strings.TrimSpace(r.FormValue("username"))+	role := r.FormValue("role")+	if role != "owner" && role != "admin" && role != "member" {+		role = "member"+	}+	target, err := s.data.GetUserByUsername(r.Context(), username)+	if err != nil {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "User not found.")+		return+	}+	if err := s.data.AddOrgMember(r.Context(), org.ID, target.ID, role); err != nil {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Could not add the member.")+		return+	}+	if err := s.syncOrgAccess(r.Context(), org.ID); err != nil {+		s.logger.Printf("sync org access after member add: %v", err)+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "org.member", org.Name+" "+target.Username+" "+role, r.UserAgent())+	redirect(w, r, "/orgs/"+org.Name+"/settings", "Member updated.", "")+}++func (s *Server) orgMemberDelete(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	userID, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid member.")+		return+	}+	if err := s.data.RemoveOrgMember(r.Context(), org.ID, userID); err != nil {+		if errors.Is(err, data.ErrConflict) {+			redirect(w, r, "/orgs/"+org.Name+"/settings", "", "The organisation needs at least one owner.")+		} else {+			redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Could not remove the member.")+		}+		return+	}+	if err := s.syncOrgAccess(r.Context(), org.ID); err != nil {+		s.logger.Printf("sync org access after member removal: %v", err)+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "org.member.remove", org.Name, r.UserAgent())+	redirect(w, r, "/orgs/"+org.Name+"/settings", "Member removed.", "")+}++func (s *Server) orgTeamCreate(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	name := strings.TrimSpace(r.FormValue("name"))+	description := auth.CleanOneLine(r.FormValue("description"), 200)+	if err := auth.ValidHandle(name); err != nil {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Team names must be 3-32 characters.")+		return+	}+	team, err := s.data.CreateTeam(r.Context(), org.ID, name, description)+	if err != nil {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Could not create the team.")+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "org.team", org.Name+" "+team.Name, r.UserAgent())+	redirect(w, r, "/orgs/"+org.Name+"/settings", "Team created.", "")+}++func (s *Server) orgTeamDelete(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	teamID, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid team.")+		return+	}+	_ = s.data.DeleteTeam(r.Context(), org.ID, teamID)+	if err := s.syncOrgAccess(r.Context(), org.ID); err != nil {+		s.logger.Printf("sync org access after team delete: %v", err)+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "org.team.remove", org.Name, r.UserAgent())+	redirect(w, r, "/orgs/"+org.Name+"/settings", "Team deleted.", "")+}++func (s *Server) orgTeamMemberAdd(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	teamID, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid team.")+		return+	}+	if _, err := s.data.GetTeam(r.Context(), org.ID, teamID); err != nil {+		s.renderError(w, r, http.StatusNotFound, "Team not found.")+		return+	}+	username := strings.TrimSpace(r.FormValue("username"))+	target, err := s.data.GetUserByUsername(r.Context(), username)+	if err != nil {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "User not found.")+		return+	}+	role, _ := s.data.OrgRole(r.Context(), org.ID, target.ID)+	if role == "" {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Add the user to the organisation first.")+		return+	}+	if err := s.data.AddTeamMember(r.Context(), teamID, target.ID); err != nil {+		redirect(w, r, "/orgs/"+org.Name+"/settings", "", "Could not add the team member.")+		return+	}+	if err := s.syncOrgAccess(r.Context(), org.ID); err != nil {+		s.logger.Printf("sync org access after team member add: %v", err)+	}+	redirect(w, r, "/orgs/"+org.Name+"/settings", "Team member added.", "")+}++func (s *Server) orgTeamMemberDelete(w http.ResponseWriter, r *http.Request) {+	org, ok := s.getOrg(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !s.orgCanAdmin(r, org, u) {+		s.renderError(w, r, http.StatusForbidden, "Organisation administrator access required.")+		return+	}+	teamID, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid team.")+		return+	}+	userID, ok := parseID(r.PathValue("uid"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid user.")+		return+	}+	_ = s.data.RemoveTeamMember(r.Context(), teamID, userID)+	if err := s.syncOrgAccess(r.Context(), org.ID); err != nil {+		s.logger.Printf("sync org access after team member removal: %v", err)+	}+	redirect(w, r, "/orgs/"+org.Name+"/settings", "Team member removed.", "")+}--- /dev/null+++ b/internal/web/password.go@@ -0,0 +1,15 @@+package web++import "veinsforge/internal/auth"++func (s *Server) hashPassword(password string) (string, error) {+	s.hashSem <- struct{}{}+	defer func() { <-s.hashSem }()+	return auth.HashPassword(password)+}++func (s *Server) verifyPassword(hash, password string) bool {+	s.hashSem <- struct{}{}+	defer func() { <-s.hashSem }()+	return auth.VerifyPassword(hash, password)+}--- /dev/null+++ b/internal/web/pulls_handlers.go@@ -0,0 +1,345 @@+package web++import (+	"fmt"+	"html/template"+	"net/http"+	"strconv"+	"strings"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+	"veinsforge/internal/vn"+)++func (s *Server) repoPulls(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	state := r.URL.Query().Get("state")+	if state != "open" && state != "closed" && state != "merged" && state != "all" {+		state = "open"+	}+	pageNo, size, offset := data.Pagination(r.URL.Query().Get("page"), "25")+	pulls, err := s.data.ListPulls(r.Context(), repo.ID, state, offset, size)+	if err != nil {+		s.renderError(w, r, http.StatusInternalServerError, "Could not load pull requests.")+		return+	}+	openCount, _ := s.data.CountPulls(r.Context(), repo.ID, "open")+	closedCount, _ := s.data.CountPulls(r.Context(), repo.ID, "closed")+	mergedCount, _ := s.data.CountPulls(r.Context(), repo.ID, "merged")+	total := openCount + closedCount + mergedCount+	switch state {+	case "open":+		total = openCount+	case "closed":+		total = closedCount+	case "merged":+		total = mergedCount+	}+	page := s.page(r, "Pull requests · "+repo.OwnerName+"/"+repo.Name)+	page.Data = map[string]any{+		"Repo": repo, "Perms": perms, "Pulls": pulls, "State": state,+		"OpenCount": openCount, "ClosedCount": closedCount, "MergedCount": mergedCount, "Total": total,+		"Page": pageNo, "HasNext": int64(offset+size) < total,+	}+	s.render(w, r, http.StatusOK, "pulls", page)+}++func (s *Server) repoPullNew(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if s.requireUser(w, r) == nil {+		return+	}+	if repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "This repository is archived.")+		return+	}+	branches, _ := s.vn.Branches(r.Context(), repo.ID, s.vn.RepoPath(repo.OwnerName, repo.Name))+	base := defaultRev(repo, branches)+	head := ""+	for _, b := range branches {+		if b.Name != base {+			head = b.Name+			break+		}+	}+	page := s.page(r, "New pull request · "+repo.OwnerName+"/"+repo.Name)+	page.Data = map[string]any{+		"Repo": repo, "Perms": perms, "Branches": branches,+		"Base": base, "Head": head,+		"EnoughBranches": len(branches) >= 2,+	}+	s.render(w, r, http.StatusOK, "pull_new", page)+}++func (s *Server) repoPullCreate(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !perms.CanView || repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "Cannot create a pull request here.")+		return+	}+	title := auth.CleanOneLine(r.FormValue("title"), 256)+	body := strings.TrimSpace(r.FormValue("body"))+	base := strings.TrimSpace(r.FormValue("base"))+	head := strings.TrimSpace(r.FormValue("head"))+	if title == "" {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Title is required.")+		return+	}+	if len(body) > 64<<10 {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Description is too long.")+		return+	}+	if err := auth.ValidBranchName(base); err != nil {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Invalid base branch.")+		return+	}+	if err := auth.ValidBranchName(head); err != nil {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Invalid head branch.")+		return+	}+	if base == head {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Base and head branches must differ.")+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	baseHash, err := s.vn.CommitHash(r.Context(), repo.ID, central, base)+	if err != nil {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Base branch not found.")+		return+	}+	headHash, err := s.vn.CommitHash(r.Context(), repo.ID, central, head)+	if err != nil {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Head branch not found.")+		return+	}+	pull, err := s.data.CreatePull(r.Context(), repo.ID, u.ID, title, body, base, head, baseHash, headHash, ipFrom(r))+	if err != nil {+		redirect(w, r, repoURL(repo)+"/pulls/new", "", "Could not create the pull request.")+		return+	}+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "pull.open", "#"+strconv.FormatInt(pull.Number, 10)+" "+title)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "pull.create", repo.OwnerName+"/"+repo.Name+"#"+strconv.FormatInt(pull.Number, 10), r.UserAgent())+	s.dispatchWebhook(repo, u, "pull_request", map[string]any{"action": "opened", "number": pull.Number, "title": title, "base": base, "head": head})+	redirect(w, r, pullURL(repo, pull.Number), "Pull request opened.", "")+}++func (s *Server) repoPull(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	number, ok := parseID(r.PathValue("number"))+	if !ok {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	pull, err := s.data.GetPull(r.Context(), repo.ID, number)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	baseCommit := pull.BaseCommit+	headCommit := pull.HeadCommit+	if h, err := s.vn.CommitHash(r.Context(), repo.ID, central, pull.HeadBranch); err == nil {+		headCommit = h+	}+	if h, err := s.vn.CommitHash(r.Context(), repo.ID, central, pull.BaseBranch); err == nil {+		baseCommit = h+	}+	diff := ""+	diffErr := ""+	if baseCommit != "" && headCommit != "" && baseCommit != headCommit {+		diff, err = s.vn.Diff(r.Context(), repo.ID, central, baseCommit, headCommit)+		if err != nil {+			diffErr = "Could not compare the branches."+		}+	}+	truncated := false+	if len(diff) > 2<<20 {+		diff = diff[:2<<20]+		truncated = true+	}+	comments, _ := s.data.ListComments(r.Context(), "pull", pull.ID)+	attachments, _ := s.data.ListAttachments(r.Context(), "pull", pull.ID)+	views := make([]commentView, 0, len(comments))+	for _, c := range comments {+		views = append(views, commentView{Comment: c, BodyHTML: RenderMarkdown(c.Body)})+	}+	u := userFrom(r)+	canClose := u != nil && (u.ID == pull.AuthorID || perms.CanWrite)+	canMerge := perms.CanWrite && pull.State == "open" && !repo.Archived && headCommit != "" && baseCommit != ""+	page := s.page(r, "#"+strconv.FormatInt(number, 10)+" "+pull.Title)+	page.Data = map[string]any{+		"Repo": repo, "Perms": perms, "Pull": pull, "Comments": views,+		"BodyHTML": RenderMarkdown(pull.Body), "Attachments": attachments,+		"Diff": diff, "DiffLines": splitDiff(diff), "DiffError": diffErr,+		"Truncated": truncated, "CanClose": canClose, "CanMerge": canMerge,+		"CanComment": u != nil && !repo.Archived, "Number": number,+		"BaseCommit": baseCommit, "HeadCommit": headCommit,+	}+	s.render(w, r, http.StatusOK, "pull", page)+}++func (s *Server) repoPullComment(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !perms.CanView || repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "Cannot comment here.")+		return+	}+	number, ok := parseID(r.PathValue("number"))+	if !ok {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	pull, err := s.data.GetPull(r.Context(), repo.ID, number)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	body := strings.TrimSpace(r.FormValue("body"))+	if body == "" || len(body) > 64<<10 {+		redirect(w, r, pullURL(repo, number), "", "Comment is empty or too long.")+		return+	}+	if _, err := s.data.AddComment(r.Context(), repo.ID, "pull", pull.ID, u.ID, body, ipFrom(r)); err != nil {+		redirect(w, r, pullURL(repo, number), "", "Could not add the comment.")+		return+	}+	_, _ = s.data.DB().ExecContext(r.Context(), `UPDATE pulls SET updated_at = strftime('%s','now') WHERE id = ?`, pull.ID)+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "pull.comment", "#"+strconv.FormatInt(number, 10))+	s.dispatchWebhook(repo, u, "comment", map[string]any{"action": "created", "pull": number})+	redirect(w, r, pullURL(repo, number)+"#comments", "Comment added.", "")+}++func (s *Server) repoPullState(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	number, ok := parseID(r.PathValue("number"))+	if !ok {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	pull, err := s.data.GetPull(r.Context(), repo.ID, number)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	if u.ID != pull.AuthorID && !perms.CanWrite {+		s.renderError(w, r, http.StatusForbidden, "You cannot change this pull request.")+		return+	}+	state := r.FormValue("state")+	if state != "open" && state != "closed" {+		redirect(w, r, pullURL(repo, number), "", "Invalid state.")+		return+	}+	if pull.State == "merged" && state == "open" {+		redirect(w, r, pullURL(repo, number), "", "Merged pull requests cannot be reopened.")+		return+	}+	if err := s.data.SetPullState(r.Context(), pull.ID, state, u.ID); err != nil {+		redirect(w, r, pullURL(repo, number), "", "Could not update the pull request.")+		return+	}+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "pull."+state, "#"+strconv.FormatInt(number, 10))+	s.dispatchWebhook(repo, u, "pull_request", map[string]any{"action": state, "number": number, "title": pull.Title})+	redirect(w, r, pullURL(repo, number), "Pull request "+state+".", "")+}++func (s *Server) repoPullMerge(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	if !perms.CanWrite {+		s.renderError(w, r, http.StatusForbidden, "Write access is required to merge.")+		return+	}+	if repo.Archived {+		s.renderError(w, r, http.StatusForbidden, "This repository is archived.")+		return+	}+	number, ok := parseID(r.PathValue("number"))+	if !ok {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	pull, err := s.data.GetPull(r.Context(), repo.ID, number)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Pull request not found.")+		return+	}+	if pull.State != "open" {+		redirect(w, r, pullURL(repo, number), "", "Only open pull requests can be merged.")+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	message := fmt.Sprintf("Merge pull request #%d: %s", pull.Number, pull.Title)+	display := u.DisplayName+	if display == "" {+		display = u.Username+	}+	email := u.Email+	if email == "" {+		email = u.Username + "@users.noreply.veinsforge"+	}+	result, err := s.vn.MergePull(r.Context(), repo.ID, central, pull.BaseBranch, pull.HeadBranch, message, display, email)+	if err != nil {+		s.logger.Printf("merge pull %s/%s#%d: %v", repo.OwnerName, repo.Name, number, err)+		redirect(w, r, pullURL(repo, number), "", "Merge failed: "+truncateString(err.Error(), 300))+		return+	}+	if result == nil {+		redirect(w, r, pullURL(repo, number), "", "Merge failed.")+		return+	}+	if len(result.Conflicts) > 0 {+		list := strings.Join(result.Conflicts, ", ")+		redirect(w, r, pullURL(repo, number), "", "Merge has conflicts: "+truncateString(list, 400))+		return+	}+	if err := s.data.MarkPullMerged(r.Context(), pull.ID, result.CommitHash, u.ID); err != nil {+		redirect(w, r, pullURL(repo, number), "", "Merged, but the pull request status could not be saved.")+		return+	}+	_, _ = s.data.DB().ExecContext(r.Context(), `UPDATE pulls SET base_commit = ?, head_commit = ? WHERE id = ?`, result.CommitHash, result.CommitHash, pull.ID)+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "pull.merge", "#"+strconv.FormatInt(number, 10)+" "+shortHash(result.CommitHash))+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "pull.merge", repo.OwnerName+"/"+repo.Name+"#"+strconv.FormatInt(number, 10)+" "+result.CommitHash, r.UserAgent())+	s.dispatchWebhook(repo, u, "pull_request", map[string]any{"action": "merged", "number": number, "title": pull.Title, "merge_commit": result.CommitHash})+	redirect(w, r, pullURL(repo, number), "Merged as "+shortHash(result.CommitHash)+".", "")+}++var _ template.HTML+var _ vn.Branch--- /dev/null+++ b/internal/web/ratelimit.go@@ -0,0 +1,131 @@+package web++import (+	"sync"+	"time"+)++type bucket struct {+	tokens float64+	last   time.Time+}++type limiter struct {+	mu         sync.Mutex+	general    map[string]*bucket+	auth       map[string]*bucket+	write      map[string]*bucket+	strikes    map[string]int+	banned     map[string]time.Time+	rate       float64+	burst      float64+	authRate   float64+	authBurst  float64+	writeRate  float64+	writeBurst float64+	lastGC     time.Time+}++func newLimiter(perSecond float64, burst, authPerMinute, writePerMinute int) *limiter {+	if perSecond <= 0 {+		perSecond = 20+	}+	if burst <= 0 {+		burst = 40+	}+	if authPerMinute <= 0 {+		authPerMinute = 10+	}+	if writePerMinute <= 0 {+		writePerMinute = 30+	}+	return &limiter{+		general:    make(map[string]*bucket),+		auth:       make(map[string]*bucket),+		write:      make(map[string]*bucket),+		strikes:    make(map[string]int),+		banned:     make(map[string]time.Time),+		rate:       perSecond,+		burst:      float64(burst),+		authRate:   float64(authPerMinute) / 60,+		authBurst:  float64(authPerMinute),+		writeRate:  float64(writePerMinute) / 60,+		writeBurst: float64(writePerMinute),+		lastGC:     time.Now(),+	}+}++func (l *limiter) Allow(ip, class string) bool {+	now := time.Now()+	l.mu.Lock()+	defer l.mu.Unlock()+	if until, ok := l.banned[ip]; ok {+		if now.Before(until) {+			return false+		}+		delete(l.banned, ip)+		delete(l.strikes, ip)+	}+	m := l.general+	rate, burst := l.rate, l.burst+	switch class {+	case "auth":+		m, rate, burst = l.auth, l.authRate, l.authBurst+	case "write":+		m, rate, burst = l.write, l.writeRate, l.writeBurst+	}+	b := m[ip]+	if b == nil {+		b = &bucket{tokens: burst, last: now}+		m[ip] = b+	}+	elapsed := now.Sub(b.last).Seconds()+	if elapsed > 0 {+		b.tokens += elapsed * rate+		if b.tokens > burst {+			b.tokens = burst+		}+		b.last = now+	}+	if b.tokens >= 1 {+		b.tokens--+		l.strikes[ip] = 0+		l.maybeGC(now)+		return true+	}+	l.strikes[ip]+++	if l.strikes[ip] >= 60 {+		l.banned[ip] = now.Add(10 * time.Minute)+	}+	l.maybeGC(now)+	return false+}++func (l *limiter) maybeGC(now time.Time) {+	if now.Sub(l.lastGC) < 5*time.Minute {+		return+	}+	l.lastGC = now+	cutoff := now.Add(-10 * time.Minute)+	for k, b := range l.general {+		if b.last.Before(cutoff) {+			delete(l.general, k)+		}+	}+	for k, b := range l.auth {+		if b.last.Before(cutoff) {+			delete(l.auth, k)+		}+	}+	for k, b := range l.write {+		if b.last.Before(cutoff) {+			delete(l.write, k)+		}+	}+	for k, until := range l.banned {+		if now.After(until) {+			delete(l.banned, k)+			delete(l.strikes, k)+		}+	}+}--- /dev/null+++ b/internal/web/ratelimit_test.go@@ -0,0 +1,23 @@+package web++import "testing"++func TestLimiterBurst(t *testing.T) {+	l := newLimiter(1, 2, 2, 2)+	ip := "203.0.113.10"+	if !l.Allow(ip, "general") || !l.Allow(ip, "general") {+		t.Fatal("burst was rejected")+	}+	if l.Allow(ip, "general") {+		t.Fatal("request over burst was allowed")+	}+	if !l.Allow(ip, "auth") || !l.Allow(ip, "auth") {+		t.Fatal("auth burst was rejected")+	}+	if l.Allow(ip, "auth") {+		t.Fatal("auth request over burst was allowed")+	}+	if !l.Allow("198.51.100.2", "general") {+		t.Fatal("different IP was limited")+	}+}--- /dev/null+++ b/internal/web/repo_browse.go@@ -0,0 +1,397 @@+package web++import (+	"errors"+	"mime"+	"net/http"+	"net/url"+	"path"+	"path/filepath"+	"strconv"+	"strings"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+	"veinsforge/internal/vn"+)++func (s *Server) repoFromPath(w http.ResponseWriter, r *http.Request) (*data.Repo, data.Permissions, bool) {+	repo, err := s.data.GetRepo(r.Context(), r.PathValue("owner"), r.PathValue("repo"))+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Repository not found.")+		return nil, data.Permissions{}, false+	}+	perms, err := s.data.Permissions(r.Context(), repo, userFrom(r))+	if err != nil {+		s.renderError(w, r, http.StatusInternalServerError, "Could not check repository permissions.")+		return nil, data.Permissions{}, false+	}+	if !perms.CanView {+		if userFrom(r) == nil {+			next := url.QueryEscape(r.URL.RequestURI())+			http.Redirect(w, r, "/login?next="+next, http.StatusSeeOther)+		} else {+			s.renderError(w, r, http.StatusNotFound, "Repository not found.")+		}+		return nil, data.Permissions{}, false+	}+	return repo, perms, true+}++func defaultRev(repo *data.Repo, branches []vn.Branch) string {+	for _, b := range branches {+		if b.Name == repo.DefaultBranch {+			return b.Name+		}+	}+	if len(branches) > 0 {+		return branches[0].Name+	}+	return ""+}++func safeRevInput(rev string) error {+	if rev == "" || rev == "@" || rev == "." || rev == ".." {+		return errors.New("invalid revision")+	}+	return auth.ValidRevision(rev)+}++func (s *Server) repoOverview(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	branches, err := s.vn.Branches(r.Context(), repo.ID, s.vn.RepoPath(repo.OwnerName, repo.Name))+	if err != nil {+		s.logger.Printf("branches %s/%s: %v", repo.OwnerName, repo.Name, err)+	}+	rev := defaultRev(repo, branches)+	page := s.page(r, repo.OwnerName+"/"+repo.Name)+	dataMap := map[string]any{+		"Repo":          repo,+		"Perms":         perms,+		"Branches":      branches,+		"Rev":           rev,+		"DefaultBranch": repo.DefaultBranch,+		"Empty":         rev == "",+	}+	if u := userFrom(r); u != nil {+		dataMap["Starred"] = s.data.IsStarred(r.Context(), repo.ID, u.ID)+	}+	dataMap["StarCount"] = repo.Stars+	dataMap["NativeURL"] = s.cfg.NativeURL(repo.OwnerName, repo.Name)+	if s.native != nil {+		_, _, pin, _ := s.native.Status()+		dataMap["NativePin"] = pin+	}+	dataMap["IssueCount"], _ = s.data.CountIssues(r.Context(), repo.ID, "open")+	dataMap["PullCount"], _ = s.data.CountPulls(r.Context(), repo.ID, "open")+	dataMap["Activity"], _ = s.data.ListActivity(r.Context(), repo.ID, 12)+	if rev != "" {+		central := s.vn.RepoPath(repo.OwnerName, repo.Name)+		files, err := s.vn.ListFiles(r.Context(), repo.ID, central, rev)+		if err != nil {+			s.logger.Printf("list files %s/%s: %v", repo.OwnerName, repo.Name, err)+			dataMap["FilesError"] = "Could not read the tracked file list."+		} else {+			dataMap["Files"] = files+			dataMap["Tree"] = buildTree(files, "")+			if readme := firstReadme(files); readme != "" {+				if f, err := s.vn.ReadFile(r.Context(), repo.ID, central, rev, readme, 512<<10); err == nil {+					if lines, binary, _ := splitCode(f.Data); !binary && len(lines) > 0 {+						_ = lines+						dataMap["Readme"] = RenderRepoMarkdown(string(f.Data), repo, rev, "")+						dataMap["ReadmePath"] = readme+					}+				}+			}+		}+		dataMap["Commits"], _ = s.vn.Log(r.Context(), repo.ID, central, rev, 6)+	}+	page.Data = dataMap+	s.render(w, r, http.StatusOK, "repo", page)+}++func (s *Server) repoTree(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	rev := r.PathValue("rev")+	if err := safeRevInput(rev); err != nil {+		s.renderError(w, r, http.StatusBadRequest, "Invalid revision.")+		return+	}+	dir := strings.Trim(r.PathValue("path"), "/")+	if err := auth.ValidRepoPath(dir); err != nil {+		s.renderError(w, r, http.StatusBadRequest, "Invalid path.")+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	files, err := s.vn.ListFiles(r.Context(), repo.ID, central, rev)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Could not read that revision.")+		return+	}+	if dir != "" {+		isDir := false+		for _, f := range files {+			if f == dir {+				http.Redirect(w, r, blobURL(repo, rev, dir), http.StatusSeeOther)+				return+			}+			if strings.HasPrefix(f, dir+"/") {+				isDir = true+			}+		}+		if !isDir {+			s.renderError(w, r, http.StatusNotFound, "Path not found.")+			return+		}+	}+	branches, _ := s.vn.Branches(r.Context(), repo.ID, central)+	parent := ""+	if dir != "" {+		parent = path.Dir(dir)+		if parent == "." {+			parent = ""+		}+	}+	page := s.page(r, repo.OwnerName+"/"+repo.Name+" · "+rev)+	page.Data = map[string]any{+		"Repo":     repo,+		"Perms":    perms,+		"Branches": branches,+		"Rev":      rev,+		"Path":     dir,+		"Parent":   parent,+		"Entries":  buildTree(files, dir),+		"Commits":  func() []vn.Commit { c, _ := s.vn.Log(r.Context(), repo.ID, central, rev, 3); return c }(),+	}+	s.render(w, r, http.StatusOK, "tree", page)+}++func (s *Server) repoBlob(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	rev := r.PathValue("rev")+	if err := safeRevInput(rev); err != nil {+		s.renderError(w, r, http.StatusBadRequest, "Invalid revision.")+		return+	}+	p := strings.Trim(r.PathValue("path"), "/")+	if err := auth.ValidRepoPath(p); err != nil {+		s.renderError(w, r, http.StatusBadRequest, "Invalid path.")+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	f, err := s.vn.ReadFile(r.Context(), repo.ID, central, rev, p, 2<<20)+	if err != nil {+		if errors.Is(err, vn.ErrTooLarge) {+			s.renderError(w, r, http.StatusRequestEntityTooLarge, "File is too large to display.")+			return+		}+		s.renderError(w, r, http.StatusNotFound, "File not found.")+		return+	}+	parent := path.Dir(p)+	if parent == "." {+		parent = ""+	}+	branches, _ := s.vn.Branches(r.Context(), repo.ID, central)+	dataMap := map[string]any{+		"Repo":        repo,+		"Perms":       perms,+		"Branches":    branches,+		"Rev":         rev,+		"Path":        p,+		"Parent":      parent,+		"Name":        path.Base(p),+		"Size":        f.Size,+		"IsSymlink":   f.IsSymlink,+		"LinkTarget":  f.LinkTarget,+		"RawURL":      rawURL(repo, rev, p),+		"DownloadURL": rawURL(repo, rev, p) + "?download=1",+		"BranchesURL": repoURL(repo) + "/branches",+	}+	if f.IsSymlink {+		dataMap["Binary"] = false+		dataMap["Lines"] = []CodeLine{{Number: 1, Text: "symlink → " + f.LinkTarget}}+	} else {+		lines, binary, truncated := splitCode(f.Data)+		dataMap["Binary"] = binary+		dataMap["Lines"] = lines+		dataMap["Truncated"] = truncated+	}+	page := s.page(r, path.Base(p)+" · "+repo.OwnerName+"/"+repo.Name)+	page.Data = dataMap+	s.render(w, r, http.StatusOK, "blob", page)+}++func (s *Server) repoRaw(w http.ResponseWriter, r *http.Request) {+	repo, _, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	rev := r.PathValue("rev")+	if err := safeRevInput(rev); err != nil {+		http.Error(w, "invalid revision", http.StatusBadRequest)+		return+	}+	p := strings.Trim(r.PathValue("path"), "/")+	if err := auth.ValidRepoPath(p); err != nil {+		http.Error(w, "invalid path", http.StatusBadRequest)+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	f, err := s.vn.ReadFile(r.Context(), repo.ID, central, rev, p, 20<<20)+	if err != nil {+		if errors.Is(err, vn.ErrTooLarge) {+			http.Error(w, "file too large", http.StatusRequestEntityTooLarge)+			return+		}+		http.NotFound(w, r)+		return+	}+	name := filepath.Base(p)+	mimeType := mimeFor(name)+	w.Header().Set("X-Content-Type-Options", "nosniff")+	if mimeType == "image/svg+xml" || strings.HasSuffix(strings.ToLower(name), ".html") || strings.HasSuffix(strings.ToLower(name), ".htm") {+		mimeType = "text/plain; charset=utf-8"+	}+	if r.URL.Query().Get("download") == "1" {+		w.Header().Set("Content-Type", "application/octet-stream")+		w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name}))+	} else if isSafeImage(mimeType) {+		w.Header().Set("Content-Type", mimeType)+		w.Header().Set("Cache-Control", "private, max-age=300")+	} else {+		w.Header().Set("Content-Type", mimeType)+		if !strings.HasPrefix(mimeType, "text/") {+			w.Header().Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name}))+		}+	}+	_, _ = w.Write(f.Data)+}++func (s *Server) repoCommits(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	branches, _ := s.vn.Branches(r.Context(), repo.ID, central)+	rev := r.PathValue("rev")+	if rev == "" {+		rev = defaultRev(repo, branches)+	}+	if rev != "" {+		if err := safeRevInput(rev); err != nil {+			s.renderError(w, r, http.StatusBadRequest, "Invalid revision.")+			return+		}+	}+	commits := []vn.Commit{}+	if rev != "" {+		commits, _ = s.vn.Log(r.Context(), repo.ID, central, rev, 300)+	}+	page := s.page(r, "Commits · "+repo.OwnerName+"/"+repo.Name)+	page.Data = map[string]any{+		"Repo":     repo,+		"Perms":    perms,+		"Branches": branches,+		"Rev":      rev,+		"Commits":  commits,+	}+	s.render(w, r, http.StatusOK, "commits", page)+}++func (s *Server) repoCommit(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	rev := r.PathValue("rev")+	if err := safeRevInput(rev); err != nil {+		s.renderError(w, r, http.StatusBadRequest, "Invalid revision.")+		return+	}+	central := s.vn.RepoPath(repo.OwnerName, repo.Name)+	detail, err := s.vn.Show(r.Context(), repo.ID, central, rev)+	if err != nil {+		s.renderError(w, r, http.StatusNotFound, "Commit not found.")+		return+	}+	truncated := false+	diff := detail.Diff+	if len(diff) > 2<<20 {+		diff = diff[:2<<20]+		truncated = true+	}+	detail.Diff = diff+	page := s.page(r, "Commit "+shortHash(detail.Hash))+	page.Data = map[string]any{+		"Repo":      repo,+		"Perms":     perms,+		"Detail":    detail,+		"Lines":     splitDiff(diff),+		"Truncated": truncated,+	}+	s.render(w, r, http.StatusOK, "commit", page)+}++func (s *Server) repoBranches(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	branches, _ := s.vn.Branches(r.Context(), repo.ID, s.vn.RepoPath(repo.OwnerName, repo.Name))+	page := s.page(r, "Branches · "+repo.OwnerName+"/"+repo.Name)+	page.Data = map[string]any{+		"Repo":          repo,+		"Perms":         perms,+		"Branches":      branches,+		"DefaultBranch": repo.DefaultBranch,+	}+	s.render(w, r, http.StatusOK, "branches", page)+}++func (s *Server) repoStar(w http.ResponseWriter, r *http.Request) {+	repo, _, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	added, err := s.data.ToggleStar(r.Context(), repo.ID, u.ID)+	if err != nil {+		redirect(w, r, repoURL(repo), "", "Could not update the star.")+		return+	}+	action := "removed"+	if added {+		action = "added"+	}+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "star", action)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "star."+action, repo.OwnerName+"/"+repo.Name, r.UserAgent())+	s.dispatchWebhook(repo, u, "star", map[string]any{"action": action, "stars": func() int64 { n, _ := s.data.StarCount(r.Context(), repo.ID); return n }()})+	target := repoURL(repo)+	if ref := r.Referer(); ref != "" {+		if parsed, err := url.Parse(ref); err == nil && parsed.Host == r.Host {+			target = parsed.RequestURI()+		}+	}+	redirect(w, r, target, "Star "+action+".", "")+}++func (s *Server) repoAttachmentUpload(w http.ResponseWriter, r *http.Request) {+	// Handled in attachments.go to keep multipart parsing together.+	s.handleAttachmentUpload(w, r)+}++var _ = strconv.Itoa--- /dev/null+++ b/internal/web/repo_manage.go@@ -0,0 +1,379 @@+package web++import (+	"errors"+	"net/http"+	"strconv"+	"strings"+	"time"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++type ownerOption struct {+	Type        string+	ID          int64+	Name        string+	DisplayName string+}++func (s *Server) ownerOptions(r *http.Request, u *data.User) []ownerOption {+	opts := []ownerOption{{Type: "user", ID: u.ID, Name: u.Username, DisplayName: u.DisplayName}}+	orgs, _ := s.data.ListUserOrgs(r.Context(), u.ID)+	for _, org := range orgs {+		role, _ := s.data.OrgRole(r.Context(), org.ID, u.ID)+		if role == "owner" || role == "admin" {+			opts = append(opts, ownerOption{Type: "org", ID: org.ID, Name: org.Name, DisplayName: org.DisplayName})+		}+	}+	return opts+}++func (s *Server) newRepoPage(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	page := s.page(r, "New repository")+	page.Data = map[string]any{"Owners": s.ownerOptions(r, u)}+	s.render(w, r, http.StatusOK, "new_repo", page)+}++func (s *Server) newRepoPost(w http.ResponseWriter, r *http.Request) {+	u := s.requireUser(w, r)+	if u == nil {+		return+	}+	name := strings.TrimSpace(r.FormValue("name"))+	display := auth.CleanOneLine(r.FormValue("display_name"), 80)+	description := strings.TrimSpace(r.FormValue("description"))+	visibility := r.FormValue("visibility")+	if visibility != "public" && visibility != "private" {+		visibility = "public"+	}+	if len(description) > 2000 {+		redirect(w, r, "/new", "", "Description is too long.")+		return+	}+	if err := auth.ValidRepoName(name); err != nil {+		redirect(w, r, "/new", "", err.Error())+		return+	}+	if display == "" {+		display = name+	}+	owners := s.ownerOptions(r, u)+	var owner *ownerOption+	want := r.FormValue("owner")+	for i := range owners {+		candidate := owners[i]+		key := candidate.Type + ":" + strconv.FormatInt(candidate.ID, 10)+		if key == want || (want == "" && i == 0) {+			owner = &owners[i]+			break+		}+	}+	if owner == nil {+		redirect(w, r, "/new", "", "You do not have permission to create a repository for that owner.")+		return+	}+	repo, err := s.data.CreateRepo(r.Context(), owner.Type, owner.ID, owner.Name, name, display, description, visibility)+	if err != nil {+		if errors.Is(err, data.ErrConflict) {+			redirect(w, r, "/new", "", "A repository with that name already exists for this owner.")+		} else {+			redirect(w, r, "/new", "", "Could not create the repository record.")+		}+		return+	}+	if _, err := s.vn.CreateRepo(r.Context(), owner.Name, name); err != nil {+		_ = s.data.DeleteRepo(r.Context(), repo.ID)+		s.logger.Printf("vn init %s/%s: %v", owner.Name, name, err)+		redirect(w, r, "/new", "", "Could not initialise the veins repository.")+		return+	}+	if err := s.syncRepoAccess(r.Context(), repo); err != nil {+		s.logger.Printf("sync access for new repo %d: %v", repo.ID, err)+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "repo.create", owner.Name+"/"+name, r.UserAgent())+	s.data.AddActivity(r.Context(), repo.ID, &u.ID, "repo.create", "")+	redirect(w, r, repoURL(repo), "Repository created. Push a bookmark to get started.", "")+}++func (s *Server) repoSettings(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	collaborators, _ := s.data.ListCollaborators(r.Context(), repo.ID)+	repoTeams, _ := s.data.ListRepoTeams(r.Context(), repo.ID)+	webhooks, _ := s.data.ListWebhooks(r.Context(), repo.ID)+	branches, _ := s.vn.Branches(r.Context(), repo.ID, s.vn.RepoPath(repo.OwnerName, repo.Name))+	var orgTeams []*data.Team+	if repo.OwnerType == "org" {+		orgTeams, _ = s.data.ListTeams(r.Context(), repo.OwnerID)+	}+	page := s.page(r, "Settings · "+repo.OwnerName+"/"+repo.Name)+	page.Data = map[string]any{+		"Repo":          repo,+		"Perms":         perms,+		"Collaborators": collaborators,+		"Teams":         repoTeams,+		"OrgTeams":      orgTeams,+		"Webhooks":      webhooks,+		"Branches":      branches,+	}+	s.render(w, r, http.StatusOK, "repo_settings", page)+}++func (s *Server) repoSettingsPost(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	u := userFrom(r)+	display := auth.CleanOneLine(r.FormValue("display_name"), 80)+	description := strings.TrimSpace(r.FormValue("description"))+	visibility := r.FormValue("visibility")+	defaultBranch := strings.TrimSpace(r.FormValue("default_branch"))+	archived := r.FormValue("archived") == "on"+	if visibility != "public" && visibility != "private" {+		visibility = "public"+	}+	if err := auth.ValidBranchName(defaultBranch); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "Invalid default branch name.")+		return+	}+	if display == "" {+		display = repo.Name+	}+	if len(description) > 2000 {+		redirect(w, r, repoURL(repo)+"/settings", "", "Description is too long.")+		return+	}+	if err := s.data.UpdateRepo(r.Context(), repo.ID, display, description, visibility, defaultBranch, archived); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "Could not save repository settings.")+		return+	}+	repo.DisplayName = display+	repo.Description = description+	repo.Visibility = visibility+	repo.DefaultBranch = defaultBranch+	repo.Archived = archived+	if err := s.syncRepoAccess(r.Context(), repo); err != nil {+		s.logger.Printf("sync access after settings %d: %v", repo.ID, err)+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "repo.settings", repo.OwnerName+"/"+repo.Name, r.UserAgent())+	s.dispatchWebhook(repo, u, "repository", map[string]any{"action": "edited"})+	redirect(w, r, repoURL(repo)+"/settings", "Settings saved.", "")+}++func (s *Server) repoCollaboratorPost(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	u := userFrom(r)+	username := strings.TrimSpace(r.FormValue("username"))+	role := r.FormValue("role")+	if role != "read" && role != "write" && role != "admin" {+		role = "read"+	}+	target, err := s.data.GetUserByUsername(r.Context(), username)+	if err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "User not found.")+		return+	}+	if err := s.data.SetCollaborator(r.Context(), repo.ID, target.ID, role); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "Could not add collaborator.")+		return+	}+	if err := s.syncRepoAccess(r.Context(), repo); err != nil {+		s.logger.Printf("sync access after collaborator: %v", err)+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "repo.collaborator", repo.OwnerName+"/"+repo.Name+" "+target.Username, r.UserAgent())+	redirect(w, r, repoURL(repo)+"/settings", "Collaborator updated.", "")+}++func (s *Server) repoCollaboratorDelete(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	userID, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid collaborator.")+		return+	}+	_ = s.data.RemoveCollaborator(r.Context(), repo.ID, userID)+	if err := s.syncRepoAccess(r.Context(), repo); err != nil {+		s.logger.Printf("sync access after collaborator removal: %v", err)+	}+	u := userFrom(r)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "repo.collaborator.remove", repo.OwnerName+"/"+repo.Name, r.UserAgent())+	redirect(w, r, repoURL(repo)+"/settings", "Collaborator removed.", "")+}++func (s *Server) repoTeamPost(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	if repo.OwnerType != "org" {+		redirect(w, r, repoURL(repo)+"/settings", "", "Only organisation repositories can use teams.")+		return+	}+	teamID, ok := parseID(r.FormValue("team_id"))+	if !ok {+		redirect(w, r, repoURL(repo)+"/settings", "", "Choose a team.")+		return+	}+	if _, err := s.data.GetTeam(r.Context(), repo.OwnerID, teamID); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "Team not found in this organisation.")+		return+	}+	role := r.FormValue("permission")+	if role != "read" && role != "write" && role != "admin" {+		role = "read"+	}+	if err := s.data.SetRepoTeam(r.Context(), repo.ID, teamID, role); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "Could not grant team access.")+		return+	}+	if err := s.syncRepoAccess(r.Context(), repo); err != nil {+		s.logger.Printf("sync access after team: %v", err)+	}+	u := userFrom(r)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "repo.team", repo.OwnerName+"/"+repo.Name, r.UserAgent())+	redirect(w, r, repoURL(repo)+"/settings", "Team access updated.", "")+}++func (s *Server) repoTeamDelete(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	teamID, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid team.")+		return+	}+	_ = s.data.RemoveRepoTeam(r.Context(), repo.ID, teamID)+	if err := s.syncRepoAccess(r.Context(), repo); err != nil {+		s.logger.Printf("sync access after team removal: %v", err)+	}+	redirect(w, r, repoURL(repo)+"/settings", "Team access removed.", "")+}++func (s *Server) repoWebhookCreate(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	target := strings.TrimSpace(r.FormValue("url"))+	if err := s.validateWebhookURL(r.Context(), target); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", err.Error())+		return+	}+	secret := strings.TrimSpace(r.FormValue("secret"))+	if secret == "" {+		secret, _ = auth.RandomToken(32)+	}+	if len(secret) > 256 {+		redirect(w, r, repoURL(repo)+"/settings", "", "Webhook secret is too long.")+		return+	}+	var events []string+	for _, ev := range []string{"issue", "pull_request", "comment", "star", "repository"} {+		if r.FormValue("event_"+ev) == "on" {+			events = append(events, ev)+		}+	}+	if len(events) == 0 {+		events = []string{"issue", "pull_request", "comment", "star", "repository"}+	}+	u := userFrom(r)+	if err := s.data.CreateWebhook(r.Context(), repo.ID, u.ID, target, secret, strings.Join(events, ",")); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "Could not create webhook.")+		return+	}+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "webhook.create", repo.OwnerName+"/"+repo.Name+" "+target, r.UserAgent())+	s.dispatchWebhook(repo, u, "repository", map[string]any{"action": "webhook_created"})+	redirect(w, r, repoURL(repo)+"/settings", "Webhook created.", "")+}++func (s *Server) repoWebhookDelete(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	id, ok := parseID(r.PathValue("id"))+	if !ok {+		s.renderError(w, r, http.StatusBadRequest, "Invalid webhook.")+		return+	}+	_ = s.data.DeleteWebhook(r.Context(), repo.ID, id)+	u := userFrom(r)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "webhook.delete", repo.OwnerName+"/"+repo.Name, r.UserAgent())+	redirect(w, r, repoURL(repo)+"/settings", "Webhook removed.", "")+}++func (s *Server) repoDelete(w http.ResponseWriter, r *http.Request) {+	repo, perms, ok := s.repoFromPath(w, r)+	if !ok {+		return+	}+	if !perms.CanAdmin {+		s.renderError(w, r, http.StatusForbidden, "Repository administrator access required.")+		return+	}+	if strings.TrimSpace(r.FormValue("confirm")) != repo.Name {+		redirect(w, r, repoURL(repo)+"/settings", "", "Type the repository name to confirm deletion.")+		return+	}+	u := userFrom(r)+	s.data.RecordAudit(r.Context(), &u.ID, u.Username, ipFrom(r), "repo.delete", repo.OwnerName+"/"+repo.Name, r.UserAgent())+	if err := s.data.DeleteRepo(r.Context(), repo.ID); err != nil {+		redirect(w, r, repoURL(repo)+"/settings", "", "Could not delete the repository.")+		return+	}+	if err := s.vn.RemoveRepo(r.Context(), repo.OwnerName, repo.Name, repo.ID); err != nil {+		s.logger.Printf("remove repo files %s/%s: %v", repo.OwnerName, repo.Name, err)+	}+	redirect(w, r, "/", "Repository deleted.", "")+}++var _ = time.Now--- /dev/null+++ b/internal/web/repo_router.go@@ -0,0 +1,197 @@+package web++import (+	"net/http"+	"strings"+)++// repoDispatchGet routes three-or-more-segment repository URLs manually. Keeping+// a single wildcard pattern avoids ambiguities between repository paths and+// literal application routes in net/http's enhanced ServeMux.+func (s *Server) repoDispatchGet(w http.ResponseWriter, r *http.Request) {+	rest := splitRest(r.PathValue("rest"))+	if len(rest) == 0 {+		s.repoOverview(w, r)+		return+	}+	switch rest[0] {+	case "tree":+		if len(rest) < 2 {+			s.renderError(w, r, http.StatusNotFound, "Path not found.")+			return+		}+		r.SetPathValue("rev", decodeRevPath(rest[1]))+		r.SetPathValue("path", strings.Join(rest[2:], "/"))+		s.repoTree(w, r)+	case "blob":+		if len(rest) < 3 {+			s.renderError(w, r, http.StatusNotFound, "File not found.")+			return+		}+		r.SetPathValue("rev", decodeRevPath(rest[1]))+		r.SetPathValue("path", strings.Join(rest[2:], "/"))+		s.repoBlob(w, r)+	case "raw":+		if len(rest) < 3 {+			http.NotFound(w, r)+			return+		}+		r.SetPathValue("rev", decodeRevPath(rest[1]))+		r.SetPathValue("path", strings.Join(rest[2:], "/"))+		s.repoRaw(w, r)+	case "commits":+		if len(rest) >= 2 {+			r.SetPathValue("rev", decodeRevPath(rest[1]))+		}+		s.repoCommits(w, r)+	case "commit":+		if len(rest) < 2 {+			s.renderError(w, r, http.StatusNotFound, "Commit not found.")+			return+		}+		r.SetPathValue("rev", decodeRevPath(rest[1]))+		s.repoCommit(w, r)+	case "branches":+		s.repoBranches(w, r)+	case "issues":+		if len(rest) >= 2 && rest[1] == "new" {+			s.repoIssueNew(w, r)+			return+		}+		if len(rest) >= 2 {+			r.SetPathValue("number", rest[1])+			s.repoIssue(w, r)+			return+		}+		s.repoIssues(w, r)+	case "pulls":+		if len(rest) >= 2 && rest[1] == "new" {+			s.repoPullNew(w, r)+			return+		}+		if len(rest) >= 2 {+			r.SetPathValue("number", rest[1])+			s.repoPull(w, r)+			return+		}+		s.repoPulls(w, r)+	case "settings":+		if len(rest) == 1 {+			s.repoSettings(w, r)+			return+		}+		s.renderError(w, r, http.StatusNotFound, "Not found.")+	default:+		s.renderError(w, r, http.StatusNotFound, "Not found.")+	}+}++func (s *Server) repoDispatchPost(w http.ResponseWriter, r *http.Request) {+	rest := splitRest(r.PathValue("rest"))+	if len(rest) == 0 {+		s.renderError(w, r, http.StatusNotFound, "Not found.")+		return+	}+	switch rest[0] {+	case "star":+		s.repoStar(w, r)+	case "issues":+		if len(rest) == 1 {+			s.repoIssueCreate(w, r)+			return+		}+		if len(rest) == 3 {+			r.SetPathValue("number", rest[1])+			switch rest[2] {+			case "comments":+				s.repoIssueComment(w, r)+				return+			case "state":+				s.repoIssueState(w, r)+				return+			}+		}+		s.renderError(w, r, http.StatusNotFound, "Not found.")+	case "pulls":+		if len(rest) == 1 {+			s.repoPullCreate(w, r)+			return+		}+		if len(rest) == 3 {+			r.SetPathValue("number", rest[1])+			switch rest[2] {+			case "comments":+				s.repoPullComment(w, r)+				return+			case "state":+				s.repoPullState(w, r)+				return+			case "merge":+				s.repoPullMerge(w, r)+				return+			}+		}+		s.renderError(w, r, http.StatusNotFound, "Not found.")+	case "attachments":+		s.repoAttachmentUpload(w, r)+	case "settings":+		if len(rest) == 1 {+			s.repoSettingsPost(w, r)+			return+		}+		switch rest[1] {+		case "collaborators":+			if len(rest) == 2 {+				s.repoCollaboratorPost(w, r)+				return+			}+			if len(rest) == 4 && rest[3] == "delete" {+				r.SetPathValue("id", rest[2])+				s.repoCollaboratorDelete(w, r)+				return+			}+		case "teams":+			if len(rest) == 2 {+				s.repoTeamPost(w, r)+				return+			}+			if len(rest) == 4 && rest[3] == "delete" {+				r.SetPathValue("id", rest[2])+				s.repoTeamDelete(w, r)+				return+			}+		case "webhooks":+			if len(rest) == 2 {+				s.repoWebhookCreate(w, r)+				return+			}+			if len(rest) == 4 && rest[3] == "delete" {+				r.SetPathValue("id", rest[2])+				s.repoWebhookDelete(w, r)+				return+			}+		case "delete":+			if len(rest) == 2 {+				s.repoDelete(w, r)+				return+			}+		}+		s.renderError(w, r, http.StatusNotFound, "Not found.")+	default:+		s.renderError(w, r, http.StatusNotFound, "Not found.")+	}+}++func splitRest(rest string) []string {+	rest = strings.Trim(rest, "/")+	if rest == "" {+		return nil+	}+	parts := strings.Split(rest, "/")+	for _, p := range parts {+		if p == "" || p == "." || p == ".." {+			return nil+		}+	}+	return parts+}--- /dev/null+++ b/internal/web/server.go@@ -0,0 +1,345 @@+package web++import (+	"context"+	"embed"+	"fmt"+	"html/template"+	"io/fs"+	"log"+	"net"+	"net/http"+	"strings"+	"sync"+	"time"++	"veinsforge/internal/auth"+	"veinsforge/internal/config"+	"veinsforge/internal/data"+	"veinsforge/internal/vn"+)++//go:embed templates/*.html+var templateFS embed.FS++//go:embed static/*+var staticFS embed.FS++type Server struct {+	cfg        config.Config+	data       *data.Store+	vn         *vn.Runner+	native     *vn.NativeServer+	logger     *log.Logger+	templates  map[string]*template.Template+	limiter    *limiter+	trusted    []*net.IPNet+	sem        chan struct{}+	hashSem    chan struct{}+	webhookSem chan struct{}+	accessMu   sync.Mutex+	siteName   string+	siteDesc   string+	regOpen    bool+	dummyHash  string+}++type Page struct {+	Title     string+	Path      string+	User      *data.User+	CSRF      string+	Notice    string+	Error     string+	SiteName  string+	SiteDesc  string+	Data      any+	NativePin string+	NativeURL string+}++func New(cfg config.Config, store *data.Store, runner *vn.Runner, native *vn.NativeServer, logger *log.Logger) (*Server, error) {+	dummy, _ := auth.HashPassword("veinsforge-dummy-password")+	s := &Server{+		cfg:        cfg,+		data:       store,+		vn:         runner,+		native:     native,+		logger:     logger,+		limiter:    newLimiter(cfg.RateLimitPerSec, cfg.RateLimitBurst, cfg.AuthLimitPerMin, cfg.WriteLimitPerMin),+		sem:        make(chan struct{}, cfg.MaxConcurrent),+		hashSem:    make(chan struct{}, 4),+		webhookSem: make(chan struct{}, 16),+		siteName:   store.Setting(context.Background(), "site_name", "veinsforge"),+		siteDesc:   store.Setting(context.Background(), "site_description", "A brutalist forge for veins repositories."),+		dummyHash:  dummy,+	}+	for _, cidr := range cfg.TrustedProxies {+		if !strings.Contains(cidr, "/") {+			if ip := net.ParseIP(cidr); ip != nil {+				bits := 128+				if ip.To4() != nil {+					bits = 32+				}+				cidr = fmt.Sprintf("%s/%d", cidr, bits)+			}+		}+		_, block, err := net.ParseCIDR(cidr)+		if err == nil {+			s.trusted = append(s.trusted, block)+		}+	}+	funcs := template.FuncMap{+		"date":       formatDate,+		"timeago":    timeAgo,+		"short":      shortHash,+		"avatarURL":  avatarURL,+		"orgAvatar":  orgAvatarURL,+		"initials":   initials,+		"repoURL":    repoURL,+		"ownerURL":   ownerURL,+		"issueURL":   issueURL,+		"pullURL":    pullURL,+		"commitURL":  commitURL,+		"treeURL":    treeURL,+		"blobURL":    blobURL,+		"rawURL":     rawURL,+		"add":        func(a, b int) int { return a + b },+		"sub":        func(a, b int) int { return a - b },+		"stateClass": stateClass,+		"roleLabel":  roleLabel,+		"join":       strings.Join,+		"hasPrefix":  strings.HasPrefix,+		"percent":    percent,+		"revPath":    revPath,+	}+	s.templates = make(map[string]*template.Template)+	pages := []string{+		"home", "explore", "login", "signup", "user", "repo", "tree", "blob",+		"commits", "commit", "branches", "issues", "issue_new", "issue",+		"pulls", "pull_new", "pull", "settings_user", "repo_settings", "new_repo",+		"org", "org_new", "org_settings", "admin", "error",+	}+	for _, name := range pages {+		t, err := template.New("layout").Funcs(funcs).ParseFS(templateFS,+			"templates/layout.html", "templates/"+name+".html")+		if err != nil {+			return nil, fmt.Errorf("parse template %s: %w", name, err)+		}+		s.templates[name] = t+	}+	return s, nil+}++func (s *Server) Handler() http.Handler {+	mux := http.NewServeMux()+	s.routes(mux)+	sub, _ := fs.Sub(staticFS, "static")+	fileServer := http.FileServer(http.FS(sub))+	for _, name := range []string{"app.css", "app.js", "favicon.svg"} {+		mux.Handle("GET /static/"+name, http.StripPrefix("/static/", cacheStatic(fileServer)))+	}+	mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {+		w.Header().Set("Content-Type", "text/plain; charset=utf-8")+		w.WriteHeader(http.StatusOK)+		_, _ = w.Write([]byte("ok\n"))+	})+	mux.HandleFunc("GET /robots.txt", func(w http.ResponseWriter, r *http.Request) {+		w.Header().Set("Content-Type", "text/plain; charset=utf-8")+		_, _ = w.Write([]byte("User-agent: *\nDisallow: /settings\nDisallow: /admin\nDisallow: /avatars\nDisallow: /attachments\n"))+	})+	var h http.Handler = mux+	h = s.loadSession(h)+	h = s.withCSRF(h)+	h = s.limit(h)+	h = s.security(h)+	h = s.recover(h)+	return h+}++func (s *Server) routes(mux *http.ServeMux) {+	mux.HandleFunc("GET /{$}", s.home)+	mux.HandleFunc("GET /explore", s.explore)+	mux.HandleFunc("GET /login", s.loginPage)+	mux.HandleFunc("POST /login", s.loginPost)+	mux.HandleFunc("GET /signup", s.signupPage)+	mux.HandleFunc("POST /signup", s.signupPost)+	mux.HandleFunc("POST /logout", s.logout)+	mux.HandleFunc("GET /settings", s.userSettings)+	mux.HandleFunc("POST /settings/profile", s.userProfilePost)+	mux.HandleFunc("POST /settings/password", s.userPasswordPost)+	mux.HandleFunc("POST /settings/keys", s.userKeyAdd)+	mux.HandleFunc("POST /settings/keys/{id}/delete", s.userKeyDelete)+	mux.HandleFunc("POST /settings/avatar", s.userAvatarPost)+	mux.HandleFunc("POST /settings/avatar/delete", s.userAvatarDelete)+	mux.HandleFunc("GET /new", s.newRepoPage)+	mux.HandleFunc("POST /new", s.newRepoPost)+	mux.HandleFunc("GET /u/{username}", s.userPage)+	mux.HandleFunc("GET /avatars/{username}", s.userAvatar)+	mux.HandleFunc("GET /orgs/new", s.newOrgPage)+	mux.HandleFunc("POST /orgs/new", s.newOrgPost)+	mux.HandleFunc("GET /orgs/{org}", s.orgPage)+	mux.HandleFunc("GET /orgs/{org}/settings", s.orgSettings)+	mux.HandleFunc("POST /orgs/{org}/settings", s.orgSettingsPost)+	mux.HandleFunc("POST /orgs/{org}/members", s.orgMemberAdd)+	mux.HandleFunc("POST /orgs/{org}/members/{id}/delete", s.orgMemberDelete)+	mux.HandleFunc("POST /orgs/{org}/teams", s.orgTeamCreate)+	mux.HandleFunc("POST /orgs/{org}/teams/{id}/delete", s.orgTeamDelete)+	mux.HandleFunc("POST /orgs/{org}/teams/{id}/members", s.orgTeamMemberAdd)+	mux.HandleFunc("POST /orgs/{org}/teams/{id}/members/{uid}/delete", s.orgTeamMemberDelete)+	mux.HandleFunc("GET /attachments/{id}", s.attachmentGet)++	mux.HandleFunc("GET /{owner}/{repo}", s.repoOverview)+	mux.HandleFunc("GET /{owner}/{repo}/{rest...}", s.repoDispatchGet)+	mux.HandleFunc("POST /{owner}/{repo}/{rest...}", s.repoDispatchPost)++	mux.HandleFunc("GET /admin", s.adminPage)+	mux.HandleFunc("GET /admin/users", s.adminUsers)+	mux.HandleFunc("POST /admin/users", s.adminUserCreate)+	mux.HandleFunc("POST /admin/users/{id}/active", s.adminUserActive)+	mux.HandleFunc("POST /admin/users/{id}/admin", s.adminUserAdmin)+	mux.HandleFunc("POST /admin/users/{id}/password", s.adminUserPassword)+	mux.HandleFunc("GET /admin/repos", s.adminRepos)+	mux.HandleFunc("GET /admin/audit", s.adminAudit)+	mux.HandleFunc("POST /admin/settings", s.adminSettings)+}++func (s *Server) render(w http.ResponseWriter, r *http.Request, status int, name string, page Page) {+	t := s.templates[name]+	if t == nil {+		http.Error(w, "template not found", http.StatusInternalServerError)+		return+	}+	if page.SiteName == "" {+		page.SiteName = s.siteName+	}+	if page.SiteDesc == "" {+		page.SiteDesc = s.siteDesc+	}+	if page.Path == "" && r != nil {+		page.Path = r.URL.Path+	}+	if page.CSRF == "" {+		page.CSRF = csrfFrom(r)+	}+	if page.NativePin == "" && s.native != nil {+		_, _, page.NativePin, page.NativeURL = s.native.Status()+	}+	w.Header().Set("Content-Type", "text/html; charset=utf-8")+	w.WriteHeader(status)+	if err := t.ExecuteTemplate(w, "layout", page); err != nil {+		s.logger.Printf("render %s: %v", name, err)+	}+}++func (s *Server) renderError(w http.ResponseWriter, r *http.Request, status int, msg string) {+	s.render(w, r, status, "error", Page{+		Title: http.StatusText(status),+		Error: msg,+		User:  userFrom(r),+		CSRF:  csrfFrom(r),+	})+}++func (s *Server) page(r *http.Request, title string) Page {+	notice := auth.CleanOneLine(r.URL.Query().Get("notice"), 300)+	errMsg := auth.CleanOneLine(r.URL.Query().Get("error"), 500)+	return Page{+		Title:  title,+		Path:   r.URL.Path,+		User:   userFrom(r),+		CSRF:   csrfFrom(r),+		Notice: notice,+		Error:  errMsg,+	}+}++func cacheStatic(next http.Handler) http.Handler {+	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+		w.Header().Set("Cache-Control", "public, max-age=86400")+		next.ServeHTTP(w, r)+	})+}++func formatDate(t time.Time) string {+	if t.IsZero() {+		return ""+	}+	return t.UTC().Format("2006-01-02")+}++func timeAgo(t time.Time) string {+	if t.IsZero() {+		return ""+	}+	d := time.Since(t)+	switch {+	case d < time.Minute:+		return "now"+	case d < time.Hour:+		return fmt.Sprintf("%dm ago", int(d.Minutes()))+	case d < 24*time.Hour:+		return fmt.Sprintf("%dh ago", int(d.Hours()))+	case d < 30*24*time.Hour:+		return fmt.Sprintf("%dd ago", int(d.Hours()/24))+	default:+		return t.UTC().Format("2006-01-02")+	}+}++func shortHash(h string) string {+	if len(h) <= 12 {+		return h+	}+	return h[:12]+}++func initials(name string) string {+	name = strings.TrimSpace(name)+	if name == "" {+		return "?"+	}+	parts := strings.Fields(name)+	if len(parts) == 1 {+		if len(parts[0]) >= 2 {+			return strings.ToUpper(parts[0][:2])+		}+		return strings.ToUpper(parts[0])+	}+	return strings.ToUpper(parts[0][:1] + parts[len(parts)-1][:1])+}++func stateClass(state string) string {+	switch state {+	case "open", "merged":+		return "state-" + state+	case "closed":+		return "state-closed"+	default:+		return ""+	}+}++func roleLabel(role string) string {+	switch role {+	case "admin":+		return "Admin"+	case "write":+		return "Write"+	case "read":+		return "Read"+	case "owner":+		return "Owner"+	case "member":+		return "Member"+	default:+		return role+	}+}++func percent(part, total int64) int {+	if total <= 0 {+		return 0+	}+	return int(part * 100 / total)+}--- /dev/null+++ b/internal/web/static/app.css@@ -0,0 +1,504 @@+/* veinsforge */+:root {+  --font-body: system-ui, -apple-system, "Segoe UI", sans-serif;+  --font-mono: ui-monospace, "SFMono-Regular", Menlo, Consolas, monospace;+  --max: 880px;+}++:root[data-theme="dark"] {+  --bg: #080d16;+  --panel: #0b1220;+  --panel-2: #101a2c;+  --ink: #dce4f0;+  --ink-soft: #b7c2d2;+  --muted: #7f8da3;+  --line: #22314a;+  --line-strong: #3a4f70;+  --red: #e04448;+  --red-soft: #ff6b6f;+  --code-bg: #05090f;+  --code-ink: #d7e0ee;+  --code-muted: #596b83;+  --add: #78c7a6;+  --add-bg: rgba(57, 153, 118, 0.12);+  --del: #ff7c7c;+  --del-bg: rgba(224, 68, 72, 0.12);+}++:root[data-theme="light"] {+  --bg: #f6f5ef;+  --panel: #fbfaf5;+  --panel-2: #eeebe2;+  --ink: #101620;+  --ink-soft: #303a48;+  --muted: #65707f;+  --line: #cec8b9;+  --line-strong: #8a8272;+  --red: #b9161d;+  --red-soft: #8f1016;+  --code-bg: #171e29;+  --code-ink: #e2e8f2;+  --code-muted: #7b8ca3;+  --add: #1f7a59;+  --add-bg: rgba(31, 122, 89, 0.09);+  --del: #a61c21;+  --del-bg: rgba(185, 22, 29, 0.08);+}++* { box-sizing: border-box; }+html { color-scheme: dark light; }+body {+  margin: 0;+  background: var(--bg);+  color: var(--ink);+  font-family: var(--font-body);+  font-size: 15px;+  line-height: 1.55;+  min-height: 100vh;+  display: flex;+  flex-direction: column;+}++a {+  color: var(--ink);+  text-decoration: underline;+  text-decoration-thickness: 1px;+  text-underline-offset: 2px;+}+a:hover { color: var(--red); }++h1, h2, h3 {+  font-weight: 700;+  line-height: 1.2;+  margin: 1.8rem 0 .6rem;+}+h1 {+  font-size: clamp(1.65rem, 4vw, 2.25rem);+  letter-spacing: -.02em;+  margin-top: 1.4rem;+}+h2 { font-size: 1.15rem; }+h3 { font-size: 1rem; }+p { margin: 0 0 .95rem; }+ul, ol { margin: 0 0 1rem; padding-left: 1.3rem; }+li { margin: .15rem 0; }+hr { border: 0; border-top: 1px solid var(--line); margin: 1.5rem 0; }+pre { margin: 0 0 1rem; }+img { max-width: 100%; }+code, pre, .mono { font-family: var(--font-mono); font-size: .9em; }+code { color: var(--ink-soft); }++.skip {+  position: absolute;+  left: -9999px;+  top: 0;+  padding: .4rem .7rem;+  background: var(--red);+  color: #fff;+  z-index: 10;+}+.skip:focus { left: .5rem; }++.wrap {+  width: min(var(--max), calc(100% - 2.4rem));+  margin: 0 auto;+}++.site-header {+  border-bottom: 1px solid var(--line-strong);+  background: var(--bg);+}+.header-inner {+  display: flex;+  align-items: baseline;+  justify-content: space-between;+  gap: 1rem;+  padding: .9rem 0;+  flex-wrap: wrap;+}+.brand {+  font-family: var(--font-mono);+  font-size: 1.05rem;+  font-weight: 700;+  text-decoration: none;+  color: var(--ink);+}+.brand:hover { color: var(--red); }+.nav {+  display: flex;+  align-items: baseline;+  gap: .85rem;+  flex-wrap: wrap;+  font-family: var(--font-mono);+  font-size: .8rem;+}+.nav a { text-decoration: none; }+.nav a:hover { text-decoration: underline; }+.nav-user { display: inline-flex; align-items: center; gap: .35rem; }+.inline { display: inline; margin: 0; }+.link, .linkbtn {+  border: 0;+  background: none;+  color: var(--ink);+  padding: 0;+  font: inherit;+  cursor: pointer;+  text-decoration: underline;+  text-decoration-thickness: 1px;+  text-underline-offset: 2px;+}+.link:hover, .linkbtn:hover { color: var(--red); }+.theme-toggle { font-family: var(--font-mono); font-size: .8rem; }++main { flex: 1; padding: .5rem 0 3rem; }++.flash-ok, .flash-error {+  margin: 1rem 0;+  font-family: var(--font-mono);+  font-size: .82rem;+}+.flash-ok { color: var(--add); }+.flash-error { color: var(--red); }+.flash-ok::before { content: "[ok] "; }+.flash-error::before { content: "[error] "; }++.muted { color: var(--muted); }+.small, small { font-size: .83rem; }+.break { word-break: break-all; overflow-wrap: anywhere; }+.nowrap { white-space: nowrap; }+.kicker {+  font-family: var(--font-mono);+  font-size: .76rem;+  color: var(--muted);+  margin: 1.4rem 0 .2rem;+}+.kicker a { color: var(--muted); }+.kicker a:hover { color: var(--red); }++.btn {+  display: inline-block;+  border: 1px solid var(--line-strong);+  background: transparent;+  color: var(--ink);+  font-family: var(--font-mono);+  font-size: .8rem;+  padding: .35rem .6rem;+  cursor: pointer;+  line-height: 1.3;+}+.btn:hover { border-color: var(--red); color: var(--red); }+.btn-primary { border-color: var(--red); color: var(--red); }+.btn-primary:hover { background: var(--red); color: #fff; }+.btn-danger { border-color: var(--red); color: var(--red); }+.btn-danger:hover { background: var(--red); color: #fff; }+.btn-small { padding: .2rem .4rem; font-size: .74rem; }+.btn-block { display: block; width: 100%; text-align: center; }+.count { opacity: .8; }++input, select, textarea {+  width: 100%;+  border: 1px solid var(--line-strong);+  background: var(--panel);+  color: var(--ink);+  font-family: var(--font-mono);+  font-size: .85rem;+  padding: .4rem .5rem;+  border-radius: 0;+  outline: none;+}+input:focus, select:focus, textarea:focus {+  border-color: var(--red);+}+textarea { resize: vertical; }+input[type="checkbox"], input[type="radio"] { width: auto; accent-color: var(--red); }+input[type="file"] { border-style: dashed; padding: .3rem; }++label {+  display: flex;+  flex-direction: column;+  gap: .2rem;+  margin-bottom: .8rem;+  font-family: var(--font-mono);+  font-size: .78rem;+  color: var(--ink-soft);+}+label small { font-family: var(--font-body); color: var(--muted); }+label.checkbox, label.radio {+  flex-direction: row;+  align-items: flex-start;+  gap: .45rem;+  font-family: var(--font-body);+  font-size: .9rem;+  color: var(--ink-soft);+}+label.radio span { display: flex; flex-direction: column; }+fieldset { border: 1px solid var(--line); padding: .8rem; }+legend { font-family: var(--font-mono); font-size: .78rem; padding: 0 .3rem; }+.stack { display: flex; flex-direction: column; gap: .6rem; }+.form-narrow { max-width: 480px; margin: 1rem 0 1.5rem; }+.inline-form {+  display: flex;+  flex-wrap: wrap;+  align-items: center;+  gap: .45rem;+  margin: 1rem 0;+}+.inline-form input, .inline-form select { width: auto; min-width: 9rem; flex: 1 1 9rem; }+.attach-form {+  display: flex;+  flex-wrap: wrap;+  gap: .45rem;+  align-items: center;+  margin: 1rem 0;+  max-width: 480px;+}+.attach-form input { flex: 1 1 14rem; }+.two-col { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; }+.checkbox-row { display: flex; flex-wrap: wrap; gap: .8rem; margin-bottom: .8rem; }++.avatar {+  border: 1px solid var(--line);+  object-fit: cover;+  vertical-align: middle;+}+.avatar-sm { width: 20px; height: 20px; }+.avatar-lg { width: 72px; height: 72px; }+.avatar-empty { display: inline-block; background: var(--panel-2); }++.pager {+  display: flex;+  gap: 1rem;+  align-items: baseline;+  flex-wrap: wrap;+  margin: 1.2rem 0;+  font-family: var(--font-mono);+  font-size: .8rem;+}++.repo-list, .link-list, .file-list, .issue-list, .commit-list, .activity {+  list-style: none;+  padding: 0;+  margin: .4rem 0 1.2rem;+}+.repo-list li, .link-list li, .issue-list li, .commit-list li, .activity li {+  padding: .45rem 0;+  border-bottom: 1px solid var(--line);+}+.repo-list li > a, .link-list li > a { font-weight: 600; }+.repo-desc { color: var(--ink-soft); }+.repo-desc::before { content: " — "; color: var(--muted); }+.repo-meta {+  display: inline-block;+  margin-left: .4rem;+  font-family: var(--font-mono);+  font-size: .73rem;+  color: var(--muted);+}+.link-list li .muted, .issue-list li .muted, .commit-list li .muted { font-family: var(--font-mono); font-size: .78rem; }+.file-list li { padding: .15rem 0; border-bottom: 1px dotted var(--line); }+.file-list li a { display: block; font-family: var(--font-mono); font-size: .86rem; padding: .15rem 0; }+.issue-list li > a { font-weight: 600; }+.state {+  font-family: var(--font-mono);+  font-size: .72rem;+  color: var(--muted);+  margin-left: .35rem;+}+.state-open { color: var(--add); }+.state-merged { color: var(--red); }+.state-closed { color: var(--muted); }++.commit-strip {+  display: flex;+  justify-content: space-between;+  gap: 1rem;+  flex-wrap: wrap;+  border-top: 1px solid var(--line);+  border-bottom: 1px solid var(--line);+  padding: .45rem 0;+  margin: .4rem 0 1rem;+  font-family: var(--font-mono);+  font-size: .78rem;+}+.commit-strip span:first-child { min-width: 0; overflow: hidden; text-overflow: ellipsis; }+.commit-message {+  white-space: pre-wrap;+  font-family: var(--font-mono);+  font-size: .88rem;+  border-left: 2px solid var(--line-strong);+  padding-left: .8rem;+  margin: 1rem 0 1.5rem;+}++.tabs {+  display: flex;+  flex-wrap: wrap;+  gap: .25rem 1rem;+  border-bottom: 1px solid var(--line-strong);+  padding-bottom: .45rem;+  margin: 1rem 0 1.2rem;+  font-family: var(--font-mono);+  font-size: .8rem;+}+.tabs a { text-decoration: none; color: var(--muted); }+.tabs a:hover { color: var(--red); text-decoration: underline; }+.tabs a.active { color: var(--ink); text-decoration: underline; }++.repo-actions { font-family: var(--font-mono); font-size: .8rem; }+.profile-head {+  display: flex;+  gap: 1.1rem;+  align-items: flex-start;+  margin: 1.4rem 0 1.6rem;+}+.profile-head h1 { margin-top: 0; }++.post { margin: 1rem 0 1.4rem; }+.post > .muted { border-bottom: 1px solid var(--line); padding-bottom: .25rem; }++.markdown { color: var(--ink-soft); }+.markdown h1, .markdown h2, .markdown h3, .markdown h4 { color: var(--ink); margin-top: 1.4em; }+.markdown h1 { font-size: 1.6rem; }+.markdown h2 { font-size: 1.25rem; }+.markdown h3 { font-size: 1.05rem; }+.markdown a { color: var(--red); }+.markdown code { background: var(--panel-2); padding: .05rem .2rem; }+.markdown pre {+  background: var(--code-bg);+  color: var(--code-ink);+  padding: .8rem;+  overflow-x: auto;+  border: 1px solid var(--line-strong);+}+.markdown pre code { background: none; color: inherit; padding: 0; }+.markdown blockquote {+  border-left: 2px solid var(--line-strong);+  margin: 1rem 0;+  padding-left: .8rem;+  color: var(--muted);+}+.markdown img { border: 1px solid var(--line); }+.markdown table, .table {+  border-collapse: collapse;+  width: 100%;+  margin: .5rem 0 1.2rem;+  font-size: .88rem;+}+.markdown th, .markdown td, .table th, .table td {+  border-bottom: 1px solid var(--line);+  padding: .4rem .5rem;+  text-align: left;+  vertical-align: top;+}+.markdown th, .table th {+  font-family: var(--font-mono);+  font-size: .75rem;+  font-weight: 400;+  color: var(--muted);+}+.actions-cell { font-family: var(--font-mono); font-size: .78rem; }+.actions-cell form { margin-right: .5rem; }+.actions-cell input { width: 9rem; display: inline-block; }++pre.code, pre.diff, .code, .diff, .code-block {+  background: var(--code-bg);+  color: var(--code-ink);+  border: 1px solid var(--line-strong);+  overflow-x: auto;+  font-family: var(--font-mono);+  font-size: .8rem;+  line-height: 1.55;+}+pre.code, .code { padding: .6rem 0; }+.code-line { display: flex; min-width: max-content; }+.lineno {+  width: 4ch;+  flex: 0 0 4ch;+  text-align: right;+  padding-right: .7rem;+  margin-right: .7rem;+  color: var(--code-muted);+  border-right: 1px solid var(--line);+  user-select: none;+}+.code-text { white-space: pre; }+pre.diff, .diff { padding: .5rem 0; }+.diff-line { display: block; padding: 0 .7rem; white-space: pre; min-width: max-content; }+.diff-file { color: #9fb2cc; font-weight: 700; }+.diff-hunk { color: #83b9e8; }+.diff-add { color: var(--add); background: var(--add-bg); }+.diff-del { color: var(--del); background: var(--del-bg); }+.diff-meta, .diff-meta.diff-line { color: var(--code-muted); }+pre > code { white-space: pre; }++.settings-grid { display: block; }+.settings-card {+  border: 0;+  border-top: 1px solid var(--line);+  padding: .2rem 0 1rem;+  margin-top: 1.4rem;+}+.settings-card h2 { margin-top: .8rem; }+.settings-card.wide, .settings-card.danger { border-top: 1px solid var(--line); }+.settings-card.danger h2 { color: var(--red); }+.avatar-editor { display: flex; gap: 1rem; align-items: flex-start; }+.team-card { border-top: 1px solid var(--line); padding: .7rem 0; }+.team-head { display: flex; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }+.member-row { display: flex; flex-wrap: wrap; gap: .5rem 1rem; margin: .4rem 0; font-family: var(--font-mono); font-size: .78rem; }+.member { display: inline-flex; align-items: center; gap: .3rem; }+.table-wrap { overflow-x: auto; }+.facts { display: grid; grid-template-columns: max-content 1fr; gap: .2rem .8rem; font-size: .86rem; }+.facts dt { font-family: var(--font-mono); font-size: .75rem; color: var(--muted); }+.facts dd { margin: 0; }+.admin-nav { display: flex; gap: .8rem; flex-wrap: wrap; font-family: var(--font-mono); font-size: .8rem; }+.search-line { display: flex; gap: .4rem; align-items: center; max-width: 560px; margin: 1rem 0; }+.search-line input { flex: 1; }+.search-line a { font-family: var(--font-mono); font-size: .8rem; }++.site-footer {+  border-top: 1px solid var(--line-strong);+  padding: 1rem 0 1.5rem;+  font-family: var(--font-mono);+  font-size: .75rem;+  color: var(--muted);+  display: flex;+  gap: .45rem;+  flex-wrap: wrap;+}+.site-footer a { color: var(--muted); }++@media (max-width: 700px) {+  .wrap { width: calc(100% - 1.6rem); }+  .header-inner { align-items: flex-start; }+  .nav { gap: .55rem; font-size: .75rem; }+  .profile-head { flex-direction: column; }+  .two-col { grid-template-columns: 1fr; }+  .commit-strip { flex-direction: column; gap: .2rem; }+  .actions-cell input { width: 100%; margin-top: .2rem; }+}++@media (prefers-reduced-motion: reduce) {+  * { scroll-behavior: auto !important; }+}++.page-head {+  display: flex;+  justify-content: space-between;+  align-items: flex-start;+  gap: 1rem;+  flex-wrap: wrap;+}+.page-head-actions { font-family: var(--font-mono); font-size: .8rem; }+.table-wrap table { border-collapse: collapse; width: 100%; font-size: .88rem; }+.table-wrap th, .table-wrap td {+  border-bottom: 1px solid var(--line);+  padding: .4rem .5rem;+  text-align: left;+  vertical-align: top;+}+.table-wrap th {+  font-family: var(--font-mono);+  font-size: .75rem;+  font-weight: 400;+  color: var(--muted);+}--- /dev/null+++ b/internal/web/static/app.js@@ -0,0 +1,43 @@+(function () {+  "use strict";++  var KEY = "veinsforge-theme";+  var root = document.documentElement;++  function preferred() {+    try {+      if (window.matchMedia && window.matchMedia("(prefers-color-scheme: light)").matches) {+        return "light";+      }+    } catch (e) {}+    return "dark";+  }++  function apply(theme) {+    root.setAttribute("data-theme", theme === "light" ? "light" : "dark");+  }++  try {+    apply(localStorage.getItem(KEY) || preferred());+  } catch (e) {+    apply(preferred());+  }++  var toggle = document.getElementById("theme-toggle");+  if (toggle) {+    toggle.addEventListener("click", function () {+      var next = root.getAttribute("data-theme") === "light" ? "dark" : "light";+      apply(next);+      try {+        localStorage.setItem(KEY, next);+      } catch (e) {}+    });+  }++  var copies = document.querySelectorAll(".copy-input");+  for (var i = 0; i < copies.length; i++) {+    copies[i].addEventListener("focus", function () {+      this.select();+    });+  }+})();--- /dev/null+++ b/internal/web/static/favicon.svg@@ -0,0 +1,6 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">+  <rect width="64" height="64" fill="#060a12"/>+  <rect x="4" y="4" width="56" height="56" fill="none" stroke="#e5383b" stroke-width="3"/>+  <path d="M15 20 L27 44 L32 34 L37 44 L49 20" fill="none" stroke="#e8edf5" stroke-width="5" stroke-linejoin="bevel"/>+  <rect x="15" y="50" width="34" height="4" fill="#e5383b"/>+</svg>--- /dev/null+++ b/internal/web/templates/admin.html@@ -0,0 +1,127 @@+{{define "content"}}+<h1>Administration</h1>+<p class="small"><a href="/admin">overview</a> · <a href="/admin/users">users</a> · <a href="/admin/repos">repositories</a> · <a href="/admin/audit">audit log</a></p>++{{if .Data.Stats}}+<p class="muted">{{.Data.Stats.Users}} users · {{.Data.Stats.Repos}} repositories · {{.Data.Stats.PublicRepos}} public · {{.Data.Stats.Issues}} open issues · {{.Data.Stats.Stars}} stars</p>++<h2>Native server</h2>+<dl class="facts">+  <dt>state</dt><dd>{{if .Data.NativeState}}{{.Data.NativeState}}{{else}}disabled{{end}}</dd>+  <dt>address</dt><dd><code>{{.Data.NativeAddress}}</code></dd>+  <dt>TLS pin</dt><dd><code class="break">{{.Data.NativePin}}</code></dd>+  {{if .Data.NativeError}}<dt>last error</dt><dd>{{.Data.NativeError}}</dd>{{end}}+</dl>++<h2>Site settings</h2>+<form method="post" action="/admin/settings" class="form-narrow">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Site name <input name="site_name" value="{{.SiteName}}" maxlength="60"></label>+  <label>Description <input name="site_description" value="{{.SiteDesc}}" maxlength="240"></label>+  <label class="checkbox"><input type="checkbox" name="registration_open" {{if .Data.RegistrationOpen}}checked{{end}}> open registration</label>+  <button class="btn" type="submit">Save</button>+</form>++<h2>Audit log</h2>+<table class="table">+  <thead><tr><th>Time</th><th>User</th><th>IP</th><th>Action</th><th>Detail</th></tr></thead>+  <tbody>+  {{range .Data.Audit}}+    <tr>+      <td class="nowrap">{{date .CreatedAt}}</td>+      <td>{{if .Username}}{{.Username}}{{else}}—{{end}}</td>+      <td><code>{{.IP}}</code></td>+      <td><code>{{.Action}}</code></td>+      <td class="break">{{.Detail}}</td>+    </tr>+  {{end}}+  </tbody>+</table>+{{end}}++{{if .Data.Users}}+<h2>Users</h2>+<p class="muted">{{.Data.Count}} total</p>+<table class="table">+  <thead><tr><th>User</th><th>Email</th><th>Flags</th><th>Last IP</th><th>Created</th><th>Actions</th></tr></thead>+  <tbody>+  {{range .Data.Users}}+    <tr>+      <td><a href="/u/{{.Username}}">{{.Username}}</a><br><span class="muted small">{{.DisplayName}}</span></td>+      <td>{{if .Email}}{{.Email}}{{else}}—{{end}}</td>+      <td>{{if .IsAdmin}}admin {{end}}{{if .IsActive}}active{{else}}disabled{{end}}</td>+      <td><code>{{.LastIP}}</code></td>+      <td>{{date .CreatedAt}}</td>+      <td class="actions-cell">+        <form method="post" action="/admin/users/{{.ID}}/active" class="inline"><input type="hidden" name="csrf" value="{{$.CSRF}}"><button class="link" type="submit">{{if .IsActive}}disable{{else}}enable{{end}}</button></form>+        <form method="post" action="/admin/users/{{.ID}}/admin" class="inline"><input type="hidden" name="csrf" value="{{$.CSRF}}"><button class="link" type="submit">{{if .IsAdmin}}demote{{else}}promote{{end}}</button></form>+        <form method="post" action="/admin/users/{{.ID}}/password" class="inline"><input type="hidden" name="csrf" value="{{$.CSRF}}"><input type="password" name="password" placeholder="new password" required minlength="10"><button class="link" type="submit">reset</button></form>+      </td>+    </tr>+  {{end}}+  </tbody>+</table>+<p class="pager">+  {{if gt .Data.Page 1}}<a href="/admin/users?page={{sub .Data.Page 1}}">← previous</a>{{end}}+  <span class="muted">page {{.Data.Page}}</span>+  {{if .Data.HasNext}}<a href="/admin/users?page={{add .Data.Page 1}}">next →</a>{{end}}+</p>+<h2>Create user</h2>+<form method="post" action="/admin/users" class="inline-form">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <input name="username" placeholder="username" required maxlength="32">+  <input name="display_name" placeholder="display name" maxlength="80">+  <input type="email" name="email" placeholder="email" maxlength="254">+  <input type="password" name="password" placeholder="password" required minlength="10">+  <label class="checkbox"><input type="checkbox" name="is_admin"> admin</label>+  <button class="btn" type="submit">Create</button>+</form>+{{end}}++{{if .Data.Repos}}+<h2>Repositories</h2>+<p class="muted">{{.Data.Count}} total</p>+<table class="table">+  <thead><tr><th>Repository</th><th>Visibility</th><th>Default</th><th>Updated</th></tr></thead>+  <tbody>+  {{range .Data.Repos}}+    <tr>+      <td><a href="{{repoURL .}}">{{.OwnerName}}/{{.Name}}</a><br><span class="muted small">{{.Description}}</span></td>+      <td>{{.Visibility}}</td>+      <td><code>{{.DefaultBranch}}</code></td>+      <td>{{timeago .UpdatedAt}}</td>+    </tr>+  {{end}}+  </tbody>+</table>+<p class="pager">+  {{if gt .Data.Page 1}}<a href="/admin/repos?page={{sub .Data.Page 1}}">← previous</a>{{end}}+  <span class="muted">page {{.Data.Page}}</span>+  {{if .Data.HasNext}}<a href="/admin/repos?page={{add .Data.Page 1}}">next →</a>{{end}}+</p>+{{end}}++{{if and .Data.Audit (not .Data.Stats)}}+<h2>Audit log</h2>+<p class="muted">{{.Data.Count}} entries</p>+<table class="table">+  <thead><tr><th>Time</th><th>User</th><th>IP</th><th>Action</th><th>Detail</th></tr></thead>+  <tbody>+  {{range .Data.Audit}}+    <tr>+      <td class="nowrap">{{date .CreatedAt}}</td>+      <td>{{if .Username}}{{.Username}}{{else}}—{{end}}</td>+      <td><code>{{.IP}}</code></td>+      <td><code>{{.Action}}</code></td>+      <td class="break">{{.Detail}}</td>+    </tr>+  {{end}}+  </tbody>+</table>+<p class="pager">+  {{if gt .Data.Page 1}}<a href="/admin/audit?page={{sub .Data.Page 1}}">← previous</a>{{end}}+  <span class="muted">page {{.Data.Page}}</span>+  {{if .Data.HasNext}}<a href="/admin/audit?page={{add .Data.Page 1}}">next →</a>{{end}}+</p>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/blob.html@@ -0,0 +1,20 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / {{.Data.Rev}} / {{.Data.Path}}</p>+<h1>{{.Data.Name}}</h1>+<p class="small"><a href="{{treeURL .Data.Repo .Data.Rev .Data.Parent}}">← {{if .Data.Parent}}{{.Data.Parent}}{{else}}root{{end}}</a> · {{.Data.Size}} bytes · <a href="{{.Data.RawURL}}">raw</a> · <a href="{{.Data.DownloadURL}}">download</a></p>++<nav class="tabs" aria-label="Repository">+  <a href="{{repoURL .Data.Repo}}">code</a>+  <a href="{{repoURL .Data.Repo}}/issues">issues</a>+  <a href="{{repoURL .Data.Repo}}/pulls">pull requests</a>+  <a href="{{repoURL .Data.Repo}}/commits/{{revPath .Data.Rev}}">commits</a>+  <a href="{{repoURL .Data.Repo}}/branches">branches</a>+</nav>++{{if .Data.Binary}}+<p class="muted">Binary file. Use the raw or download link above.</p>+{{else}}+<pre class="code">{{range .Data.Lines}}<span class="code-line"><span class="lineno">{{.Number}}</span><span class="code-text">{{.Text}}</span></span>{{end}}</pre>+{{if .Data.Truncated}}<p class="muted small">Preview truncated at 5,000 lines.</p>{{end}}+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/branches.html@@ -0,0 +1,16 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a></p>+<h1>Branches</h1>+<p class="muted">{{len .Data.Branches}} bookmarks</p>++<ul class="link-list">+  {{range .Data.Branches}}+  <li>+    <a href="{{repoURL $.Data.Repo}}/commits/{{revPath .Name}}">{{.Name}}</a>+    <span class="muted"><code>{{short .Hash}}</code> · change {{.ChangeID}}{{if eq .Name $.Data.DefaultBranch}} · default{{end}}{{if .Current}} · head{{end}}</span>+  </li>+  {{else}}+  <li class="muted">No bookmarks yet.</li>+  {{end}}+</ul>+{{end}}--- /dev/null+++ b/internal/web/templates/commit.html@@ -0,0 +1,15 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / commit</p>+<h1><code>{{short .Data.Detail.Hash}}</code></h1>+<p class="muted">{{.Data.Detail.Author}}{{if .Data.Detail.Email}} &lt;{{.Data.Detail.Email}}&gt;{{end}} · {{date .Data.Detail.Date}}{{range .Data.Detail.Bookmarks}} · {{.}}{{end}}</p>+{{if .Data.Detail.Parents}}<p class="small">parents: {{range .Data.Detail.Parents}}<a href="{{commitURL $.Data.Repo .}}"><code>{{short .}}</code></a> {{end}}</p>{{end}}++<pre class="commit-message">{{.Data.Detail.Message}}</pre>++{{if .Data.Lines}}+<pre class="diff">{{range .Data.Lines}}<span class="diff-line {{.Class}}">{{.Text}}</span>{{end}}</pre>+{{if .Data.Truncated}}<p class="muted small">Diff truncated at 2 MiB.</p>{{end}}+{{else}}+<p class="muted">No diff for this commit.</p>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/commits.html@@ -0,0 +1,22 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a></p>+<h1>Commits</h1>+<p class="muted">revision <code>{{.Data.Rev}}</code></p>++{{if .Data.Branches}}+<p class="small">branches:+  {{range .Data.Branches}}<a href="{{repoURL $.Data.Repo}}/commits/{{revPath .Name}}">{{.Name}}</a> {{end}}+</p>+{{end}}++<ul class="commit-list">+  {{range .Data.Commits}}+  <li>+    <a href="{{commitURL $.Data.Repo .Hash}}">{{.Message}}</a>+    <span class="muted">— {{.Author}}, {{date .Date}}{{if .Current}} (head){{end}} · <code>{{short .Hash}}</code></span>+  </li>+  {{else}}+  <li class="muted">No commits on this revision.</li>+  {{end}}+</ul>+{{end}}--- /dev/null+++ b/internal/web/templates/error.html@@ -0,0 +1,5 @@+{{define "content"}}+<h1>{{.Title}}</h1>+<p>{{.Error}}</p>+<p><a href="/">home</a> · <a href="/explore">repositories</a></p>+{{end}}--- /dev/null+++ b/internal/web/templates/explore.html@@ -0,0 +1,19 @@+{{define "content"}}+<h1>Repositories</h1>+<form class="search-line" action="/explore" method="get">+  <input type="search" name="q" value="{{.Data.Query}}" placeholder="name, owner or description" maxlength="100">+  <button class="btn" type="submit">Search</button>+  {{if .Data.Query}}<a href="/explore">Clear</a>{{end}}+</form>+<p class="muted">{{.Data.Count}} results</p>++{{template "repo-list" .Data.Repos}}++{{if or (gt .Data.Page 1) .Data.HasNext}}+<p class="pager">+  {{if gt .Data.Page 1}}<a href="/explore?q={{.Data.Query | urlquery}}&page={{sub .Data.Page 1}}">← previous</a>{{end}}+  <span class="muted">page {{.Data.Page}}</span>+  {{if .Data.HasNext}}<a href="/explore?q={{.Data.Query | urlquery}}&page={{add .Data.Page 1}}">next →</a>{{end}}+</p>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/home.html@@ -0,0 +1,30 @@+{{define "content"}}+<h1>veinsforge</h1>+<p>A self-hosted web interface for veins repositories. Browse code and history, track issues, open pull requests, and manage repository access.</p>+<p class="muted">{{.Data.Stats.Users}} accounts · {{.Data.Stats.PublicRepos}} public repositories · {{.Data.Stats.Issues}} open issues</p>++<h2>Clone</h2>+<pre><code>vn clone veins://your-host:7419/owner/repo -key:your-key</code></pre>+<p class="small">Register an Ed25519 public key in <a href="/settings">settings</a> before pushing. Public repositories can be cloned anonymously.</p>++{{if .Data.UserRepos}}+<h2>Your repositories</h2>+{{template "repo-list" .Data.UserRepos}}+{{end}}++{{if .Data.UserOrgs}}+<h2>Your organisations</h2>+<ul class="link-list">+  {{range .Data.UserOrgs}}<li><a href="/orgs/{{.Name}}">{{.Name}}</a> <span class="muted">({{.RepoCount}} repositories)</span></li>{{end}}+</ul>+{{end}}++<h2>Repositories</h2>+{{template "repo-list" .Data.Repos}}+<p><a href="/explore">All repositories</a></p>++{{if not .User}}+<h2>Account</h2>+<p><a href="/signup">Create an account</a> or <a href="/login">sign in</a>.</p>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/issue.html@@ -0,0 +1,52 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / issue #{{.Data.Issue.Number}}</p>+<h1>{{.Data.Issue.Title}}</h1>+<p class="muted">+  <span class="state {{stateClass .Data.Issue.State}}">{{.Data.Issue.State}}</span>+  · opened by <a href="/u/{{.Data.Issue.AuthorName}}">{{.Data.Issue.AuthorName}}</a> {{timeago .Data.Issue.CreatedAt}}+  {{if .Data.CanClose}}+  · <form method="post" action="{{repoURL .Data.Repo}}/issues/{{.Data.Issue.Number}}/state" class="inline">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      {{if eq .Data.Issue.State "open"}}<input type="hidden" name="state" value="closed"><button class="link" type="submit">close</button>+      {{else}}<input type="hidden" name="state" value="open"><button class="link" type="submit">reopen</button>{{end}}+    </form>+  {{end}}+</p>++<div class="post">+  <p class="muted small"><strong>{{.Data.Issue.AuthorName}}</strong> · {{timeago .Data.Issue.CreatedAt}}</p>+  <div class="markdown">{{.Data.BodyHTML}}</div>+</div>++{{if .Data.Attachments}}+<h2>Attachments</h2>+<ul class="link-list">{{range .Data.Attachments}}<li><a href="/attachments/{{.ID}}">{{.Filename}}</a> <span class="muted">{{.Size}} bytes</span></li>{{end}}</ul>+{{end}}++<div id="comments">+{{range .Data.Comments}}+<div class="post">+  <p class="muted small"><strong><a href="/u/{{.AuthorName}}">{{.AuthorName}}</a></strong> · {{timeago .CreatedAt}}</p>+  <div class="markdown">{{.BodyHTML}}</div>+</div>+{{else}}+<p class="muted">No comments yet.</p>+{{end}}+</div>++{{if .Data.CanComment}}+<h2>Add a comment</h2>+<form method="post" action="{{repoURL .Data.Repo}}/issues/{{.Data.Issue.Number}}/comments" class="form-narrow">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <textarea name="body" rows="8" required maxlength="65536" placeholder="Markdown is supported."></textarea>+  <button class="btn" type="submit">Comment</button>+</form>+<form method="post" action="{{repoURL .Data.Repo}}/attachments" enctype="multipart/form-data" class="attach-form">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <input type="hidden" name="subject_type" value="issue">+  <input type="hidden" name="subject_id" value="{{.Data.Issue.ID}}">+  <input type="file" name="file" required>+  <button class="btn" type="submit">Upload attachment</button>+</form>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/issue_new.html@@ -0,0 +1,14 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / issues</p>+<h1>New issue</h1>+<form class="form-narrow" method="post" action="{{repoURL .Data.Repo}}/issues">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Title+    <input name="title" required maxlength="256" autofocus placeholder="Short, specific summary">+  </label>+  <label>Description+    <textarea name="body" rows="12" maxlength="65536" placeholder="Markdown is supported."></textarea>+  </label>+  <button class="btn" type="submit">Open issue</button>+</form>+{{end}}--- /dev/null+++ b/internal/web/templates/issues.html@@ -0,0 +1,30 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a></p>+<h1>Issues</h1>+<p class="small">+  {{if .User}}<a href="{{repoURL .Data.Repo}}/issues/new">new issue</a> · {{end}}+  <a class="{{if eq .Data.State "open"}}active{{end}}" href="{{repoURL .Data.Repo}}/issues?state=open">open ({{.Data.OpenCount}})</a> ·+  <a class="{{if eq .Data.State "closed"}}active{{end}}" href="{{repoURL .Data.Repo}}/issues?state=closed">closed ({{.Data.ClosedCount}})</a> ·+  <a class="{{if eq .Data.State "all"}}active{{end}}" href="{{repoURL .Data.Repo}}/issues?state=all">all</a>+</p>++<ul class="issue-list">+  {{range .Data.Issues}}+  <li>+    <a href="{{issueURL $.Data.Repo .Number}}">#{{.Number}} {{.Title}}</a>+    <span class="state {{stateClass .State}}">{{.State}}</span>+    <span class="muted">— {{.AuthorName}}, {{timeago .CreatedAt}}, {{.CommentCount}} comments</span>+  </li>+  {{else}}+  <li class="muted">No {{if eq .Data.State "all"}}issues{{else}}{{.Data.State}} issues{{end}}.</li>+  {{end}}+</ul>++{{if or (gt .Data.Page 1) .Data.HasNext}}+<p class="pager">+  {{if gt .Data.Page 1}}<a href="{{repoURL .Data.Repo}}/issues?state={{.Data.State}}&page={{sub .Data.Page 1}}">← previous</a>{{end}}+  <span class="muted">page {{.Data.Page}}</span>+  {{if .Data.HasNext}}<a href="{{repoURL .Data.Repo}}/issues?state={{.Data.State}}&page={{add .Data.Page 1}}">next →</a>{{end}}+</p>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/layout.html@@ -0,0 +1,68 @@+{{define "layout"}}+<!doctype html>+<html lang="en" data-theme="dark">+<head>+  <meta charset="utf-8">+  <meta name="viewport" content="width=device-width, initial-scale=1">+  <meta name="color-scheme" content="dark light">+  <title>{{.Title}} · {{.SiteName}}</title>+  <meta name="description" content="{{.SiteDesc}}">+  <link rel="icon" href="/static/favicon.svg" type="image/svg+xml">+  <link rel="stylesheet" href="/static/app.css">+  <script src="/static/app.js" defer></script>+</head>+<body>+<a class="skip" href="#main">Skip to content</a>+<header class="site-header">+  <div class="wrap header-inner">+    <a class="brand" href="/">veinsforge</a>+    <nav class="nav" aria-label="Main">+      <a href="/explore">repositories</a>+      {{if .User}}+        <a href="/new">new</a>+        <a href="/u/{{.User.Username}}">{{.User.Username}}</a>+        <a href="/settings">settings</a>+        {{if .User.IsAdmin}}<a href="/admin">admin</a>{{end}}+        <form method="post" action="/logout" class="inline">+          <input type="hidden" name="csrf" value="{{.CSRF}}">+          <button type="submit" class="link">sign out</button>+        </form>+      {{else}}+        <a href="/login">sign in</a>+        <a href="/signup">create account</a>+      {{end}}+      <button type="button" id="theme-toggle" class="link theme-toggle" aria-label="Toggle colour theme" title="Toggle theme">theme</button>+    </nav>+  </div>+</header>+<main id="main" class="wrap">+  {{if .Notice}}<p class="flash flash-ok" role="status">{{.Notice}}</p>{{end}}+  {{if .Error}}<p class="flash flash-error" role="alert">{{.Error}}</p>{{end}}+  {{template "content" .}}+</main>+<footer class="wrap site-footer">+  <span>{{.SiteName}}</span>+  <span>·</span>+  <a href="/explore">repositories</a>+  <span>·</span>+  <a href="/healthz">status</a>+</footer>+</body>+</html>+{{end}}++{{define "avatar"}}{{if .}}<img class="avatar avatar-sm" src="{{avatarURL .Username}}" alt="" width="20" height="20" loading="lazy">{{else}}<span class="avatar avatar-sm avatar-empty" aria-hidden="true"></span>{{end}}{{end}}++{{define "repo-list"}}+<ul class="repo-list">+  {{range .}}+  <li>+    <a href="{{repoURL .}}">{{.OwnerName}}/{{.Name}}</a>+    {{if .Description}}<span class="repo-desc">{{.Description}}</span>{{end}}+    <span class="repo-meta">★ {{.Stars}} · {{.Visibility}}{{if .Archived}} · archived{{end}} · {{timeago .UpdatedAt}}</span>+  </li>+  {{else}}+  <li class="muted">No repositories.</li>+  {{end}}+</ul>+{{end}}--- /dev/null+++ b/internal/web/templates/login.html@@ -0,0 +1,16 @@+{{define "content"}}+<h1>Sign in</h1>+<p>Sign in to manage repositories, issues, and SSH keys.</p>+<form class="form-narrow" method="post" action="/login">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <input type="hidden" name="next" value="{{if .Data.Next}}{{.Data.Next}}{{end}}">+  <label>Username+    <input name="username" value="{{if .Data.Username}}{{.Data.Username}}{{end}}" autocomplete="username" required maxlength="32" autofocus>+  </label>+  <label>Password+    <input type="password" name="password" autocomplete="current-password" required maxlength="256">+  </label>+  <button class="btn" type="submit">Sign in</button>+</form>+<p class="small">No account? <a href="/signup">Create one</a>.</p>+{{end}}--- /dev/null+++ b/internal/web/templates/new_repo.html@@ -0,0 +1,29 @@+{{define "content"}}+<h1>New repository</h1>+<form class="form-narrow" method="post" action="/new">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Owner+    <select name="owner">+      {{range $i, $o := .Data.Owners}}<option value="{{$o.Type}}:{{$o.ID}}" {{if eq $i 0}}selected{{end}}>{{$o.Name}}{{if eq $o.Type "org"}} (organisation){{end}}</option>{{end}}+    </select>+  </label>+  <label>Repository name+    <input name="name" required maxlength="100" pattern="[A-Za-z0-9][A-Za-z0-9._-]{0,99}" placeholder="my-project" autofocus>+    <small>Letters, digits, dots, hyphens, underscores.</small>+  </label>+  <label>Display name <span class="muted">(optional)</span>+    <input name="display_name" maxlength="80">+  </label>+  <label>Description <span class="muted">(optional)</span>+    <textarea name="description" rows="3" maxlength="2000"></textarea>+  </label>+  <label>Visibility+    <select name="visibility">+      <option value="public">Public — anonymous read</option>+      <option value="private">Private — explicit access only</option>+    </select>+  </label>+  <button class="btn" type="submit">Create repository</button>+</form>+<p class="small muted">The repository starts empty. Push a bookmark named <code>main</code> to populate it.</p>+{{end}}--- /dev/null+++ b/internal/web/templates/org.html@@ -0,0 +1,30 @@+{{define "content"}}+<div class="profile-head">+  <img class="avatar avatar-lg" src="{{orgAvatar .Data.Org.Name}}" alt="" width="72" height="72">+  <div>+    <h1>{{if .Data.Org.DisplayName}}{{.Data.Org.DisplayName}}{{else}}{{.Data.Org.Name}}{{end}}</h1>+    <p class="muted">@{{.Data.Org.Name}} · {{.Data.Org.MemberCount}} members · {{.Data.Org.RepoCount}} repositories{{if .Data.Role}} · {{roleLabel .Data.Role}}{{end}}</p>+    {{if .Data.Org.Description}}<p>{{.Data.Org.Description}}</p>{{end}}+    {{if .Data.CanAdmin}}<p><a href="/orgs/{{.Data.Org.Name}}/settings">Organisation settings</a></p>{{end}}+  </div>+</div>++<h2>Repositories</h2>+{{template "repo-list" .Data.Repos}}++<h2>Members</h2>+<ul class="link-list">+  {{range .Data.Members}}<li><a href="/u/{{.Username}}">{{.Username}}</a> <span class="muted">{{roleLabel .Role}}</span></li>{{end}}+</ul>++{{if .Data.Member}}+<h2>Teams</h2>+{{if .Data.Teams}}+<ul class="link-list">+  {{range .Data.Teams}}<li>{{.Name}} <span class="muted">({{.MemberCount}} members)</span></li>{{end}}+</ul>+{{else}}+<p class="muted">No teams.</p>+{{end}}+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/org_new.html@@ -0,0 +1,13 @@+{{define "content"}}+<h1>New organisation</h1>+<form class="form-narrow" method="post" action="/orgs/new">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Organisation name+    <input name="name" required minlength="3" maxlength="32" pattern="[A-Za-z0-9][A-Za-z0-9_-]{1,30}[A-Za-z0-9]" autofocus>+    <small>Used in URLs and repository paths.</small>+  </label>+  <label>Display name <span class="muted">(optional)</span><input name="display_name" maxlength="80"></label>+  <label>Description <textarea name="description" rows="4" maxlength="2000"></textarea></label>+  <button class="btn" type="submit">Create organisation</button>+</form>+{{end}}--- /dev/null+++ b/internal/web/templates/org_settings.html@@ -0,0 +1,86 @@+{{define "content"}}+<section class="page-head">+  <div><p class="kicker">ORGANISATION</p><h1>{{.Data.Org.Name}} settings</h1></div>+  <div class="page-head-actions"><a class="btn" href="/orgs/{{.Data.Org.Name}}">Back</a></div>+</section>++<div class="settings-grid">+  <section class="settings-card wide">+    <h2>General</h2>+    <form method="post" action="/orgs/{{.Data.Org.Name}}/settings" class="stack">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <label>Display name <input name="display_name" value="{{.Data.Org.DisplayName}}" maxlength="80"></label>+      <label>Description <textarea name="description" rows="4" maxlength="2000">{{.Data.Org.Description}}</textarea></label>+      <button class="btn btn-primary" type="submit">Save</button>+    </form>+  </section>++  <section class="settings-card wide">+    <h2>Members</h2>+    <div class="table-wrap">+      <table>+        <thead><tr><th>User</th><th>Role</th><th></th></tr></thead>+        <tbody>+        {{range .Data.Members}}+          <tr>+            <td><img class="avatar avatar-sm" src="{{avatarURL .Username}}" alt="" width="20" height="20"> <a href="/u/{{.Username}}">{{.Username}}</a></td>+            <td><span class="pill">{{roleLabel .Role}}</span></td>+            <td class="right">+              <form method="post" action="/orgs/{{$.Data.Org.Name}}/members/{{.UserID}}/delete" class="inline">+                <input type="hidden" name="csrf" value="{{$.CSRF}}">+                <button class="btn btn-small btn-danger" type="submit">Remove</button>+              </form>+            </td>+          </tr>+        {{end}}+        </tbody>+      </table>+    </div>+    <form method="post" action="/orgs/{{.Data.Org.Name}}/members" class="inline-form">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <input name="username" placeholder="username" required maxlength="32">+      <select name="role"><option value="member">Member</option><option value="admin">Admin</option><option value="owner">Owner</option></select>+      <button class="btn btn-small" type="submit">Add member</button>+    </form>+  </section>++  <section class="settings-card wide">+    <h2>Teams</h2>+    {{range .Data.Teams}}+    {{$teamID := .Team.ID}}+    <div class="team-card">+      <div class="team-head">+        <div><strong>{{.Team.Name}}</strong> <span class="muted small">{{.Team.Description}}</span></div>+        <form method="post" action="/orgs/{{$.Data.Org.Name}}/teams/{{.Team.ID}}/delete" class="inline">+          <input type="hidden" name="csrf" value="{{$.CSRF}}">+          <button class="btn btn-small btn-danger" type="submit">Delete team</button>+        </form>+      </div>+      <div class="member-row">+        {{range .Members}}+        <span class="member"><a href="/u/{{.Username}}">{{.Username}}</a>+          <form method="post" action="/orgs/{{$.Data.Org.Name}}/teams/{{$teamID}}/members/{{.UserID}}/delete" class="inline">+            <input type="hidden" name="csrf" value="{{$.CSRF}}">+            <button class="linkbtn" type="submit" aria-label="Remove {{.Username}}">×</button>+          </form>+        </span>+        {{else}}<span class="muted small">No members.</span>{{end}}+      </div>+      <form method="post" action="/orgs/{{$.Data.Org.Name}}/teams/{{.Team.ID}}/members" class="inline-form">+        <input type="hidden" name="csrf" value="{{$.CSRF}}">+        <input name="username" placeholder="org member username" required maxlength="32">+        <button class="btn btn-small" type="submit">Add to team</button>+      </form>+    </div>+    {{else}}+    <p class="muted">No teams yet.</p>+    {{end}}+    <form method="post" action="/orgs/{{.Data.Org.Name}}/teams" class="inline-form">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <input name="name" placeholder="team-name" required minlength="3" maxlength="32">+      <input name="description" placeholder="description" maxlength="200">+      <button class="btn btn-small" type="submit">Create team</button>+    </form>+  </section>+</div>+{{end}}--- /dev/null+++ b/internal/web/templates/pull.html@@ -0,0 +1,69 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / pull #{{.Data.Pull.Number}}</p>+<h1>{{.Data.Pull.Title}}</h1>+<p class="muted">+  <span class="state {{stateClass .Data.Pull.State}}">{{.Data.Pull.State}}</span>+  · <code>{{.Data.Pull.HeadBranch}}</code> → <code>{{.Data.Pull.BaseBranch}}</code>+  · opened by <a href="/u/{{.Data.Pull.AuthorName}}">{{.Data.Pull.AuthorName}}</a> {{timeago .Data.Pull.CreatedAt}}+  {{if .Data.CanMerge}}+  · <form method="post" action="{{repoURL .Data.Repo}}/pulls/{{.Data.Pull.Number}}/merge" class="inline">+      <input type="hidden" name="csrf" value="{{.CSRF}}"><button class="link" type="submit">merge</button>+    </form>+  {{end}}+  {{if .Data.CanClose}}+  · <form method="post" action="{{repoURL .Data.Repo}}/pulls/{{.Data.Pull.Number}}/state" class="inline">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      {{if eq .Data.Pull.State "open"}}<input type="hidden" name="state" value="closed"><button class="link" type="submit">close</button>+      {{else}}<input type="hidden" name="state" value="open"><button class="link" type="submit">reopen</button>{{end}}+    </form>+  {{end}}+</p>++{{if eq .Data.Pull.State "merged"}}+<p>Merged as <a href="{{commitURL .Data.Repo .Data.Pull.MergeCommit}}"><code>{{short .Data.Pull.MergeCommit}}</code></a>.</p>+{{end}}++<div class="post">+  <p class="muted small"><strong>{{.Data.Pull.AuthorName}}</strong> · {{timeago .Data.Pull.CreatedAt}}</p>+  <div class="markdown">{{.Data.BodyHTML}}</div>+</div>++{{if .Data.Attachments}}+<h2>Attachments</h2>+<ul class="link-list">{{range .Data.Attachments}}<li><a href="/attachments/{{.ID}}">{{.Filename}}</a></li>{{end}}</ul>+{{end}}++<h2>Changes</h2>+{{if .Data.DiffError}}<p class="flash flash-error">{{.Data.DiffError}}</p>+{{else if .Data.DiffLines}}+<pre class="diff">{{range .Data.DiffLines}}<span class="diff-line {{.Class}}">{{.Text}}</span>{{end}}</pre>+{{if .Data.Truncated}}<p class="muted small">Diff truncated at 2 MiB.</p>{{end}}+{{else}}<p class="muted">No changes between these commits.</p>{{end}}++<div id="comments">+{{range .Data.Comments}}+<div class="post">+  <p class="muted small"><strong><a href="/u/{{.AuthorName}}">{{.AuthorName}}</a></strong> · {{timeago .CreatedAt}}</p>+  <div class="markdown">{{.BodyHTML}}</div>+</div>+{{else}}+<p class="muted">No comments yet.</p>+{{end}}+</div>++{{if .Data.CanComment}}+<h2>Add a comment</h2>+<form method="post" action="{{repoURL .Data.Repo}}/pulls/{{.Data.Pull.Number}}/comments" class="form-narrow">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <textarea name="body" rows="8" required maxlength="65536" placeholder="Markdown is supported."></textarea>+  <button class="btn" type="submit">Comment</button>+</form>+<form method="post" action="{{repoURL .Data.Repo}}/attachments" enctype="multipart/form-data" class="attach-form">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <input type="hidden" name="subject_type" value="pull">+  <input type="hidden" name="subject_id" value="{{.Data.Pull.ID}}">+  <input type="file" name="file" required>+  <button class="btn" type="submit">Upload attachment</button>+</form>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/pull_new.html@@ -0,0 +1,26 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / pull requests</p>+<h1>New pull request</h1>++{{if .Data.EnoughBranches}}+<form class="form-narrow" method="post" action="{{repoURL .Data.Repo}}/pulls">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Base bookmark+    <select name="base">+      {{range .Data.Branches}}<option value="{{.Name}}" {{if eq .Name $.Data.Base}}selected{{end}}>{{.Name}}</option>{{end}}+    </select>+  </label>+  <label>Head bookmark+    <select name="head">+      {{range .Data.Branches}}<option value="{{.Name}}" {{if eq .Name $.Data.Head}}selected{{end}}>{{.Name}}</option>{{end}}+    </select>+  </label>+  <label>Title <input name="title" required maxlength="256" autofocus></label>+  <label>Description <textarea name="body" rows="10" maxlength="65536" placeholder="Markdown is supported."></textarea></label>+  <button class="btn" type="submit">Open pull request</button>+</form>+{{else}}+<p>A pull request needs at least two bookmarks. Push another bookmark first.</p>+<p><a href="{{repoURL .Data.Repo}}/branches">View branches</a></p>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/pulls.html@@ -0,0 +1,31 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a></p>+<h1>Pull requests</h1>+<p class="small">+  {{if .User}}<a href="{{repoURL .Data.Repo}}/pulls/new">new pull request</a> · {{end}}+  <a class="{{if eq .Data.State "open"}}active{{end}}" href="{{repoURL .Data.Repo}}/pulls?state=open">open ({{.Data.OpenCount}})</a> ·+  <a class="{{if eq .Data.State "closed"}}active{{end}}" href="{{repoURL .Data.Repo}}/pulls?state=closed">closed ({{.Data.ClosedCount}})</a> ·+  <a class="{{if eq .Data.State "merged"}}active{{end}}" href="{{repoURL .Data.Repo}}/pulls?state=merged">merged ({{.Data.MergedCount}})</a> ·+  <a class="{{if eq .Data.State "all"}}active{{end}}" href="{{repoURL .Data.Repo}}/pulls?state=all">all</a>+</p>++<ul class="issue-list">+  {{range .Data.Pulls}}+  <li>+    <a href="{{pullURL $.Data.Repo .Number}}">#{{.Number}} {{.Title}}</a>+    <span class="state {{stateClass .State}}">{{.State}}</span>+    <span class="muted">— <code>{{.HeadBranch}}</code> → <code>{{.BaseBranch}}</code>, {{.AuthorName}}, {{timeago .CreatedAt}}</span>+  </li>+  {{else}}+  <li class="muted">No {{if eq .Data.State "all"}}pull requests{{else}}{{.Data.State}} pull requests{{end}}.</li>+  {{end}}+</ul>++{{if or (gt .Data.Page 1) .Data.HasNext}}+<p class="pager">+  {{if gt .Data.Page 1}}<a href="{{repoURL .Data.Repo}}/pulls?state={{.Data.State}}&page={{sub .Data.Page 1}}">← previous</a>{{end}}+  <span class="muted">page {{.Data.Page}}</span>+  {{if .Data.HasNext}}<a href="{{repoURL .Data.Repo}}/pulls?state={{.Data.State}}&page={{add .Data.Page 1}}">next →</a>{{end}}+</p>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/repo.html@@ -0,0 +1,79 @@+{{define "content"}}+<p class="kicker"><a href="{{ownerURL .Data.Repo}}">{{.Data.Repo.OwnerName}}</a> / repository</p>+<h1><a href="{{ownerURL .Data.Repo}}">{{.Data.Repo.OwnerName}}</a> / {{.Data.Repo.Name}}</h1>+{{if .Data.Repo.Description}}<p>{{.Data.Repo.Description}}</p>{{end}}+<p class="muted">+  {{.Data.Repo.Visibility}}{{if .Data.Repo.Archived}} · archived{{end}} · {{.Data.StarCount}} stars+  {{if .Data.Rev}} · default branch <code>{{.Data.Rev}}</code>{{end}}+  {{if .Data.Perms.CanAdmin}} · <a href="{{repoURL .Data.Repo}}/settings">settings</a>{{end}}+</p>+<p class="repo-actions">+  {{if .User}}+  <form method="post" action="{{repoURL .Data.Repo}}/star" class="inline">+    <input type="hidden" name="csrf" value="{{.CSRF}}">+    <button class="link" type="submit">{{if .Data.Starred}}unstar{{else}}star{{end}}</button>+  </form>+  {{else}}+  <a href="/login?next={{repoURL .Data.Repo | urlquery}}">star</a>+  {{end}}+</p>++<nav class="tabs" aria-label="Repository">+  <a class="active" href="{{repoURL .Data.Repo}}">code</a>+  <a href="{{repoURL .Data.Repo}}/issues">issues ({{.Data.IssueCount}})</a>+  <a href="{{repoURL .Data.Repo}}/pulls">pull requests ({{.Data.PullCount}})</a>+  <a href="{{repoURL .Data.Repo}}/commits">commits</a>+  <a href="{{repoURL .Data.Repo}}/branches">branches ({{len .Data.Branches}})</a>+</nav>++{{if .Data.Empty}}+<h2>Empty repository</h2>+<p>No commits yet. Clone the repository, set a bookmark, add files, and push:</p>+<pre><code>vn clone {{.Data.NativeURL}} -key:your-key{{if .Data.NativePin}} -pin:{{.Data.NativePin}}{{end}}+cd {{.Data.Repo.Name}}+vn bmk set main+# add files+vn go -message "initial commit"+vn push origin main</code></pre>+{{else}}+{{with index .Data.Commits 0}}+<p class="commit-strip">+  <span><strong>{{.Author}}</strong> — {{.Message}}</span>+  <span class="muted"><a href="{{commitURL $.Data.Repo .Hash}}"><code>{{short .Hash}}</code></a> · {{timeago .Date}}</span>+</p>+{{end}}++{{if .Data.FilesError}}<p class="flash flash-error">{{.Data.FilesError}}</p>{{end}}+<ul class="file-list">+  {{range .Data.Tree}}+  <li>+    {{if .IsDir}}+    <a href="{{treeURL $.Data.Repo $.Data.Rev .Path}}">{{.Name}}/</a>+    {{else}}+    <a href="{{blobURL $.Data.Repo $.Data.Rev .Path}}">{{.Name}}</a>+    {{end}}+  </li>+  {{else}}+  <li class="muted">No tracked files.</li>+  {{end}}+</ul>+<p class="small"><a href="{{repoURL .Data.Repo}}/tree/{{revPath .Data.Rev}}">Browse full tree</a> · <a href="{{repoURL .Data.Repo}}/commits/{{revPath .Data.Rev}}">History</a></p>++{{if .Data.Readme}}+<h2>{{.Data.ReadmePath}}</h2>+<div class="markdown">{{.Data.Readme}}</div>+{{end}}+{{end}}++<h2>Clone</h2>+<pre><code>vn clone {{.Data.NativeURL}}{{if .Data.NativePin}} -pin:{{.Data.NativePin}}{{end}}</code></pre>+{{if .Data.NativePin}}<p class="small muted">TLS pin <code class="break">{{.Data.NativePin}}</code></p>{{end}}+<p class="small">Use <code>-key:your-key</code> to push. Keys are managed in <a href="/settings">settings</a>.</p>++{{if .Data.Activity}}+<h2>Activity</h2>+<ul class="activity">+  {{range .Data.Activity}}<li><span class="muted">{{timeago .CreatedAt}}</span> {{if .ActorName}}{{.ActorName}} {{end}}{{.Kind}} {{.Detail}}</li>{{end}}+</ul>+{{end}}+{{end}}--- /dev/null+++ b/internal/web/templates/repo_settings.html@@ -0,0 +1,152 @@+{{define "content"}}+<section class="page-head">+  <div>+    <p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / SETTINGS</p>+    <h1>Repository settings</h1>+  </div>+  <div class="page-head-actions"><a class="btn" href="{{repoURL .Data.Repo}}">Back to repository</a></div>+</section>++<div class="settings-grid">+  <section class="settings-card wide">+    <h2>General</h2>+    <form method="post" action="{{repoURL .Data.Repo}}/settings" class="stack">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <div class="two-col">+        <label>Display name <input name="display_name" value="{{.Data.Repo.DisplayName}}" maxlength="80"></label>+        <label>Default branch+          <input name="default_branch" value="{{.Data.Repo.DefaultBranch}}" list="branches" maxlength="200">+          <datalist id="branches">{{range .Data.Branches}}<option value="{{.Name}}">{{end}}</datalist>+        </label>+      </div>+      <label>Description <textarea name="description" rows="4" maxlength="2000">{{.Data.Repo.Description}}</textarea></label>+      <div class="two-col">+        <label>Visibility+          <select name="visibility">+            <option value="public" {{if eq .Data.Repo.Visibility "public"}}selected{{end}}>Public</option>+            <option value="private" {{if eq .Data.Repo.Visibility "private"}}selected{{end}}>Private</option>+          </select>+        </label>+        <label class="checkbox"><input type="checkbox" name="archived" {{if .Data.Repo.Archived}}checked{{end}}> Archived (read-only web actions)</label>+      </div>+      <button class="btn btn-primary" type="submit">Save settings</button>+    </form>+  </section>++  <section class="settings-card wide">+    <h2>Collaborators</h2>+    <div class="table-wrap">+      <table>+        <thead><tr><th>User</th><th>Role</th><th></th></tr></thead>+        <tbody>+        {{range .Data.Collaborators}}+          <tr>+            <td><img class="avatar avatar-sm" src="{{avatarURL .Username}}" alt="" width="20" height="20"> <a href="/u/{{.Username}}">{{.Username}}</a></td>+            <td><span class="pill">{{roleLabel .Role}}</span></td>+            <td class="right">+              <form method="post" action="{{repoURL $.Data.Repo}}/settings/collaborators/{{.UserID}}/delete" class="inline">+                <input type="hidden" name="csrf" value="{{$.CSRF}}">+                <button class="btn btn-small btn-danger" type="submit">Remove</button>+              </form>+            </td>+          </tr>+        {{else}}+          <tr><td colspan="3" class="muted">No direct collaborators.</td></tr>+        {{end}}+        </tbody>+      </table>+    </div>+    <form method="post" action="{{repoURL .Data.Repo}}/settings/collaborators" class="inline-form">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <input name="username" placeholder="username" required maxlength="32">+      <select name="role"><option value="read">Read</option><option value="write">Write</option><option value="admin">Admin</option></select>+      <button class="btn btn-small" type="submit">Add collaborator</button>+    </form>+  </section>++  {{if eq .Data.Repo.OwnerType "org"}}+  <section class="settings-card wide">+    <h2>Team access</h2>+    <div class="table-wrap">+      <table>+        <thead><tr><th>Team</th><th>Permission</th><th></th></tr></thead>+        <tbody>+        {{range .Data.Teams}}+          <tr>+            <td><strong>{{.OrgName}}/{{.TeamName}}</strong></td>+            <td><span class="pill">{{roleLabel .Permission}}</span></td>+            <td class="right">+              <form method="post" action="{{repoURL $.Data.Repo}}/settings/teams/{{.TeamID}}/delete" class="inline">+                <input type="hidden" name="csrf" value="{{$.CSRF}}">+                <button class="btn btn-small btn-danger" type="submit">Remove</button>+              </form>+            </td>+          </tr>+        {{else}}+          <tr><td colspan="3" class="muted">No teams have access.</td></tr>+        {{end}}+        </tbody>+      </table>+    </div>+    <form method="post" action="{{repoURL .Data.Repo}}/settings/teams" class="inline-form">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <select name="team_id" required>+        {{range .Data.OrgTeams}}<option value="{{.ID}}">{{.Name}}</option>{{end}}+      </select>+      <select name="permission"><option value="read">Read</option><option value="write">Write</option><option value="admin">Admin</option></select>+      <button class="btn btn-small" type="submit">Grant access</button>+    </form>+  </section>+  {{end}}++  <section class="settings-card wide">+    <h2>Webhooks</h2>+    <p class="muted small">Signed with HMAC-SHA256 in <code>X-Veinsforge-Signature</code>. Private and loopback destinations are blocked.</p>+    <div class="table-wrap">+      <table>+        <thead><tr><th>URL</th><th>Events</th><th>Last status</th><th></th></tr></thead>+        <tbody>+        {{range .Data.Webhooks}}+          <tr>+            <td><code class="break">{{.URL}}</code></td>+            <td>{{.Events}}</td>+            <td>{{if .LastStatus}}{{.LastStatus}}{{else}}—{{end}}</td>+            <td class="right">+              <form method="post" action="{{repoURL $.Data.Repo}}/settings/webhooks/{{.ID}}/delete" class="inline">+                <input type="hidden" name="csrf" value="{{$.CSRF}}">+                <button class="btn btn-small btn-danger" type="submit">Delete</button>+              </form>+            </td>+          </tr>+        {{else}}+          <tr><td colspan="4" class="muted">No webhooks.</td></tr>+        {{end}}+        </tbody>+      </table>+    </div>+    <form method="post" action="{{repoURL .Data.Repo}}/settings/webhooks" class="stack">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <label>Endpoint URL <input type="url" name="url" required maxlength="2000" placeholder="https://example.com/hook"></label>+      <label>Secret <span class="muted">(blank to generate)</span><input name="secret" maxlength="256"></label>+      <div class="checkbox-row">+        <label class="checkbox"><input type="checkbox" name="event_issue" checked> Issues</label>+        <label class="checkbox"><input type="checkbox" name="event_pull_request" checked> Pull requests</label>+        <label class="checkbox"><input type="checkbox" name="event_comment" checked> Comments</label>+        <label class="checkbox"><input type="checkbox" name="event_star" checked> Stars</label>+        <label class="checkbox"><input type="checkbox" name="event_repository" checked> Repository</label>+      </div>+      <button class="btn btn-primary" type="submit">Add webhook</button>+    </form>+  </section>++  <section class="settings-card wide danger">+    <h2>Danger zone</h2>+    <p>Deleting the repository removes its SQLite metadata and its veins object storage. This cannot be undone.</p>+    <form method="post" action="{{repoURL .Data.Repo}}/settings/delete" class="inline-form">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <input name="confirm" placeholder="type {{.Data.Repo.Name}} to confirm" required>+      <button class="btn btn-danger" type="submit">Delete repository</button>+    </form>+  </section>+</div>+{{end}}--- /dev/null+++ b/internal/web/templates/settings_user.html@@ -0,0 +1,73 @@+{{define "content"}}+<h1>Settings</h1>+<p class="muted">@{{.User.Username}}{{if .Data.Admin}} · administrator{{end}}</p>++<h2>Profile</h2>+<form method="post" action="/settings/profile" class="form-narrow">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Display name <input name="display_name" value="{{.User.DisplayName}}" maxlength="80"></label>+  <label>Email <span class="muted">(optional)</span><input type="email" name="email" value="{{.User.Email}}" maxlength="254"></label>+  <label>Bio <textarea name="bio" rows="3" maxlength="2000">{{.User.Bio}}</textarea></label>+  <button class="btn" type="submit">Save profile</button>+</form>++<h2>Avatar</h2>+<div class="avatar-editor">+  <img class="avatar avatar-lg" src="{{avatarURL .User.Username}}" alt="" width="72" height="72">+  <div>+    <form method="post" action="/settings/avatar" enctype="multipart/form-data" class="inline-form">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <input type="file" name="avatar" accept="image/png,image/jpeg,image/gif" required>+      <button class="btn" type="submit">Upload</button>+    </form>+    {{if .Data.HasAvatar}}+    <form method="post" action="/settings/avatar/delete" class="inline">+      <input type="hidden" name="csrf" value="{{.CSRF}}">+      <button class="link" type="submit">Remove avatar</button>+    </form>+    {{end}}+    <p class="muted small">PNG, JPEG or GIF, re-encoded to PNG.</p>+  </div>+</div>++<h2>SSH keys</h2>+<p class="small muted">Ed25519 keys used by <code>vn clone</code>, <code>vn fetch</code>, and <code>vn push</code>.</p>+{{if .Data.Keys}}+<table class="table">+  <thead><tr><th>Name</th><th>Fingerprint</th><th>Public key</th><th>Added</th><th></th></tr></thead>+  <tbody>+  {{range .Data.Keys}}+    <tr>+      <td>{{.Name}}</td>+      <td><code>{{.Fingerprint}}</code></td>+      <td><code class="break">{{.PublicKey}}</code></td>+      <td>{{date .CreatedAt}}</td>+      <td>+        <form method="post" action="/settings/keys/{{.ID}}/delete" class="inline">+          <input type="hidden" name="csrf" value="{{$.CSRF}}">+          <button class="link" type="submit">remove</button>+        </form>+      </td>+    </tr>+  {{end}}+  </tbody>+</table>+{{else}}+<p class="muted">No keys registered.</p>+{{end}}+<form method="post" action="/settings/keys" class="form-narrow">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Key name <input name="name" required maxlength="64" placeholder="laptop"></label>+  <label>Public key <textarea name="public_key" rows="3" required placeholder="ed25519:..."></textarea></label>+  <button class="btn" type="submit">Add key</button>+</form>++<h2>Password</h2>+<form method="post" action="/settings/password" class="form-narrow">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Current password <input type="password" name="current" required autocomplete="current-password"></label>+  <label>New password <input type="password" name="password" required minlength="10" maxlength="256" autocomplete="new-password"></label>+  <label>Confirm <input type="password" name="confirm" required minlength="10" maxlength="256" autocomplete="new-password"></label>+  <button class="btn" type="submit">Change password</button>+</form>+{{end}}--- /dev/null+++ b/internal/web/templates/signup.html@@ -0,0 +1,25 @@+{{define "content"}}+<h1>Create account</h1>+<p>Accounts are local to this server. Add an Ed25519 key after signing up to clone and push over the native protocol.</p>+<form class="form-narrow" method="post" action="/signup">+  <input type="hidden" name="csrf" value="{{.CSRF}}">+  <label>Username+    <input name="username" value="{{.Data.Username}}" autocomplete="username" required minlength="3" maxlength="32" pattern="[A-Za-z0-9][A-Za-z0-9_-]{1,30}[A-Za-z0-9]">+    <small>3-32 characters: letters, digits, hyphens, underscores.</small>+  </label>+  <label>Display name+    <input name="display_name" value="{{.Data.DisplayName}}" maxlength="80">+  </label>+  <label>Email <span class="muted">(optional)</span>+    <input type="email" name="email" value="{{.Data.Email}}" autocomplete="email" maxlength="254">+  </label>+  <label>Password+    <input type="password" name="password" autocomplete="new-password" required minlength="10" maxlength="256">+  </label>+  <label>Confirm password+    <input type="password" name="confirm" autocomplete="new-password" required minlength="10" maxlength="256">+  </label>+  <button class="btn" type="submit">Create account</button>+</form>+<p class="small">Already registered? <a href="/login">Sign in</a>.</p>+{{end}}--- /dev/null+++ b/internal/web/templates/tree.html@@ -0,0 +1,33 @@+{{define "content"}}+<p class="kicker"><a href="{{repoURL .Data.Repo}}">{{.Data.Repo.OwnerName}}/{{.Data.Repo.Name}}</a> / {{.Data.Rev}}{{if .Data.Path}} / {{.Data.Path}}{{end}}</p>+<h1>{{if .Data.Path}}{{.Data.Path}}{{else}}{{.Data.Repo.Name}}{{end}}</h1>++<nav class="tabs" aria-label="Repository">+  <a class="active" href="{{repoURL .Data.Repo}}/tree/{{revPath .Data.Rev}}">code</a>+  <a href="{{repoURL .Data.Repo}}/issues">issues</a>+  <a href="{{repoURL .Data.Repo}}/pulls">pull requests</a>+  <a href="{{repoURL .Data.Repo}}/commits/{{revPath .Data.Rev}}">commits</a>+  <a href="{{repoURL .Data.Repo}}/branches">branches</a>+</nav>++<p class="small">+  <a href="{{treeURL .Data.Repo .Data.Rev ""}}">{{.Data.Repo.Name}}</a>+  {{if .Data.Path}} / <a href="{{treeURL .Data.Repo .Data.Rev .Data.Path}}">{{.Data.Path}}</a>{{end}}+  {{if .Data.Parent}} · <a href="{{treeURL .Data.Repo .Data.Rev .Data.Parent}}">parent directory</a>{{end}}+</p>++{{with index .Data.Commits 0}}+<p class="commit-strip"><span><strong>{{.Author}}</strong> — {{.Message}}</span><span class="muted"><a href="{{commitURL $.Data.Repo .Hash}}"><code>{{short .Hash}}</code></a> · {{timeago .Date}}</span></p>+{{end}}++<ul class="file-list">+  {{range .Data.Entries}}+  <li>+    {{if .IsDir}}<a href="{{treeURL $.Data.Repo $.Data.Rev .Path}}">{{.Name}}/</a>+    {{else}}<a href="{{blobURL $.Data.Repo $.Data.Rev .Path}}">{{.Name}}</a>{{end}}+  </li>+  {{else}}+  <li class="muted">Directory is empty.</li>+  {{end}}+</ul>+{{end}}--- /dev/null+++ b/internal/web/templates/user.html@@ -0,0 +1,26 @@+{{define "content"}}+<div class="profile-head">+  <img class="avatar avatar-lg" src="{{avatarURL .Data.Profile.Username}}" alt="" width="72" height="72">+  <div>+    <h1>{{if .Data.Profile.DisplayName}}{{.Data.Profile.DisplayName}}{{else}}{{.Data.Profile.Username}}{{end}}</h1>+    <p class="muted">@{{.Data.Profile.Username}}{{if .Data.Profile.IsAdmin}} · administrator{{end}} · joined {{date .Data.Profile.CreatedAt}}{{if and .Data.Profile.Email .Data.Self}} · {{.Data.Profile.Email}}{{end}}</p>+    {{if .Data.Profile.Bio}}<p>{{.Data.Profile.Bio}}</p>{{end}}+    {{if .Data.Self}}<p><a href="/settings">Edit settings</a></p>{{end}}+  </div>+</div>++<h2>Repositories</h2>+{{template "repo-list" .Data.Repos}}++{{if .Data.Orgs}}+<h2>Organisations</h2>+<ul class="link-list">+  {{range .Data.Orgs}}<li><a href="/orgs/{{.Name}}">{{.Name}}</a> <span class="muted">({{.RepoCount}} repositories)</span></li>{{end}}+</ul>+{{end}}++{{if .Data.Starred}}+<h2>Starred repositories</h2>+{{template "repo-list" .Data.Starred}}+{{end}}+{{end}}--- /dev/null+++ b/internal/web/webhooks.go@@ -0,0 +1,229 @@+package web++import (+	"bytes"+	"context"+	"crypto/hmac"+	"crypto/sha256"+	"encoding/hex"+	"encoding/json"+	"errors"+	"fmt"+	"io"+	"net"+	"net/http"+	"net/url"+	"strings"+	"time"++	"veinsforge/internal/auth"+	"veinsforge/internal/data"+)++func (s *Server) validateWebhookURL(ctx context.Context, raw string) error {+	u, err := url.Parse(raw)+	if err != nil || u.Host == "" {+		return errors.New("invalid webhook URL")+	}+	if u.Scheme != "http" && u.Scheme != "https" {+		return errors.New("webhook URL must use http or https")+	}+	if u.User != nil {+		return errors.New("webhook URL must not contain credentials")+	}+	host := u.Hostname()+	port := u.Port()+	if port == "" {+		if u.Scheme == "https" {+			port = "443"+		} else {+			port = "80"+		}+	}+	ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)+	if err != nil {+		return errors.New("webhook host does not resolve")+	}+	for _, ip := range ips {+		if isPublicIP(ip.IP) {+			return nil+		}+	}+	return errors.New("webhook host is not a public address")+}++func (s *Server) webhookHTTPClient() *http.Client {+	dialer := &net.Dialer{Timeout: 5 * time.Second, KeepAlive: 30 * time.Second}+	transport := &http.Transport{+		Proxy:                 nil,+		DialContext:           safeDialContext(dialer),+		TLSHandshakeTimeout:   5 * time.Second,+		ResponseHeaderTimeout: 8 * time.Second,+		MaxIdleConns:          4,+		IdleConnTimeout:       30 * time.Second,+	}+	return &http.Client{+		Transport: transport,+		Timeout:   10 * time.Second,+		CheckRedirect: func(req *http.Request, via []*http.Request) error {+			if len(via) >= 3 {+				return errors.New("too many redirects")+			}+			if req.URL.Scheme != "http" && req.URL.Scheme != "https" {+				return errors.New("redirect to unsupported scheme")+			}+			if err := s.validateWebhookURL(req.Context(), req.URL.String()); err != nil {+				return err+			}+			return nil+		},+	}+}++func safeDialContext(dialer *net.Dialer) func(ctx context.Context, network, address string) (net.Conn, error) {+	return func(ctx context.Context, network, address string) (net.Conn, error) {+		host, port, err := net.SplitHostPort(address)+		if err != nil {+			return nil, err+		}+		ips, err := net.DefaultResolver.LookupIPAddr(ctx, host)+		if err != nil {+			return nil, err+		}+		for _, ip := range ips {+			if !isPublicIP(ip.IP) {+				continue+			}+			return dialer.DialContext(ctx, network, net.JoinHostPort(ip.IP.String(), port))+		}+		return nil, errors.New("destination resolves only to private addresses")+	}+}++func isPublicIP(ip net.IP) bool {+	if ip == nil || ip.IsLoopback() || ip.IsUnspecified() || ip.IsMulticast() ||+		ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsPrivate() {+		return false+	}+	if v4 := ip.To4(); v4 != nil {+		if v4[0] == 0 || v4[0] == 127 || v4[0] >= 224 {+			return false+		}+		if v4[0] == 169 && v4[1] == 254 {+			return false+		}+		if v4[0] == 100 && v4[1] >= 64 && v4[1] <= 127 {+			return false+		}+		if v4[0] == 192 && v4[1] == 0 && v4[2] == 0 {+			return false+		}+	}+	if len(ip) == net.IPv6len && ip[0]&0xfe == 0xfc {+		return false+	}+	return true+}++func (s *Server) dispatchWebhook(repo *data.Repo, actor *data.User, event string, payload any) {+	if repo == nil {+		return+	}+	hooks, err := s.data.ListWebhooks(context.Background(), repo.ID)+	if err != nil {+		return+	}+	actorName := ""+	if actor != nil {+		actorName = actor.Username+	}+	body := map[string]any{+		"event":      event,+		"timestamp":  time.Now().UTC().Format(time.RFC3339),+		"repository": map[string]any{"id": repo.ID, "owner": repo.OwnerName, "name": repo.Name, "private": repo.Visibility == "private"},+		"sender":     map[string]any{"username": actorName},+		"payload":    payload,+	}+	for _, hook := range hooks {+		if !hook.Active || !webhookWants(hook.Events, event) {+			continue+		}+		select {+		case s.webhookSem <- struct{}{}:+			go func(h *data.Webhook) {+				defer func() { <-s.webhookSem }()+				s.deliverWebhook(h, body)+			}(hook)+		default:+			if s.logger != nil {+				s.logger.Printf("webhook queue full; dropping event for hook %d", hook.ID)+			}+		}+	}+}++func webhookWants(events, event string) bool {+	if strings.TrimSpace(events) == "" || events == "*" {+		return true+	}+	for _, e := range strings.Split(events, ",") {+		if strings.TrimSpace(e) == event {+			return true+		}+	}+	return false+}++func (s *Server) deliverWebhook(hook *data.Webhook, body map[string]any) {+	delivery, _ := auth.RandomToken(16)+	payload := make(map[string]any, len(body)+1)+	for k, v := range body {+		payload[k] = v+	}+	payload["delivery"] = delivery+	raw, err := json.Marshal(payload)+	if err != nil {+		return+	}+	mac := hmac.New(sha256.New, []byte(hook.Secret))+	mac.Write(raw)+	signature := "sha256=" + hex.EncodeToString(mac.Sum(nil))+	client := s.webhookHTTPClient()+	status := 0+	ok := false+	for attempt := 0; attempt < 3; attempt++ {+		ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second)+		req, err := http.NewRequestWithContext(ctx, http.MethodPost, hook.URL, bytes.NewReader(raw))+		if err != nil {+			cancel()+			break+		}+		req.Header.Set("Content-Type", "application/json")+		req.Header.Set("User-Agent", "veinsforge-webhook/1")+		req.Header.Set("X-Veinsforge-Event", fmt.Sprint(body["event"]))+		req.Header.Set("X-Veinsforge-Delivery", delivery)+		req.Header.Set("X-Veinsforge-Signature", signature)+		resp, err := client.Do(req)+		if err != nil {+			cancel()+			time.Sleep(time.Duration(attempt+1) * time.Second)+			continue+		}+		_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))+		resp.Body.Close()+		status = resp.StatusCode+		cancel()+		if status >= 200 && status < 300 {+			ok = true+			break+		}+		if status < 500 && status != 429 {+			break+		}+		time.Sleep(time.Duration(attempt+1) * time.Second)+	}+	s.data.RecordWebhookDelivery(context.Background(), hook.ID, status, ok)+	if !ok && s.logger != nil {+		s.logger.Printf("webhook %d delivery failed (status %d)", hook.ID, status)+	}+}