first round of files
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
# ─── Required ───────────────────────────────────────────────────────────────
|
||||
# PostgreSQL connection string
|
||||
DATABASE_URL=postgres://forgebucket:password@localhost:5432/forgebucket?sslmode=disable
|
||||
|
||||
# Session cookie signing key — must be at least 32 characters
|
||||
# Generate: openssl rand -hex 32
|
||||
SESSION_SECRET=
|
||||
|
||||
# CSRF protection key — must be exactly 32 characters
|
||||
# Generate: openssl rand -hex 16
|
||||
CSRF_SECRET=
|
||||
|
||||
# ─── Server ──────────────────────────────────────────────────────────────────
|
||||
PORT=8080
|
||||
|
||||
# Absolute path where bare git repositories are stored on disk
|
||||
REPO_ROOT=/var/lib/forgebucket/repos
|
||||
|
||||
# ─── Federation (ActivityPub) ─────────────────────────────────────────────────
|
||||
# Public URL of this instance (no trailing slash)
|
||||
INSTANCE_URL=https://your-instance.example.com
|
||||
INSTANCE_NAME=ForgeBucket
|
||||
|
||||
# ─── OIDC / OAuth2 (optional) ────────────────────────────────────────────────
|
||||
# OIDC_ISSUER=https://accounts.google.com
|
||||
# OIDC_CLIENT_ID=
|
||||
# OIDC_CLIENT_SECRET=
|
||||
|
||||
# ─── Dev only ─────────────────────────────────────────────────────────────────
|
||||
# Set to true to disable Secure cookies and enable verbose logging
|
||||
DEBUG=false
|
||||
@@ -0,0 +1,58 @@
|
||||
.PHONY: dev build migrate test lint docker-up docker-down clean
|
||||
|
||||
BINARY := bin/forgebucket
|
||||
GO_CMD := ./cmd/forgebucket
|
||||
FRONTEND_DIR := frontend
|
||||
|
||||
# ─── Development ─────────────────────────────────────────────────────────────
|
||||
|
||||
dev:
|
||||
@echo "Starting backend + frontend dev servers..."
|
||||
@trap 'kill %1 %2 2>/dev/null; exit' INT; \
|
||||
go run $(GO_CMD) & \
|
||||
cd $(FRONTEND_DIR) && pnpm dev & \
|
||||
wait
|
||||
|
||||
# ─── Production build ─────────────────────────────────────────────────────────
|
||||
|
||||
build: build-frontend build-go
|
||||
|
||||
build-frontend:
|
||||
@echo "Building frontend..."
|
||||
pnpm -C $(FRONTEND_DIR) build
|
||||
@rm -rf web/dist
|
||||
@cp -r $(FRONTEND_DIR)/dist web/dist
|
||||
|
||||
build-go:
|
||||
@echo "Building Go binary..."
|
||||
@mkdir -p bin
|
||||
go build -ldflags="-s -w" -o $(BINARY) $(GO_CMD)
|
||||
|
||||
# ─── Database ─────────────────────────────────────────────────────────────────
|
||||
|
||||
migrate:
|
||||
@echo "Running database migrations..."
|
||||
go run ./cmd/migrate
|
||||
|
||||
# ─── Docker ───────────────────────────────────────────────────────────────────
|
||||
|
||||
docker-up:
|
||||
docker compose up -d
|
||||
|
||||
docker-down:
|
||||
docker compose down
|
||||
|
||||
# ─── Quality ──────────────────────────────────────────────────────────────────
|
||||
|
||||
test:
|
||||
go test ./... -race -count=1
|
||||
pnpm -C $(FRONTEND_DIR) test --run
|
||||
|
||||
lint:
|
||||
go vet ./...
|
||||
pnpm -C $(FRONTEND_DIR) lint
|
||||
|
||||
# ─── Housekeeping ─────────────────────────────────────────────────────────────
|
||||
|
||||
clean:
|
||||
rm -rf bin web/dist $(FRONTEND_DIR)/dist
|
||||
@@ -0,0 +1,68 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
"github.com/joho/godotenv"
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"github.com/forgao/forgebucket/internal/api"
|
||||
"github.com/forgao/forgebucket/internal/config"
|
||||
"github.com/forgao/forgebucket/web"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Load .env if present (dev convenience; production uses real env vars)
|
||||
_ = godotenv.Load()
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("config error: %v", err)
|
||||
}
|
||||
|
||||
store := sessions.NewCookieStore([]byte(cfg.SessionSecret))
|
||||
store.Options = &sessions.Options{
|
||||
Path: "/",
|
||||
MaxAge: 86400 * 7, // 7 days
|
||||
HttpOnly: true,
|
||||
Secure: !cfg.Debug,
|
||||
SameSite: http.SameSiteLaxMode,
|
||||
}
|
||||
|
||||
staticFS := web.FS()
|
||||
handler := api.New(cfg, store, staticFS)
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: fmt.Sprintf(":%s", cfg.Port),
|
||||
Handler: handler,
|
||||
ReadTimeout: 15 * time.Second,
|
||||
WriteTimeout: 60 * time.Second,
|
||||
IdleTimeout: 120 * time.Second,
|
||||
}
|
||||
|
||||
go func() {
|
||||
log.Printf("ForgeBucket listening on http://localhost:%s", cfg.Port)
|
||||
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
log.Fatalf("server error: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
|
||||
<-quit
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(ctx); err != nil {
|
||||
log.Printf("shutdown error: %v", err)
|
||||
}
|
||||
log.Println("ForgeBucket stopped")
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
version: "3.9"
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: forgebucket
|
||||
POSTGRES_USER: forgebucket
|
||||
POSTGRES_PASSWORD: password
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U forgebucket"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
|
||||
app:
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
env_file: .env
|
||||
environment:
|
||||
DATABASE_URL: postgres://forgebucket:password@postgres:5432/forgebucket?sslmode=disable
|
||||
ports:
|
||||
- "8080:8080"
|
||||
volumes:
|
||||
- repo_data:/var/lib/forgebucket/repos
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
repo_data:
|
||||
@@ -0,0 +1,26 @@
|
||||
module github.com/forgeo/forgebucket
|
||||
|
||||
go 1.26.2
|
||||
|
||||
require (
|
||||
github.com/go-chi/chi/v5 v5.2.5 // indirect
|
||||
github.com/go-chi/cors v1.2.2 // indirect
|
||||
github.com/goccy/go-json v0.10.5 // indirect
|
||||
github.com/golang/snappy v0.0.4 // indirect
|
||||
github.com/gorilla/csrf v1.7.3 // indirect
|
||||
github.com/gorilla/securecookie v1.1.2 // indirect
|
||||
github.com/gorilla/sessions v1.4.0 // indirect
|
||||
github.com/joho/godotenv v1.5.1 // indirect
|
||||
github.com/lib/pq v1.12.3 // indirect
|
||||
github.com/syndtr/goleveldb v1.0.0 // indirect
|
||||
golang.org/x/crypto v0.50.0 // indirect
|
||||
golang.org/x/net v0.52.0 // indirect
|
||||
golang.org/x/sys v0.43.0 // indirect
|
||||
golang.org/x/text v0.36.0 // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect
|
||||
google.golang.org/grpc v1.81.0 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
nhooyr.io/websocket v1.8.17 // indirect
|
||||
xorm.io/builder v0.3.13 // indirect
|
||||
xorm.io/xorm v1.3.11 // indirect
|
||||
)
|
||||
@@ -0,0 +1,60 @@
|
||||
gitea.com/xorm/sqlfiddle v0.0.0-20180821085327-62ce714f951a/go.mod h1:EXuID2Zs0pAQhH8yz+DNjUbjppKQzKFAn28TMYPB6IU=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/go-chi/chi/v5 v5.2.5 h1:Eg4myHZBjyvJmAFjFvWgrqDTXFyOzjj7YIm3L3mu6Ug=
|
||||
github.com/go-chi/chi/v5 v5.2.5/go.mod h1:X7Gx4mteadT3eDOMTsXzmI4/rwUpOwBHLpAfupzFJP0=
|
||||
github.com/go-chi/cors v1.2.2 h1:Jmey33TE+b+rB7fT8MUy1u0I4L+NARQlK6LhzKPSyQE=
|
||||
github.com/go-chi/cors v1.2.2/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
|
||||
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=
|
||||
github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/gorilla/csrf v1.7.3 h1:BHWt6FTLZAb2HtWT5KDBf6qgpZzvtbp9QWDRKZMXJC0=
|
||||
github.com/gorilla/csrf v1.7.3/go.mod h1:F1Fj3KG23WYHE6gozCmBAezKookxbIvUJT+121wTuLk=
|
||||
github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA=
|
||||
github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo=
|
||||
github.com/gorilla/sessions v1.4.0 h1:kpIYOp/oi6MG/p5PgxApU8srsSw9tuFbt46Lt7auzqQ=
|
||||
github.com/gorilla/sessions v1.4.0/go.mod h1:FLWm50oby91+hl7p/wRxDth9bWSuk0qVL2emc7lT5ik=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/lib/pq v1.12.3 h1:tTWxr2YLKwIvK90ZXEw8GP7UFHtcbTtty8zsI+YjrfQ=
|
||||
github.com/lib/pq v1.12.3/go.mod h1:/p+8NSbOcwzAEI7wiMXFlgydTwcgTr3OSKMsD2BitpA=
|
||||
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
|
||||
github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/syndtr/goleveldb v1.0.0 h1:fBdIW9lB4Iz0n9khmH8w27SJ3QEJ7+IgjPEwGSZiFdE=
|
||||
github.com/syndtr/goleveldb v1.0.0/go.mod h1:ZVVdQEZoIme9iO1Ch2Jdy24qqXrMMOU6lpPAyBWyWuQ=
|
||||
golang.org/x/crypto v0.50.0 h1:zO47/JPrL6vsNkINmLoo/PH1gcxpls50DNogFvB5ZGI=
|
||||
golang.org/x/crypto v0.50.0/go.mod h1:3muZ7vA7PBCE6xgPX7nkzzjiUq87kRItoJQM1Yo8S+Q=
|
||||
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.52.0 h1:He/TN1l0e4mmR3QqHMT2Xab3Aj3L9qjbhRm78/6jrW0=
|
||||
golang.org/x/net v0.52.0/go.mod h1:R1MAz7uMZxVMualyPXb+VaqGSa3LIaUqk0eEt3w36Sw=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
|
||||
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.36.0 h1:JfKh3XmcRPqZPKevfXVpI1wXPTqbkE5f7JA92a55Yxg=
|
||||
golang.org/x/text v0.36.0/go.mod h1:NIdBknypM8iqVmPiuco0Dh6P5Jcdk8lJL0CUebqK164=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
|
||||
google.golang.org/grpc v1.81.0 h1:W3G9N3KQf3BU+YuCtGKJk0CmxQNbAISICD/9AORxLIw=
|
||||
google.golang.org/grpc v1.81.0/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I=
|
||||
google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
|
||||
google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
|
||||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y=
|
||||
nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c=
|
||||
xorm.io/builder v0.3.13 h1:a3jmiVVL19psGeXx8GIurTp7p0IIgqeDmwhcR6BAOAo=
|
||||
xorm.io/builder v0.3.13/go.mod h1:aUW0S9eb9VCaPohFCH3j7czOx1PMW3i1HrSzbLYGBSE=
|
||||
xorm.io/xorm v1.3.11 h1:i4tlVUASogb0ZZFJHA7dZqoRU2pUpUsutnNdaOlFyMI=
|
||||
xorm.io/xorm v1.3.11/go.mod h1:cs0ePc8O4a0jD78cNvD+0VFwhqotTvLQZv372QsDw7Q=
|
||||
@@ -0,0 +1,22 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type PipelineHandler struct{}
|
||||
|
||||
func NewPipelineHandler() *PipelineHandler {
|
||||
return &PipelineHandler{}
|
||||
}
|
||||
|
||||
func (h *PipelineHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *PipelineHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type PRHandler struct{}
|
||||
|
||||
func NewPRHandler() *PRHandler {
|
||||
return &PRHandler{}
|
||||
}
|
||||
|
||||
func (h *PRHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *PRHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "created"})
|
||||
}
|
||||
|
||||
func (h *PRHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *PRHandler) Merge(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "merged"})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type RepoHandler struct{}
|
||||
|
||||
func NewRepoHandler() *RepoHandler {
|
||||
return &RepoHandler{}
|
||||
}
|
||||
|
||||
func (h *RepoHandler) List(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Create(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "created"})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Get(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Tree(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode([]any{})
|
||||
}
|
||||
|
||||
func (h *RepoHandler) Blob(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"content": ""})
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
)
|
||||
|
||||
type UserHandler struct {
|
||||
store sessions.Store
|
||||
}
|
||||
|
||||
func NewUserHandler(store sessions.Store) *UserHandler {
|
||||
return &UserHandler{store: store}
|
||||
}
|
||||
|
||||
func (h *UserHandler) Me(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Login(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (h *UserHandler) Logout(w http.ResponseWriter, r *http.Request) {
|
||||
session, _ := h.store.Get(r, "fb_session")
|
||||
session.Options.MaxAge = -1
|
||||
session.Save(r, w)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"nhooyr.io/websocket"
|
||||
"nhooyr.io/websocket/wsjson"
|
||||
)
|
||||
|
||||
type WSHandler struct{}
|
||||
|
||||
func NewWSHandler() *WSHandler {
|
||||
return &WSHandler{}
|
||||
}
|
||||
|
||||
func (h *WSHandler) Hub(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{
|
||||
OriginPatterns: []string{"localhost:*"},
|
||||
})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
|
||||
ctx := r.Context()
|
||||
for {
|
||||
var msg map[string]any
|
||||
if err := wsjson.Read(ctx, conn, &msg); err != nil {
|
||||
break
|
||||
}
|
||||
if err := wsjson.Write(ctx, conn, msg); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/gorilla/sessions"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const (
|
||||
ContextKeyUserID contextKey = "userID"
|
||||
ContextKeyUsername contextKey = "username"
|
||||
ContextKeyIsAdmin contextKey = "isAdmin"
|
||||
)
|
||||
|
||||
type AuthMiddleware struct {
|
||||
store sessions.Store
|
||||
}
|
||||
|
||||
func NewAuth(store sessions.Store) *AuthMiddleware {
|
||||
return &AuthMiddleware{store: store}
|
||||
}
|
||||
|
||||
func (a *AuthMiddleware) Require(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session, err := a.store.Get(r, "fb_session")
|
||||
if err != nil || session.IsNew {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := session.Values["userID"].(int64)
|
||||
if !ok || userID == 0 {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), ContextKeyUserID, userID)
|
||||
if username, ok := session.Values["username"].(string); ok {
|
||||
ctx = context.WithValue(ctx, ContextKeyUsername, username)
|
||||
}
|
||||
if isAdmin, ok := session.Values["isAdmin"].(bool); ok {
|
||||
ctx = context.WithValue(ctx, ContextKeyIsAdmin, isAdmin)
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func (a *AuthMiddleware) Optional(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
session, err := a.store.Get(r, "fb_session")
|
||||
if err == nil && !session.IsNew {
|
||||
if userID, ok := session.Values["userID"].(int64); ok && userID != 0 {
|
||||
ctx := context.WithValue(r.Context(), ContextKeyUserID, userID)
|
||||
r = r.WithContext(ctx)
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func UserIDFromContext(ctx context.Context) (int64, bool) {
|
||||
id, ok := ctx.Value(ContextKeyUserID).(int64)
|
||||
return id, ok
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func RequireAdmin(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
isAdmin, _ := r.Context().Value(ContextKeyIsAdmin).(bool)
|
||||
if !isAdmin {
|
||||
http.Error(w, "forbidden", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
chimiddleware "github.com/go-chi/chi/v5/middleware"
|
||||
"github.com/go-chi/cors"
|
||||
gcsrf "github.com/gorilla/csrf"
|
||||
"github.com/gorilla/sessions"
|
||||
|
||||
"github.com/forgao/forgebucket/internal/api/handlers"
|
||||
"github.com/forgao/forgebucket/internal/api/middleware"
|
||||
"github.com/forgao/forgebucket/internal/config"
|
||||
)
|
||||
|
||||
func New(cfg *config.Config, store sessions.Store, staticFiles fs.FS) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
|
||||
r.Use(chimiddleware.Logger)
|
||||
r.Use(chimiddleware.RealIP)
|
||||
r.Use(chimiddleware.Recoverer)
|
||||
r.Use(cors.Handler(cors.Options{
|
||||
AllowedOrigins: []string{"http://localhost:5173", cfg.InstanceURL},
|
||||
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"},
|
||||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
|
||||
AllowCredentials: true,
|
||||
MaxAge: 300,
|
||||
}))
|
||||
|
||||
csrfMiddleware := gcsrf.Protect(
|
||||
[]byte(cfg.CSRFSecret),
|
||||
gcsrf.Secure(!cfg.Debug),
|
||||
gcsrf.SameSite(gcsrf.SameSiteLaxMode),
|
||||
gcsrf.ErrorHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "CSRF validation failed", http.StatusForbidden)
|
||||
})),
|
||||
)
|
||||
|
||||
auth := middleware.NewAuth(store)
|
||||
|
||||
repoH := handlers.NewRepoHandler()
|
||||
userH := handlers.NewUserHandler(store)
|
||||
prH := handlers.NewPRHandler()
|
||||
pipeH := handlers.NewPipelineHandler()
|
||||
wsH := handlers.NewWSHandler()
|
||||
|
||||
// Health check (no auth, no CSRF)
|
||||
r.Get("/api/v1/health", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"status":"ok"}`))
|
||||
})
|
||||
|
||||
// CSRF token endpoint for SPA bootstrap
|
||||
r.With(csrfMiddleware).Get("/api/v1/csrf", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-CSRF-Token", gcsrf.Token(r))
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"ok":true}`))
|
||||
})
|
||||
|
||||
// Auth routes (CSRF protected, no session required)
|
||||
r.With(csrfMiddleware).Route("/api/v1/auth", func(r chi.Router) {
|
||||
r.Post("/login", userH.Login)
|
||||
r.Post("/logout", userH.Logout)
|
||||
})
|
||||
|
||||
// Authenticated API routes
|
||||
r.With(csrfMiddleware).With(auth.Require).Route("/api/v1", func(r chi.Router) {
|
||||
r.Get("/me", userH.Me)
|
||||
|
||||
r.Route("/repos", func(r chi.Router) {
|
||||
r.Get("/", repoH.List)
|
||||
r.Post("/", repoH.Create)
|
||||
r.Route("/{owner}/{repo}", func(r chi.Router) {
|
||||
r.Get("/", repoH.Get)
|
||||
r.Get("/tree", repoH.Tree)
|
||||
r.Get("/blob", repoH.Blob)
|
||||
r.Route("/pulls", func(r chi.Router) {
|
||||
r.Get("/", prH.List)
|
||||
r.Post("/", prH.Create)
|
||||
r.Get("/{prID}", prH.Get)
|
||||
r.Post("/{prID}/merge", prH.Merge)
|
||||
})
|
||||
r.Route("/pipelines", func(r chi.Router) {
|
||||
r.Get("/", pipeH.List)
|
||||
r.Get("/{runID}", pipeH.Get)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// WebSocket hub (auth via session cookie, no CSRF needed for WS)
|
||||
r.With(auth.Optional).Get("/ws", wsH.Hub)
|
||||
|
||||
// SPA fallback — serve embedded React app for all other routes
|
||||
r.Handle("/*", spaHandler(staticFiles))
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func spaHandler(staticFiles fs.FS) http.Handler {
|
||||
fileServer := http.FileServer(http.FS(staticFiles))
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := staticFiles.Open(r.URL.Path)
|
||||
if err != nil {
|
||||
// Unknown path → serve index.html for client-side routing
|
||||
index, err := staticFiles.Open("index.html")
|
||||
if err != nil {
|
||||
http.Error(w, "not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
index.Close()
|
||||
r.URL.Path = "/"
|
||||
}
|
||||
fileServer.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
// Server
|
||||
Port string
|
||||
|
||||
// Database
|
||||
DatabaseURL string
|
||||
|
||||
// Storage
|
||||
RepoRoot string
|
||||
|
||||
// Security
|
||||
SessionSecret string // must be 32 or 64 bytes for AES-GCM
|
||||
CSRFSecret string // must be 32 bytes
|
||||
|
||||
// OIDC (optional)
|
||||
OIDCIssuer string
|
||||
OIDCClientID string
|
||||
OIDCClientSecret string
|
||||
|
||||
// Federation
|
||||
InstanceURL string
|
||||
InstanceName string
|
||||
|
||||
// Dev
|
||||
Debug bool
|
||||
}
|
||||
|
||||
func Load() (*Config, error) {
|
||||
cfg := &Config{
|
||||
Port: getEnv("PORT", "8080"),
|
||||
RepoRoot: getEnv("REPO_ROOT", "/var/lib/forgebucket/repos"),
|
||||
Debug: getEnvBool("DEBUG", false),
|
||||
|
||||
InstanceURL: getEnv("INSTANCE_URL", ""),
|
||||
InstanceName: getEnv("INSTANCE_NAME", "ForgeBucket"),
|
||||
}
|
||||
|
||||
var missing []string
|
||||
|
||||
cfg.DatabaseURL = requireEnv("DATABASE_URL", &missing)
|
||||
cfg.SessionSecret = requireEnv("SESSION_SECRET", &missing)
|
||||
cfg.CSRFSecret = requireEnv("CSRF_SECRET", &missing)
|
||||
|
||||
// Optional OIDC
|
||||
cfg.OIDCIssuer = os.Getenv("OIDC_ISSUER")
|
||||
cfg.OIDCClientID = os.Getenv("OIDC_CLIENT_ID")
|
||||
cfg.OIDCClientSecret = os.Getenv("OIDC_CLIENT_SECRET")
|
||||
|
||||
if len(missing) > 0 {
|
||||
return nil, fmt.Errorf("missing required env vars: %v", missing)
|
||||
}
|
||||
|
||||
if len(cfg.SessionSecret) < 32 {
|
||||
return nil, fmt.Errorf("SESSION_SECRET must be at least 32 characters")
|
||||
}
|
||||
if len(cfg.CSRFSecret) != 32 {
|
||||
return nil, fmt.Errorf("CSRF_SECRET must be exactly 32 characters")
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func requireEnv(key string, missing *[]string) string {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
*missing = append(*missing, key)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func getEnv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func getEnvBool(key string, fallback bool) bool {
|
||||
v := os.Getenv(key)
|
||||
if v == "" {
|
||||
return fallback
|
||||
}
|
||||
b, err := strconv.ParseBool(v)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return b
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package git
|
||||
|
||||
import "strings"
|
||||
|
||||
// ParseAGitRef extracts target and source branch from an AGit push ref.
|
||||
// AGit refs follow the pattern: refs/for/<target>[/<source>]
|
||||
// Returns ("", "", false) if the ref is not an AGit ref.
|
||||
func ParseAGitRef(ref string) (target, source string, ok bool) {
|
||||
const prefix = "refs/for/"
|
||||
if !strings.HasPrefix(ref, prefix) {
|
||||
return "", "", false
|
||||
}
|
||||
rest := strings.TrimPrefix(ref, prefix)
|
||||
parts := strings.SplitN(rest, "/", 2)
|
||||
target = parts[0]
|
||||
if len(parts) == 2 {
|
||||
source = parts[1]
|
||||
} else {
|
||||
source = target
|
||||
}
|
||||
return target, source, true
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package git
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var ErrPathTraversal = errors.New("repo path outside of configured root")
|
||||
|
||||
var repoRoot string
|
||||
|
||||
func SetRepoRoot(root string) {
|
||||
repoRoot = filepath.Clean(root)
|
||||
}
|
||||
|
||||
// run executes a git command inside repoPath with strict safety guarantees:
|
||||
// - repoPath is validated to be under the configured repoRoot
|
||||
// - args are passed as discrete values — never via shell interpolation
|
||||
// - the process inherits only a minimal environment
|
||||
func run(repoPath string, args ...string) ([]byte, error) {
|
||||
clean := filepath.Clean(repoPath)
|
||||
if repoRoot != "" && !strings.HasPrefix(clean, repoRoot+string(filepath.Separator)) && clean != repoRoot {
|
||||
return nil, ErrPathTraversal
|
||||
}
|
||||
|
||||
cmd := exec.Command("git", args...)
|
||||
cmd.Dir = clean
|
||||
cmd.Env = []string{
|
||||
"GIT_TERMINAL_PROMPT=0",
|
||||
"HOME=" + filepath.Dir(repoRoot), // needed for .gitconfig lookups
|
||||
}
|
||||
return cmd.Output()
|
||||
}
|
||||
|
||||
func Init(path string) error {
|
||||
_, err := run(path, "init", "--bare")
|
||||
return err
|
||||
}
|
||||
|
||||
type Commit struct {
|
||||
Hash string
|
||||
Author string
|
||||
Message string
|
||||
Date string
|
||||
}
|
||||
|
||||
func Log(repoPath, branch string, limit int) ([]Commit, error) {
|
||||
out, err := run(repoPath, "log", branch,
|
||||
"--format=%H\x1f%an\x1f%s\x1f%ci",
|
||||
"--max-count", strings.TrimSpace(string(rune(limit+'0'))),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var commits []Commit
|
||||
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
|
||||
parts := strings.Split(line, "\x1f")
|
||||
if len(parts) != 4 {
|
||||
continue
|
||||
}
|
||||
commits = append(commits, Commit{
|
||||
Hash: parts[0],
|
||||
Author: parts[1],
|
||||
Message: parts[2],
|
||||
Date: parts[3],
|
||||
})
|
||||
}
|
||||
return commits, nil
|
||||
}
|
||||
|
||||
type TreeEntry struct {
|
||||
Mode string
|
||||
Type string
|
||||
Hash string
|
||||
Name string
|
||||
}
|
||||
|
||||
func TreeLS(repoPath, ref, subPath string) ([]TreeEntry, error) {
|
||||
treeRef := ref + ":" + subPath
|
||||
out, err := run(repoPath, "ls-tree", treeRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var entries []TreeEntry
|
||||
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
// format: <mode> SP <type> SP <hash> TAB <name>
|
||||
tabIdx := strings.Index(line, "\t")
|
||||
if tabIdx < 0 {
|
||||
continue
|
||||
}
|
||||
name := line[tabIdx+1:]
|
||||
fields := strings.Fields(line[:tabIdx])
|
||||
if len(fields) != 3 {
|
||||
continue
|
||||
}
|
||||
entries = append(entries, TreeEntry{
|
||||
Mode: fields[0],
|
||||
Type: fields[1],
|
||||
Hash: fields[2],
|
||||
Name: name,
|
||||
})
|
||||
}
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
func BlobCat(repoPath, ref, filePath string) ([]byte, error) {
|
||||
return run(repoPath, "show", ref+":"+filePath)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type FederationActor struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
UserID int64 `xorm:"notnull unique index"`
|
||||
APID string `xorm:"notnull unique varchar(500)"` // https://instance/users/alice
|
||||
InboxURL string `xorm:"notnull varchar(500)"`
|
||||
OutboxURL string `xorm:"notnull varchar(500)"`
|
||||
PublicKey string `xorm:"text notnull"`
|
||||
PrivateKey string `xorm:"text notnull"` // AES-GCM encrypted at rest
|
||||
CreatedAt time.Time `xorm:"created"`
|
||||
UpdatedAt time.Time `xorm:"updated"`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"github.com/forgao/forgebucket/internal/models"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
func Run(engine *xorm.Engine) error {
|
||||
return engine.Sync2(
|
||||
&models.User{},
|
||||
&models.Repository{},
|
||||
&models.PullRequest{},
|
||||
&models.FederationActor{},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type PRStatus string
|
||||
|
||||
const (
|
||||
PRStatusOpen PRStatus = "open"
|
||||
PRStatusMerged PRStatus = "merged"
|
||||
PRStatusClosed PRStatus = "closed"
|
||||
)
|
||||
|
||||
type PullRequest struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
RepoID int64 `xorm:"notnull index"`
|
||||
AuthorID int64 `xorm:"notnull index"`
|
||||
Title string `xorm:"notnull varchar(255)"`
|
||||
Body string `xorm:"text"`
|
||||
SourceBranch string `xorm:"notnull varchar(255)"`
|
||||
TargetBranch string `xorm:"default 'main' varchar(255)"`
|
||||
Status PRStatus `xorm:"default 'open' varchar(16)"`
|
||||
CreatedAt time.Time `xorm:"created"`
|
||||
UpdatedAt time.Time `xorm:"updated"`
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type Repository struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
OwnerID int64 `xorm:"notnull index"`
|
||||
Name string `xorm:"notnull varchar(100)"`
|
||||
Description string `xorm:"varchar(500)"`
|
||||
IsPrivate bool `xorm:"default false"`
|
||||
DefaultBranch string `xorm:"default 'main' varchar(255)"`
|
||||
DiskPath string `xorm:"notnull"` // absolute path under REPO_ROOT
|
||||
CreatedAt time.Time `xorm:"created"`
|
||||
UpdatedAt time.Time `xorm:"updated"`
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID int64 `xorm:"pk autoincr"`
|
||||
Username string `xorm:"unique notnull varchar(64)"`
|
||||
Email string `xorm:"unique notnull varchar(255)"`
|
||||
PasswordHash string `xorm:"notnull"`
|
||||
AvatarURL string `xorm:"varchar(500)"`
|
||||
IsAdmin bool `xorm:"default false"`
|
||||
CreatedAt time.Time `xorm:"created"`
|
||||
UpdatedAt time.Time `xorm:"updated"`
|
||||
}
|
||||
Vendored
+14
@@ -0,0 +1,14 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>ForgeBucket</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<p style="font-family:sans-serif;padding:2rem">
|
||||
Frontend not built yet — run <code>make build</code> or <code>make dev</code>.
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,20 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
//go:embed all:dist
|
||||
var staticFiles embed.FS
|
||||
|
||||
// FS returns the embedded frontend/dist subtree.
|
||||
// Falls back to an empty FS during development (before `make build` runs).
|
||||
func FS() fs.FS {
|
||||
sub, err := fs.Sub(staticFiles, "dist")
|
||||
if err != nil {
|
||||
return http.FS(http.Dir(""))
|
||||
}
|
||||
return sub
|
||||
}
|
||||
Reference in New Issue
Block a user