Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 89 additions & 0 deletions admin/console.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"net/url"
"os"
"sort"
"strings"
"time"
Expand All @@ -19,6 +20,60 @@ import (
"mu/work"
)

// InviteHandler serves the admin invite page at /admin/invite.
func InviteHandler(w http.ResponseWriter, r *http.Request) {
sess, _, err := auth.RequireAdmin(r)
if err != nil {
app.Forbidden(w, r, "Admin access required")
return
}

if r.Method == "POST" {
r.ParseForm()
email := strings.TrimSpace(r.FormValue("email"))
if email == "" {
app.BadRequest(w, r, "Email is required")
return
}
code, err := auth.CreateInvite(email, sess.Account)
if err != nil {
app.ServerError(w, r, "Failed to create invite: "+err.Error())
return
}
base := app.PublicURL()
link := base + "/signup?invite=" + code

// Try to email the invite. If mail isn't configured, show the link.
if app.EmailSender != nil {
plain := fmt.Sprintf("You've been invited to join Mu.\n\nSign up here: %s\n\nThis link is single-use.", link)
html := fmt.Sprintf(`<p>You've been invited to join Mu.</p><p><a href="%s">Sign up here</a></p><p>This link is single-use.</p>`, link)
if err := app.EmailSender(email, "You're invited to Mu", plain, html); err != nil {
app.Log("admin", "Failed to email invite to %s: %v", email, err)
}
}

content := fmt.Sprintf(`<div class="card">
<h4>Invite sent</h4>
<p>Invite created for <strong>%s</strong></p>
<p><a href="%s">%s</a></p>
<p class="text-muted text-sm">Link has been emailed (if mail is configured). Single use.</p>
<p><a href="/admin/invite">Invite another →</a> · <a href="/home">Home →</a></p>
</div>`, email, link, link)
w.Write([]byte(app.RenderHTML("Invite Sent", "Invite sent", content)))
return
}

content := `<div class="card">
<h4>Invite a user</h4>
<p class="text-sm">Enter their email address. They'll receive a single-use signup link.</p>
<form method="POST" action="/admin/invite" class="mt-4">
<input type="email" name="email" placeholder="user@example.com" required class="form-input">
<button type="submit" class="mt-2">Send invite</button>
</form>
</div>`
w.Write([]byte(app.RenderHTML("Invite User", "Invite a user", content)))
}

// ConsoleHandler provides an admin console.
func ConsoleHandler(w http.ResponseWriter, r *http.Request) {
_, _, err := auth.RequireAdmin(r)
Expand Down Expand Up @@ -270,6 +325,40 @@ func runCommand(cmd string) string {
user.ClearStatusHistory(arg(1))
return fmt.Sprintf("Cleared all status history for %s", arg(1))

case "invite":
if arg(1) == "" {
return "usage: invite <email>"
}
email := arg(1)
// Use "admin" as the admin ID for console-created invites
code, err := auth.CreateInvite(email, "admin")
if err != nil {
return "invite failed: " + err.Error()
}
url := ""
if v := os.Getenv("PUBLIC_URL"); v != "" {
url = v
} else if v := os.Getenv("MAIL_DOMAIN"); v != "" {
url = "https://" + v
}
link := url + "/signup?invite=" + code
return fmt.Sprintf("Invite created for %s\nCode: %s\nLink: %s", email, code, link)

case "invites":
list := auth.ListInvites()
if len(list) == 0 {
return "No invites"
}
var sb strings.Builder
for _, inv := range list {
used := "unused"
if inv.UsedBy != "" {
used = "used by " + inv.UsedBy
}
sb.WriteString(fmt.Sprintf(" %s → %s (%s, %s)\n", inv.Code[:8]+"...", inv.Email, used, inv.CreatedAt.Format("2 Jan 15:04")))
}
return sb.String()

// --- Wallet ---
case "wallet":
if arg(1) == "" {
Expand Down
28 changes: 17 additions & 11 deletions apps/apps.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"mu/internal/auth"
"mu/internal/data"
"mu/internal/event"
"mu/internal/flag"
"mu/wallet"

"github.com/google/uuid"
Expand Down Expand Up @@ -571,15 +572,6 @@ func handleCreate(w http.ResponseWriter, r *http.Request) {
return
}

if !auth.CanPost(acc.ID) {
app.Forbidden(w, r, auth.PostBlockReason(acc.ID))
return
}
if err := auth.CheckPostRate(acc.ID); err != nil {
app.Forbidden(w, r, err.Error())
return
}

var name, slug, icon, description, tags, html string
var public bool
var price int
Expand Down Expand Up @@ -693,6 +685,15 @@ func handleCreate(w http.ResponseWriter, r *http.Request) {

app.Log("apps", "Created app %q by %s", name, acc.ID)

// Async content moderation — flags and auto-bans on detection.
go func(authorID, appName, appDesc string) {
flag.CheckContent("app", slug, appName, appDesc)
if item := flag.GetItem("app", slug); item != nil && item.Flagged {
app.Log("moderation", "Auto-banning %s after app %q flagged", authorID, appName)
auth.BanAccount(authorID)
}
}(acc.ID, name, description)

// Notify home dashboard to refresh
event.Publish(event.Event{Type: "apps_updated"})

Expand Down Expand Up @@ -1579,9 +1580,14 @@ func GetPublicApps() []*App {

var list []*App
for _, a := range apps {
if a.Public {
list = append(list, a)
if !a.Public {
continue
}
// Hide apps from banned users and flagged apps.
if auth.IsBanned(a.AuthorID) || flag.IsHidden("app", a.Slug) {
continue
}
list = append(list, a)
}
sort.Slice(list, func(i, j int) bool {
if list[i].Installs != list[j].Installs {
Expand Down
57 changes: 2 additions & 55 deletions apps/builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"mu/internal/app"
"mu/internal/auth"
"mu/internal/event"
"mu/wallet"

"github.com/google/uuid"
)
Expand Down Expand Up @@ -283,17 +282,12 @@ func handleGenerate(w http.ResponseWriter, r *http.Request) {
return
}

_, acc, err := auth.RequireSession(r)
_, _, err := auth.RequireSession(r)
if err != nil {
app.Unauthorized(w, r)
return
}

if !auth.CanPost(acc.ID) {
app.RespondError(w, http.StatusForbidden, auth.PostBlockReason(acc.ID))
return
}

var req struct {
Prompt string `json:"prompt"`
Code string `json:"code"` // Existing code for follow-on prompts
Expand All @@ -309,27 +303,6 @@ func handleGenerate(w http.ResponseWriter, r *http.Request) {
return
}

// Charge for AI generation — edit if there's existing code, otherwise build.
op := wallet.OpAppBuild
if req.Code != "" {
op = wallet.OpAppEdit
}
canProceed, _, cost, _ := wallet.CheckQuota(acc.ID, op)
if !canProceed {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(402)
json.NewEncoder(w).Encode(map[string]any{
"error": "insufficient_credits",
"message": fmt.Sprintf("AI generation requires %d credits. Top up at /wallet", cost),
"cost": cost,
})
return
}
if err := wallet.ConsumeQuota(acc.ID, op); err != nil {
app.RespondError(w, http.StatusForbidden, err.Error())
return
}

// Build the AI prompt
question := req.Prompt
var rag []string
Expand Down Expand Up @@ -488,17 +461,12 @@ func handleFrameworkGenerate(w http.ResponseWriter, r *http.Request) {
return
}

_, acc, err := auth.RequireSession(r)
_, _, err := auth.RequireSession(r)
if err != nil {
app.Unauthorized(w, r)
return
}

if !auth.CanPost(acc.ID) {
app.RespondError(w, http.StatusForbidden, auth.PostBlockReason(acc.ID))
return
}

var req struct {
Prompt string `json:"prompt"`
Blocks []Block `json:"blocks"` // Existing blocks for editing
Expand All @@ -513,27 +481,6 @@ func handleFrameworkGenerate(w http.ResponseWriter, r *http.Request) {
return
}

// Charge for AI generation — edit if blocks present, otherwise build.
op := wallet.OpAppBuild
if len(req.Blocks) > 0 {
op = wallet.OpAppEdit
}
canProceed, _, cost, _ := wallet.CheckQuota(acc.ID, op)
if !canProceed {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(402)
json.NewEncoder(w).Encode(map[string]any{
"error": "insufficient_credits",
"message": fmt.Sprintf("AI generation requires %d credits. Top up at /wallet", cost),
"cost": cost,
})
return
}
if err := wallet.ConsumeQuota(acc.ID, op); err != nil {
app.RespondError(w, http.StatusForbidden, err.Error())
return
}

question := req.Prompt
var rag []string

Expand Down
64 changes: 0 additions & 64 deletions blog/blog.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
"mu/internal/data"
"mu/internal/event"
"mu/internal/flag"
"mu/wallet"
)

//go:embed topics.json
Expand Down Expand Up @@ -1233,45 +1232,13 @@ func PostHandler(w http.ResponseWriter, r *http.Request) {
author := acc.Name
authorID := acc.ID

// Check quota for blog creation
canProceed, _, cost, _ := wallet.CheckQuota(acc.ID, wallet.OpBlogCreate)
if !canProceed {
if app.SendsJSON(r) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(402)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": "quota_exceeded",
"message": "Daily limit reached. Please top up credits at /wallet",
"cost": cost,
})
return
}
content := wallet.QuotaExceededPage(wallet.OpBlogCreate, cost)
html := app.RenderHTMLForRequest("Quota Exceeded", "Daily limit reached", content, r)
w.Write([]byte(html))
return
}

// Verified email is required to post.
if !auth.CanPost(acc.ID) {
app.Forbidden(w, r, auth.PostBlockReason(acc.ID))
return
}
if err := auth.CheckPostRate(acc.ID); err != nil {
app.Forbidden(w, r, err.Error())
return
}

// Create post
postID := fmt.Sprintf("%d", time.Now().UnixNano())
if err := CreatePost(title, content, author, authorID, tags, private); err != nil {
http.Error(w, "Failed to save post", http.StatusInternalServerError)
return
}

// Consume quota for blog creation
wallet.ConsumeQuota(acc.ID, wallet.OpBlogCreate)

// Run async LLM-based content moderation
go flag.CheckContent("post", postID, title, content)

Expand Down Expand Up @@ -1803,37 +1770,6 @@ func CommentHandler(w http.ResponseWriter, r *http.Request) {
return
}

// Verified email is required to post.
if !auth.CanPost(acc.ID) {
app.Forbidden(w, r, auth.PostBlockReason(acc.ID))
return
}
if err := auth.CheckPostRate(acc.ID); err != nil {
app.Forbidden(w, r, err.Error())
return
}

// Charge per comment — makes spam expensive.
canProceed, _, cost, _ := wallet.CheckQuota(acc.ID, wallet.OpBlogComment)
if !canProceed {
if app.SendsJSON(r) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(402)
json.NewEncoder(w).Encode(map[string]interface{}{
"error": "insufficient_credits",
"message": fmt.Sprintf("Comments require %d credit. Top up at /wallet", cost),
"cost": cost,
})
return
}
app.Forbidden(w, r, fmt.Sprintf("Comments require %d credit. Top up at /wallet", cost))
return
}
if err := wallet.ConsumeQuota(acc.ID, wallet.OpBlogComment); err != nil {
app.Forbidden(w, r, err.Error())
return
}

// Get the authenticated user
author := acc.Name
authorID := acc.ID
Expand Down
9 changes: 7 additions & 2 deletions home/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -287,9 +287,14 @@ func Handler(w http.ResponseWriter, r *http.Request) {

var b strings.Builder

// Date header
// Date header + admin actions
now := time.Now()
b.WriteString(fmt.Sprintf(`<p id="home-date">%s</p>`, now.Format("Monday, 2 January 2006")))
_, viewerAcc := auth.TrySession(r)
inviteLink := ""
if viewerAcc != nil && viewerAcc.Admin && auth.InviteOnly() {
inviteLink = ` <a href="/admin/invite" style="float:right;font-size:13px;color:#555;text-decoration:none">+ Invite user</a>`
}
b.WriteString(fmt.Sprintf(`<p id="home-date">%s%s</p>`, now.Format("Monday, 2 January 2006"), inviteLink))

// Status card content (will be prepended to left column).
// Built by user.RenderStatusStream so the fragment endpoint and the
Expand Down
Loading
Loading