Compare commits

...
13 Commits
Author SHA1 Message Date
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
10 changed files with 9623 additions and 228 deletions
File diff suppressed because it is too large Load Diff
+153 -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,7 +145,32 @@ 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
@@ -210,12 +230,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 +245,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)
@@ -257,61 +277,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 +391,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 +411,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 +457,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 +485,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 +512,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 +538,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:9000", "unityadmin", "UnityAdmin2026!").Run()
exec.Command("mc", "admin", "user", "add", "cosmos", ak, sk).Run()
exec.Command("mc", "mb", "--ignore-existing", "cosmos/"+bucket).Run()
exec.Command("mc", "version", "enable", "cosmos/"+bucket).Run()
@@ -482,7 +549,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 +642,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)
@@ -812,6 +878,7 @@ func main() {
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"))
+40 -18
View File
@@ -26,6 +26,7 @@ import (
)
const minioEndpoint = "127.0.0.1:9000"
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 +41,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 +99,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)
@@ -426,6 +441,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 +520,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 +539,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 +696,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 +736,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 +782,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 +836,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 +897,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"
}
@@ -991,7 +1013,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 +1045,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 +1086,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 ──────────────────────────────────────────────
@@ -1156,7 +1178,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 +1187,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"
}
@@ -1197,7 +1219,7 @@ func handleS3PublicProxy(w http.ResponseWriter, r *http.Request, username, path
}
targetPath := fmt.Sprintf("/%s/%s", actualBucket, objectKey)
targetUrl, _ := url.Parse("http://127.0.0.1:9000")
proxy := httputil.NewSingleHostReverseProxy(targetUrl)
proxy.Transport = proxyTransport
@@ -1483,7 +1505,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)
+1066
View File
File diff suppressed because it is too large Load Diff
+1327
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()
}
}
}
}
+346 -5
View File
@@ -180,12 +180,14 @@ body.m-open .mmenu a:nth-child(3){transition-delay:.24s}
background:linear-gradient(90deg,transparent,rgba(143,216,255,.8),transparent);
animation:packet 8.5s linear infinite}
.divider.d-ember::after{background:linear-gradient(90deg,transparent,rgba(255,171,77,.75),transparent)}
.divider.d-violet::after{background:linear-gradient(90deg,transparent,rgba(168,85,247,.85),transparent)}
@keyframes packet{to{left:calc(100% + 130px)}}
/* ─── MODULE SECTIONS ─── */
.module{position:relative;z-index:10;padding:clamp(90px,11vw,170px) var(--pad);scroll-margin-top:70px}
.m-forge{--ac:255,171,77}
.m-oort{--ac:143,216,255}
.m-orbit{--ac:168,85,247}
.module-inner{max-width:1260px;margin:0 auto;display:grid;grid-template-columns:1.02fr 1fr;
gap:clamp(48px,7vw,110px);align-items:center}
.module-inner.flip .m-text{order:2}
@@ -230,9 +232,9 @@ body.m-open .mmenu a:nth-child(3){transition-delay:.24s}
@supports(-webkit-text-stroke:1px red){
.m-ghost{color:transparent;-webkit-text-stroke:1.3px rgba(var(--ac),.16)}
}
.m-oort canvas{touch-action:pan-y}
body:not(.has-cur) .m-oort canvas{cursor:grab}
body:not(.has-cur).grabbing .m-oort canvas{cursor:grabbing}
.m-oort canvas,.m-orbit canvas{touch-action:pan-y}
body:not(.has-cur) .m-oort canvas,body:not(.has-cur) .m-orbit canvas{cursor:grab}
body:not(.has-cur).grabbing .m-oort canvas,body:not(.has-cur).grabbing .m-orbit canvas{cursor:grabbing}
/* glass panels */
.glass{position:absolute;z-index:5;background:rgba(5,9,18,.72);
@@ -254,13 +256,17 @@ body:not(.has-cur).grabbing .m-oort canvas{cursor:grabbing}
@keyframes sweep{0%{top:0;opacity:0}8%{opacity:1}88%{opacity:1}100%{top:100%;opacity:0}}
.stat{right:max(-3.5%,-26px);top:4%;padding:16px 18px 14px;min-width:214px}
.m-orbit .stat{left:max(-3.5%,-26px);bottom:5%;top:auto;right:auto;min-width:236px}
.srow{display:flex;align-items:baseline;gap:10px;padding:5.5px 0}
.srow span{font-family:var(--mono);font-size:9px;letter-spacing:.18em;text-transform:uppercase;color:rgba(226,234,242,.34)}
.srow b{font-family:var(--mono);font-size:14px;font-weight:500;color:#cfeafc;margin-left:auto}
.srow em{font-style:normal;font-family:var(--mono);font-size:9px;color:rgba(143,216,255,.55);letter-spacing:.08em}
.m-orbit .srow b{color:#f1f5f9}
.m-orbit .srow em{color:rgba(168,85,247,.85)}
.bars{display:flex;gap:3px;height:22px;align-items:flex-end;margin-top:12px}
.bars i{width:3px;border-radius:1px;background:rgba(143,216,255,.55);
animation:bar 1s ease-in-out infinite alternate;transform-origin:bottom}
.m-orbit .bars i{background:linear-gradient(to top, rgba(168,85,247,.65), rgba(56,189,248,.85))}
@keyframes bar{from{transform:scaleY(.12)}to{transform:scaleY(1)}}
/* ─── FOOTER ─── */
@@ -325,6 +331,7 @@ footer{position:relative;z-index:10;border-top:1px solid var(--line);
<div class="nav-links">
<a href="/git"><i>01</i>Forge</a>
<a href="/oort"><i>02</i>Oort</a>
<a href="/orbit"><i>03</i>Orbit</a>
</div>
<div class="nav-right">
<span class="nav-status"><i></i>NOMINAL</span>
@@ -337,6 +344,7 @@ footer{position:relative;z-index:10;border-top:1px solid var(--line);
<div class="mmenu" id="mmenu">
<a href="/git"><i>01</i>Forge</a>
<a href="/oort"><i>02</i>Oort</a>
<a href="/orbit"><i>03</i>Orbit</a>
<a href="/oort/login"><i>→</i>Sign In</a>
</div>
@@ -468,6 +476,39 @@ footer{position:relative;z-index:10;border-top:1px solid var(--line);
</div>
</section>
<div class="divider d-violet"></div>
<!-- ORBIT MODULE -->
<section class="module m-orbit">
<div class="module-inner">
<div class="m-text" data-reveal>
<p class="m-index" data-scr>MODULE 03 · APPLICATION PLATFORM</p>
<h2 class="m-name"><span class="msk"><span class="msk-in">Orbit</span></span></h2>
<p class="m-desc">Self-hosted application platform &amp; container runtime. 1-click deploy from Forge Git, smart zero-config buildpacks, dynamic reverse proxying, and live telemetry.</p>
<ul class="caps">
<li class="cap"><span class="tick"><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg></span>1-Click deployment directly from Forge Git repositories</li>
<li class="cap"><span class="tick"><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg></span>Zero-config detection for Node.js, Go, Python &amp; Dockerfile</li>
<li class="cap"><span class="tick"><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg></span>Live streaming build logs &amp; container telemetry (CPU/RAM)</li>
<li class="cap"><span class="tick"><svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg></span>Dynamic internal reverse proxy &amp; port isolation (:4100–:4999)</li>
</ul>
<a href="/orbit" class="m-cta mag">
Launch Orbit
<svg width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M7 17L17 7M17 7H7M17 7v10"/></svg>
</a>
</div>
<div class="m-visual" data-reveal data-cursor="drag">
<span class="m-ghost" aria-hidden="true">03</span>
<canvas id="orbitCv" aria-hidden="true"></canvas>
<div class="glass stat">
<div class="srow"><span>container engine</span><b>Docker</b><em>v1.45</em></div>
<div class="srow"><span>active runtime</span><b id="orbPorts">:4100</b><em>proxy</em></div>
<div class="srow"><span>orchestrator</span><b id="orbHealth">Healthy</b><em>100%</em></div>
<div class="bars" id="orbitBars"></div>
</div>
</div>
</div>
</section>
<!-- FOOTER -->
<footer data-reveal>
<div class="ft-l">
@@ -933,6 +974,283 @@ function oortFrame(t,dt){
drawParts(true); /* near particles */
}
/* ═══════════════ ORBIT — draggable 3D multi-ring reactor system ═══════════════ */
const orbCv=$('#orbitCv'),orbCtx=orbCv?orbCv.getContext('2d'):null,orbBox=orbCv?orbCv.parentElement:null;
let orbW=0,orbH=0,orbR=0,orbCX=0,orbCY=0,orbVis=false,orbInit=false;
let orbYaw=.48,orbPitch=.42,orbPitchT=.42,orbYawV=.0028,orbDrag=false,orbLx=0,orbLy=0;
let orbRings=[],orbNodes=[],orbPulses=[],orbDust=[],nextOrbPulse=1800;
function orbitResize(){
if(!orbBox||!orbCv)return;
const s=orbBox.clientWidth;if(!s)return;
orbW=s;orbH=s;
orbCv.width=s*DPR;orbCv.height=s*DPR;
orbCv.style.width=s+'px';orbCv.style.height=s+'px';
orbCtx.setTransform(DPR,0,0,DPR,0,0);
orbR=s*.175;orbCX=s*.5;orbCY=s*.5;
}
function orbitBuild(){
orbRings=[
{r:1.18,incX:.35,incY:.25,rotSpeed:.55,a:0,color:'rgba(56,189,248,',segs:64},
{r:1.62,incX:-.48,incY:.38,rotSpeed:-.42,a:1.2,color:'rgba(168,85,247,',segs:72},
{r:2.08,incX:.22,incY:-.52,rotSpeed:.28,a:2.5,color:'rgba(14,165,233,',segs:80}
];
orbNodes=[
{ring:0,a:.2,w:.55,sz:5.5,label:'WEB',port:':4100',color:[56,189,248]},
{ring:0,a:3.3,w:.55,sz:5.0,label:'API',port:':4101',color:[16,185,129]},
{ring:1,a:1.5,w:-.42,sz:6.0,label:'SVC',port:':4102',color:[168,85,247]},
{ring:1,a:4.7,w:-.42,sz:4.8,label:'AUTH',port:':4103',color:[245,158,11]},
{ring:2,a:.8,w:.28,sz:5.2,label:'DATA',port:':4104',color:[14,165,233]},
{ring:2,a:3.9,w:.28,sz:5.6,label:'CRON',port:':4105',color:[16,185,129]}
];
orbDust=[];
for(let i=0;i<180;i++){
const rr=.75+Math.random()*1.55;
orbDust.push({
rr,
a:Math.random()*TAU,
w:(.7/Math.pow(rr,1.4))*(.85+Math.random()*.3),
y:(Math.random()-0.5)*.35,
sz:Math.random()<.1?1.4+Math.random()*.8:.6+Math.random()*.6,
al:.25+Math.random()*.65,
isPurple:Math.random()>.5
});
}
}
if(orbCv){
orbCv.addEventListener('pointerdown',e=>{
orbDrag=true;orbLx=e.clientX;orbLy=e.clientY;
try{orbCv.setPointerCapture(e.pointerId);}catch(_){}
document.body.classList.add('grabbing');
});
orbCv.addEventListener('pointermove',e=>{
if(!orbDrag)return;
const dx=e.clientX-orbLx,dy=e.clientY-orbLy;
orbLx=e.clientX;orbLy=e.clientY;
orbYaw+=dx*.0056;orbYawV=dx*.0056;
orbPitchT=clamp(orbPitchT+dy*.0035,-.6,1.2);
});
['pointerup','pointercancel'].forEach(ev=>orbCv.addEventListener(ev,()=>{
orbDrag=false;document.body.classList.remove('grabbing');
}));
}
function orbitFrame(t,dt){
if(!orbInit){orbitBuild();orbInit=true;}
if(!orbDrag){
if(!RM)orbYawV+=(.0028-orbYawV)*.02;
else orbYawV*=.9;
orbYaw+=orbYawV;
}
orbPitch+=(orbPitchT-orbPitch)*.09;
const cyw=Math.cos(orbYaw),syw=Math.sin(orbYaw);
const cp=Math.cos(orbPitch),sp=Math.sin(orbPitch);
const P=(x,y,z)=>{
const x1=x*cyw+z*syw,z1=-x*syw+z*cyw;
const y2=y*cp-z1*sp,z2=y*sp+z1*cp;
const pr=900/(900+z2);
return{x:orbCX+x1*pr,y:orbCY+y2*pr,z:z2,pr};
};
const ringPt=(ring,angle)=>{
const rad=ring.r*orbR;
const rx=Math.cos(angle)*rad;
const ry=0;
const rz=Math.sin(angle)*rad;
const cx=Math.cos(ring.incX),sx=Math.sin(ring.incX);
const y1=ry*cx-rz*sx,z1=ry*sx+rz*cx;
const cy=Math.cos(ring.incY),sy=Math.sin(ring.incY);
const x2=rx*cy+z1*sy,z2=-rx*sy+z1*cy;
return P(x2,y1,z2);
};
orbCtx.clearRect(0,0,orbW,orbH);
for(const r of orbRings)r.a+=r.rotSpeed*dt;
for(const n of orbNodes)n.a+=n.w*dt;
for(const d of orbDust)d.a+=d.w*dt;
/* Far dust */
for(const d of orbDust){
const q=P(Math.cos(d.a)*d.rr*orbR,d.y*orbR,Math.sin(d.a)*d.rr*orbR);
if(q.z>0)continue;
const al=d.al*clamp((q.pr-.75)*1.8,.2,1);
orbCtx.fillStyle=d.isPurple?`rgba(168,85,247,${al.toFixed(3)})`:`rgba(56,189,248,${al.toFixed(3)})`;
orbCtx.beginPath();orbCtx.arc(q.x,q.y,d.sz*q.pr,0,TAU);orbCtx.fill();
}
/* Far ring segments */
for(const ring of orbRings){
orbCtx.lineWidth=1.1;
for(let k=0;k<ring.segs;k++){
const a1=(k/ring.segs)*TAU;
const a2=((k+1)/ring.segs)*TAU;
const q1=ringPt(ring,a1);
const q2=ringPt(ring,a2);
if(q1.z<=0||q2.z<=0){
const alpha=clamp((q1.pr-.72)*1.5,.1,.45);
orbCtx.strokeStyle=ring.color+alpha.toFixed(3)+')';
orbCtx.beginPath();orbCtx.moveTo(q1.x,q1.y);orbCtx.lineTo(q2.x,q2.y);orbCtx.stroke();
}
}
}
/* Central Quantum Engine Core / Docker Host */
const corePulse=.5+.5*Math.sin(t*.003);
orbCtx.globalCompositeOperation='screen';
let cg=orbCtx.createRadialGradient(orbCX,orbCY,orbR*.2,orbCX,orbCY,orbR*1.7);
cg.addColorStop(0,`rgba(56,189,248,${(.25+corePulse*.15).toFixed(3)})`);
cg.addColorStop(.5,`rgba(168,85,247,${(.12+corePulse*.08).toFixed(3)})`);
cg.addColorStop(1,'rgba(0,0,0,0)');
orbCtx.fillStyle=cg;orbCtx.beginPath();orbCtx.arc(orbCX,orbCY,orbR*1.7,0,TAU);orbCtx.fill();
orbCtx.globalCompositeOperation='source-over';
cg=orbCtx.createRadialGradient(orbCX-orbR*.35,orbCY-orbR*.35,orbR*.05,orbCX,orbCY,orbR*.85);
cg.addColorStop(0,'#e0f2fe');
cg.addColorStop(.3,'#38bdf8');
cg.addColorStop(.65,'#6366f1');
cg.addColorStop(.9,'#1e1b4b');
cg.addColorStop(1,'#05070d');
orbCtx.fillStyle=cg;orbCtx.beginPath();orbCtx.arc(orbCX,orbCY,orbR*.85,0,TAU);orbCtx.fill();
/* Rotating Core Hex Brackets */
orbCtx.save();
orbCtx.translate(orbCX,orbCY);
orbCtx.rotate(t*.0008);
orbCtx.strokeStyle='rgba(56,189,248,.7)';
orbCtx.lineWidth=1.4;
orbCtx.beginPath();
for(let i=0;i<6;i++){
const ang=(i/6)*TAU;
const hx=Math.cos(ang)*orbR*.62;
const hy=Math.sin(ang)*orbR*.62;
if(i===0)orbCtx.moveTo(hx,hy);else orbCtx.lineTo(hx,hy);
}
orbCtx.closePath();orbCtx.stroke();
orbCtx.restore();
/* Central Core Badge */
orbCtx.save();
orbCtx.font=`700 ${(orbR*.36)|0}px var(--font-disp, monospace)`;
orbCtx.textAlign='center';orbCtx.textBaseline='middle';
orbCtx.fillStyle='#ffffff';
orbCtx.shadowColor='rgba(56,189,248,.9)';orbCtx.shadowBlur=10;
orbCtx.fillText('⬡',orbCX,orbCY-1);
orbCtx.restore();
/* Core Shockwave Radar Pings */
if(!RM&&t>nextOrbPulse){
orbPulses.push({t0:t});
nextOrbPulse=t+3200+Math.random()*2200;
}
for(let i=orbPulses.length-1;i>=0;i--){
const f=(t-orbPulses[i].t0)/2200;
if(f>=1){orbPulses.splice(i,1);continue;}
const prp=(.85+f*1.4)*orbR;
const alp=((1-f)*.45).toFixed(3);
orbCtx.strokeStyle=`rgba(56,189,248,${alp})`;
orbCtx.lineWidth=1.5;
orbCtx.beginPath();
orbCtx.arc(orbCX,orbCY,prp,0,TAU);
orbCtx.stroke();
}
/* Near Ring Segments */
for(const ring of orbRings){
orbCtx.lineWidth=1.3;
for(let k=0;k<ring.segs;k++){
const a1=(k/ring.segs)*TAU;
const a2=((k+1)/ring.segs)*TAU;
const q1=ringPt(ring,a1);
const q2=ringPt(ring,a2);
if(q1.z>0&&q2.z>0){
const alpha=clamp((q1.pr-.72)*2.2,.25,.95);
orbCtx.strokeStyle=ring.color+alpha.toFixed(3)+')';
orbCtx.beginPath();orbCtx.moveTo(q1.x,q1.y);orbCtx.lineTo(q2.x,q2.y);orbCtx.stroke();
}
}
}
/* Container Nodes & Laser Beams */
const renderedNodes=orbNodes.map(n=>{
const ring=orbRings[n.ring];
const pos=ringPt(ring,n.a);
return{...n,pos};
}).sort((a,b)=>a.pos.z-b.pos.z);
for(const node of renderedNodes){
const q=node.pos;
const r=node.sz*q.pr;
const [cr,cg,cb]=node.color;
const cl=clamp((q.pr-.75)*1.9,.35,1);
if(q.z>0||Math.abs(q.z)<orbR*.8){
const laserGrad=orbCtx.createLinearGradient(orbCX,orbCY,q.x,q.y);
laserGrad.addColorStop(0,`rgba(56,189,248,${(.12*cl).toFixed(3)})`);
laserGrad.addColorStop(.7,`rgba(${cr},${cg},${cb},${(.35*cl).toFixed(3)})`);
laserGrad.addColorStop(1,`rgba(${cr},${cg},${cb},${(.85*cl).toFixed(3)})`);
orbCtx.strokeStyle=laserGrad;
orbCtx.lineWidth=1.2;
orbCtx.beginPath();
orbCtx.moveTo(orbCX,orbCY);
orbCtx.lineTo(q.x,q.y);
orbCtx.stroke();
const pktPos=(t*.0018+node.a)%1;
const px=orbCX+(q.x-orbCX)*pktPos;
const py=orbCY+(q.y-orbCY)*pktPos;
orbCtx.fillStyle='#fff';
orbCtx.beginPath();
orbCtx.arc(px,py,1.8*q.pr,0,TAU);
orbCtx.fill();
}
orbCtx.globalCompositeOperation='lighter';
let g=orbCtx.createRadialGradient(q.x,q.y,0,q.x,q.y,r*4.5);
g.addColorStop(0,`rgba(${cr},${cg},${cb},${(.6*cl).toFixed(3)})`);
g.addColorStop(1,`rgba(${cr},${cg},${cb},0)`);
orbCtx.fillStyle=g;
orbCtx.beginPath();orbCtx.arc(q.x,q.y,r*4.5,0,TAU);orbCtx.fill();
orbCtx.globalCompositeOperation='source-over';
g=orbCtx.createRadialGradient(q.x-r*.3,q.y-r*.3,0,q.x,q.y,r);
g.addColorStop(0,'#ffffff');
g.addColorStop(.45,`rgb(${cr},${cg},${cb})`);
g.addColorStop(1,'#05070d');
orbCtx.fillStyle=g;
orbCtx.beginPath();orbCtx.arc(q.x,q.y,r,0,TAU);orbCtx.fill();
orbCtx.strokeStyle=`rgba(255,255,255,${(.8*cl).toFixed(2)})`;
orbCtx.lineWidth=1;
orbCtx.stroke();
if(q.z>-orbR*.4){
orbCtx.save();
orbCtx.font=`600 ${Math.max(9,(10*q.pr)|0)}px var(--font-mono, monospace)`;
orbCtx.textAlign='left';
orbCtx.textBaseline='middle';
orbCtx.fillStyle=`rgba(241,245,249,${(.9*cl).toFixed(2)})`;
orbCtx.fillText(`${node.label} ${node.port}`,q.x+r+6,q.y);
orbCtx.restore();
}
}
/* Near dust */
for(const d of orbDust){
const q=P(Math.cos(d.a)*d.rr*orbR,d.y*orbR,Math.sin(d.a)*d.rr*orbR);
if(q.z<=0)continue;
const al=d.al*clamp((q.pr-.75)*2.2,.35,1);
orbCtx.fillStyle=d.isPurple?`rgba(192,132,252,${al.toFixed(3)})`:`rgba(125,211,252,${al.toFixed(3)})`;
orbCtx.beginPath();orbCtx.arc(q.x,q.y,d.sz*q.pr,0,TAU);orbCtx.fill();
}
}
/* ═══════════════ UI — cursor · reveals · scramble · telemetry ═══════════════ */
let curDot=null,curRing=null,curShown=false,crx=innerWidth/2,cry=innerHeight/2;
if(FINE&&!RM){curDot=$('#curDot');curRing=$('#curRing');document.body.classList.add('has-cur');}
@@ -989,8 +1307,9 @@ setTimeout(()=>scramble($('#tagScr')),350);
const vio=new IntersectionObserver(es=>{for(const en of es){
if(en.target===fbox)fVis=en.isIntersecting;
if(en.target===obox)oVis=en.isIntersecting;
if(orbBox&&en.target===orbBox)orbVis=en.isIntersecting;
}},{rootMargin:'80px'});
vio.observe(fbox);vio.observe(obox);
vio.observe(fbox);vio.observe(obox);if(orbBox)vio.observe(orbBox);
/* magnetic buttons */
if(FINE&&!RM)$$('.mag').forEach(b=>{
@@ -1039,6 +1358,26 @@ for(let i=0;i<14;i++){
bars.appendChild(b);
}
/* orbit stats — live jitter + telemetry bars */
const orbPorts=$('#orbPorts');
if(orbPorts){
const portsList=[':4100',':4102',':4105',':4280',':4310',':4450'];
setInterval(()=>{
if(RM)return;
orbPorts.textContent=portsList[(Math.random()*portsList.length)|0];
},2200);
}
const orbitBars=$('#orbitBars');
if(orbitBars){
for(let i=0;i<14;i++){
const b=document.createElement('i');
b.style.height=(5+Math.random()*17)+'px';
b.style.animationDuration=(.6+Math.random()*.8)+'s';
b.style.animationDelay=(-Math.random()*2).toFixed(2)+'s';
orbitBars.appendChild(b);
}
}
/* HUD telemetry — UTC clock, pointer RA/DEC, session uptime */
const hudRa=$('#hudRa'),hudDec=$('#hudDec'),hudUtc=$('#hudUtc'),ftUp=$('#ftUp');
const t0=Date.now();
@@ -1074,7 +1413,8 @@ skyResize();buildStars();nebTex=makeNebula();
addEventListener('resize',()=>{skyResize();buildStars();});
new ResizeObserver(forgeResize).observe(fbox);
new ResizeObserver(oortResize).observe(obox);
forgeResize();oortResize();
if(orbBox)new ResizeObserver(orbitResize).observe(orbBox);
forgeResize();oortResize();if(orbBox)orbitResize();
/* pre-bake forge textures during idle time so scrolling never hitches */
const warm=()=>{if(!fInit)forgeInit();};
@@ -1090,6 +1430,7 @@ function loop(t){
skyFrame(tt,dt);
if(fVis)forgeFrame(tt,dt);
if(oVis)oortFrame(tt,dt);
if(orbVis)orbitFrame(tt,dt);
uiFrame(t);
requestAnimationFrame(loop);
}
+1106 -119
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+358
View File
@@ -0,0 +1,358 @@
<!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=JetBrains+Mono:wght@400;500;600&family=Space+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root {
--bg: #030712;
--card-bg: rgba(15, 23, 42, 0.75);
--border: rgba(148, 163, 184, 0.15);
--border-glow: rgba(56, 189, 248, 0.3);
--accent: #38bdf8;
--accent-glow: rgba(56, 189, 248, 0.2);
--text: #f8fafc;
--text-muted: #94a3b8;
--text-dim: #64748b;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
background-color: var(--bg);
color: var(--text);
font-family: 'Space Grotesk', sans-serif;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 24px;
overflow-x: hidden;
position: relative;
}
#stars {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 0;
}
.nebula {
position: fixed;
width: 600px;
height: 600px;
border-radius: 50%;
background: radial-gradient(circle, rgba(56, 189, 248, 0.08) 0%, rgba(99, 102, 241, 0.05) 40%, transparent 70%);
filter: blur(60px);
pointer-events: none;
z-index: 0;
}
.share-card {
position: relative;
z-index: 10;
width: 100%;
max-width: 480px;
background: var(--card-bg);
border: 1px solid var(--border);
backdrop-filter: blur(20px);
border-radius: 20px;
padding: 36px 32px;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.5), 0 0 40px rgba(56, 189, 248, 0.08);
animation: floatUp 0.6s cubic-bezier(0.16, 1, 0.3, 1);
}
@keyframes floatUp {
from { opacity: 0; transform: translateY(20px); }
to { opacity: 1; transform: translateY(0); }
}
.brand {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 28px;
}
.brand-icon {
width: 36px;
height: 36px;
background: rgba(56, 189, 248, 0.1);
border: 1px solid rgba(56, 189, 248, 0.3);
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
}
.brand-name {
font-weight: 700;
font-size: 16px;
letter-spacing: 0.08em;
color: #fff;
}
.brand-pill {
font-family: 'JetBrains Mono', monospace;
font-size: 10px;
padding: 2px 8px;
border-radius: 999px;
background: rgba(56, 189, 248, 0.12);
color: var(--accent);
border: 1px solid rgba(56, 189, 248, 0.25);
}
.file-box {
background: rgba(0, 0, 0, 0.3);
border: 1px solid var(--border);
border-radius: 14px;
padding: 20px;
margin-bottom: 24px;
display: flex;
align-items: center;
gap: 16px;
}
.file-icon {
width: 48px;
height: 48px;
border-radius: 12px;
background: rgba(99, 102, 241, 0.15);
border: 1px solid rgba(99, 102, 241, 0.3);
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
color: #818cf8;
}
.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: 'JetBrains Mono', monospace;
font-size: 12px;
color: var(--text-muted);
display: flex;
gap: 12px;
}
.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.03);
border: 1px solid rgba(255, 255, 255, 0.06);
padding: 12px;
border-radius: 10px;
}
.stat-label {
font-size: 11px;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 0.08em;
margin-bottom: 4px;
}
.stat-val {
font-family: 'JetBrains Mono', monospace;
font-size: 13px;
font-weight: 500;
color: var(--text);
}
.btn-download {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
width: 100%;
padding: 14px 20px;
background: linear-gradient(135deg, #38bdf8 0%, #6366f1 100%);
color: #fff;
text-decoration: none;
border: none;
border-radius: 12px;
font-weight: 600;
font-size: 15px;
cursor: pointer;
transition: all 0.2s ease;
box-shadow: 0 4px 20px rgba(56, 189, 248, 0.25);
}
.btn-download:hover {
transform: translateY(-2px);
box-shadow: 0 8px 30px rgba(56, 189, 248, 0.4);
}
.input-pass {
width: 100%;
padding: 13px 16px;
background: rgba(0, 0, 0, 0.35);
border: 1px solid var(--border);
border-radius: 10px;
color: #fff;
font-family: inherit;
font-size: 14px;
outline: none;
margin-bottom: 16px;
transition: border-color 0.2s;
}
.input-pass:focus {
border-color: var(--accent);
box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.2);
}
.error-msg {
background: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.3);
color: #f87171;
padding: 10px 14px;
border-radius: 8px;
font-size: 13px;
margin-bottom: 16px;
}
.footer {
position: relative;
z-index: 10;
margin-top: 24px;
font-size: 12px;
color: var(--text-dim);
text-align: center;
}
</style>
</head>
<body>
<div class="nebula"></div>
<canvas id="stars"></canvas>
<div class="share-card">
<div class="brand">
<div class="brand-icon">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#38bdf8" 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>
<div class="brand-name">COSMOS OORT</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)">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:#38bdf8">{{.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:8px">This file is password-protected. Enter password to unlock:</div>
<input type="password" name="password" class="input-pass" placeholder="Enter file 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 File
</a>
{{end}}
{{end}}
</div>
<div class="footer">
Powered by <strong>Cosmos Oort</strong> · Sovereign Cloud Workstation
</div>
<script>
// Particle canvas background
const canvas = document.getElementById('stars');
const ctx = canvas.getContext('2d');
let W, H, stars = [];
function resize() {
W = canvas.width = window.innerWidth;
H = canvas.height = window.innerHeight;
stars = Array.from({length: 60}, () => ({
x: Math.random() * W,
y: Math.random() * H,
r: Math.random() * 1.5 + 0.5,
alpha: Math.random() * 0.8 + 0.2,
speed: Math.random() * 0.02 + 0.005
}));
}
window.addEventListener('resize', resize);
resize();
function anim() {
ctx.clearRect(0, 0, W, H);
stars.forEach(s => {
s.alpha += s.speed;
if(s.alpha > 1 || s.alpha < 0.2) s.speed = -s.speed;
ctx.fillStyle = `rgba(255, 255, 255, ${s.alpha})`;
ctx.beginPath();
ctx.arc(s.x, s.y, s.r, 0, Math.PI * 2);
ctx.fill();
});
requestAnimationFrame(anim);
}
anim();
</script>
</body>
</html>