package main
import (
"bytes"
"crypto/rand"
"embed"
"encoding/base64"
"io"
"fmt"
"html/template"
"log"
"net"
"net/http"
"net/url"
"strings"
"sync"
"math/big"
"os"
"os/exec"
"time"
"github.com/gocql/gocql"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
//go:embed templates/*
var templatesFS embed.FS
var tmpl *template.Template
var scyllaSession *gocql.Session
func initDB() {
cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "system"
cluster.Timeout = 10 * time.Second
var sys *gocql.Session
var err error
for i := 0; i < 60; i++ {
sys, err = cluster.CreateSession()
if err == nil {
break
}
log.Printf("[DB] Waiting for ScyllaDB (%d/60): %v", i+1, err)
time.Sleep(5 * time.Second)
}
if err != nil {
log.Fatalf("[DB] Failed to connect: %v", err)
}
err = sys.Query("CREATE KEYSPACE IF NOT EXISTS unity WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 1}").Exec()
if err != nil {
log.Fatalf("[DB] Failed to create keyspace: %v", err)
}
sys.Close()
kCluster := gocql.NewCluster("127.0.0.1")
kCluster.Keyspace = "cosmos"
kCluster.Timeout = 10 * time.Second
scyllaSession, err = kCluster.CreateSession()
if err != nil {
log.Fatalf("[DB] Failed to connect to unity keyspace: %v", err)
}
scyllaSession.Query(`CREATE TABLE IF NOT EXISTS users (
service text,
email text,
name text,
password_hash text,
access_key text,
secret_key text,
bucket text,
session_id text,
created_at bigint,
PRIMARY KEY ((service, email))
)`).Exec()
scyllaSession.Query(`CREATE INDEX IF NOT EXISTS users_session ON cosmos.users (session_id)`).Exec()
// Migrate existing tables: add created_at if missing (ignore errors on existing columns)
scyllaSession.Query(`ALTER TABLE cosmos.users ADD created_at bigint`).Exec()
scyllaSession.Query(`CREATE TABLE IF NOT EXISTS pending (
service text,
reg_token text,
session_id text,
name text,
email text,
password_hash text,
PRIMARY KEY ((service, reg_token))
)`).Exec()
// raw_password column no longer used — stored in memory only; ignore error if already dropped
scyllaSession.Query(`ALTER TABLE cosmos.pending DROP raw_password`).Exec()
// Forgot-password reset tokens — 'token' is a CQL reserved word, use reset_token
// Drop the old broken table (if it exists with wrong schema) and recreate
scyllaSession.Query(`DROP TABLE IF EXISTS cosmos.password_reset_tokens`).Exec()
scyllaSession.Query(`CREATE TABLE IF NOT EXISTS cosmos.password_reset_tokens (
reset_token text PRIMARY KEY,
service text,
email text,
expires_at bigint
)`).Exec()
log.Println("[DB] ScyllaDB ready")
}
var pendingPasswords sync.Map // map[service+":"+regToken]rawPassword — in-memory only, never written to DB
func init() {
tmpl = template.Must(template.ParseFS(templatesFS, "templates/*.html"))
}
func generateOTP() string {
n, _ := rand.Int(rand.Reader, big.NewInt(1000000))
return fmt.Sprintf("%06d", n.Int64())
}
func sendVerificationEmail(email, token, service string) {
msg := fmt.Sprintf("From: noreply@cosmos.linuxguy.space\r\nTo: %s\r\nSubject: Verify your Cosmos %s Account\r\n\r\nYour verification code is: %s\r\n\r\nEnter this 6-digit code in the portal to verify your account.\r\n",
email, strings.ToUpper(service), token)
cmd := exec.Command("msmtp", "-t")
cmd.Stdin = bytes.NewBufferString(msg)
if err := cmd.Run(); err != nil {
log.Printf("[MAIL] Failed: %v", err)
}
}
// sessionMaxAge is the maximum age of a valid session (30 days).
const sessionMaxAge = 30 * 24 * time.Hour
func lookupBySession(service, sid string) (name, ak, sk, bucket string, err error) {
var createdAt int64
err = scyllaSession.Query(
`SELECT name, access_key, secret_key, bucket, created_at FROM cosmos.users WHERE session_id = ? ALLOW FILTERING`,
sid).Scan(&name, &ak, &sk, &bucket, &createdAt)
if err != nil {
return
}
// Enforce session expiry — createdAt=0 means old session (pre-expiry feature), allow it
if createdAt > 0 && time.Since(time.Unix(createdAt, 0)) > sessionMaxAge {
err = fmt.Errorf("session expired")
name, ak, sk, bucket = "", "", "", ""
}
return
}
func checkAndProxyOrbitDomain(w http.ResponseWriter, r *http.Request) bool {
host := r.Host
if h, _, err := net.SplitHostPort(host); err == nil {
host = h
}
host = strings.ToLower(strings.TrimSpace(host))
if host == "localhost" || host == "127.0.0.1" {
return false
}
if scyllaSession == nil {
return false
}
var appID string
var portNum int
var status string
if err := scyllaSession.Query(`SELECT app_id, exposed_port, status FROM cosmos.orbit_apps WHERE custom_domain = ? ALLOW FILTERING`, host).Scan(&appID, &portNum, &status); err == nil && appID != "" {
handleOrbitDomainRouteProxy(w, r)
return true
}
return false
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
if checkAndProxyOrbitDomain(w, r) {
return
}
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "index.html", nil)
}
func handleServicePage(w http.ResponseWriter, r *http.Request, service string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, service+".html", nil)
}
func handlePoll(w http.ResponseWriter, r *http.Request, service string) {
sid := r.URL.Query().Get("sid")
w.Header().Set("Content-Type", "application/json")
_, _, _, _, err := lookupBySession(service, sid)
if err == nil {
w.Write([]byte(`{"ok": true}`))
} else {
w.Write([]byte(`{"ok": false}`))
}
}
// Replacing handleSignup
func handleSignup(w http.ResponseWriter, r *http.Request, service string) {
if r.Method == "GET" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "signup.html", map[string]string{"Service": service})
return
}
r.ParseMultipartForm(10 << 20)
name := strings.TrimSpace(r.FormValue("name"))
username := strings.ToLower(strings.TrimSpace(r.FormValue("username")))
email := strings.ToLower(strings.TrimSpace(r.FormValue("email")))
password := r.FormValue("password")
confirm := r.FormValue("confirm_password")
if email == "" || password == "" || name == "" || username == "" {
http.Error(w, "All fields required", http.StatusBadRequest)
return
}
if password != confirm {
http.Error(w, "Passwords do not match", http.StatusBadRequest)
return
}
// Read profile image if present
var profileImageBase64 string
file, _, err := r.FormFile("profile_image")
if err == nil {
defer file.Close()
bytes, err := io.ReadAll(file)
if err == nil && len(bytes) > 0 {
profileImageBase64 = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(bytes)
}
}
var ex string
if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE email = ? ALLOW FILTERING`, email).Scan(&ex) == nil {
http.Error(w, "Email already registered", http.StatusConflict)
return
}
// Also check username uniqueness
if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE username = ? ALLOW FILTERING`, username).Scan(&ex) == nil {
http.Error(w, "Username already taken", http.StatusConflict)
return
}
hash, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
regToken := generateOTP()
sessionID := uuid.New().String()
// Store session+OTP in pending table — raw_password NOT stored in DB (security)
if err := scyllaSession.Query(`INSERT INTO unity.pending (service, reg_token, session_id, name, email, password_hash, username, profile_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
service, regToken, sessionID, name, email, string(hash), username, profileImageBase64).Exec(); err != nil {
log.Printf("[SIGNUP] DB: %v", err)
http.Error(w, "Database error", 500)
return
}
// Store plain password in memory (not DB) for Gitea provisioning — auto-expire after 15 min
pendingPasswords.Store(service+":"+regToken, password)
go func(key string) {
time.Sleep(15 * time.Minute)
pendingPasswords.Delete(key)
}(service + ":" + regToken)
go sendVerificationEmail(email, regToken, service)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Write([]byte(`
Verify Email – CosmosCheck your email
We sent a 6-digit verification code to ` + email + `.
It may take a moment to arrive.
`))
}
// Replacing handleLogin
func handleLogin(w http.ResponseWriter, r *http.Request, service string) {
if r.Method == "GET" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := map[string]string{"Service": service}
if r.URL.Query().Get("error") != "" {
data["Error"] = "Invalid credentials."
}
tmpl.ExecuteTemplate(w, "login.html", data)
return
}
r.ParseForm()
ident := strings.ToLower(strings.TrimSpace(r.FormValue("email")))
password := r.FormValue("password")
var sessionID, passwordHash, userEmail, userName string
var err error
// Query single unified user database by email or username
if strings.Contains(ident, "@") {
err = scyllaSession.Query(
`SELECT session_id, password_hash, email, username FROM cosmos.users WHERE email = ? ALLOW FILTERING`,
ident,
).Scan(&sessionID, &passwordHash, &userEmail, &userName)
} else {
err = scyllaSession.Query(
`SELECT session_id, password_hash, email, username FROM cosmos.users WHERE username = ? ALLOW FILTERING`,
ident,
).Scan(&sessionID, &passwordHash, &userEmail, &userName)
}
if err != nil || sessionID == "" {
log.Printf("[LOGIN] User not found for '%s': %v", ident, err)
http.Redirect(w, r, "/"+service+"/login?error=1", http.StatusFound)
return
}
if bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(password)) != nil {
log.Printf("[LOGIN] Password mismatch for '%s'", ident)
http.Redirect(w, r, "/"+service+"/login?error=1", http.StatusFound)
return
}
// Set unified SSO session cookies across all Cosmos modules
isSecure := r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https"
http.SetCookie(w, &http.Cookie{
Name: "cosmos_sid",
Value: sessionID,
Path: "/",
MaxAge: 86400 * 30,
HttpOnly: true,
Secure: isSecure,
SameSite: http.SameSiteLaxMode,
})
http.SetCookie(w, &http.Cookie{
Name: "oort_session",
Value: sessionID,
Path: "/",
MaxAge: 86400 * 30,
HttpOnly: true,
Secure: isSecure,
SameSite: http.SameSiteLaxMode,
})
http.SetCookie(w, &http.Cookie{
Name: "orbit_session",
Value: sessionID,
Path: "/",
MaxAge: 86400 * 30,
HttpOnly: true,
Secure: isSecure,
SameSite: http.SameSiteLaxMode,
})
// Also log into Gitea to establish the i_like_gitea session
giteaUser := userName
if giteaUser == "" {
giteaUser = ident
}
if cookies, gErr := loginGitea(giteaUser, password); gErr == nil {
for _, c := range cookies {
if c.Name == "i_like_gitea" && c.Value != "" {
http.SetCookie(w, &http.Cookie{
Name: c.Name,
Value: c.Value,
Path: "/source",
MaxAge: 86400 * 7,
HttpOnly: true,
Secure: isSecure,
SameSite: http.SameSiteLaxMode,
})
}
}
} else {
log.Printf("[LOGIN] Gitea login attempt for %s: %v", giteaUser, gErr)
}
if service == "git" {
http.Redirect(w, r, "/source/", http.StatusFound)
return
}
if service == "oort" {
http.Redirect(w, r, "/oort/console?sid="+sessionID, http.StatusFound)
return
}
if service == "orbit" {
http.Redirect(w, r, "/orbit", http.StatusFound)
return
}
http.Redirect(w, r, "/"+service+"/dashboard?sid="+sessionID, http.StatusFound)
}
func handleVerify(w http.ResponseWriter, r *http.Request, service string) {
if r.Method == "POST" {
r.ParseForm()
}
token := r.FormValue("code")
if token == "" {
token = r.FormValue("token")
}
if token == "" {
token = r.URL.Query().Get("token")
}
if token == "" {
http.Error(w, "Missing token", 400)
return
}
var sessionID, name, email, passwordHash, username, profileImage string
// raw_password is never stored in DB — read from in-memory map only
err := scyllaSession.Query(`SELECT session_id, name, email, password_hash, username, profile_image FROM unity.pending WHERE service = ? AND reg_token = ?`,
service, token).Scan(&sessionID, &name, &email, &passwordHash, &username, &profileImage)
if err != nil {
if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
http.Error(w, "Invalid token", 400)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprint(w, `Invalid or expired link.
`)
return
}
// Retrieve raw password from in-memory map (for Gitea provisioning only) — never stored in DB
var rawPassword string
if val, ok := pendingPasswords.Load(service + ":" + token); ok {
rawPassword = val.(string)
}
accessKey := email
secretKey := strings.ReplaceAll(uuid.New().String(), "-", "") + strings.ReplaceAll(uuid.New().String(), "-", "")[:8]
bucket := "unity-" + strings.ReplaceAll(uuid.New().String(), "-", "")[:8]
// Store created_at for future session expiry checks
createdAt := time.Now().Unix()
if err = scyllaSession.Query(`INSERT INTO cosmos.users (service, email, name, password_hash, access_key, secret_key, bucket, bucket_display_name, session_id, username, profile_image, created_at) VALUES ('git', ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?, ?)`,
email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage, createdAt).Exec(); err != nil {
// created_at column may not exist yet — fall back without it
if err2 := scyllaSession.Query(`INSERT INTO cosmos.users (service, email, name, password_hash, access_key, secret_key, bucket, bucket_display_name, session_id, username, profile_image) VALUES ('git', ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?)`,
email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage).Exec(); err2 != nil {
log.Printf("[VERIFY] Insert failed: %v", err2)
http.Error(w, "Failed to create account", 500)
return
}
}
scyllaSession.Query(`DELETE FROM unity.pending WHERE service = ? AND reg_token = ?`, service, token).Exec()
// Clear raw password from memory immediately after use
pendingPasswords.Delete(service + ":" + token)
go func() {
provisionMinIO(accessKey, secretKey, bucket)
if rawPassword != "" {
provisionGitea(username, email, rawPassword)
}
}()
if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"redirect": "/%s/login?verified=1"}`, service)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
fmt.Fprintf(w, `Verified – Cosmos
Email Verified!
Your Cosmos %s account is provisioned.
You can now sign in.
Continue to Login
`, strings.ToUpper(service), service)
}
func handleLogout(w http.ResponseWriter, r *http.Request, service string) {
http.SetCookie(w, &http.Cookie{Name: "cosmos_sid", Value: "", Path: "/", MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: "oort_session", Value: "", Path: "/", MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: "orbit_session", Value: "", Path: "/", MaxAge: -1})
http.SetCookie(w, &http.Cookie{Name: "i_like_gitea", Value: "", Path: "/source", MaxAge: -1})
http.Redirect(w, r, "/" + service, http.StatusFound)
}
func handleDashboard(w http.ResponseWriter, r *http.Request, service string) {
sid := r.URL.Query().Get("sid")
if sid == "" {
if c, err := r.Cookie("cosmos_sid"); err == nil {
sid = c.Value
}
}
if sid == "" {
if c, err := r.Cookie("oort_session"); err == nil {
sid = c.Value
}
}
if sid == "" {
http.Redirect(w, r, "/"+service+"/login", http.StatusFound)
return
}
name, ak, sk, bucket, err := lookupBySession(service, sid)
if err != nil {
log.Printf("[DASHBOARD] Lookup failed service=%s sid=%s: %v", service, sid, err)
http.Redirect(w, r, "/"+service+"/login", http.StatusFound)
return
}
if service == "oort" {
http.Redirect(w, r, "/oort/console?sid="+sid, http.StatusFound)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
switch service {
case "oort":
fmt.Fprintf(w, `S3 – Cosmos
Welcome, %s.
Your S3 workspace is provisioned.
S3 Endpoint
https://cosmos.linuxguy.space
Open Storage Console →
`, name, ak, sk, bucket, sid)
case "git":
fmt.Fprintf(w, `Git – Cosmos
Welcome, %s.
Your Forge workspace is connected.
Open Git Server →
`, name)
}
}
func provisionMinIO(ak, sk, bucket string) {
log.Printf("[MinIO] Provisioning %s", ak)
exec.Command("mc", "alias", "set", "cosmos", "http://127.0.0.1:9000", "unityadmin", "UnityAdmin2026!").Run()
exec.Command("mc", "admin", "user", "add", "cosmos", ak, sk).Run()
exec.Command("mc", "mb", "--ignore-existing", "cosmos/"+bucket).Run()
exec.Command("mc", "version", "enable", "cosmos/"+bucket).Run()
// Create user-specific policy restricting them to their own bucket
policyStr := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:*"],"Resource":["arn:aws:s3:::%s","arn:aws:s3:::%s/*"]}]}`, bucket, bucket)
policyFile := "/tmp/policy_" + bucket + ".json"
os.WriteFile(policyFile, []byte(policyStr), 0644)
exec.Command("mc", "admin", "policy", "create", "cosmos", "policy_"+bucket, policyFile).Run()
exec.Command("mc", "admin", "policy", "attach", "cosmos", "policy_"+bucket, "--user", ak).Run()
// Set 10GB quota
exec.Command("mc", "quota", "set", "cosmos/"+bucket, "--size", "10G").Run()
log.Printf("[MinIO] Done: %s, bucket %s (10GB Quota)", ak, bucket)
}
func provisionGitea(username, email, password string) {
log.Printf("[Gitea] Provisioning %s as %s", email, username)
time.Sleep(3 * time.Second)
cmd := exec.Command("sudo", "docker", "exec", "-u", "git", "-i", "gitea-gitea-1",
"gitea", "admin", "user", "create",
"--username", username,
"--email", email,
"--password", password,
"--must-change-password=false")
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("[Gitea] Failed: %v | %s", err, string(out))
}
}
func syncGiteaPassword(username, newPassword string) error {
log.Printf("[Gitea] Synchronizing password for user: %s", username)
cmd := exec.Command("sudo", "docker", "exec", "-u", "git", "-i", "gitea-gitea-1",
"gitea", "admin", "user", "change-password",
"--username", username,
"--password", newPassword,
"--must-change-password=false")
out, err := cmd.CombinedOutput()
if err != nil {
log.Printf("[Gitea] Password sync failed for %s: %v | %s", username, err, string(out))
return err
}
log.Printf("[Gitea] Password synced successfully for %s", username)
return nil
}
func loginGitea(username, password string) ([]*http.Cookie, error) {
form := url.Values{
"user_name": {username},
"password": {password},
}
req, err := http.NewRequest("POST", "http://127.0.0.1:3000/user/login", strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
client := &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
return http.ErrUseLastResponse
},
Timeout: 5 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusSeeOther || resp.StatusCode == http.StatusFound {
return resp.Cookies(), nil
}
// If login returned 200 (auth failed), Gitea password might be out of sync.
// Auto-heal by syncing password from Cosmos and retrying!
log.Printf("[Gitea] Login returned status %d for %s — syncing password and retrying...", resp.StatusCode, username)
if syncErr := syncGiteaPassword(username, password); syncErr == nil {
req2, _ := http.NewRequest("POST", "http://127.0.0.1:3000/user/login", strings.NewReader(form.Encode()))
req2.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp2, err2 := client.Do(req2)
if err2 == nil {
defer resp2.Body.Close()
if resp2.StatusCode == http.StatusSeeOther || resp2.StatusCode == http.StatusFound {
log.Printf("[Gitea] Auto-heal login succeeded for %s", username)
return resp2.Cookies(), nil
}
}
}
return nil, fmt.Errorf("gitea login failed with status %d", resp.StatusCode)
}
// ─── FORGOT PASSWORD ──────────────────────────────────────────────────────────
const resetTokenMaxAge = time.Hour // Reset links expire after 1 hour
// sendPasswordResetEmail sends the reset link to the user's email address.
func sendPasswordResetEmail(toEmail, token, service string) {
link := fmt.Sprintf("https://cosmos.linuxguy.space/%s/reset-password?token=%s", service, token)
msg := fmt.Sprintf(
"From: noreply@cosmos.linuxguy.space\r\nTo: %s\r\nSubject: Reset your Cosmos %s password\r\n\r\n"+
"Hi,\r\n\r\n"+
"We received a request to reset the password for your Cosmos %s account (%s).\r\n\r\n"+
"Click the link below to set a new password. This link is valid for 1 hour.\r\n\r\n"+
" %s\r\n\r\n"+
"If you did not request this, you can safely ignore this email — your account remains secure.\r\n\r\n"+
"— Cosmos Team\r\n",
toEmail, strings.ToUpper(service), strings.ToUpper(service), toEmail, link,
)
cmd := exec.Command("msmtp", "-t")
cmd.Stdin = bytes.NewBufferString(msg)
if err := cmd.Run(); err != nil {
log.Printf("[MAIL] Reset email failed for %s: %v", toEmail, err)
}
}
// handleForgotPassword handles GET (show form) and POST (send reset email).
func handleForgotPassword(w http.ResponseWriter, r *http.Request, service string) {
if r.Method == "GET" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := map[string]any{"Service": service, "Step": "request"}
if r.URL.Query().Get("sent") == "1" {
data["Sent"] = true
}
tmpl.ExecuteTemplate(w, "forgot-password.html", data)
return
}
// POST — look up user, generate token, send email
r.ParseForm()
email := strings.ToLower(strings.TrimSpace(r.FormValue("email")))
if email == "" {
http.Redirect(w, r, "/"+service+"/forgot-password", http.StatusFound)
return
}
// Always redirect to "sent" page regardless of whether the email exists
// (prevents user enumeration — attacker can't tell if an email is registered)
go func() {
var name string
err := scyllaSession.Query(
`SELECT name FROM cosmos.users WHERE service = ? AND email = ?`, service, email,
).Scan(&name)
if err != nil {
// User not found — do nothing, but we still showed "email sent" to the requester
log.Printf("[RESET] Email not found: %s (service=%s)", email, service)
return
}
// Generate a cryptographically secure token (UUID v4)
token := uuid.New().String()
expiresAt := time.Now().Add(resetTokenMaxAge).Unix()
// Delete any previous unused tokens for this email to prevent token accumulation
scyllaSession.Query(
`DELETE FROM cosmos.password_reset_tokens WHERE reset_token = ?`, token,
).Exec() // no-op if not exists; real cleanup via secondary scan would need an index
// Store token
if err := scyllaSession.Query(
`INSERT INTO cosmos.password_reset_tokens (reset_token, service, email, expires_at) VALUES (?, ?, ?, ?)`,
token, service, email, expiresAt,
).Exec(); err != nil {
log.Printf("[RESET] DB insert failed: %v", err)
return
}
sendPasswordResetEmail(email, token, service)
}()
// Always show "check your email" — prevents user enumeration
http.Redirect(w, r, "/"+service+"/forgot-password?sent=1", http.StatusFound)
}
// handleResetPassword handles GET (show new-password form) and POST (apply new password).
func handleResetPassword(w http.ResponseWriter, r *http.Request, service string) {
token := r.URL.Query().Get("token")
if r.Method == "POST" {
r.ParseForm()
token = r.FormValue("token")
}
renderError := func(msg string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "forgot-password.html", map[string]any{
"Service": service,
"Step": "reset",
"Token": token,
"Error": msg,
})
}
if token == "" {
http.Redirect(w, r, "/"+service+"/forgot-password", http.StatusFound)
return
}
// Look up token
var storedService, email string
var expiresAt int64
err := scyllaSession.Query(
`SELECT service, email, expires_at FROM cosmos.password_reset_tokens WHERE reset_token = ?`, token,
).Scan(&storedService, &email, &expiresAt)
if err != nil || storedService != service {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "forgot-password.html", map[string]any{
"Service": service,
"Step": "invalid",
})
return
}
// Check expiry
if time.Now().Unix() > expiresAt {
scyllaSession.Query(`DELETE FROM cosmos.password_reset_tokens WHERE reset_token = ?`, token).Exec()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "forgot-password.html", map[string]any{
"Service": service,
"Step": "expired",
})
return
}
if r.Method == "GET" {
// Show the new-password form
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "forgot-password.html", map[string]any{
"Service": service,
"Step": "reset",
"Token": token,
"Email": email,
})
return
}
// POST — apply new password
newPassword := r.FormValue("password")
confirmPassword := r.FormValue("confirm_password")
if len(newPassword) < 8 {
renderError("Password must be at least 8 characters.")
return
}
if newPassword != confirmPassword {
renderError("Passwords do not match.")
return
}
hash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
if err != nil {
renderError("Internal error. Please try again.")
return
}
// Update password in database
if err := scyllaSession.Query(
`UPDATE cosmos.users SET password_hash = ? WHERE service = ? AND email = ?`,
string(hash), service, email,
).Exec(); err != nil {
log.Printf("[RESET] Password update failed for %s: %v", email, err)
renderError("Failed to update password. Please try again.")
return
}
// If resetting git/forge password, synchronize with Gitea internal database
if service == "git" {
var giteaUser string
scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = ? AND email = ?`, service, email).Scan(&giteaUser)
if giteaUser != "" {
if err := syncGiteaPassword(giteaUser, newPassword); err != nil {
log.Printf("[RESET] Gitea password sync warning for %s: %v", giteaUser, err)
}
}
}
// Invalidate the reset token immediately
scyllaSession.Query(`DELETE FROM cosmos.password_reset_tokens WHERE reset_token = ?`, token).Exec()
log.Printf("[RESET] Password successfully reset for %s (service=%s)", email, service)
// Show success page
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "forgot-password.html", map[string]any{
"Service": service,
"Step": "done",
})
}
func serviceRouter(service string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
prefix := "/" + service + "/"
action := strings.TrimPrefix(r.URL.Path, prefix)
sub := ""
if idx := strings.Index(action, "/"); idx != -1 {
sub = action[idx+1:]
action = action[:idx]
if action == "api" && sub == "poll" {
handlePoll(w, r, service)
return
}
}
switch action {
case "signup":
handleSignup(w, r, service)
case "login":
handleLogin(w, r, service)
case "verify":
handleVerify(w, r, service)
case "logout":
handleLogout(w, r, service)
case "dashboard":
handleDashboard(w, r, service)
case "forgot-password":
handleForgotPassword(w, r, service)
case "reset-password":
handleResetPassword(w, r, service)
case "":
handleServicePage(w, r, service)
default:
if service == "oort" {
handleS3PublicProxy(w, r, action, sub)
return
}
http.NotFound(w, r)
}
}
}
func main() {
initDB()
mux := http.NewServeMux()
mux.HandleFunc("/tailwind.css", func(w http.ResponseWriter, r *http.Request) {
data, _ := templatesFS.ReadFile("templates/tailwind.css")
w.Header().Set("Content-Type", "text/css; charset=utf-8")
w.Write(data)
})
mux.HandleFunc("/three.min.js", func(w http.ResponseWriter, r *http.Request) {
data, _ := templatesFS.ReadFile("templates/three.min.js")
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
w.Write(data)
})
RegisterS3ConsoleRoutes(mux)
RegisterOrbitRoutes(mux)
mux.HandleFunc("/oort", func(w http.ResponseWriter, r *http.Request) { handleServicePage(w, r, "oort") })
mux.HandleFunc("/git", func(w http.ResponseWriter, r *http.Request) { handleServicePage(w, r, "git") })
mux.HandleFunc("/oort/", serviceRouter("oort"))
mux.HandleFunc("/git/", serviceRouter("git"))
mux.HandleFunc("/", handleIndex)
log.Println("[SERVER] Starting Cosmos Portals on 127.0.0.1:8000")
log.Fatal(http.ListenAndServe("127.0.0.1:8000", mux))
}