Compare commits

...
31 Commits
Author SHA1 Message Date
admin 339cf82b8d fix(oort): complete redesign of Oort landing page with native cursor and operable layout 2026-11-15 02:21:37 +05:30
admin c269fdea23 feat(nas): add bucket selector in Mornye NAS view and mobile sidebar backdrop 2026-11-15 02:15:20 +05:30
admin a772cfe370 feat(oort): complete redesign and rewrite of Oort S3 and Mornye NAS console 2026-11-15 02:12:22 +05:30
admin f13b9bfb7c fix(mobile): enforce single-station snap per swipe and prevent runaway touch inertia 2026-11-07 13:17:40 +05:30
admin 777863a635 fix(cache): replace 1-year immutable cache with no-cache revalidation across all static and console routes 2026-11-07 12:19:18 +05:30
admin 76783b95e6 fix(http): enforce strict no-cache headers on all dynamic portal routes 2026-11-07 12:04:47 +05:30
admin e2f8433803 revert: restore Forge, Orbit, Login, Signup pages to clean state from ff4d288 2026-11-07 12:01:27 +05:30
admin 56d12612e3 fix(home): restore Station 3 Oort text and links from bb61db8 2026-11-07 11:43:54 +05:30
admin 757089c1fa revert: restore original Cosmos home page (templates/index.html) 2026-11-07 11:31:26 +05:30
admin 181dc6664a feat(ui): redesign Cosmos home, Oort auth, Forge, and Orbit with 3D space theme 2026-11-07 11:27:09 +05:30
admin ff4d288bf5 feat(nas): configure pure WebDAV and HTTP directory NAS server for Mornye 2026-11-07 03:45:59 +05:30
admin 7720d15a00 feat(oort): transform cloud storage into dedicated Mornye NAS streaming service 2026-11-07 03:23:06 +05:30
admin bb61db8092 feat(ui): hide 3D background planets to ensure text is crystal clear 2026-11-07 02:15:05 +05:30
admin 90a66aefa6 feat(scroll): make backward scrolling animation completely fluid and smooth 2026-11-07 02:11:03 +05:30
admin e6e5b91e3b feat(scroll): implement station-wise navigation with rock-solid pause and calibrated celestial distances 2026-11-07 01:03:36 +05:30
admin 72a6b2cbf9 fix(scroll): calibrate scroll sensitivity and dwell zones to prevent skipping stations 2026-11-07 00:46:48 +05:30
admin 8fec2ce4c2 3d-site page 2026-11-07 00:30:41 +05:30
admin e5a368043c fix(orbit): map cosmos.linuxguy.space git clone URLs to local Gitea port 2026-10-30 00:39:39 +05:30
vaishnosingh 49d5559d8f feat(orbit): add dedicated templates showcase, zero-latency catalog, and full 28-section technical documentation 2026-10-14 18:42:41 +05:30
vaishnosingh 25bac8e8d8 fix(orbit): sync logs header directly with DB running state 2026-10-14 17:44:30 +05:30
vaishnosingh cd661abfeb feat(orbit): hook custom domain proxy into main HTTP router 2026-10-14 17:42:45 +05:30
vaishnosingh ba64943275 feat(orbit): resilient Go/Node builders + local Gitea starter templates 2026-10-14 17:41:06 +05:30
vaishnosingh 745e69f042 fix(orbit): fix multi-stage Dockerfile syntax for pack-static builds
COPY instructions cannot use shell redirects (2>/dev/null).
Replace with a RUN step that copies built output (dist/build/public/out)
to a clean /output dir, then single COPY --from=builder /output → nginx.
Also use node:22-alpine for Node.js >= 22 compatibility (h5bp, modern SPAs).
2026-10-14 17:30:35 +05:30
vaishnosingh 5f4730b8d0 fix(orbit): 502 fix + log clearing + stack detection overhaul
- Fix 502: detectAndInjectDockerfile now checks npm start script before
  using pack-node — repos with package.json but no start script now
  correctly build as pack-static via nginx
- Static builds with npm run build now use node:22-alpine + proper
  multi-stage Dockerfile with dist/build/public/out fallback copy chain
- Python: auto-detect entry point (app.py, wsgi.py, run.py, server.py)
- All failure paths in deployAppAsync now call orbitBuildLogs.Delete()
  so stale build logs don't stay in memory after deployment ends
- Logs handler: add X-App-Status response header for UI polling control
- Logs handler: newest deployment log fetched from orbit_deployments
  (iterate all, pick latest created_at) instead of LIMIT 1
- UI: refreshLogs() reads X-App-Status header, stops interval when done
- UI: log output colorized with inline CSS spans per log tag
- UI: toast shown on deploy success/failure, app list reloads on finish
- Updated action handler saveDeploymentRecord calls + log delete
2026-10-14 17:29:23 +05:30
vaishnosingh 3fea647670 feat(orbit): enterprise UI rebuild + custom domain support + 10-port limit
- Complete UI rewrite: sidebar nav layout, glassmorphism, animated
  orbital-ring + constellation particle canvas, hover animations on all
  interactive elements
- Custom domain support: POST /orbit/api/apps/:id/domain with CNAME
  instructions, collision detection, domain proxy routing
- 10-app/port limit per user enforced at API level (403 with clear message)
- UI port quota bar in sidebar showing X/10 usage
- Custom domain view tab listing all mapped domains
- Env vars editor modal
- Mobile responsive sidebar with toggle
- Added custom_domain column migration to orbit_apps ScyllaDB table
2026-10-14 17:15:59 +05:30
vaishnosingh ed6d36a1e6 fix(auth): unify user database across Forge, Oort, and Orbit with SSO and delete split oort records 2026-10-14 17:02:03 +05:30
vaishnosingh 12a146129e feat(orbit): add 3D orbital motion graphics canvas and vibrant hover highlights 2026-10-14 16:48:17 +05:30
vaishnosingh a3bf00cd64 feat(orbit): add Oort S3 container backup and Forge webhook auto-deploy 2026-10-14 16:20:32 +05:30
vaishnosingh 11b41bd5cb feat(orbit): implement Cosmos Orbit (Module 03) container PaaS engine and console 2026-10-14 16:16:22 +05:30
vaishnosingh fae4d304a9 feat(ui): add dashboard storage breakdown donut and refine browser search toolbar 2026-10-14 15:49:41 +05:30
vaishnosingh 1d8a836e50 feat(oort): add secure share links, media preview/code editor, static site hosting, event webhooks, batch ops, category filters, and storage breakdown donut chart 2026-10-14 15:32:57 +05:30
16 changed files with 18513 additions and 6415 deletions
File diff suppressed because it is too large Load Diff
+179 -86
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"html/template"
"log"
"net"
"net/http"
"net/url"
"strings"
@@ -48,24 +49,18 @@ func initDB() {
log.Fatalf("[DB] Failed to connect: %v", err)
}
// Ensure cosmos keyspace exists
if err = sys.Query("CREATE KEYSPACE IF NOT EXISTS cosmos WITH replication = {'class': 'NetworkTopologyStrategy', 'datacenter1': 1}").Exec(); err != nil {
sys.Query("CREATE KEYSPACE IF NOT EXISTS cosmos WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}").Exec()
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)
}
// Backward compatibility keyspace alias
sys.Query("CREATE KEYSPACE IF NOT EXISTS unity WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}").Exec()
sys.Close()
scyllaHost := os.Getenv("SCYLLA_HOST")
if scyllaHost == "" {
scyllaHost = "127.0.0.1"
}
kCluster := gocql.NewCluster(scyllaHost)
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 cosmos keyspace: %v", err)
log.Fatalf("[DB] Failed to connect to unity keyspace: %v", err)
}
scyllaSession.Query(`CREATE TABLE IF NOT EXISTS users (
@@ -122,8 +117,8 @@ func generateOTP() string {
}
func sendVerificationEmail(email, token, service string) {
msg := fmt.Sprintf("From: %s\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",
getEmailFrom(), email, strings.ToUpper(service), token)
msg := fmt.Sprintf("From: [email protected]\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 {
@@ -137,8 +132,8 @@ 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 service = ? AND session_id = ? ALLOW FILTERING`,
service, sid).Scan(&name, &ak, &sk, &bucket, &createdAt)
`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
}
@@ -150,16 +145,47 @@ func lookupBySession(service, sid string) (name, ak, sk, bucket string, err erro
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("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
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("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, service+".html", nil)
}
@@ -178,6 +204,9 @@ func handlePoll(w http.ResponseWriter, r *http.Request, service string) {
// Replacing handleSignup
func handleSignup(w http.ResponseWriter, r *http.Request, service string) {
if r.Method == "GET" {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "signup.html", map[string]string{"Service": service})
return
@@ -210,12 +239,12 @@ func handleSignup(w http.ResponseWriter, r *http.Request, service string) {
}
var ex string
if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE service = ? AND email = ?`, service, email).Scan(&ex) == nil {
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 service = ? AND username = ? ALLOW FILTERING`, service, username).Scan(&ex) == nil {
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
}
@@ -225,7 +254,7 @@ func handleSignup(w http.ResponseWriter, r *http.Request, service string) {
sessionID := uuid.New().String()
// Store session+OTP in pending table — raw_password NOT stored in DB (security)
if err := scyllaSession.Query(`INSERT INTO cosmos.pending (service, reg_token, session_id, name, email, password_hash, username, profile_image) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
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)
@@ -246,6 +275,9 @@ func handleSignup(w http.ResponseWriter, r *http.Request, service string) {
// Replacing handleLogin
func handleLogin(w http.ResponseWriter, r *http.Request, service string) {
if r.Method == "GET" {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := map[string]string{"Service": service}
if r.URL.Query().Get("error") != "" {
@@ -257,61 +289,98 @@ func handleLogin(w http.ResponseWriter, r *http.Request, service string) {
r.ParseForm()
ident := strings.ToLower(strings.TrimSpace(r.FormValue("email")))
password := r.FormValue("password")
var sessionID, passwordHash string
// Check if ident is email or username
query := `SELECT session_id, password_hash FROM cosmos.users WHERE service = ? AND email = ?`
if !strings.Contains(ident, "@") {
query = `SELECT session_id, password_hash FROM cosmos.users WHERE service = ? AND username = ? ALLOW FILTERING`
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 := scyllaSession.Query(query, service, ident).Scan(&sessionID, &passwordHash); err != nil {
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
}
if service == "git" {
var giteaUser string
scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = ? AND email = ?`, service, ident).Scan(&giteaUser)
if giteaUser == "" {
scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = ? AND username = ? ALLOW FILTERING`, service, ident).Scan(&giteaUser)
}
if giteaUser == "" {
giteaUser = ident
}
cookies, err := loginGitea(giteaUser, password)
if err == 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: r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https",
SameSite: http.SameSiteLaxMode,
})
}
// 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,
})
}
http.SetCookie(w, &http.Cookie{
Name: "cosmos_sid",
Value: sessionID,
Path: "/",
MaxAge: 86400 * 30,
HttpOnly: true,
Secure: r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https",
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, "/source/", http.StatusFound)
return
}
log.Printf("[LOGIN] Gitea login attempt failed for %s: %v", giteaUser, err)
} 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)
@@ -334,7 +403,7 @@ func handleVerify(w http.ResponseWriter, r *http.Request, service string) {
}
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 cosmos.pending WHERE service = ? AND reg_token = ?`,
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" {
@@ -354,32 +423,28 @@ func handleVerify(w http.ResponseWriter, r *http.Request, service string) {
accessKey := email
secretKey := strings.ReplaceAll(uuid.New().String(), "-", "") + strings.ReplaceAll(uuid.New().String(), "-", "")[:8]
bucket := "cosmos-" + 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 (?, ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?, ?)`,
service, email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage, createdAt).Exec(); err != nil {
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 (?, ?, ?, ?, ?, ?, ?, 'mybucket', ?, ?, ?)`,
service, email, name, passwordHash, accessKey, secretKey, bucket, sessionID, username, profileImage).Exec(); err2 != nil {
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 cosmos.pending WHERE service = ? AND reg_token = ?`, service, token).Exec()
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() {
switch service {
case "oort":
provisionMinIO(accessKey, secretKey, bucket)
case "git":
if rawPassword != "" {
provisionGitea(username, email, rawPassword)
}
provisionMinIO(accessKey, secretKey, bucket)
if rawPassword != "" {
provisionGitea(username, email, rawPassword)
}
}()
if r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" {
@@ -404,14 +469,24 @@ a{background:#fafafa;color:#000;padding:14px 28px;border-radius:8px;text-decorat
func handleLogout(w http.ResponseWriter, r *http.Request, service string) {
http.SetCookie(w, &http.Cookie{Name: "cosmos_sid", Value: "", Path: "/", MaxAge: -1})
if service == "git" {
http.SetCookie(w, &http.Cookie{Name: "i_like_gitea", Value: "", Path: "/source", 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
@@ -422,6 +497,10 @@ func handleDashboard(w http.ResponseWriter, r *http.Request, service string) {
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":
@@ -445,9 +524,9 @@ h1{font-size:48px;font-weight:700;margin-bottom:8px}
<div class="card"><div class="lbl">Access Key ID</div><div class="val">%s</div></div>
<div class="card"><div class="lbl">Secret Access Key</div><div class="val">%s</div></div>
<div class="card"><div class="lbl">Private Bucket</div><div class="val">%s</div></div>
<div class="card"><div class="lbl">S3 Endpoint</div><div class="val">%s</div></div>
<div class="card"><div class="lbl">S3 Endpoint</div><div class="val">https://cosmos.linuxguy.space</div></div>
<a href="/oort/console?sid=%s" class="btn">Open Storage Console →</a>
</div></body></html>`, name, ak, sk, bucket, getCosmosBaseURL(), sid)
</div></body></html>`, name, ak, sk, bucket, sid)
case "git":
fmt.Fprintf(w, `<!DOCTYPE html><html><head><meta charset="utf-8"><title>Git – Cosmos</title><style>
@@ -471,7 +550,7 @@ h1{font-size:48px;font-weight:700;margin-bottom:8px}
func provisionMinIO(ak, sk, bucket string) {
log.Printf("[MinIO] Provisioning %s", ak)
exec.Command("mc", "alias", "set", "cosmos", "http://127.0.0.1:9000", getMinioRootUser(), getMinioRootPassword()).Run()
exec.Command("mc", "alias", "set", "cosmos", "http://127.0.0.1:9010", "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()
@@ -482,7 +561,6 @@ func provisionMinIO(ak, sk, bucket string) {
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()
os.Remove(policyFile)
// Set 10GB quota
exec.Command("mc", "quota", "set", "cosmos/"+bucket, "--size", "10G").Run()
@@ -576,16 +654,16 @@ 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("%s/%s/reset-password?token=%s", getCosmosBaseURL(), service, token)
link := fmt.Sprintf("https://cosmos.linuxguy.space/%s/reset-password?token=%s", service, token)
msg := fmt.Sprintf(
"From: %s\r\nTo: %s\r\nSubject: Reset your Cosmos %s password\r\n\r\n"+
"From: [email protected]\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",
getEmailFrom(), toEmail, strings.ToUpper(service), strings.ToUpper(service), toEmail, link,
toEmail, strings.ToUpper(service), strings.ToUpper(service), toEmail, link,
)
cmd := exec.Command("msmtp", "-t")
cmd.Stdin = bytes.NewBufferString(msg)
@@ -596,6 +674,9 @@ func sendPasswordResetEmail(toEmail, token, service string) {
// handleForgotPassword handles GET (show form) and POST (send reset email).
func handleForgotPassword(w http.ResponseWriter, r *http.Request, service string) {
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
if r.Method == "GET" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := map[string]any{"Service": service, "Step": "request"}
@@ -809,9 +890,21 @@ func main() {
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.Header().Set("Cache-Control", "no-cache, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
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", "no-cache, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
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"))
+525 -28
View File
@@ -5,6 +5,8 @@ import (
"context"
"encoding/json"
"encoding/base64"
"encoding/xml"
"html"
"github.com/google/uuid"
"fmt"
"io"
@@ -16,6 +18,7 @@ import (
"os"
"os/exec"
"path"
"path/filepath"
"strconv"
"strings"
"time"
@@ -25,7 +28,8 @@ import (
"github.com/minio/minio-go/v7/pkg/credentials"
)
const minioEndpoint = "127.0.0.1:9000"
const minioEndpoint = "127.0.0.1:9010"
const publicMinioEndpoint = "cosmos.linuxguy.space"
// authS3Console validates the session and returns (accessKey, secretKey, bucket).
// It looks up the session from the cosmos.users table.
@@ -40,10 +44,22 @@ func authS3Console(r *http.Request) (ak, sk, bucket string, ok bool) {
sid = cookie.Value
}
}
if sid == "" {
cookie, err := r.Cookie("oort_session")
if err == nil {
sid = cookie.Value
}
}
if sid == "" {
cookie, err := r.Cookie("orbit_session")
if err == nil {
sid = cookie.Value
}
}
if sid == "" {
return "", "", "", false
}
_, ak, sk, bucket, err := lookupBySession("oort", sid)
_, ak, sk, bucket, err := lookupBySession("", sid)
if err != nil || ak == "" {
return "", "", "", false
}
@@ -86,6 +102,8 @@ func RegisterS3ConsoleRoutes(mux *http.ServeMux) {
owner_email text
)`).Exec()
RegisterExpansionRoutes(mux)
mux.HandleFunc("/oort/api/objects/versions", handleS3ObjectVersions)
mux.HandleFunc("/oort/api/objects/restore", handleS3ObjectRestore)
mux.HandleFunc("/oort/api/objects/share", handleS3ShareObject)
@@ -119,6 +137,8 @@ func RegisterS3ConsoleRoutes(mux *http.ServeMux) {
mux.HandleFunc("/oort/api/password", handleS3Password)
mux.HandleFunc("/oort/api/objects/move", handleS3Move)
mux.HandleFunc("/oort/api/buckets/rename", handleS3RenameBucket)
mux.HandleFunc("/oort/api/nas/info", handleMornyeNASInfo)
mux.HandleFunc("/oort/api/nas/enable-streaming", handleMornyeNASEnableStreaming)
}
// ─── Console HTML page ────────────────────────────────────────────────────────
@@ -132,7 +152,7 @@ func handleS3ConsolePage(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://static.cloudflareinsights.com; img-src 'self' data: blob:;")
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://static.cloudflareinsights.com; img-src 'self' data: blob: https:; media-src 'self' blob: data:; connect-src 'self';")
sid := r.URL.Query().Get("sid")
if sid == "" {
@@ -151,6 +171,10 @@ func handleS3ConsolePage(w http.ResponseWriter, r *http.Request) {
})
var username string
scyllaSession.Query(`SELECT username FROM cosmos.users WHERE session_id=? ALLOW FILTERING`, sid).Scan(&username)
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
tmpl.ExecuteTemplate(w, "oortconsole.html", map[string]string{"SID": sid, "Username": username})
}
@@ -426,6 +450,7 @@ func handleS3UploadComplete(w http.ResponseWriter, r *http.Request) {
// Record a write hit for analytics
go recordHit(bucket, 200, 0, false, r.Header.Get("CF-IPCountry"), "write")
go dispatchWebhooks(bucket, "object:created", upload.Key, 0, "")
jsonOK(w, map[string]any{
"key": upload.Key,
@@ -504,6 +529,7 @@ func handleS3Delete(w http.ResponseWriter, r *http.Request) {
}
}
go dispatchWebhooks(bucket, "object:deleted", key, 0, "")
jsonOK(w, map[string]bool{"deleted": true})
}
@@ -522,9 +548,9 @@ func handleS3Presign(w http.ResponseWriter, r *http.Request) {
jsonErr(w, "missing key", 400)
return
}
mc, err := minio.New(getPublicMinioEndpoint(), &minio.Options{
mc, err := minio.New(publicMinioEndpoint, &minio.Options{
Creds: credentials.NewStaticV4(ak, sk, ""),
Secure: !strings.HasPrefix(getPublicMinioEndpoint(), "localhost") && !strings.HasPrefix(getPublicMinioEndpoint(), "127.0.0.1"),
Secure: true,
})
if err != nil {
jsonErr(w, "minio error", 500)
@@ -679,7 +705,7 @@ func handleS3RenameBucket(w http.ResponseWriter, r *http.Request) {
if req.OldName == defBucket {
// Rename default bucket
scyllaSession.Query(`UPDATE cosmos.users SET bucket_display_name = ? WHERE service = 'oort' AND email = ?`, displayName, ak).Exec()
scyllaSession.Query(`UPDATE cosmos.users SET bucket_display_name = ? WHERE service = 'git' AND email = ?`, displayName, ak).Exec()
} else {
// Verify ownership in DB
var owner string
@@ -719,13 +745,13 @@ func handleS3Profile(w http.ResponseWriter, r *http.Request) {
return
}
var name, username, profileImage string
scyllaSession.Query(`SELECT name, username, profile_image FROM cosmos.users WHERE service = 'oort' AND email = ?`, ak).Scan(&name, &username, &profileImage)
scyllaSession.Query(`SELECT name, username, profile_image FROM cosmos.users WHERE service = 'git' AND email = ?`, ak).Scan(&name, &username, &profileImage)
jsonOK(w, map[string]any{
"access_key": ak,
"secret_key": sk,
"default_bucket": defaultBucket,
"endpoint": getCosmosBaseURL(),
"endpoint": "https://cosmos.linuxguy.space",
"name": name,
"username": username,
"profile_image": profileImage,
@@ -765,8 +791,8 @@ func handleS3Quota(w http.ResponseWriter, r *http.Request) {
}
func sendQuotaEmail(userEmail, token string, amount int) {
link := fmt.Sprintf("%s/oort/api/quota/approve?token=%s", getCosmosBaseURL(), token)
msg := fmt.Sprintf("From: %s\r\nTo: %s\r\nSubject: Quota Request from %s\r\n\r\nUser %s has requested a quota increase to %d GB.\r\n\r\nClick here to approve: %s\r\n", getEmailFrom(), getAdminEmail(), userEmail, userEmail, amount, link)
link := fmt.Sprintf("https://cosmos.linuxguy.space/oort/api/quota/approve?token=%s", token)
msg := fmt.Sprintf("From: [email protected]\r\nTo: [email protected]\r\nSubject: Quota Request from %s\r\n\r\nUser %s has requested a quota increase to %d GB.\r\n\r\nClick here to approve: %s\r\n", userEmail, userEmail, amount, link)
cmd := exec.Command("msmtp", "-t")
cmd.Stdin = bytes.NewBufferString(msg)
if err := cmd.Run(); err != nil {
@@ -819,11 +845,16 @@ func handleS3Password(w http.ResponseWriter, r *http.Request) {
// Change in ScyllaDB ONLY. MinIO API token (secret_key) remains unchanged.
hash, _ := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost)
err := scyllaSession.Query(`UPDATE cosmos.users SET password_hash = ? WHERE service = 'oort' AND email = ?`,
err := scyllaSession.Query(`UPDATE cosmos.users SET password_hash = ? WHERE service = 'git' AND email = ?`,
string(hash), ak).Exec()
if err != nil {
log.Printf("[S3] password update scylla: %v", err)
}
var gUser string
scyllaSession.Query(`SELECT username FROM cosmos.users WHERE service = 'git' AND email = ?`, ak).Scan(&gUser)
if gUser != "" {
syncGiteaPassword(gUser, req.NewPassword)
}
jsonOK(w, map[string]bool{"success": true})
}
@@ -875,7 +906,7 @@ func handleS3Buckets(w http.ResponseWriter, r *http.Request) {
// Always include the default private bucket
if defBucket != "" {
var defDisp string
scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='oort' AND email=?`, ak).Scan(&defDisp)
scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='git' AND email=?`, ak).Scan(&defDisp)
if defDisp == "" {
defDisp = "mybucket"
}
@@ -927,6 +958,9 @@ func handleS3CreateBucket(w http.ResponseWriter, r *http.Request) {
// Enable versioning
exec.Command("mc", "version", "enable", "cosmos/"+internalName).Run()
// Enable public streaming for Mornye NAS
exec.Command("mc", "anonymous", "set", "download", "cosmos/"+internalName).Run()
// Save to DB
scyllaSession.Query(`INSERT INTO cosmos.buckets (bucket_name, owner_email, display_name) VALUES (?, ?, ?)`, internalName, ak, displayName).Exec()
@@ -991,7 +1025,7 @@ func handleS3ProfileImage(w http.ResponseWriter, r *http.Request) {
return
}
encoded := "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(bytes)
if err := scyllaSession.Query(`UPDATE cosmos.users SET profile_image = ? WHERE service = 'oort' AND email = ?`, encoded, ak).Exec(); err != nil {
if err := scyllaSession.Query(`UPDATE cosmos.users SET profile_image = ? WHERE service = 'git' AND email = ?`, encoded, ak).Exec(); err != nil {
jsonErr(w, "db error", 500)
return
}
@@ -1023,12 +1057,12 @@ func handleS3ProfileUpdate(w http.ResponseWriter, r *http.Request) {
}
var ex string
if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE service = 'oort' AND username = ? ALLOW FILTERING`, req.Username).Scan(&ex) == nil && ex != ak {
if scyllaSession.Query(`SELECT email FROM cosmos.users WHERE username = ? ALLOW FILTERING`, req.Username).Scan(&ex) == nil && ex != ak {
jsonErr(w, "username already taken", 409)
return
}
if err := scyllaSession.Query(`UPDATE cosmos.users SET name = ?, username = ? WHERE service = 'oort' AND email = ?`, req.Name, req.Username, ak).Exec(); err != nil {
if err := scyllaSession.Query(`UPDATE cosmos.users SET name = ?, username = ? WHERE service = 'git' AND email = ?`, req.Name, req.Username, ak).Exec(); err != nil {
jsonErr(w, "db error", 500)
return
}
@@ -1064,7 +1098,7 @@ func handleS3ShareObject(w http.ResponseWriter, r *http.Request) {
return
}
jsonOK(w, map[string]string{"url": strings.Replace(presignedURL.String(), "http://"+minioEndpoint, getCosmosBaseURL(), 1)})
jsonOK(w, map[string]string{"url": strings.Replace(presignedURL.String(), "http://"+minioEndpoint, "https://"+publicMinioEndpoint, 1)})
}
// ─── GET /oort/api/objects/versions ──────────────────────────────────────────────
@@ -1138,16 +1172,336 @@ var proxyTransport = &http.Transport{
}
type MornyeTrackItem struct {
Key string `json:"key"`
Name string `json:"name"`
Title string `json:"title"`
Size int64 `json:"size"`
Format string `json:"format"`
StreamURL string `json:"stream_url"`
LastModified string `json:"last_modified"`
}
func handleMornyeNASInfo(w http.ResponseWriter, r *http.Request) {
ak, sk, defBucket, ok := authS3Console(r)
if !ok {
jsonErr(w, "unauthorized", 401)
return
}
var username, name string
scyllaSession.Query(`SELECT username, name FROM cosmos.users WHERE service='git' AND email=?`, ak).Scan(&username, &name)
if username == "" {
username = strings.Split(ak, "@")[0]
}
var defDisp string
scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='git' AND email=?`, ak).Scan(&defDisp)
if defDisp == "" {
defDisp = "mybucket"
}
type NASBucketInfo struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
IsDefault bool `json:"is_default"`
IsPublic bool `json:"is_public"`
NASUrl string `json:"nas_url"`
PlaylistUrl string `json:"playlist_url"`
TrackCount int `json:"track_count"`
MusicBytes int64 `json:"music_bytes"`
}
var bucketList []NASBucketInfo
rawBuckets := []struct{ name, disp string }{ {defBucket, defDisp} }
iter := scyllaSession.Query(`SELECT bucket_name, display_name FROM cosmos.buckets WHERE owner_email = ?`, ak).Iter()
var b, disp string
for iter.Scan(&b, &disp) {
if disp == "" { disp = b }
rawBuckets = append(rawBuckets, struct{ name, disp string }{b, disp})
}
iter.Close()
mc, _ := minioClient(ak, sk)
ctx := context.Background()
for i, rb := range rawBuckets {
if rb.name == "" { continue }
cmd := exec.Command("mc", "anonymous", "get", "cosmos/"+rb.name)
out, _ := cmd.CombinedOutput()
isPub := strings.Contains(string(out), "download") || strings.Contains(string(out), "public")
trackCount := 0
var musicBytes int64 = 0
if mc != nil {
for obj := range mc.ListObjects(ctx, rb.name, minio.ListObjectsOptions{Recursive: true}) {
if obj.Err == nil && !strings.HasSuffix(obj.Key, "/") {
lower := strings.ToLower(obj.Key)
if strings.HasSuffix(lower, ".flac") || strings.HasSuffix(lower, ".mp3") ||
strings.HasSuffix(lower, ".wav") || strings.HasSuffix(lower, ".m4a") ||
strings.HasSuffix(lower, ".aac") || strings.HasSuffix(lower, ".ogg") ||
strings.HasSuffix(lower, ".opus") || strings.HasSuffix(lower, ".alac") {
trackCount++
musicBytes += obj.Size
}
}
}
}
bucketList = append(bucketList, NASBucketInfo{
Name: rb.name,
DisplayName: rb.disp,
IsDefault: (i == 0),
IsPublic: isPub,
NASUrl: fmt.Sprintf("https://cosmos.linuxguy.space/oort/%s/%s/", username, rb.disp),
PlaylistUrl: fmt.Sprintf("https://cosmos.linuxguy.space/oort/%s/%s/playlist.m3u", username, rb.disp),
TrackCount: trackCount,
MusicBytes: musicBytes,
})
}
jsonOK(w, map[string]any{
"username": username,
"name": name,
"email": ak,
"secret_key": sk,
"s3_endpoint": "https://cosmos.linuxguy.space",
"default_bucket": defBucket,
"buckets": bucketList,
})
}
func handleMornyeNASEnableStreaming(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
jsonErr(w, "method not allowed", 405)
return
}
ak, _, defBucket, ok := authS3Console(r)
if !ok {
jsonErr(w, "unauthorized", 401)
return
}
var req struct {
Bucket string `json:"bucket"`
}
json.NewDecoder(r.Body).Decode(&req)
if req.Bucket == "" { req.Bucket = defBucket }
isOwner := false
if req.Bucket == defBucket {
isOwner = true
} else {
var owner string
if err := scyllaSession.Query(`SELECT owner_email FROM cosmos.buckets WHERE bucket_name=?`, req.Bucket).Scan(&owner); err == nil && owner == ak {
isOwner = true
}
}
if !isOwner {
jsonErr(w, "forbidden", 403)
return
}
cmd := exec.Command("mc", "anonymous", "set", "download", "cosmos/"+req.Bucket)
if out, err := cmd.CombinedOutput(); err != nil {
log.Printf("[NAS] enable streaming error for %s: %v | %s", req.Bucket, err, string(out))
jsonErr(w, "failed to enable streaming", 500)
return
}
jsonOK(w, map[string]any{"success": true, "bucket": req.Bucket, "status": "streaming_enabled"})
}
func escapeDAVPath(p string) string {
parts := strings.Split(p, "/")
for i, part := range parts {
parts[i] = url.PathEscape(part)
}
return strings.Join(parts, "/")
}
func xmlEscape(s string) string {
var b strings.Builder
xml.EscapeText(&b, []byte(s))
return b.String()
}
func mimeForFilename(filename string) string {
lower := strings.ToLower(filename)
switch {
case strings.HasSuffix(lower, ".flac"):
return "audio/flac"
case strings.HasSuffix(lower, ".mp3"):
return "audio/mpeg"
case strings.HasSuffix(lower, ".wav"):
return "audio/wav"
case strings.HasSuffix(lower, ".m4a"):
return "audio/mp4"
case strings.HasSuffix(lower, ".aac"):
return "audio/aac"
case strings.HasSuffix(lower, ".ogg"):
return "audio/ogg"
case strings.HasSuffix(lower, ".opus"):
return "audio/opus"
case strings.HasSuffix(lower, ".alac"):
return "audio/alac"
case strings.HasSuffix(lower, ".m3u"), strings.HasSuffix(lower, ".m3u8"):
return "audio/x-mpegurl"
case strings.HasSuffix(lower, ".lrc"):
return "text/plain; charset=utf-8"
case strings.HasSuffix(lower, ".json"):
return "application/json"
default:
return "application/octet-stream"
}
}
func handleWebDAVPropfind(w http.ResponseWriter, r *http.Request, username, displayBucket, actualBucket, objectKey string) {
mc, err := minio.New(minioEndpoint, &minio.Options{
Creds: credentials.NewStaticV4("unityadmin", "UnityAdmin2026!", ""),
Secure: false,
})
if err != nil {
http.Error(w, "WebDAV backend error", 500)
return
}
depth := r.Header.Get("Depth")
if depth == "" {
depth = "1"
}
w.Header().Set("Content-Type", "application/xml; charset=\"utf-8\"")
w.Header().Set("DAV", "1, 2")
w.Header().Set("MS-Author-Via", "DAV")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PROPFIND")
w.Header().Set("Access-Control-Allow-Headers", "Depth, Content-Type, Authorization, Range")
w.WriteHeader(207) // HTTP 207 Multi-Status
var buf strings.Builder
buf.WriteString("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n")
buf.WriteString("<D:multistatus xmlns:D=\"DAV:\">\n")
rootHref := fmt.Sprintf("/oort/%s/%s/", username, displayBucket)
if objectKey == "" {
// Root collection self entry
buf.WriteString(" <D:response>\n")
buf.WriteString(fmt.Sprintf(" <D:href>%s</D:href>\n", xmlEscape(rootHref)))
buf.WriteString(" <D:propstat>\n")
buf.WriteString(" <D:prop>\n")
buf.WriteString(fmt.Sprintf(" <D:displayname>%s</D:displayname>\n", xmlEscape(displayBucket)))
buf.WriteString(" <D:resourcetype><D:collection/></D:resourcetype>\n")
buf.WriteString(" </D:prop>\n")
buf.WriteString(" <D:status>HTTP/1.1 200 OK</D:status>\n")
buf.WriteString(" </D:propstat>\n")
buf.WriteString(" </D:response>\n")
if depth != "0" {
ctx := context.Background()
for obj := range mc.ListObjects(ctx, actualBucket, minio.ListObjectsOptions{Recursive: true}) {
if obj.Err == nil && !strings.HasSuffix(obj.Key, "/") {
itemHref := rootHref + escapeDAVPath(obj.Key)
mime := mimeForFilename(obj.Key)
lastMod := obj.LastModified.UTC().Format(http.TimeFormat)
name := filepath.Base(obj.Key)
buf.WriteString(" <D:response>\n")
buf.WriteString(fmt.Sprintf(" <D:href>%s</D:href>\n", xmlEscape(itemHref)))
buf.WriteString(" <D:propstat>\n")
buf.WriteString(" <D:prop>\n")
buf.WriteString(fmt.Sprintf(" <D:displayname>%s</D:displayname>\n", xmlEscape(name)))
buf.WriteString(" <D:resourcetype/>\n")
buf.WriteString(fmt.Sprintf(" <D:getcontentlength>%d</D:getcontentlength>\n", obj.Size))
buf.WriteString(fmt.Sprintf(" <D:getcontenttype>%s</D:getcontenttype>\n", mime))
buf.WriteString(fmt.Sprintf(" <D:getlastmodified>%s</D:getlastmodified>\n", lastMod))
buf.WriteString(" </D:prop>\n")
buf.WriteString(" <D:status>HTTP/1.1 200 OK</D:status>\n")
buf.WriteString(" </D:propstat>\n")
buf.WriteString(" </D:response>\n")
}
}
}
} else {
// Specific file PROPFIND
ctx := context.Background()
objInfo, err := mc.StatObject(ctx, actualBucket, objectKey, minio.StatObjectOptions{})
if err != nil {
buf.WriteString(" <D:response>\n")
buf.WriteString(fmt.Sprintf(" <D:href>%s%s</D:href>\n", xmlEscape(rootHref), xmlEscape(escapeDAVPath(objectKey))))
buf.WriteString(" <D:status>HTTP/1.1 404 Not Found</D:status>\n")
buf.WriteString(" </D:response>\n")
} else {
itemHref := rootHref + escapeDAVPath(objInfo.Key)
mime := mimeForFilename(objInfo.Key)
lastMod := objInfo.LastModified.UTC().Format(http.TimeFormat)
name := filepath.Base(objInfo.Key)
buf.WriteString(" <D:response>\n")
buf.WriteString(fmt.Sprintf(" <D:href>%s</D:href>\n", xmlEscape(itemHref)))
buf.WriteString(" <D:propstat>\n")
buf.WriteString(" <D:prop>\n")
buf.WriteString(fmt.Sprintf(" <D:displayname>%s</D:displayname>\n", xmlEscape(name)))
buf.WriteString(" <D:resourcetype/>\n")
buf.WriteString(fmt.Sprintf(" <D:getcontentlength>%d</D:getcontentlength>\n", objInfo.Size))
buf.WriteString(fmt.Sprintf(" <D:getcontenttype>%s</D:getcontenttype>\n", mime))
buf.WriteString(fmt.Sprintf(" <D:getlastmodified>%s</D:getlastmodified>\n", lastMod))
buf.WriteString(" </D:prop>\n")
buf.WriteString(" <D:status>HTTP/1.1 200 OK</D:status>\n")
buf.WriteString(" </D:propstat>\n")
buf.WriteString(" </D:response>\n")
}
}
buf.WriteString("</D:multistatus>\n")
w.Write([]byte(buf.String()))
}
func renderNASDirectoryIndex(w http.ResponseWriter, username, displayBucket string, tracks []MornyeTrackItem) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, PROPFIND")
w.Header().Set("Access-Control-Allow-Headers", "Range, Authorization, Content-Type, Depth")
w.Header().Set("DAV", "1, 2")
var buf strings.Builder
buf.WriteString("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n")
buf.WriteString(fmt.Sprintf("<html>\n<head><title>Index of /oort/%s/%s/</title></head>\n<body>\n", html.EscapeString(username), html.EscapeString(displayBucket)))
buf.WriteString(fmt.Sprintf("<h1>Index of /oort/%s/%s/</h1>\n<hr>\n<pre><a href=\"../\">Parent Directory</a>\n", html.EscapeString(username), html.EscapeString(displayBucket)))
for _, t := range tracks {
escaped := escapeDAVPath(t.Key)
displayName := t.Name
if len(displayName) > 55 {
displayName = displayName[:52] + "..."
}
padded := displayName
if len(padded) < 55 {
padded += strings.Repeat(" ", 55-len(padded))
}
buf.WriteString(fmt.Sprintf("<a href=\"%s\">%s</a> %s %10d\n", escaped, html.EscapeString(padded), t.LastModified, t.Size))
}
buf.WriteString("</pre>\n<hr>\n<address>Mornye NAS Server at cosmos.linuxguy.space Port 443</address>\n</body>\n</html>")
w.Write([]byte(buf.String()))
}
func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path string) {
idx := strings.Index(path, "/")
if idx == -1 {
trimmed := strings.Trim(path, "/")
var displayBucket, objectKey string
if idx := strings.Index(trimmed, "/"); idx != -1 {
displayBucket = trimmed[:idx]
objectKey = trimmed[idx+1:]
} else {
displayBucket = trimmed
objectKey = ""
}
if displayBucket == "" {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(404)
w.Write([]byte("<html><body><h1>404 - Not Found</h1></body></html>"))
return
}
displayBucket := path[:idx]
objectKey := path[idx+1:]
cacheKey := username + ":" + displayBucket
var actualBucket string
@@ -1156,7 +1510,7 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path
actualBucket = cached.(string)
} else {
var email, defBucket string
err := scyllaSession.Query(`SELECT email, bucket FROM cosmos.users WHERE service='oort' AND username=? ALLOW FILTERING`, username).Scan(&email, &defBucket)
err := scyllaSession.Query(`SELECT email, bucket FROM cosmos.users WHERE username=? ALLOW FILTERING`, username).Scan(&email, &defBucket)
if err != nil {
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(404)
@@ -1165,7 +1519,7 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path
}
var defDisp string
scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='oort' AND email=?`, email).Scan(&defDisp)
scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='git' AND email=?`, email).Scan(&defDisp)
if defDisp == "" {
defDisp = "mybucket"
}
@@ -1196,21 +1550,163 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path
publicBucketCache.Store(cacheKey, actualBucket)
}
// WebDAV OPTIONS method handling
if r.Method == "OPTIONS" {
w.Header().Set("DAV", "1, 2")
w.Header().Set("MS-Author-Via", "DAV")
w.Header().Set("Allow", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PROPFIND, MKCOL, COPY, MOVE")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PROPFIND, MKCOL, COPY, MOVE")
w.Header().Set("Access-Control-Allow-Headers", "Depth, Content-Type, Authorization, Range, X-Requested-With")
w.Header().Set("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges, DAV")
w.WriteHeader(http.StatusOK)
return
}
// WebDAV PROPFIND method handling
if r.Method == "PROPFIND" {
handleWebDAVPropfind(w, r, username, displayBucket, actualBucket, objectKey)
return
}
// Check if this is a Mornye NAS root, index.json, or playlist.m3u request
isPlaylist := objectKey == "playlist.m3u" || objectKey == "mornye.m3u" || r.URL.Query().Get("format") == "m3u"
isJSON := objectKey == "index.json" || objectKey == "mornye.json" || r.URL.Query().Get("format") == "json" || strings.Contains(r.Header.Get("Accept"), "application/json")
isRoot := (objectKey == "")
if isRoot && r.Method == "HEAD" {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("DAV", "1, 2")
w.WriteHeader(http.StatusOK)
return
}
if isRoot || isPlaylist || isJSON {
mc, err := minio.New(minioEndpoint, &minio.Options{
Creds: credentials.NewStaticV4("unityadmin", "UnityAdmin2026!", ""),
Secure: false,
})
if err != nil {
http.Error(w, "NAS storage backend error", 500)
return
}
var tracks []MornyeTrackItem
var totalBytes int64 = 0
ctx := context.Background()
for obj := range mc.ListObjects(ctx, actualBucket, minio.ListObjectsOptions{Recursive: true}) {
if obj.Err == nil && !strings.HasSuffix(obj.Key, "/") {
lower := strings.ToLower(obj.Key)
ext := strings.TrimPrefix(filepath.Ext(lower), ".")
name := filepath.Base(obj.Key)
title := strings.TrimSuffix(name, filepath.Ext(name))
displayTitle := strings.ReplaceAll(title, "_", " ")
isAudio := ext == "flac" || ext == "mp3" || ext == "wav" || ext == "m4a" || ext == "aac" || ext == "ogg" || ext == "opus" || ext == "alac"
if isAudio || isRoot {
streamURL := fmt.Sprintf("https://cosmos.linuxguy.space/oort/%s/%s/%s", username, displayBucket, escapeDAVPath(obj.Key))
tracks = append(tracks, MornyeTrackItem{
Key: obj.Key,
Name: name,
Title: displayTitle,
Size: obj.Size,
Format: strings.ToUpper(ext),
StreamURL: streamURL,
LastModified: obj.LastModified.Format(time.RFC3339),
})
totalBytes += obj.Size
}
}
}
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, PROPFIND")
w.Header().Set("DAV", "1, 2")
if isPlaylist {
w.Header().Set("Content-Type", "audio/x-mpegurl; charset=utf-8")
w.Header().Set("Content-Disposition", fmt.Sprintf("inline; filename=\"%s-mornye.m3u\"", displayBucket))
var buf strings.Builder
buf.WriteString("#EXTM3U\n")
buf.WriteString(fmt.Sprintf("#PLAYLIST:Mornye NAS - %s - %s\n\n", username, displayBucket))
for _, t := range tracks {
buf.WriteString(fmt.Sprintf("#EXTINF:-1,%s\n%s\n", t.Title, t.StreamURL))
}
w.Write([]byte(buf.String()))
return
}
if isJSON {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
json.NewEncoder(w).Encode(map[string]any{
"service": "Mornye NAS",
"version": "2.0",
"status": "online",
"account": username,
"bucket": displayBucket,
"nas_url": fmt.Sprintf("https://cosmos.linuxguy.space/oort/%s/%s/", username, displayBucket),
"playlist_url": fmt.Sprintf("https://cosmos.linuxguy.space/oort/%s/%s/playlist.m3u", username, displayBucket),
"s3_endpoint": "https://cosmos.linuxguy.space",
"tracks_count": len(tracks),
"total_bytes": totalBytes,
"tracks": tracks,
})
return
}
// NAS Root: Pure Directory Index for Mornye / HTTP(S) network storage
renderNASDirectoryIndex(w, username, displayBucket, tracks)
return
}
targetPath := fmt.Sprintf("/%s/%s", actualBucket, objectKey)
targetUrl, _ := url.Parse("http://127.0.0.1:9000")
targetUrl, _ := url.Parse("http://127.0.0.1:9010")
proxy := httputil.NewSingleHostReverseProxy(targetUrl)
proxy.Transport = proxyTransport
r.URL.Path = targetPath
r.URL.RawPath = targetPath
// CRITICAL: Strip any Authorization header before proxying to MinIO.
// Mornye or WebDAV clients often send HTTP Basic Auth, which MinIO rejects with 400 InvalidRequest.
r.Header.Del("Authorization")
proxy.ModifyResponse = func(resp *http.Response) error {
if resp.StatusCode == 403 {
resp.StatusCode = 403
resp.Body = io.NopCloser(strings.NewReader("<html><body><h1>403 - Access Denied</h1><p>Public access is not enabled for this bucket.</p></body></html>"))
resp.Header.Set("Content-Length", fmt.Sprintf("%d", len("<html><body><h1>403 - Access Denied</h1><p>Public access is not enabled for this bucket.</p></body></html>")))
resp.Body = io.NopCloser(strings.NewReader("<html><body><h1>403 - Access Denied</h1><p>Public streaming access is not enabled for this Mornye NAS bucket. Enable public streaming in Oort NAS Console.</p></body></html>"))
resp.Header.Set("Content-Length", fmt.Sprintf("%d", len("<html><body><h1>403 - Access Denied</h1><p>Public streaming access is not enabled for this Mornye NAS bucket. Enable public streaming in Oort NAS Console.</p></body></html>")))
resp.Header.Set("Content-Type", "text/html")
return nil
}
resp.Header.Set("Access-Control-Allow-Origin", "*")
resp.Header.Set("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
resp.Header.Set("Access-Control-Allow-Headers", "Range, Authorization, Content-Type")
resp.Header.Set("Access-Control-Expose-Headers", "Content-Range, Content-Length, Accept-Ranges")
resp.Header.Set("Accept-Ranges", "bytes")
lowerKey := strings.ToLower(objectKey)
switch {
case strings.HasSuffix(lowerKey, ".flac"):
resp.Header.Set("Content-Type", "audio/flac")
case strings.HasSuffix(lowerKey, ".mp3"):
resp.Header.Set("Content-Type", "audio/mpeg")
case strings.HasSuffix(lowerKey, ".wav"):
resp.Header.Set("Content-Type", "audio/wav")
case strings.HasSuffix(lowerKey, ".m4a"):
resp.Header.Set("Content-Type", "audio/mp4")
case strings.HasSuffix(lowerKey, ".aac"):
resp.Header.Set("Content-Type", "audio/aac")
case strings.HasSuffix(lowerKey, ".ogg"):
resp.Header.Set("Content-Type", "audio/ogg")
case strings.HasSuffix(lowerKey, ".opus"):
resp.Header.Set("Content-Type", "audio/opus")
case strings.HasSuffix(lowerKey, ".lrc"):
resp.Header.Set("Content-Type", "text/plain; charset=utf-8")
}
return nil
}
@@ -1220,6 +1716,7 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path
recordHit(actualBucket, tw.statusCode, tw.bytes, false, r.Header.Get("CF-IPCountry"), "read")
}
func handleS3BucketSettings(w http.ResponseWriter, r *http.Request) {
ak, _, defBucket, ok := authS3Console(r)
if !ok {
@@ -1483,7 +1980,7 @@ func handleS3Analytics(w http.ResponseWriter, r *http.Request) {
}
var disp string
if b == defBucket {
scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='oort' AND email=?`, ak).Scan(&disp)
scyllaSession.Query(`SELECT bucket_display_name FROM cosmos.users WHERE service='git' AND email=?`, ak).Scan(&disp)
if disp == "" { disp = "mybucket" }
} else {
scyllaSession.Query(`SELECT display_name FROM cosmos.buckets WHERE bucket_name = ?`, b).Scan(&disp)
@@ -1691,7 +2188,7 @@ func handleS3CDNProxy(w http.ResponseWriter, r *http.Request) {
targetPath := "/" + bucket + "/" + key
targetUrl, _ := url.Parse("http://127.0.0.1:9000")
targetUrl, _ := url.Parse("http://127.0.0.1:9010")
proxy := httputil.NewSingleHostReverseProxy(targetUrl)
proxy.Director = func(req *http.Request) {
req.URL.Scheme = targetUrl.Scheme
+1066
View File
File diff suppressed because it is too large Load Diff
+1340
View File
File diff suppressed because it is too large Load Diff
+496
View File
@@ -0,0 +1,496 @@
package main
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
)
// DockerClient returns an http.Client communicating directly with the Docker daemon unix socket.
func DockerClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", "/var/run/docker.sock")
},
},
Timeout: 0, // Infinite timeout for long-lived operations (build, stream logs)
}
}
// DockerPing verifies the Docker daemon is reachable.
func DockerPing(ctx context.Context) error {
client := DockerClient()
req, err := http.NewRequestWithContext(ctx, "GET", "http://localhost/v1.45/_ping", nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("docker ping failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("docker ping returned status %d", resp.StatusCode)
}
return nil
}
// DockerContainerSummary represents basic container metadata from Docker API.
type DockerContainerSummary struct {
ID string `json:"Id"`
Names []string `json:"Names"`
Image string `json:"Image"`
State string `json:"State"`
Status string `json:"Status"`
Created int64 `json:"Created"`
Labels map[string]string `json:"Labels"`
Ports []struct {
PrivatePort int `json:"PrivatePort"`
PublicPort int `json:"PublicPort"`
Type string `json:"Type"`
IP string `json:"IP"`
} `json:"Ports"`
}
// ListOrbitContainers returns all containers managed by Orbit (labeled with orbit=true).
func ListOrbitContainers(ctx context.Context) ([]DockerContainerSummary, error) {
client := DockerClient()
u := "http://localhost/v1.45/containers/json?all=1"
req, err := http.NewRequestWithContext(ctx, "GET", u, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var all []DockerContainerSummary
if err := json.NewDecoder(resp.Body).Decode(&all); err != nil {
return nil, err
}
var orbitContainers []DockerContainerSummary
for _, c := range all {
if c.Labels != nil && c.Labels["cosmos.orbit"] == "true" {
orbitContainers = append(orbitContainers, c)
}
}
return orbitContainers, nil
}
// InspectDockerContainer returns detailed information about a container.
func InspectDockerContainer(ctx context.Context, containerID string) (map[string]interface{}, error) {
client := DockerClient()
u := fmt.Sprintf("http://localhost/v1.45/containers/%s/json", url.PathEscape(containerID))
req, err := http.NewRequestWithContext(ctx, "GET", u, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, fmt.Errorf("container not found")
}
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, err
}
return data, nil
}
// StartDockerContainer starts a stopped container.
func StartDockerContainer(ctx context.Context, containerID string) error {
client := DockerClient()
u := fmt.Sprintf("http://localhost/v1.45/containers/%s/start", url.PathEscape(containerID))
req, err := http.NewRequestWithContext(ctx, "POST", u, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotModified {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to start container: %s", string(body))
}
return nil
}
// StopDockerContainer gracefully stops a container (10s timeout).
func StopDockerContainer(ctx context.Context, containerID string) error {
client := DockerClient()
u := fmt.Sprintf("http://localhost/v1.45/containers/%s/stop?t=10", url.PathEscape(containerID))
req, err := http.NewRequestWithContext(ctx, "POST", u, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotModified {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to stop container: %s", string(body))
}
return nil
}
// RestartDockerContainer restarts a container.
func RestartDockerContainer(ctx context.Context, containerID string) error {
client := DockerClient()
u := fmt.Sprintf("http://localhost/v1.45/containers/%s/restart?t=10", url.PathEscape(containerID))
req, err := http.NewRequestWithContext(ctx, "POST", u, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to restart container: %s", string(body))
}
return nil
}
// RemoveDockerContainer stops and removes a container.
func RemoveDockerContainer(ctx context.Context, containerID string) error {
client := DockerClient()
u := fmt.Sprintf("http://localhost/v1.45/containers/%s?force=true&v=true", url.PathEscape(containerID))
req, err := http.NewRequestWithContext(ctx, "DELETE", u, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusNotFound {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to remove container: %s", string(body))
}
return nil
}
// OrbitContainerSpec holds configuration for spawning a container.
type OrbitContainerSpec struct {
Name string
Image string
Env []string
AppID string
InternalPort int // e.g. 3000, 8080
ExposedPort int // e.g. 4100
MemLimitMB int // e.g. 512
CPULimit float64 // e.g. 1.0
}
// CreateAndStartOrbitContainer creates and starts an Orbit-managed container.
func CreateAndStartOrbitContainer(ctx context.Context, spec OrbitContainerSpec) (string, error) {
client := DockerClient()
intPortStr := fmt.Sprintf("%d/tcp", spec.InternalPort)
hostPortStr := fmt.Sprintf("%d", spec.ExposedPort)
memBytes := int64(spec.MemLimitMB) * 1024 * 1024
if memBytes <= 0 {
memBytes = 512 * 1024 * 1024 // 512MB default
}
nanoCPUs := int64(spec.CPULimit * 1e9)
if nanoCPUs <= 0 {
nanoCPUs = 1e9 // 1 CPU default
}
createPayload := map[string]interface{}{
"Image": spec.Image,
"Env": spec.Env,
"Labels": map[string]string{
"cosmos.orbit": "true",
"cosmos.app_id": spec.AppID,
"cosmos.app_name": spec.Name,
},
"ExposedPorts": map[string]interface{}{
intPortStr: map[string]interface{}{},
},
"HostConfig": map[string]interface{}{
"PortBindings": map[string]interface{}{
intPortStr: []map[string]string{
{
"HostIp": "0.0.0.0",
"HostPort": hostPortStr,
},
},
},
"RestartPolicy": map[string]string{
"Name": "unless-stopped",
},
"Memory": memBytes,
"NanoCpus": nanoCPUs,
},
}
payloadBytes, err := json.Marshal(createPayload)
if err != nil {
return "", err
}
createURL := fmt.Sprintf("http://localhost/v1.45/containers/create?name=%s", url.QueryEscape("orbit-"+spec.AppID))
req, err := http.NewRequestWithContext(ctx, "POST", createURL, bytes.NewReader(payloadBytes))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("create container request failed: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
body, _ := io.ReadAll(resp.Body)
return "", fmt.Errorf("docker create returned %d: %s", resp.StatusCode, string(body))
}
var res struct {
ID string `json:"Id"`
}
if err := json.NewDecoder(resp.Body).Decode(&res); err != nil {
return "", err
}
// Start the container
if err := StartDockerContainer(ctx, res.ID); err != nil {
// Clean up on failure
_ = RemoveDockerContainer(ctx, res.ID)
return "", fmt.Errorf("failed to start container: %w", err)
}
return res.ID, nil
}
// BuildDockerImage builds a Docker image from a tar stream of the build context.
func BuildDockerImage(ctx context.Context, tarStream io.Reader, tag string, logWriter io.Writer) error {
client := DockerClient()
buildURL := fmt.Sprintf("http://localhost/v1.45/build?t=%s&rm=1&forcerm=1", url.QueryEscape(tag))
req, err := http.NewRequestWithContext(ctx, "POST", buildURL, tarStream)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/x-tar")
resp, err := client.Do(req)
if err != nil {
return fmt.Errorf("build request failed: %w", err)
}
defer resp.Body.Close()
// Stream build JSON messages: {"stream": "Step 1/5 : FROM alpine\n"}
dec := json.NewDecoder(resp.Body)
for {
var msg struct {
Stream string `json:"stream"`
Error string `json:"error"`
Status string `json:"status"`
}
if err := dec.Decode(&msg); err != nil {
if err == io.EOF {
break
}
return err
}
if msg.Error != "" {
if logWriter != nil {
fmt.Fprintf(logWriter, "ERROR: %s\n", msg.Error)
}
return fmt.Errorf("docker build error: %s", msg.Error)
}
if msg.Stream != "" && logWriter != nil {
io.WriteString(logWriter, msg.Stream)
} else if msg.Status != "" && logWriter != nil {
fmt.Fprintf(logWriter, "%s\n", msg.Status)
}
}
return nil
}
// ContainerLiveStats holds live CPU, RAM, and network metrics.
type ContainerLiveStats struct {
CPUPct float64 `json:"cpu_percent"`
MemUsageMB float64 `json:"mem_usage_mb"`
MemLimitMB float64 `json:"mem_limit_mb"`
MemPct float64 `json:"mem_percent"`
NetRxMB float64 `json:"net_rx_mb"`
NetTxMB float64 `json:"net_tx_mb"`
}
// GetContainerStats queries live resource utilization for a container.
func GetContainerStats(ctx context.Context, containerID string) (*ContainerLiveStats, error) {
client := DockerClient()
u := fmt.Sprintf("http://localhost/v1.45/containers/%s/stats?stream=false", url.PathEscape(containerID))
req, err := http.NewRequestWithContext(ctx, "GET", u, nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("docker stats returned status %d", resp.StatusCode)
}
var s struct {
CPUStats struct {
CPUUsage struct {
TotalUsage uint64 `json:"total_usage"`
PercpuUsage []uint64 `json:"percpu_usage"`
} `json:"cpu_usage"`
SystemCPUUsage uint64 `json:"system_cpu_usage"`
OnlineCPUs int `json:"online_cpus"`
} `json:"cpu_stats"`
PreCPUStats struct {
CPUUsage struct {
TotalUsage uint64 `json:"total_usage"`
} `json:"cpu_usage"`
SystemCPUUsage uint64 `json:"system_cpu_usage"`
} `json:"precpu_stats"`
MemoryStats struct {
Usage uint64 `json:"usage"`
Limit uint64 `json:"limit"`
} `json:"memory_stats"`
Networks map[string]struct {
RxBytes uint64 `json:"rx_bytes"`
TxBytes uint64 `json:"tx_bytes"`
} `json:"networks"`
}
if err := json.NewDecoder(resp.Body).Decode(&s); err != nil {
return nil, err
}
// Calculate CPU %
cpuDelta := float64(s.CPUStats.CPUUsage.TotalUsage) - float64(s.PreCPUStats.CPUUsage.TotalUsage)
systemDelta := float64(s.CPUStats.SystemCPUUsage) - float64(s.PreCPUStats.SystemCPUUsage)
cpuPct := 0.0
numCPUs := s.CPUStats.OnlineCPUs
if numCPUs <= 0 {
numCPUs = len(s.CPUStats.CPUUsage.PercpuUsage)
}
if numCPUs <= 0 {
numCPUs = 1
}
if systemDelta > 0 && cpuDelta > 0 {
cpuPct = (cpuDelta / systemDelta) * float64(numCPUs) * 100.0
}
// Memory
memMB := float64(s.MemoryStats.Usage) / (1024 * 1024)
limitMB := float64(s.MemoryStats.Limit) / (1024 * 1024)
memPct := 0.0
if limitMB > 0 {
memPct = (memMB / limitMB) * 100.0
}
// Network
var rxTotal, txTotal uint64
for _, n := range s.Networks {
rxTotal += n.RxBytes
txTotal += n.TxBytes
}
return &ContainerLiveStats{
CPUPct: cpuPct,
MemUsageMB: memMB,
MemLimitMB: limitMB,
MemPct: memPct,
NetRxMB: float64(rxTotal) / (1024 * 1024),
NetTxMB: float64(txTotal) / (1024 * 1024),
}, nil
}
// StreamDockerLogs streams container stdout/stderr. Docker demultiplexes with 8-byte frames.
func StreamDockerLogs(ctx context.Context, containerID string, tail string, follow bool, w io.Writer) error {
client := DockerClient()
followVal := "0"
if follow {
followVal = "1"
}
if tail == "" {
tail = "200"
}
u := fmt.Sprintf("http://localhost/v1.45/containers/%s/logs?stdout=1&stderr=1&tail=%s&follow=%s&timestamps=1",
url.PathEscape(containerID), url.QueryEscape(tail), followVal)
req, err := http.NewRequestWithContext(ctx, "GET", u, nil)
if err != nil {
return err
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("failed to fetch logs: %s", string(body))
}
// Demultiplex Docker log stream:
// Header: 8 bytes -> [STREAM_TYPE, 0, 0, 0, SIZE1, SIZE2, SIZE3, SIZE4]
hdr := make([]byte, 8)
for {
select {
case <-ctx.Done():
return nil
default:
}
_, err := io.ReadFull(resp.Body, hdr)
if err != nil {
if err == io.EOF || strings.Contains(err.Error(), "closed") {
return nil
}
return err
}
payloadSize := binary.BigEndian.Uint32(hdr[4:8])
if payloadSize > 0 {
// Read payload
lr := io.LimitReader(resp.Body, int64(payloadSize))
if _, err := io.Copy(w, lr); err != nil {
return err
}
if f, ok := w.(http.Flusher); ok {
f.Flush()
}
}
}
}
File diff suppressed because it is too large Load Diff
+1209 -333
View File
File diff suppressed because it is too large Load Diff
+1273 -1025
View File
File diff suppressed because it is too large Load Diff
+679 -185
View File
@@ -3,120 +3,516 @@
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Sign In — Cosmos Storage</title>
<meta name="description" content="Sign in to your Cosmos Storage account."/>
<title>Sign In — Cosmos {{.Service}}</title>
<meta name="description" content="Sign in to your Cosmos {{.Service}} sovereign workspace."/>
<link rel="icon" href='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="6" fill="%23eef3f8"/><ellipse cx="16" cy="16" rx="14" ry="5.5" fill="none" stroke="%238fd9ff" stroke-width="1.5" transform="rotate(-24 16 16)"/></svg>'/>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@1&family=JetBrains+Mono:wght@300;400;500&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@1&family=JetBrains+Mono:wght@300;400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet"/>
<style>
:root{--bg:#020308;--ink:#eef3f8;--dim:rgba(226,234,242,.55);--faint:rgba(226,234,242,.3);--line:rgba(226,234,242,.08);--ok:#43e5a0;--ac:143,216,255;--mono:'JetBrains Mono',ui-monospace,monospace;--disp:'Space Grotesk',sans-serif;--serif:'Instrument Serif',serif;--pad:clamp(24px,5vw,84px);--ez:cubic-bezier(.16,1,.3,1)}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html,body{min-height:100%}
body{font-family:var(--disp);background:var(--bg);color:var(--ink);min-height:100vh;min-height:100svh;display:flex;flex-direction:column;overflow-x:hidden;-webkit-font-smoothing:antialiased;animation:bootIn 1s ease both}
@keyframes bootIn{from{opacity:0}}
::selection{background:rgba(var(--ac),.3)}
a:focus-visible,button:focus-visible{outline:1px solid rgba(238,243,248,.55);outline-offset:4px;border-radius:4px}
#sky{position:fixed;inset:0;z-index:0;pointer-events:none}
.grain{position:fixed;inset:-8%;z-index:2;pointer-events:none;opacity:.05;background-image:url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");background-size:180px 180px;animation:grain .9s steps(3) infinite}
@keyframes grain{0%,100%{transform:translate(0,0)}33%{transform:translate(-1.4%,1%)}66%{transform:translate(1%,-1.4%)}}
.vig{position:fixed;inset:0;z-index:2;pointer-events:none;background:radial-gradient(ellipse at 50% 42%,transparent 55%,rgba(1,2,8,.55) 100%)}
.authbar{position:relative;z-index:10;display:flex;justify-content:space-between;align-items:center;padding:28px var(--pad) 12px;font-family:var(--mono);font-size:9.5px;letter-spacing:.22em;text-transform:uppercase;animation:softUp .9s var(--ez) both}
.authbar a{color:var(--dim);text-decoration:none;transition:color .25s}
.authbar a:hover{color:#fff}
.authbar .svc{color:rgba(226,234,242,.3);display:flex;align-items:center;gap:10px}
.authbar .svc::before{content:'';width:5px;height:5px;border-radius:50%;background:var(--ok);box-shadow:0 0 8px var(--ok);animation:dotPulse 2.4s ease infinite}
@keyframes dotPulse{0%,100%{opacity:1}50%{opacity:.35}}
@keyframes softUp{from{opacity:0;transform:translateY(20px)}}
.auth-shell{position:relative;z-index:10;flex:1;display:grid;place-items:center;padding:20px var(--pad) 60px}
.cardbox{width:100%;display:flex;justify-content:center;animation:softUp .9s .15s var(--ez) both}
.card{width:100%;max-width:440px;background:rgba(6,10,20,.72);border:1px solid var(--line);border-radius:18px;padding:44px 40px 40px;backdrop-filter:blur(24px);-webkit-backdrop-filter:blur(24px);box-shadow:0 30px 80px rgba(0,0,4,.55);position:relative;transition:transform .5s var(--ez);will-change:transform}
.cnr{position:absolute;width:16px;height:16px;border:1px solid rgba(var(--ac),.4);transition:border-color .35s,width .35s var(--ez),height .35s var(--ez)}
.c1{top:-1px;left:-1px;border-right:0;border-bottom:0;border-top-left-radius:6px}
.c2{top:-1px;right:-1px;border-left:0;border-bottom:0;border-top-right-radius:6px}
.c3{bottom:-1px;left:-1px;border-right:0;border-top:0;border-bottom-left-radius:6px}
.c4{bottom:-1px;right:-1px;border-left:0;border-top:0;border-bottom-right-radius:6px}
.card:focus-within .cnr{border-color:rgba(var(--ac),.95);width:22px;height:22px;box-shadow:0 0 12px rgba(var(--ac),.15)}
.brand{display:flex;align-items:center;gap:12px;text-decoration:none;color:var(--ink);margin-bottom:34px}
.brand .mark{width:34px;height:34px;animation:markSpin 16s linear infinite}
@keyframes markSpin{to{transform:rotate(360deg)}}
.brand b{font-size:18px;font-weight:600;letter-spacing:-.02em}
.brand b em{font-family:var(--serif);font-style:italic;font-weight:400;color:rgb(var(--ac))}
.h-t{font-size:27px;font-weight:600;letter-spacing:-.03em;margin-bottom:8px}
.h-s{font-size:14.5px;color:var(--dim);margin-bottom:32px}
.error-box{background:rgba(248,113,113,.08);border:1px solid rgba(248,113,113,.3);border-radius:10px;padding:12px 16px;margin-bottom:22px;font-size:13.5px;color:#f87171;font-weight:500;display:none}
.error-box.visible{display:block}
.fg{margin-bottom:20px}
.fl{display:block;font-family:var(--mono);font-size:9.5px;font-weight:500;letter-spacing:.18em;text-transform:uppercase;color:rgba(226,234,242,.5);margin-bottom:9px}
.fc{width:100%;background:rgba(226,234,242,.03);border:1px solid rgba(226,234,242,.1);color:#fff;padding:13px 16px;border-radius:11px;font-size:14.5px;font-weight:500;font-family:inherit;outline:none;transition:border-color .25s,box-shadow .25s,background .25s}
.fc::placeholder{color:rgba(226,234,242,.28)}
.fc:focus{border-color:rgba(var(--ac),.55);box-shadow:0 0 0 3px rgba(var(--ac),.14);background:rgba(226,234,242,.05)}
.pwd-wrap{position:relative}
.pwd-wrap .fc{padding-right:48px}
.pwd-toggle{position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;cursor:pointer;color:rgba(226,234,242,.35);display:flex;padding:6px;transition:color .2s}
.pwd-toggle:hover{color:var(--ink)}
.pwd-toggle svg{width:18px;height:18px}
.pwd-toggle .slash{display:none}
.pwd-toggle.shown .slash{display:block}
.caps-warn{display:none;font-family:var(--mono);font-size:9.5px;letter-spacing:.16em;color:#fbbf24;margin-top:8px;align-items:center;gap:7px;text-transform:uppercase}
.caps-warn.on{display:flex}
.caps-warn i{width:5px;height:5px;background:#fbbf24;border-radius:1px;box-shadow:0 0 8px #fbbf24;flex:none}
.btn-submit{width:100%;padding:14px 24px;border-radius:11px;border:none;background:#fff;color:#04060d;font-family:inherit;font-size:14.5px;font-weight:700;cursor:pointer;letter-spacing:-.01em;box-shadow:0 8px 34px rgba(255,255,255,.1);transition:all .25s;margin-top:6px}
.btn-submit:hover{box-shadow:0 14px 54px rgba(255,255,255,.2)}
.btn-submit:active{transform:scale(.985)}
.btn-submit:disabled{opacity:.75;cursor:progress}
.auth-footer{text-align:center;margin-top:26px;font-size:13.5px;color:rgba(226,234,242,.4)}
.auth-footer a{color:rgb(var(--ac));text-decoration:none;font-weight:600;transition:color .2s}
.auth-footer a:hover{color:#fff}
.authfoot{position:relative;z-index:10;padding:20px var(--pad);display:flex;justify-content:center;font-family:var(--mono);font-size:9px;letter-spacing:.22em;color:rgba(226,234,242,.22);text-transform:uppercase;gap:18px;flex-wrap:wrap}
@media(max-width:480px){.card{padding:36px 26px 32px}.authbar{padding-top:24px}}
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation-duration:.01ms!important;transition-duration:.01ms!important}}
:root {
--bg: #020308;
--ink: #eef3f8;
--dim: rgba(226, 234, 242, 0.58);
--faint: rgba(226, 234, 242, 0.32);
--line: rgba(226, 234, 242, 0.08);
--line-strong: rgba(226, 234, 242, 0.16);
--ok: #43e5a0;
--ac: 143, 216, 255;
--ac-rgb: 143, 216, 255;
--mono: 'JetBrains Mono', ui-monospace, monospace;
--disp: 'Space Grotesk', -apple-system, sans-serif;
--serif: 'Instrument Serif', Georgia, serif;
--pad: clamp(24px, 5vw, 72px);
--ez: cubic-bezier(0.16, 1, 0.3, 1);
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
html, body { min-height: 100%; }
body {
font-family: var(--disp);
background: var(--bg);
color: var(--ink);
min-height: 100vh;
min-height: 100svh;
display: flex;
flex-direction: column;
overflow-x: hidden;
-webkit-font-smoothing: antialiased;
position: relative;
selection-background: rgba(var(--ac-rgb), 0.3);
}
::selection { background: rgba(var(--ac-rgb), 0.3); color: #fff; }
a:focus-visible, button:focus-visible, input:focus-visible {
outline: 1px solid rgba(var(--ac-rgb), 0.7);
outline-offset: 3px;
border-radius: 6px;
}
/* ── 3D Viewport & Atmospheric Layers ── */
#webgl-bg {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
z-index: 1;
pointer-events: none;
}
.noise-overlay {
position: fixed;
inset: -10%;
width: 120%;
height: 120%;
z-index: 2;
pointer-events: none;
opacity: 0.045;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-size: 160px 160px;
}
.radial-vignette {
position: fixed;
inset: 0;
z-index: 2;
pointer-events: none;
background: radial-gradient(ellipse at 50% 45%, transparent 40%, rgba(2, 3, 8, 0.7) 85%, #020308 100%);
}
/* ── Top Navigation Bar ── */
.authbar {
position: relative;
z-index: 10;
display: flex;
justify-content: space-between;
align-items: center;
padding: 28px var(--pad) 12px;
font-family: var(--mono);
font-size: 10px;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.authbar a.back-link {
color: var(--dim);
text-decoration: none;
display: inline-flex;
align-items: center;
gap: 8px;
transition: color 0.25s, transform 0.25s var(--ez);
}
.authbar a.back-link:hover {
color: #fff;
transform: translateX(-3px);
}
.authbar .channel-badge {
display: inline-flex;
align-items: center;
gap: 9px;
padding: 5px 12px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.03);
border: 1px solid var(--line);
color: var(--dim);
font-size: 9.5px;
backdrop-filter: blur(10px);
}
.authbar .pulse-dot {
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--ok);
box-shadow: 0 0 10px var(--ok);
animation: dotPulse 2.4s ease infinite;
}
@keyframes dotPulse {
0%, 100% { opacity: 1; transform: scale(1); }
50% { opacity: 0.4; transform: scale(0.85); }
}
/* ── Main Auth Card Container ── */
.auth-shell {
position: relative;
z-index: 10;
flex: 1;
display: grid;
place-items: center;
padding: 20px var(--pad) 50px;
perspective: 1200px;
}
.card-wrapper {
width: 100%;
max-width: 440px;
will-change: transform;
}
/* ── Signature Stuudio/Jockey Floating 3D Card with Conic Edge Lighting ── */
.card-3d {
position: relative;
border-radius: 20px;
padding: 44px 38px 40px;
background: linear-gradient(145deg, rgba(10, 15, 28, 0.82), rgba(4, 7, 14, 0.88)) padding-box,
conic-gradient(from var(--rim-angle, 0deg) at var(--mx, 50%) var(--my, 50%),
rgba(143, 216, 255, 0.85) 0deg,
rgba(255, 255, 255, 0.1) 60deg,
rgba(143, 216, 255, 0.05) 160deg,
rgba(143, 216, 255, 0.45) 260deg,
rgba(143, 216, 255, 0.85) 360deg) border-box;
border: 1px solid transparent;
backdrop-filter: blur(28px);
-webkit-backdrop-filter: blur(28px);
box-shadow: 0 35px 85px rgba(0, 0, 0, 0.65), 0 0 50px rgba(143, 216, 255, 0.05);
transform-style: preserve-3d;
transition: transform 0.2s cubic-bezier(0.2, 0.8, 0.3, 1), box-shadow 0.3s;
}
.card-3d:hover {
box-shadow: 0 45px 100px rgba(0, 0, 0, 0.75), 0 0 60px rgba(143, 216, 255, 0.1);
}
/* Corner Reticle Accents */
.cnr {
position: absolute;
width: 14px;
height: 14px;
border: 1px solid rgba(var(--ac-rgb), 0.35);
pointer-events: none;
transition: border-color 0.3s, width 0.3s var(--ez), height 0.3s var(--ez);
}
.c1 { top: -1px; left: -1px; border-right: 0; border-bottom: 0; border-top-left-radius: 8px; }
.c2 { top: -1px; right: -1px; border-left: 0; border-bottom: 0; border-top-right-radius: 8px; }
.c3 { bottom: -1px; left: -1px; border-right: 0; border-top: 0; border-bottom-left-radius: 8px; }
.c4 { bottom: -1px; right: -1px; border-left: 0; border-top: 0; border-bottom-right-radius: 8px; }
.card-3d:focus-within .cnr {
border-color: rgba(var(--ac-rgb), 0.95);
width: 20px;
height: 20px;
box-shadow: 0 0 10px rgba(var(--ac-rgb), 0.2);
}
/* ── Brand Mark ── */
.brand {
display: inline-flex;
align-items: center;
gap: 12px;
text-decoration: none;
color: var(--ink);
margin-bottom: 30px;
}
.brand-icon {
width: 34px;
height: 34px;
animation: markSpin 24s linear infinite;
flex-shrink: 0;
}
@keyframes markSpin {
to { transform: rotate(360deg); }
}
.brand-text {
font-size: 18px;
font-weight: 600;
letter-spacing: -0.02em;
}
.brand-text em {
font-family: var(--serif);
font-style: italic;
font-weight: 400;
color: rgb(var(--ac-rgb));
margin-left: 2px;
}
/* Headings */
.h-title {
font-size: 26px;
font-weight: 600;
letter-spacing: -0.03em;
margin-bottom: 8px;
color: #fff;
}
.h-sub {
font-size: 14px;
color: var(--dim);
margin-bottom: 28px;
line-height: 1.5;
}
/* Error Alert Box */
.error-box {
background: rgba(248, 113, 113, 0.08);
border: 1px solid rgba(248, 113, 113, 0.3);
border-radius: 10px;
padding: 12px 16px;
margin-bottom: 22px;
font-size: 13.5px;
color: #f87171;
font-weight: 500;
display: none;
}
.error-box.visible { display: block; }
/* ── Form Inputs ── */
.form-group {
margin-bottom: 20px;
}
.form-label {
display: block;
font-family: var(--mono);
font-size: 9.5px;
font-weight: 500;
letter-spacing: 0.16em;
text-transform: uppercase;
color: rgba(226, 234, 242, 0.6);
margin-bottom: 8px;
}
.input-ctrl {
width: 100%;
background: rgba(226, 234, 242, 0.03);
border: 1px solid var(--line-strong);
color: #fff;
padding: 13px 16px;
border-radius: 11px;
font-size: 14.5px;
font-weight: 500;
font-family: inherit;
outline: none;
transition: border-color 0.25s, box-shadow 0.25s, background 0.25s;
}
.input-ctrl::placeholder {
color: rgba(226, 234, 242, 0.28);
}
.input-ctrl:focus {
border-color: rgba(var(--ac-rgb), 0.65);
box-shadow: 0 0 0 3px rgba(var(--ac-rgb), 0.15);
background: rgba(226, 234, 242, 0.05);
}
.pwd-wrap {
position: relative;
}
.pwd-wrap .input-ctrl {
padding-right: 48px;
}
.pwd-toggle {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
background: none;
border: none;
cursor: pointer;
color: rgba(226, 234, 242, 0.38);
display: flex;
padding: 6px;
transition: color 0.2s;
}
.pwd-toggle:hover {
color: var(--ink);
}
.pwd-toggle svg { width: 18px; height: 18px; }
.pwd-toggle .slash { display: none; }
.pwd-toggle.shown .slash { display: block; }
.caps-warn {
display: none;
font-family: var(--mono);
font-size: 9.5px;
letter-spacing: 0.14em;
color: #fbbf24;
margin-top: 8px;
align-items: center;
gap: 7px;
text-transform: uppercase;
}
.caps-warn.on { display: flex; }
.caps-warn i {
width: 5px;
height: 5px;
background: #fbbf24;
border-radius: 1px;
box-shadow: 0 0 8px #fbbf24;
flex: none;
}
.forgot-link-row {
text-align: right;
margin-top: 9px;
}
.forgot-link-row a {
font-size: 12.5px;
color: rgba(226, 234, 242, 0.45);
text-decoration: none;
font-family: var(--mono);
letter-spacing: 0.04em;
transition: color 0.2s;
}
.forgot-link-row a:hover {
color: rgb(var(--ac-rgb));
}
/* ── Magnetic Submit Button ── */
.btn-submit {
width: 100%;
padding: 14px 24px;
border-radius: 11px;
border: none;
background: #fff;
color: #04060d;
font-family: inherit;
font-size: 14.5px;
font-weight: 700;
cursor: pointer;
letter-spacing: -0.01em;
box-shadow: 0 8px 30px rgba(255, 255, 255, 0.12);
transition: transform 0.2s var(--ez), box-shadow 0.25s, opacity 0.25s;
margin-top: 6px;
position: relative;
overflow: hidden;
}
.btn-submit:hover {
box-shadow: 0 12px 40px rgba(255, 255, 255, 0.22);
transform: translateY(-1px);
}
.btn-submit:active {
transform: scale(0.985);
}
.btn-submit:disabled {
opacity: 0.75;
cursor: wait;
}
/* ── Auth Footer ── */
.auth-footer {
text-align: center;
margin-top: 26px;
font-size: 13.5px;
color: rgba(226, 234, 242, 0.42);
}
.auth-footer a {
color: rgb(var(--ac-rgb));
text-decoration: none;
font-weight: 600;
margin-left: 4px;
transition: color 0.2s;
}
.auth-footer a:hover {
color: #fff;
}
/* ── Page Footer ── */
.authfoot {
position: relative;
z-index: 10;
padding: 20px var(--pad);
display: flex;
justify-content: center;
font-family: var(--mono);
font-size: 9px;
letter-spacing: 0.2em;
color: rgba(226, 234, 242, 0.25);
text-transform: uppercase;
gap: 18px;
flex-wrap: wrap;
}
@media (max-width: 480px) {
.card-3d { padding: 36px 24px 30px; }
.authbar { padding-top: 20px; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
</style>
</head>
<body>
<canvas id="sky" aria-hidden="true"></canvas>
<div class="grain" aria-hidden="true"></div>
<div class="vig" aria-hidden="true"></div>
<!-- Three.js Ambient 3D Starfield & Orbital Precession Viewport -->
<div id="webgl-bg" aria-hidden="true"></div>
<div class="noise-overlay" aria-hidden="true"></div>
<div class="radial-vignette" aria-hidden="true"></div>
<header class="authbar">
<a href="/">&#8592; Cosmos</a>
<span class="svc"><span data-scr>SECURE CHANNEL · {{.Service}}</span></span>
<a href="/" class="back-link">&#8592; Cosmos Core</a>
<div class="channel-badge">
<span class="pulse-dot"></span>
<span data-scr>SECURE CHANNEL · {{.Service}}</span>
</div>
</header>
<main class="auth-shell">
<div class="cardbox">
<div class="card" id="card">
<div class="card-wrapper" id="cardWrapper">
<div class="card-3d" id="card">
<i class="cnr c1"></i><i class="cnr c2"></i><i class="cnr c3"></i><i class="cnr c4"></i>
<a href="/" class="brand">
<svg class="mark" viewBox="0 0 34 34" aria-hidden="true"><ellipse cx="17" cy="17" rx="14.5" ry="6" fill="none" stroke="rgba(238,243,248,.55)" stroke-width="1" transform="rotate(-24 17 17)"/><circle cx="17" cy="17" r="4.4" fill="#eef3f8"/><circle cx="27.4" cy="12.2" r="1.8" fill="rgb(var(--ac))"/></svg>
<b>Cosmos <em>Oort</em></b>
<svg class="brand-icon" viewBox="0 0 34 34" aria-hidden="true">
<ellipse cx="17" cy="17" rx="14.5" ry="6" fill="none" stroke="rgba(238,243,248,.55)" stroke-width="1.2" transform="rotate(-24 17 17)"/>
<circle cx="17" cy="17" r="4.4" fill="#eef3f8"/>
<circle cx="27.4" cy="12.2" r="1.8" fill="rgb(var(--ac-rgb))"/>
</svg>
<span class="brand-text">Cosmos <em>{{.Service}}</em></span>
</a>
<div class="h-t">Welcome back</div>
<div class="h-s">Sign in to your account to continue</div>
<h1 class="h-title">Welcome back</h1>
<p class="h-sub">Sign in to your sovereign enclave to continue</p>
{{if .Error}}
<div class="error-box visible">{{.Error}}</div>
{{end}}
<form action="/{{.Service}}/login" method="POST" id="loginForm">
<div class="fg">
<label class="fl" for="lg-email">Username or Email</label>
<input type="text" id="lg-email" name="email" class="fc" placeholder="janedoe or [email protected]" required autocomplete="username"/>
<div class="form-group">
<label class="form-label" for="lg-email">Username or Email</label>
<input type="text" id="lg-email" name="email" class="input-ctrl" placeholder="janedoe or [email protected]" required autocomplete="username"/>
</div>
<div class="fg">
<label class="fl" for="pwd">Password</label>
<div class="form-group">
<label class="form-label" for="pwd">Password</label>
<div class="pwd-wrap">
<input type="password" name="password" id="pwd" class="fc" placeholder="&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;" required autocomplete="current-password"/>
<input type="password" name="password" id="pwd" class="input-ctrl" placeholder="••••••••" required autocomplete="current-password"/>
<button type="button" class="pwd-toggle" onclick="togglePwd('pwd')" aria-label="Toggle password visibility">
<svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/><line class="slash" x1="4" y1="4" x2="20" y2="20" stroke-linecap="round"/></svg>
<svg fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
<circle cx="12" cy="12" r="3"/>
<line class="slash" x1="4" y1="4" x2="20" y2="20" stroke-linecap="round"/>
</svg>
</button>
</div>
<div class="caps-warn"><i></i>Caps Lock is on</div>
<div style="text-align:right;margin-top:10px;">
<a href="/{{.Service}}/forgot-password" style="font-size:13px;color:rgba(226,234,242,.45);text-decoration:none;font-family:var(--mono);letter-spacing:.06em;transition:color .2s;" onmouseover="this.style.color='rgb(var(--ac))'" onmouseout="this.style.color='rgba(226,234,242,.45)'">Forgot password?</a>
<div class="forgot-link-row">
<a href="/{{.Service}}/forgot-password">Forgot password?</a>
</div>
</div>
@@ -132,95 +528,183 @@ a:focus-visible,button:focus-visible{outline:1px solid rgba(238,243,248,.55);out
<footer class="authfoot">
<span>51.4778° N · 0.0015° W</span>
<span>Self-hosted &amp; private</span>
<span>Zero Cloud Leakage</span>
<span>Sovereign Enclave</span>
</footer>
<!-- Local Zero-Latency Three.js Engine -->
<script src="/three.min.js"></script>
<script>
/* ── shared deterministic noise ── */
function h2(x,y,s){var h=Math.imul(x,374761393)^Math.imul(y,668265263)^Math.imul(s,974711);h=Math.imul(h^h>>>13,1274126177);return((h^h>>>16)>>>0)/4294967296}
function vn(x,y,s){var ix=Math.floor(x),iy=Math.floor(y),fx=x-ix,fy=y-iy,u=fx*fx*(3-2*fx),v=fy*fy*(3-2*fy),a=h2(ix,iy,s),b=h2(ix+1,iy,s),c=h2(ix,iy+1,s),d=h2(ix+1,iy+1,s);return a+(b-a)*u+(c-a)*v+(a-b-c+d)*u*v}
function fbm(x,y,o,s){var a=1,S=0,n=0;for(var i=0;i<o;i++){S+=a*vn(x,y,s+i*131);n+=a;a*=.5;x*=2;y*=2}return S/n}
var RMQ=matchMedia('(prefers-reduced-motion: reduce)').matches,DPRQ=Math.min(2,devicePixelRatio||1);
/* ══ 1. THREE.JS 3D CELESTIAL BACKGROUND ══ */
(function(){
'use strict';
var container = document.getElementById('webgl-bg');
if(!window.THREE || !container) return;
/* ══ SKY ENGINE ══ */
(function(){'use strict';
var cv=document.getElementById('sky');if(!cv)return;
var cx=cv.getContext('2d'),TAU=Math.PI*2,RM=RMQ,DPR=DPRQ;
var CFG={density:420,tint:[.82,.95,1.12],planet:[.15,.86,.13]};
var W,H,stars=[],meteors=[],comets=[],neb=null,nextMet=3200,nextCom=9000;
var m={x:.5,y:.5,sx:.5,sy:.5};
function resize(){W=innerWidth;H=innerHeight;cv.width=W*DPR;cv.height=H*DPR;cv.style.width=W+'px';cv.style.height=H+'px';cx.setTransform(DPR,0,0,DPR,0,0)}
function buildStars(){stars=[];var n=Math.round(CFG.density*W*H/(1440*800));for(var i=0;i<n;i++){var r=Math.pow(Math.random(),2.3)*1.9+.28,roll=Math.random();stars.push({x:Math.random(),y:Math.random(),r:r,p:.012+(r/2.2)*.06,a:.2+Math.random()*.7,tw:Math.random()*TAU,ts:.4+Math.random()*1.9,c:roll<.6?[255,255,255]:roll<.78?[201,215,255]:roll<.92?[255,238,220]:[255,208,176]})}}
function makeNeb(){var w=460,h=260,c=document.createElement('canvas');c.width=w;c.height=h;var g=c.getContext('2d'),im=g.createImageData(w,h),d=im.data,T=CFG.tint,nx=.749,ny=-.663;
for(var y=0;y<h;y++)for(var x=0;x<w;x++){var i=(y*w+x)*4,band=Math.exp(-Math.pow(((x/w-.18)*nx+(y/h-.86)*ny)/.16,2)),n1=fbm(x*.012,y*.012,5,7),mm=fbm(x*.022,y*.022,3,44),cl=(n1-.42)/.36;cl=cl<0?0:cl>1?1:cl;cl=cl*cl*(3-2*cl);var den=Math.min(1,cl*(.3+band*.85)),warm=mm*mm*mm,core=den>.55?(den-.55)/.45:0;
d[i]=Math.min(255,(18+warm*46+core*10)*T[0]);d[i+1]=Math.min(255,(30+mm*28+core*40)*T[1]);d[i+2]=Math.min(255,(66+mm*40+core*58)*T[2]);d[i+3]=Math.min(255,den*210)}
g.putImageData(im,0,0);return c}
function drawNeb(ox,oy,t){cx.globalCompositeOperation='screen';var s0=Math.max(W/neb.width,H/neb.height);
cx.globalAlpha=.32;cx.save();cx.translate(W/2-ox*34+Math.sin(t*5e-5)*40,H/2-oy*20+Math.cos(t*4e-5)*24);cx.drawImage(neb,-neb.width*s0*.92,-neb.height*s0*.92,neb.width*s0*1.85,neb.height*s0*1.85);cx.restore();
cx.globalAlpha=.22;cx.save();cx.translate(W/2-ox*80+Math.cos(t*4e-5)*34,H/2-oy*46+Math.sin(t*6e-5)*26);cx.rotate(.55);cx.drawImage(neb,-neb.width*s0*1.6,-neb.height*s0*1.6,neb.width*s0*3.2,neb.height*s0*3.2);cx.restore();
cx.globalAlpha=1;cx.globalCompositeOperation='source-over'}
function drawPlanet(ox,oy){var P=CFG.planet,px=W*P[0]-ox*30,py=H*P[1]-oy*18,r=Math.min(W,H)*P[2];
var g=cx.createRadialGradient(px-r*.3,py-r*.35,r*.1,px,py,r);
g.addColorStop(0,'rgba(52,70,102,.15)');g.addColorStop(.7,'rgba(22,34,60,.07)');g.addColorStop(1,'rgba(10,16,34,0)');
cx.fillStyle=g;cx.beginPath();cx.arc(px,py,r,0,TAU);cx.fill();
cx.strokeStyle='rgba(190,212,240,.14)';cx.lineWidth=1;cx.beginPath();cx.arc(px,py,r-.5,Math.PI*1.02,Math.PI*1.48);cx.stroke();
cx.save();cx.translate(px,py);cx.rotate(-.44);cx.scale(1,.3);
for(var i=0;i<2;i++){cx.beginPath();cx.arc(0,0,r*(1.55+i*.35),0,TAU);cx.strokeStyle='rgba(150,180,225,'+(.07-i*.03)+')';cx.lineWidth=5+i*4;cx.stroke()}cx.restore()}
function spawnMeteor(){var ang=.5+Math.random()*.7,dir=Math.random()<.5?1:-1;meteors.push({x:Math.random()*1.1*W-.05*W,y:Math.random()*.45*H-.05*H,dx:Math.cos(ang)*dir,dy:Math.sin(ang),sp:430+Math.random()*390,dur:.8+Math.random()*.55,life:0,len:60+Math.random()*90})}
function spawnComet(){var fr=Math.random()<.55;comets.push({x:fr?W+170:-170,y:Math.random()*.55*H+.05*H,vx:(fr?-1:1)*(48+Math.random()*57),vy:-22+Math.random()*56,a:0,ph:0,core:1.5+Math.random()*1.1,tail:[]})}
function drawMeteors(dt){cx.globalCompositeOperation='lighter';
for(var i=meteors.length-1;i>=0;i--){var m=meteors[i];m.life+=dt;var f=m.life/m.dur;
if(f>=1){meteors.splice(i,1);continue}
var a=Math.sin(Math.PI*f)*.9,hx=m.x+m.dx*m.sp*m.life,hy=m.y+m.dy*m.sp*m.life,tx=hx-m.dx*m.len,ty=hy-m.dy*m.len;
var g=cx.createLinearGradient(tx,ty,hx,hy);g.addColorStop(0,'rgba(180,205,255,0)');g.addColorStop(1,'rgba(220,235,255,'+a+')');
cx.strokeStyle=g;cx.lineWidth=1.4;cx.beginPath();cx.moveTo(tx,ty);cx.lineTo(hx,hy);cx.stroke();
cx.fillStyle='rgba(255,255,255,'+a+')';cx.beginPath();cx.arc(hx,hy,1.1,0,TAU);cx.fill()}
cx.globalCompositeOperation='source-over'}
function drawComets(dt){cx.globalCompositeOperation='lighter';
for(var i=comets.length-1;i>=0;i--){var c=comets[i];
if(c.ph===0){c.a=Math.min(1,c.a+dt*.5);if(c.a>=1)c.ph=1}
else if(c.ph===1){if(c.x<-260||c.x>W+260||c.y<-260||c.y>H+260)c.ph=2}
else{c.a=Math.max(0,c.a-dt*.35);if(c.a<=0){comets.splice(i,1);continue}}
c.x+=c.vx*dt;c.y+=c.vy*dt;c.tail.push({x:c.x,y:c.y});if(c.tail.length>130)c.tail.shift();
var n=c.tail.length;
for(var j=0;j<n-1;j++){var f=j/n,al=f*f*c.a*.5;
cx.strokeStyle='rgba(168,216,255,'+al+')';cx.lineWidth=Math.max(.3,f*c.core*2.6);
cx.beginPath();cx.moveTo(c.tail[j].x,c.tail[j].y);cx.lineTo(c.tail[j+1].x,c.tail[j+1].y);cx.stroke();
if(f>.6){cx.strokeStyle='rgba(255,255,255,'+((f-.6)/.4*c.a*.32)+')';cx.lineWidth=Math.max(.2,f*c.core*.5);cx.beginPath();cx.moveTo(c.tail[j].x,c.tail[j].y);cx.lineTo(c.tail[j+1].x,c.tail[j+1].y);cx.stroke()}}
var g=cx.createRadialGradient(c.x,c.y,0,c.x,c.y,c.core*7);
g.addColorStop(0,'rgba(255,255,255,'+c.a+')');g.addColorStop(.3,'rgba(178,226,255,'+c.a*.7+')');g.addColorStop(1,'rgba(0,0,0,0)');
cx.fillStyle=g;cx.beginPath();cx.arc(c.x,c.y,c.core*7,0,TAU);cx.fill();
cx.fillStyle='rgba(244,251,255,'+c.a+')';cx.beginPath();cx.arc(c.x,c.y,c.core,0,TAU);cx.fill()}
cx.globalCompositeOperation='source-over'}
function frame(t,dt){cx.clearRect(0,0,W,H);
var ox=m.sx-.5,oy=m.sy-.5;
drawNeb(ox,oy,t);
if(CFG.planet)drawPlanet(ox,oy);
var ts=t/1000;
for(var i=0;i<stars.length;i++){var s=stars[i];
var sx=((s.x*W-ox*s.p*240)%W+W)%W,sy=((s.y*H-oy*s.p*150)%H+H)%H;
var a=s.a*(.68+.32*Math.sin(ts*s.ts+s.tw));
cx.fillStyle='rgba('+s.c[0]+','+s.c[1]+','+s.c[2]+','+a+')';cx.beginPath();cx.arc(sx,sy,s.r,0,TAU);cx.fill();
if(s.r>1.42){cx.strokeStyle='rgba('+s.c[0]+','+s.c[1]+','+s.c[2]+','+(a*.3)+')';cx.lineWidth=.6;var L=s.r*5.2;
cx.beginPath();cx.moveTo(sx-L,sy);cx.lineTo(sx+L,sy);cx.moveTo(sx,sy-L);cx.lineTo(sx,sy+L);cx.stroke()}}
if(!RM){if(t>nextMet){spawnMeteor();if(Math.random()<.4)spawnMeteor();nextMet=t+3600+Math.random()*5200}
if(t>nextCom){spawnComet();nextCom=t+20000+Math.random()*17000}}
drawMeteors(dt);drawComets(dt)}
addEventListener('mousemove',function(e){m.x=e.clientX/innerWidth;m.y=e.clientY/innerHeight},{passive:true});
addEventListener('resize',function(){resize();buildStars()});
resize();buildStars();neb=makeNeb();
var last=performance.now();
(function loop(t){var dt=RM?0:Math.min(.05,(t-last)/1000)||.016;last=t;
m.sx+=(m.x-m.sx)*.06;m.sy+=(m.y-m.sy)*.06;frame(RM?2000:t,dt);requestAnimationFrame(loop)})(performance.now());
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 28;
var renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
// Deep Starfield Particle Nodes
var starCount = 1400;
var starGeo = new THREE.BufferGeometry();
var starPos = new Float32Array(starCount * 3);
var starColors = new Float32Array(starCount * 3);
var colA = new THREE.Color(0x8fd9ff);
var colB = new THREE.Color(0xffffff);
var colC = new THREE.Color(0x43e5a0);
for(var i = 0; i < starCount; i++){
var i3 = i * 3;
starPos[i3] = (Math.random() - 0.5) * 80;
starPos[i3 + 1] = (Math.random() - 0.5) * 60;
starPos[i3 + 2] = (Math.random() - 0.5) * 50 - 5;
var roll = Math.random();
var c = roll < 0.6 ? colB : (roll < 0.85 ? colA : colC);
starColors[i3] = c.r;
starColors[i3 + 1] = c.g;
starColors[i3 + 2] = c.b;
}
starGeo.setAttribute('position', new THREE.BufferAttribute(starPos, 3));
starGeo.setAttribute('color', new THREE.BufferAttribute(starColors, 3));
var starMat = new THREE.PointsMaterial({
size: 0.18,
vertexColors: true,
transparent: true,
opacity: 0.75,
blending: THREE.AdditiveBlending
});
var starField = new THREE.Points(starGeo, starMat);
scene.add(starField);
// Subtle 3D Gyroscopic Rings Floating in Celestial Horizon
var ringGroup = new THREE.Group();
scene.add(ringGroup);
var r1Geo = new THREE.TorusGeometry(12, 0.02, 16, 120);
var r1Mat = new THREE.MeshBasicMaterial({ color: 0x8fd9ff, transparent: true, opacity: 0.18 });
var ring1 = new THREE.Mesh(r1Geo, r1Mat);
ring1.rotation.x = Math.PI / 3;
ringGroup.add(ring1);
var r2Geo = new THREE.TorusGeometry(15, 0.015, 16, 120);
var r2Mat = new THREE.MeshBasicMaterial({ color: 0x43e5a0, transparent: true, opacity: 0.1 });
var ring2 = new THREE.Mesh(r2Geo, r2Mat);
ring2.rotation.y = Math.PI / 4;
ring2.rotation.x = Math.PI / 5;
ringGroup.add(ring2);
var mouse = { x: 0, y: 0, targetX: 0, targetY: 0 };
window.addEventListener('mousemove', function(e){
mouse.targetX = (e.clientX / window.innerWidth - 0.5) * 2;
mouse.targetY = -(e.clientY / window.innerHeight - 0.5) * 2;
}, { passive: true });
window.addEventListener('resize', function(){
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
var clock = new THREE.Clock();
function animate(){
requestAnimationFrame(animate);
if(document.hidden) return;
var elapsedTime = clock.getElapsedTime();
mouse.x += (mouse.targetX - mouse.x) * 0.05;
mouse.y += (mouse.targetY - mouse.y) * 0.05;
starField.rotation.y = elapsedTime * 0.015;
starField.rotation.x = elapsedTime * 0.008;
ring1.rotation.z = elapsedTime * 0.04;
ring2.rotation.z = -elapsedTime * 0.03;
ringGroup.position.x = mouse.x * 1.5;
ringGroup.position.y = mouse.y * 1.2;
camera.position.x = mouse.x * 2;
camera.position.y = mouse.y * 1.5;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
animate();
})();
/* ══ form behavior (original functions preserved) ══ */
/* ══ 2. STUUDIO/JOCKEY SIGNATURE 3D CARD TILT & CONIC RIM LIGHT ══ */
(function(){
'use strict';
var card = document.getElementById('card');
var wrapper = document.getElementById('cardWrapper');
if(!card || !wrapper) return;
var rect = null;
function updateRect(){ rect = card.getBoundingClientRect(); }
window.addEventListener('resize', updateRect);
updateRect();
var currentTiltX = 0, currentTiltY = 0;
var targetTiltX = 0, targetTiltY = 0;
window.addEventListener('mousemove', function(e){
if(!rect) updateRect();
var cx = rect.left + rect.width / 2;
var cy = rect.top + rect.height / 2;
var dx = e.clientX - cx;
var dy = e.clientY - cy;
// Conic Rim Lighting angle and position
var angle = Math.atan2(dy, dx) * (180 / Math.PI) + 90;
card.style.setProperty('--rim-angle', angle + 'deg');
var mxPercent = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
var myPercent = Math.max(0, Math.min(100, ((e.clientY - rect.top) / rect.height) * 100));
card.style.setProperty('--mx', mxPercent + '%');
card.style.setProperty('--my', myPercent + '%');
// 3D perspective tilt calculation
var dist = Math.hypot(dx, dy);
var maxDist = Math.hypot(window.innerWidth, window.innerHeight) / 2;
if(dist < maxDist){
targetTiltY = (dx / (rect.width * 1.8)) * 12;
targetTiltX = -(dy / (rect.height * 1.8)) * 12;
} else {
targetTiltX = 0;
targetTiltY = 0;
}
}, { passive: true });
window.addEventListener('mouseleave', function(){
targetTiltX = 0;
targetTiltY = 0;
});
function tiltLoop(){
currentTiltX += (targetTiltX - currentTiltX) * 0.08;
currentTiltY += (targetTiltY - currentTiltY) * 0.08;
card.style.transform = 'rotateX(' + currentTiltX.toFixed(2) + 'deg) rotateY(' + currentTiltY.toFixed(2) + 'deg)';
requestAnimationFrame(tiltLoop);
}
tiltLoop();
})();
/* ══ 3. ORIGINAL PRESERVED AUTH BEHAVIORS ══ */
function togglePwd(id) {
var el = document.getElementById(id);
el.type = el.type === 'password' ? 'text' : 'password';
var b = el.parentElement.querySelector('.pwd-toggle');
if (b) b.classList.toggle('shown');
}
document.getElementById('loginForm').addEventListener('submit', function() {
var btn = document.getElementById('submitBtn');
btn.textContent = 'Signing in…';
@@ -228,33 +712,43 @@ document.getElementById('loginForm').addEventListener('submit', function() {
btn.disabled = true;
});
/* Caps Lock detection on password fields */
/* Caps Lock detection */
document.querySelectorAll('input[type=password]').forEach(function(inp){
function h(e){var on=e.getModifierState&&e.getModifierState('CapsLock');
var w=inp.closest('.fg');if(!w)return;var cw=w.querySelector('.caps-warn');
if(cw)cw.classList.toggle('on',!!on);}
inp.addEventListener('keyup',h);inp.addEventListener('keydown',h);
function checkCaps(e){
var on = e.getModifierState && e.getModifierState('CapsLock');
var group = inp.closest('.form-group');
if(!group) return;
var warn = group.querySelector('.caps-warn');
if(warn) warn.classList.toggle('on', !!on);
}
inp.addEventListener('keyup', checkCaps);
inp.addEventListener('keydown', checkCaps);
});
/* card parallax */
(function(){'use strict';
var card=document.getElementById('card');
if(!matchMedia('(pointer:fine)').matches||RMQ)return;
addEventListener('mousemove',function(e){
var dx=e.clientX/innerWidth-.5,dy=e.clientY/innerHeight-.5;
card.style.transform='translate3d('+(dx*8)+'px,'+(dy*6)+'px,0)';
},{passive:true});
})();
/* scramble decode */
(function(){'use strict';
function scramble(el){var tgt=el.dataset.txt;if(RMQ){el.textContent=tgt;return}
var f=0,total=Math.max(16,tgt.length*1.15),CH='ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>/[]·';
var iv=setInterval(function(){f++;var done=Math.floor(tgt.length*f/total),s='';
for(var i=0;i<tgt.length;i++){var ch=tgt[i];s+=i<done?ch:(ch===' '?' ':CH[Math.random()*CH.length|0])}
el.textContent=s;if(f>=total){el.textContent=tgt;clearInterval(iv)}},26)}
document.querySelectorAll('[data-scr]').forEach(function(el){el.dataset.txt=el.textContent});
setTimeout(function(){var t=document.querySelector('[data-scr]');if(t)scramble(t)},400);
/* Scramble decode on secure channel badge */
(function(){
'use strict';
function scramble(el){
var tgt = el.dataset.txt;
var f = 0, total = Math.max(16, tgt.length * 1.2), CH = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789<>/[]·';
var iv = setInterval(function(){
f++;
var done = Math.floor(tgt.length * f / total), s = '';
for(var i = 0; i < tgt.length; i++){
var ch = tgt[i];
s += i < done ? ch : (ch === ' ' ? ' ' : CH[Math.random() * CH.length | 0]);
}
el.textContent = s;
if(f >= total){ el.textContent = tgt; clearInterval(iv); }
}, 28);
}
document.querySelectorAll('[data-scr]').forEach(function(el){
el.dataset.txt = el.textContent;
});
setTimeout(function(){
var t = document.querySelector('[data-scr]');
if(t) scramble(t);
}, 350);
})();
</script>
</body>
+1099 -326
View File
File diff suppressed because it is too large Load Diff
+3687 -3908
View File
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
+547
View File
@@ -0,0 +1,547 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{if .FileName}}{{.FileName}} — Cosmos Oort Share{{else}}Cosmos Oort Share{{end}}</title>
<link rel="icon" href='data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="6" fill="%23eef3f8"/><ellipse cx="16" cy="16" rx="14" ry="5.5" fill="none" stroke="%238fd9ff" stroke-width="1.5" transform="rotate(-24 16 16)"/></svg>'>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@1&family=JetBrains+Mono:wght@400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #020308;
--card-bg: rgba(9, 14, 26, 0.82);
--border: rgba(226, 234, 242, 0.08);
--line-strong: rgba(226, 234, 242, 0.16);
--accent: #8fd9ff;
--accent-rgb: 143, 216, 255;
--text: #f8fafc;
--text-muted: rgba(226, 234, 242, 0.6);
--text-dim: rgba(226, 234, 242, 0.35);
--mono: 'JetBrains Mono', ui-monospace, monospace;
--disp: 'Space Grotesk', -apple-system, sans-serif;
--serif: 'Instrument Serif', Georgia, serif;
--ez: cubic-bezier(0.16, 1, 0.3, 1);
}
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
body {
background-color: var(--bg);
color: var(--text);
font-family: var(--disp);
min-height: 100vh;
min-height: 100svh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 24px;
overflow-x: hidden;
position: relative;
-webkit-font-smoothing: antialiased;
}
::selection { background: rgba(var(--accent-rgb), 0.3); color: #fff; }
#webgl-bg {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 1;
}
.noise-overlay {
position: fixed;
inset: -10%;
width: 120%;
height: 120%;
pointer-events: none;
opacity: 0.045;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.85' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-size: 160px 160px;
z-index: 2;
}
.radial-vignette {
position: fixed;
inset: 0;
pointer-events: none;
background: radial-gradient(ellipse at 50% 50%, transparent 40%, rgba(2, 3, 8, 0.75) 85%, #020308 100%);
z-index: 2;
}
.card-wrapper {
position: relative;
z-index: 10;
width: 100%;
max-width: 480px;
perspective: 1200px;
}
/* ── Signature Stuudio/Jockey 3D Glass Card with Conic Edge Illumination ── */
.share-card {
position: relative;
width: 100%;
border-radius: 20px;
padding: 38px 34px 34px;
background: linear-gradient(145deg, rgba(10, 15, 28, 0.85), rgba(4, 7, 14, 0.9)) padding-box,
conic-gradient(from var(--rim-angle, 0deg) at var(--mx, 50%) var(--my, 50%),
rgba(143, 216, 255, 0.85) 0deg,
rgba(255, 255, 255, 0.1) 60deg,
rgba(143, 216, 255, 0.05) 160deg,
rgba(143, 216, 255, 0.45) 260deg,
rgba(143, 216, 255, 0.85) 360deg) border-box;
border: 1px solid transparent;
backdrop-filter: blur(28px);
-webkit-backdrop-filter: blur(28px);
box-shadow: 0 35px 85px rgba(0, 0, 0, 0.65), 0 0 50px rgba(143, 216, 255, 0.06);
transform-style: preserve-3d;
transition: transform 0.2s cubic-bezier(0.2, 0.8, 0.3, 1), box-shadow 0.3s;
}
/* Reticle Corners */
.cnr {
position: absolute;
width: 14px;
height: 14px;
border: 1px solid rgba(var(--accent-rgb), 0.35);
pointer-events: none;
}
.c1 { top: -1px; left: -1px; border-right: 0; border-bottom: 0; border-top-left-radius: 8px; }
.c2 { top: -1px; right: -1px; border-left: 0; border-bottom: 0; border-top-right-radius: 8px; }
.c3 { bottom: -1px; left: -1px; border-right: 0; border-top: 0; border-bottom-left-radius: 8px; }
.c4 { bottom: -1px; right: -1px; border-left: 0; border-top: 0; border-bottom-right-radius: 8px; }
.brand {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 28px;
}
.brand-left {
display: flex;
align-items: center;
gap: 10px;
}
.brand-icon {
width: 32px;
height: 32px;
background: rgba(var(--accent-rgb), 0.1);
border: 1px solid rgba(var(--accent-rgb), 0.25);
border-radius: 9px;
display: flex;
align-items: center;
justify-content: center;
}
.brand-name {
font-weight: 700;
font-size: 15px;
letter-spacing: -0.01em;
color: #fff;
}
.brand-name em {
font-family: var(--serif);
font-style: italic;
font-weight: 400;
color: rgb(var(--accent-rgb));
margin-left: 3px;
}
.brand-pill {
font-family: var(--mono);
font-size: 9px;
letter-spacing: 0.14em;
text-transform: uppercase;
padding: 4px 10px;
border-radius: 999px;
background: rgba(var(--accent-rgb), 0.1);
color: var(--accent);
border: 1px solid rgba(var(--accent-rgb), 0.22);
}
.file-box {
background: rgba(0, 0, 0, 0.4);
border: 1px solid var(--border);
border-radius: 14px;
padding: 18px 20px;
margin-bottom: 22px;
display: flex;
align-items: center;
gap: 16px;
}
.file-icon {
width: 46px;
height: 46px;
border-radius: 12px;
background: rgba(143, 216, 255, 0.08);
border: 1px solid rgba(143, 216, 255, 0.25);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: var(--accent);
}
.file-details {
min-width: 0;
flex: 1;
}
.file-name {
font-size: 15px;
font-weight: 600;
color: #fff;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
margin-bottom: 4px;
}
.file-meta {
font-family: var(--mono);
font-size: 11px;
color: var(--text-muted);
display: flex;
gap: 10px;
}
.meta-item {
display: flex;
align-items: center;
gap: 4px;
}
.stats-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 24px;
}
.stat-pill {
background: rgba(255, 255, 255, 0.02);
border: 1px solid var(--border);
padding: 12px 14px;
border-radius: 11px;
}
.stat-label {
font-family: var(--mono);
font-size: 9px;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 0.12em;
margin-bottom: 4px;
}
.stat-val {
font-family: var(--mono);
font-size: 13.5px;
font-weight: 500;
color: var(--text);
}
.btn-download {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
padding: 14px 22px;
background: #fff;
color: #04060d;
text-decoration: none;
border: none;
border-radius: 11px;
font-weight: 700;
font-size: 14.5px;
cursor: pointer;
letter-spacing: -0.01em;
transition: all 0.2s ease;
box-shadow: 0 8px 30px rgba(255, 255, 255, 0.12);
}
.btn-download:hover {
box-shadow: 0 12px 40px rgba(255, 255, 255, 0.22);
transform: translateY(-1px);
}
.btn-download:active {
transform: scale(0.985);
}
.input-pass {
width: 100%;
padding: 13px 16px;
background: rgba(226, 234, 242, 0.03);
border: 1px solid var(--line-strong);
border-radius: 11px;
color: #fff;
font-family: inherit;
font-size: 14px;
outline: none;
margin-bottom: 16px;
transition: border-color 0.2s, box-shadow 0.2s;
}
.input-pass:focus {
border-color: rgba(var(--accent-rgb), 0.65);
box-shadow: 0 0 0 3px rgba(var(--accent-rgb), 0.15);
}
.error-msg {
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.3);
color: #f87171;
padding: 11px 14px;
border-radius: 10px;
font-size: 13px;
margin-bottom: 18px;
}
.footer {
position: relative;
z-index: 10;
margin-top: 24px;
font-family: var(--mono);
font-size: 10px;
letter-spacing: 0.1em;
color: var(--text-dim);
text-align: center;
text-transform: uppercase;
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
</style>
</head>
<body>
<div id="webgl-bg" aria-hidden="true"></div>
<div class="noise-overlay" aria-hidden="true"></div>
<div class="radial-vignette" aria-hidden="true"></div>
<div class="card-wrapper" id="cardWrapper">
<div class="share-card" id="card">
<i class="cnr c1"></i><i class="cnr c2"></i><i class="cnr c3"></i><i class="cnr c4"></i>
<div class="brand">
<div class="brand-left">
<div class="brand-icon">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#8fd9ff" stroke-width="2">
<circle cx="12" cy="12" r="10"/>
<line x1="2" y1="12" x2="22" y2="12"/>
<path d="M12 2a15.3 15.3 0 014 10 15.3 15.3 0 01-4 10 15.3 15.3 0 01-4-10 15.3 15.3 0 014-10z"/>
</svg>
</div>
<div class="brand-name">COSMOS <em>OORT</em></div>
</div>
<span class="brand-pill">SECURE SHARE</span>
</div>
{{if .Error}}
<div class="error-msg">{{.Error}}</div>
{{end}}
{{if .Expired}}
<div style="text-align:center; padding: 24px 0;">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="#f87171" stroke-width="1.5" style="margin-bottom:12px">
<circle cx="12" cy="12" r="10"/>
<line x1="12" y1="8" x2="12" y2="12"/>
<line x1="12" y1="16" x2="12.01" y2="16"/>
</svg>
<h2 style="font-size:18px; margin-bottom:8px; color:#fff">Share Link Inactive</h2>
<p style="font-size:13px; color:var(--text-muted); line-height:1.5">This link has expired, exceeded its download quota, or has been revoked by the owner.</p>
</div>
{{else}}
<div class="file-box">
<div class="file-icon">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z"/>
<polyline points="14 2 14 8 20 8"/>
<line x1="12" y1="18" x2="12" y2="12"/>
<line x1="9" y1="15" x2="15" y2="15"/>
</svg>
</div>
<div class="file-details">
<div class="file-name" title="{{.FileName}}">{{.FileName}}</div>
<div class="file-meta">
<span class="meta-item">{{.FileSize}}</span>
{{if .ContentType}}<span class="meta-item">• {{.ContentType}}</span>{{end}}
</div>
</div>
</div>
<div class="stats-row">
<div class="stat-pill">
<div class="stat-label">Expires In</div>
<div class="stat-val" style="color:#8fd9ff">{{.ExpiresIn}}</div>
</div>
<div class="stat-pill">
<div class="stat-label">Downloads</div>
<div class="stat-val">{{.DownloadsRemaining}}</div>
</div>
</div>
{{if .RequiresPassword}}
<form method="POST" action="/s/{{.Token}}">
<div style="font-size:13px; color:var(--text-muted); margin-bottom:10px">This transmission is passphrase-protected:</div>
<input type="password" name="password" class="input-pass" placeholder="Enter download passphrase" required autofocus />
<button type="submit" class="btn-download">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<rect x="3" y="11" width="18" height="11" rx="2" ry="2"/>
<path d="M7 11V7a5 5 0 0110 0v4"/>
</svg>
Unlock &amp; Download
</button>
</form>
{{else}}
<a href="{{.DownloadURL}}" class="btn-download">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
<polyline points="7 10 12 15 17 10"/>
<line x1="12" y1="15" x2="12" y2="3"/>
</svg>
Download Transmission
</a>
{{end}}
{{end}}
</div>
</div>
<div class="footer">
Powered by <strong>Cosmos Oort</strong> · Sovereign Cloud Workstation
</div>
<!-- Local Zero-Latency Three.js Engine -->
<script src="/three.min.js"></script>
<script>
/* ══ 1. THREE.JS 3D CELESTIAL BACKGROUND ══ */
(function(){
'use strict';
var container = document.getElementById('webgl-bg');
if(!window.THREE || !container) return;
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 28;
var renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true, powerPreference: 'high-performance' });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
container.appendChild(renderer.domElement);
var starCount = 1200;
var starGeo = new THREE.BufferGeometry();
var starPos = new Float32Array(starCount * 3);
var starColors = new Float32Array(starCount * 3);
var colA = new THREE.Color(0x8fd9ff);
var colB = new THREE.Color(0xffffff);
for(var i = 0; i < starCount; i++){
var i3 = i * 3;
starPos[i3] = (Math.random() - 0.5) * 80;
starPos[i3 + 1] = (Math.random() - 0.5) * 60;
starPos[i3 + 2] = (Math.random() - 0.5) * 50 - 5;
var c = Math.random() < 0.65 ? colB : colA;
starColors[i3] = c.r;
starColors[i3 + 1] = c.g;
starColors[i3 + 2] = c.b;
}
starGeo.setAttribute('position', new THREE.BufferAttribute(starPos, 3));
starGeo.setAttribute('color', new THREE.BufferAttribute(starColors, 3));
var starMat = new THREE.PointsMaterial({
size: 0.18,
vertexColors: true,
transparent: true,
opacity: 0.75,
blending: THREE.AdditiveBlending
});
var starField = new THREE.Points(starGeo, starMat);
scene.add(starField);
// Orbital Ring
var rGeo = new THREE.TorusGeometry(12, 0.02, 16, 120);
var rMat = new THREE.MeshBasicMaterial({ color: 0x8fd9ff, transparent: true, opacity: 0.15 });
var ring = new THREE.Mesh(rGeo, rMat);
ring.rotation.x = Math.PI / 3;
scene.add(ring);
var mouse = { x: 0, y: 0, targetX: 0, targetY: 0 };
window.addEventListener('mousemove', function(e){
mouse.targetX = (e.clientX / window.innerWidth - 0.5) * 2;
mouse.targetY = -(e.clientY / window.innerHeight - 0.5) * 2;
}, { passive: true });
window.addEventListener('resize', function(){
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
var clock = new THREE.Clock();
function animate(){
requestAnimationFrame(animate);
if(document.hidden) return;
var t = clock.getElapsedTime();
mouse.x += (mouse.targetX - mouse.x) * 0.05;
mouse.y += (mouse.targetY - mouse.y) * 0.05;
starField.rotation.y = t * 0.015;
ring.rotation.z = t * 0.035;
camera.position.x = mouse.x * 2;
camera.position.y = mouse.y * 1.5;
camera.lookAt(scene.position);
renderer.render(scene, camera);
}
animate();
})();
/* ══ 2. STUUDIO/JOCKEY SIGNATURE 3D CARD TILT & CONIC RIM LIGHT ══ */
(function(){
'use strict';
var card = document.getElementById('card');
if(!card) return;
var rect = null;
function updateRect(){ rect = card.getBoundingClientRect(); }
window.addEventListener('resize', updateRect);
updateRect();
var currentTiltX = 0, currentTiltY = 0;
var targetTiltX = 0, targetTiltY = 0;
window.addEventListener('mousemove', function(e){
if(!rect) updateRect();
var cx = rect.left + rect.width / 2;
var cy = rect.top + rect.height / 2;
var dx = e.clientX - cx;
var dy = e.clientY - cy;
var angle = Math.atan2(dy, dx) * (180 / Math.PI) + 90;
card.style.setProperty('--rim-angle', angle + 'deg');
var mxPercent = Math.max(0, Math.min(100, ((e.clientX - rect.left) / rect.width) * 100));
var myPercent = Math.max(0, Math.min(100, ((e.clientY - rect.top) / rect.height) * 100));
card.style.setProperty('--mx', mxPercent + '%');
card.style.setProperty('--my', myPercent + '%');
var dist = Math.hypot(dx, dy);
var maxDist = Math.hypot(window.innerWidth, window.innerHeight) / 2;
if(dist < maxDist){
targetTiltY = (dx / (rect.width * 1.8)) * 12;
targetTiltX = -(dy / (rect.height * 1.8)) * 12;
} else {
targetTiltX = 0;
targetTiltY = 0;
}
}, { passive: true });
function tiltLoop(){
currentTiltX += (targetTiltX - currentTiltX) * 0.08;
currentTiltY += (targetTiltY - currentTiltY) * 0.08;
card.style.transform = 'rotateX(' + currentTiltX.toFixed(2) + 'deg) rotateY(' + currentTiltY.toFixed(2) + 'deg)';
requestAnimationFrame(tiltLoop);
}
tiltLoop();
})();
</script>
</body>
</html>
+842 -267
View File
File diff suppressed because it is too large Load Diff
+6
View File
File diff suppressed because one or more lines are too long