Something went wrong. Try again.
(READ ONLY) Margin is an open annotation layer for the internet. Powered by the AT Protocol.
margin.at
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149package api
import ( "encoding/json" "fmt" "io" "net/http" "strconv" "strings" "time"
"github.com/go-chi/chi/v5"
"margin.at/internal/cloudflare" "margin.at/internal/config" "margin.at/internal/db" "margin.at/internal/logger" "margin.at/internal/xrpc")
type ReadingRoomTheme struct { BackgroundColor string `json:"backgroundColor"` AccentColor string `json:"accentColor"` FontFamily string `json:"fontFamily"` Layout string `json:"layout"`}
type ReadingRoomConfigResponse struct { Enabled bool `json:"enabled"` Title string `json:"title"` Subtitle string `json:"subtitle"` Description string `json:"description"` Theme ReadingRoomTheme `json:"theme"` FeaturedURIs []string `json:"featuredUris"` HasSubscription bool `json:"hasSubscription"` ShowExternalBookmarks bool `json:"showExternalBookmarks"`}
type ReadingRoomPublicResponse struct { Handle string `json:"handle"` DID string `json:"did"` Title string `json:"title"` Subtitle string `json:"subtitle"` Description string `json:"description"` Theme ReadingRoomTheme `json:"theme"` DisplayName string `json:"displayName"` Avatar string `json:"avatar"` Bio string `json:"bio"` CustomDomain string `json:"customDomain,omitempty"` Featured []interface{} `json:"featured"` Recent []interface{} `json:"recent"` TotalCount int `json:"totalCount"` TypeCounts map[string]int `json:"typeCounts"`}
type BillingStatusResponse struct { Status string `json:"status"` Plan string `json:"plan"` CurrentPeriodEnd *time.Time `json:"currentPeriodEnd,omitempty"` HasSubscription bool `json:"hasSubscription"`}
type CustomDomainResponse struct { Domain string `json:"domain"` Status string `json:"status"` VerificationRecords interface{} `json:"verificationRecords"`}
func parseTheme(themeJSON string) ReadingRoomTheme { t := ReadingRoomTheme{ BackgroundColor: "#fcfcfc", AccentColor: "#3b82f6", FontFamily: "sans-serif", Layout: "masonry", } if themeJSON != "" { json.Unmarshal([]byte(themeJSON), &t) } return t}
func parseFeaturedURIs(urisJSON string) []string { var uris []string if urisJSON != "" { json.Unmarshal([]byte(urisJSON), &uris) } if uris == nil { uris = []string{} } return uris}
func (h *Handler) resolveHandleOrDID(r *http.Request, handleOrDID string) string { if strings.HasPrefix(handleOrDID, "did:") { return handleOrDID } var did string h.db.Pool().QueryRow(r.Context(), "SELECT did FROM oauth_sessions WHERE handle = $1 LIMIT 1", handleOrDID).Scan(&did) if did != "" { return did } did, err := xrpc.ResolveHandle(handleOrDID) if err != nil { return "" } return did}
func (h *Handler) resolveDIDToHandle(r *http.Request, did string) string { var handle string h.db.Pool().QueryRow(r.Context(), "SELECT handle FROM oauth_sessions WHERE did = $1 ORDER BY created_at DESC LIMIT 1", did).Scan(&handle) return handle}
func isExternalBookmark(uri string) bool { return strings.Contains(uri, "network.cosmik") || strings.Contains(uri, "semble") || strings.Contains(uri, "wiki.lichen.bookmark") || strings.Contains(uri, "community.lexicon.bookmarks.bookmark")}
func (h *Handler) GetPublicReadingRoom(w http.ResponseWriter, r *http.Request) { handle := chi.URLParam(r, "handle") if handle == "" { WriteBadRequest(w, "handle required") return }
did := h.resolveHandleOrDID(r, handle) if did == "" { WriteNotFound(w, "Reading room not found") return }
if !h.db.HasActiveSubscription(r.Context(), did) { WriteNotFound(w, "Reading room not found") return }
rrConfig, err := h.db.GetReadingRoomConfig(r.Context(), did) if err != nil { fmt.Printf("[GetPublicReadingRoom] DB error: %v\n", err) WriteInternalError(w, "Failed to fetch reading room") return } if rrConfig == nil { rrConfig = &db.ReadingRoomConfig{} }
theme := parseTheme(rrConfig.Theme) featuredURIs := parseFeaturedURIs(rrConfig.FeaturedURIs)
profile, _ := h.db.GetProfile(r.Context(), did) displayName, avatar, bio := "", "", "" if profile != nil { if profile.DisplayName != nil { displayName = *profile.DisplayName } if profile.Avatar != nil { avatar = *profile.Avatar } if profile.Bio != nil { bio = *profile.Bio } }
if rrConfig != nil && !rrConfig.ShowExternalBookmarks { filteredURIs := featuredURIs[:0] for _, u := range featuredURIs { if !isExternalBookmark(u) { filteredURIs = append(filteredURIs, u) } } featuredURIs = filteredURIs }
featured := h.fetchNotesByURIs(r, featuredURIs)
recentNotes, err := h.noteRepo.List(r.Context(), db.NoteFilter{ AuthorDID: did, Limit: 20, Offset: 0, }) if err != nil { recentNotes = nil } recentNotes = h.filterHiddenNotes(r.Context(), h.getViewerDID(r), recentNotes) excludeExternal := rrConfig != nil && !rrConfig.ShowExternalBookmarks if excludeExternal { filtered := recentNotes[:0] for _, n := range recentNotes { if !isExternalBookmark(n.URI) { filtered = append(filtered, n) } } recentNotes = filtered } lc, _ := h.hydration.Load(r.Context(), recentNotes, h.getViewerDID(r)) recent := make([]interface{}, len(recentNotes)) for i, n := range recentNotes { recent[i] = h.hydration.ToAPINote(n, lc) }
totalCount, _ := h.db.CountNotesByAuthor(r.Context(), did, excludeExternal) typeCounts, _ := h.db.CountNotesByAuthorByType(r.Context(), did, excludeExternal)
customDomain := "" if rrConfig.DomainStatus == "active" { customDomain = rrConfig.CustomDomain }
resolvedHandle := handle if strings.HasPrefix(handle, "did:") { resolvedHandle = h.resolveDIDToHandle(r, did) if resolvedHandle == "" { resolvedHandle = did } }
WriteSuccess(w, ReadingRoomPublicResponse{ Handle: resolvedHandle, DID: did, Title: rrConfig.Title, Subtitle: rrConfig.Subtitle, Description: rrConfig.Description, Theme: theme, DisplayName: displayName, Avatar: avatar, Bio: bio, CustomDomain: customDomain, Featured: featured, Recent: recent, TotalCount: totalCount, TypeCounts: typeCounts, })}
func (h *Handler) fetchNotesByURIs(r *http.Request, uris []string) []interface{} { if len(uris) == 0 { return []interface{}{} } viewerDID := h.getViewerDID(r) result := make([]interface{}, 0, len(uris)) for _, uri := range uris { note, err := h.noteRepo.GetByURI(r.Context(), uri) if err != nil || note == nil { continue } lc, _ := h.hydration.Load(r.Context(), []db.Note{*note}, viewerDID) result = append(result, h.hydration.ToAPINote(*note, lc)) } return result}
type ReadingRoomNoteResponse struct { Handle string `json:"handle"` DID string `json:"did"` RoomTitle string `json:"roomTitle"` DisplayName string `json:"displayName"` Avatar string `json:"avatar"` Theme ReadingRoomTheme `json:"theme"` Note interface{} `json:"note"`}
func (h *Handler) GetPublicReadingRoomNote(w http.ResponseWriter, r *http.Request) { handle := chi.URLParam(r, "handle") uri := r.URL.Query().Get("uri") if handle == "" || uri == "" { WriteBadRequest(w, "handle and uri required") return }
did := h.resolveHandleOrDID(r, handle) if did == "" { WriteNotFound(w, "Reading room not found") return }
if !h.db.HasActiveSubscription(r.Context(), did) { WriteNotFound(w, "Reading room not found") return }
if !strings.HasPrefix(uri, "at://"+did+"/") { WriteNotFound(w, "Note not found") return }
note, err := h.noteRepo.GetByURI(r.Context(), uri) if err != nil || note == nil { WriteNotFound(w, "Note not found") return }
hidden := h.filterHiddenNotes(r.Context(), h.getViewerDID(r), []db.Note{*note}) if len(hidden) == 0 { WriteNotFound(w, "Note not found") return }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), did) if rrConfig == nil { rrConfig = &db.ReadingRoomConfig{} } theme := parseTheme(rrConfig.Theme)
profile, _ := h.db.GetProfile(r.Context(), did) displayName, avatar := "", "" if profile != nil { if profile.DisplayName != nil { displayName = *profile.DisplayName } if profile.Avatar != nil { avatar = *profile.Avatar } }
lc, _ := h.hydration.Load(r.Context(), []db.Note{*note}, h.getViewerDID(r))
resolvedHandle := handle if strings.HasPrefix(handle, "did:") { resolvedHandle = h.resolveDIDToHandle(r, did) if resolvedHandle == "" { resolvedHandle = did } }
WriteSuccess(w, ReadingRoomNoteResponse{ Handle: resolvedHandle, DID: did, RoomTitle: rrConfig.Title, DisplayName: displayName, Avatar: avatar, Theme: theme, Note: h.hydration.ToAPINote(*note, lc), })}
func (h *Handler) GetReadingRoomNotes(w http.ResponseWriter, r *http.Request) { handle := chi.URLParam(r, "handle") if handle == "" { WriteBadRequest(w, "handle required") return }
did := h.resolveHandleOrDID(r, handle) if did == "" { WriteNotFound(w, "Reading room not found") return }
if !h.db.HasActiveSubscription(r.Context(), did) { WriteNotFound(w, "Reading room not found") return }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), did) excludeExternal := rrConfig != nil && !rrConfig.ShowExternalBookmarks
offset := 20 limit := 20 if s := r.URL.Query().Get("offset"); s != "" { if v, err := strconv.Atoi(s); err == nil && v >= 0 { offset = v } } if s := r.URL.Query().Get("limit"); s != "" { if v, err := strconv.Atoi(s); err == nil && v > 0 && v <= 50 { limit = v } }
notes, err := h.noteRepo.List(r.Context(), db.NoteFilter{ AuthorDID: did, Limit: limit, Offset: offset, }) if err != nil { notes = nil } notes = h.filterHiddenNotes(r.Context(), h.getViewerDID(r), notes) if excludeExternal { filtered := notes[:0] for _, n := range notes { if !isExternalBookmark(n.URI) { filtered = append(filtered, n) } } notes = filtered }
lc, _ := h.hydration.Load(r.Context(), notes, h.getViewerDID(r)) result := make([]interface{}, len(notes)) for i, n := range notes { result[i] = h.hydration.ToAPINote(n, lc) }
totalCount, _ := h.db.CountNotesByAuthor(r.Context(), did, excludeExternal)
WriteSuccess(w, map[string]interface{}{ "notes": result, "totalCount": totalCount, })}
func (h *Handler) GetReadingRoomConfig(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
rrConfig, err := h.db.GetReadingRoomConfig(r.Context(), session.DID) if err != nil { WriteInternalError(w, "Failed to fetch config") return }
sub, _ := h.db.GetSubscription(r.Context(), session.DID) hasSub := sub != nil && (sub.Status == "active" || sub.Status == "trialing")
resp := ReadingRoomConfigResponse{ Enabled: rrConfig != nil, HasSubscription: hasSub, ShowExternalBookmarks: true, Theme: ReadingRoomTheme{ AccentColor: "#3b82f6", FontFamily: "sans-serif", Layout: "masonry", }, FeaturedURIs: []string{}, }
if rrConfig != nil { resp.Title = rrConfig.Title resp.Subtitle = rrConfig.Subtitle resp.Description = rrConfig.Description resp.Theme = parseTheme(rrConfig.Theme) resp.FeaturedURIs = parseFeaturedURIs(rrConfig.FeaturedURIs) resp.ShowExternalBookmarks = rrConfig.ShowExternalBookmarks }
WriteSuccess(w, resp)}
func (h *Handler) UpdateReadingRoomConfig(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
if !h.db.HasActiveSubscription(r.Context(), session.DID) { WriteForbidden(w, "Margin Pro required") return }
var input struct { Title string `json:"title"` Subtitle string `json:"subtitle"` Description string `json:"description"` Theme ReadingRoomTheme `json:"theme"` ShowExternalBookmarks *bool `json:"showExternalBookmarks"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { WriteBadRequest(w, "Invalid input") return }
if len(input.Title) > 200 { WriteBadRequest(w, "Title too long") return } if len(input.Description) > 2000 { WriteBadRequest(w, "Description too long") return } if input.Theme.AccentColor == "" { input.Theme.AccentColor = "#3b82f6" } if input.Theme.FontFamily == "" { input.Theme.FontFamily = "sans-serif" } if input.Theme.Layout == "" { input.Theme.Layout = "masonry" }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), session.DID) var featuredURIs []string if rrConfig != nil { featuredURIs = parseFeaturedURIs(rrConfig.FeaturedURIs) }
theme := &xrpc.ReadingRoomThemeRecord{ BackgroundColor: input.Theme.BackgroundColor, AccentColor: input.Theme.AccentColor, FontFamily: input.Theme.FontFamily, Layout: input.Theme.Layout, }
if err := h.writeReadingRoomRecord(r, session, input.Title, input.Subtitle, input.Description, theme, featuredURIs, input.ShowExternalBookmarks, rrConfig); err != nil { WriteBadRequest(w, err.Error()) return }
w.WriteHeader(http.StatusOK)}
func (h *Handler) writeReadingRoomRecord(r *http.Request, session *SessionData, title, subtitle, description string, theme *xrpc.ReadingRoomThemeRecord, featuredURIs []string, showExternalBookmarks *bool, rrConfig *db.ReadingRoomConfig) error { record := xrpc.NewReadingRoomRecord(title, subtitle, description, theme, featuredURIs, showExternalBookmarks) if err := record.Validate(); err != nil { return err }
pdsErr := h.refresher.ExecuteWithAutoRefresh(r, session, func(client *xrpc.Client, did string) error { _, err := client.PutRecord(r.Context(), did, xrpc.CollectionReadingRoom, "self", record) return err }) if pdsErr != nil { fmt.Printf("[ReadingRoom] PDS write failed: %v\n", pdsErr) }
themeJSON := "{}" if theme != nil { b, _ := json.Marshal(theme) themeJSON = string(b) } featuredURIsJSON := "[]" if len(featuredURIs) > 0 { b, _ := json.Marshal(featuredURIs) featuredURIsJSON = string(b) }
showExternal := true if showExternalBookmarks != nil { showExternal = *showExternalBookmarks }
if err := h.db.UpsertReadingRoomConfigFromRecord(r.Context(), session.DID, title, subtitle, description, themeJSON, featuredURIsJSON, showExternal); err != nil { fmt.Printf("[ReadingRoom] local upsert failed: %v\n", err) }
h.writeReadingRoomPublication(r, session, title, description, rrConfig) return nil}
func (h *Handler) writeReadingRoomPublication(r *http.Request, session *SessionData, title, description string, rrConfig *db.ReadingRoomConfig) { baseURL := config.Get().BaseURL if baseURL == "" { baseURL = "https://margin.at" } pubURL := fmt.Sprintf("%s/reading-room/%s", baseURL, session.Handle) if rrConfig != nil && rrConfig.CustomDomain != "" && rrConfig.DomainStatus == "active" { pubURL = "https://" + rrConfig.CustomDomain }
name := title if name == "" { name = session.Handle + "'s Reading Room" }
record := xrpc.NewPublicationRecord(pubURL, name, description) if err := record.Validate(); err != nil { fmt.Printf("[ReadingRoom] publication invalid: %v\n", err) return }
err := h.refresher.ExecuteWithAutoRefresh(r, session, func(client *xrpc.Client, did string) error { _, err := client.PutRecord(r.Context(), did, xrpc.CollectionPublication, "reading-room", record) return err }) if err != nil { fmt.Printf("[ReadingRoom] publication PDS write failed: %v\n", err) }}
func (h *Handler) UpdateFeaturedItems(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
if !h.db.HasActiveSubscription(r.Context(), session.DID) { WriteForbidden(w, "Margin Pro required") return }
var input struct { URIs []string `json:"uris"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { WriteBadRequest(w, "Invalid input") return }
if len(input.URIs) > 12 { WriteBadRequest(w, "Maximum 12 featured items") return }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), session.DID) var title, subtitle, description string var theme *xrpc.ReadingRoomThemeRecord if rrConfig != nil { title = rrConfig.Title subtitle = rrConfig.Subtitle description = rrConfig.Description if rrConfig.Theme != "" { var t xrpc.ReadingRoomThemeRecord if json.Unmarshal([]byte(rrConfig.Theme), &t) == nil { theme = &t } } }
if err := h.writeReadingRoomRecord(r, session, title, subtitle, description, theme, input.URIs, nil, rrConfig); err != nil { WriteBadRequest(w, err.Error()) return }
w.WriteHeader(http.StatusOK)}
func (h *Handler) GetRSSFeed(w http.ResponseWriter, r *http.Request) { handle := chi.URLParam(r, "handle") if handle == "" { WriteBadRequest(w, "handle required") return }
did := h.resolveHandleOrDID(r, handle) if did == "" { WriteNotFound(w, "Reading room not found") return }
if !h.db.HasActiveSubscription(r.Context(), did) { WriteNotFound(w, "Reading room not found") return }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), did) title := handle + "'s Reading Room" if rrConfig != nil && rrConfig.Title != "" { title = rrConfig.Title } description := "" if rrConfig != nil { description = rrConfig.Description }
notes, _ := h.noteRepo.List(r.Context(), db.NoteFilter{ AuthorDID: did, Limit: 30, Offset: 0, }) notes = h.filterHiddenNotes(r.Context(), "", notes)
baseURL := config.Get().BaseURL if baseURL == "" { baseURL = "https://margin.at" }
var b strings.Builder b.WriteString(`<?xml version="1.0" encoding="UTF-8"?>`) b.WriteString(`<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">`) b.WriteString(`<channel>`) b.WriteString(fmt.Sprintf(`<title>%s</title>`, escapeXML(title))) b.WriteString(fmt.Sprintf(`<link>%s/reading-room/%s</link>`, escapeXML(baseURL), escapeXML(handle))) b.WriteString(fmt.Sprintf(`<description>%s</description>`, escapeXML(description))) b.WriteString(fmt.Sprintf(`<atom:link href="%s/reading-room/%s" rel="self" type="application/rss+xml"/>`, escapeXML(baseURL), escapeXML(handle)))
for _, n := range notes { lc, _ := h.hydration.Load(r.Context(), []db.Note{n}, "") apiNote := h.hydration.ToAPINote(n, lc) itemTitle := apiNote.Target.Title if itemTitle == "" && apiNote.Body != nil && apiNote.Body.Value != "" { itemTitle = apiNote.Body.Value } b.WriteString(`<item>`) b.WriteString(fmt.Sprintf(`<title>%s</title>`, escapeXML(itemTitle))) b.WriteString(fmt.Sprintf(`<link>%s</link>`, escapeXML(apiNote.Target.Source))) b.WriteString(fmt.Sprintf(`<guid>%s</guid>`, escapeXML(n.URI))) b.WriteString(fmt.Sprintf(`<pubDate>%s</pubDate>`, n.CreatedAt.UTC().Format(time.RFC1123Z))) if apiNote.Body != nil && apiNote.Body.Value != "" { b.WriteString(fmt.Sprintf(`<description>%s</description>`, escapeXML(apiNote.Body.Value))) } b.WriteString(`</item>`) }
b.WriteString(`</channel></rss>`)
w.Header().Set("Content-Type", "application/rss+xml; charset=utf-8") w.Header().Set("Cache-Control", "public, max-age=300") w.Write([]byte(b.String()))}
func escapeXML(s string) string { s = strings.ReplaceAll(s, "&", "&") s = strings.ReplaceAll(s, "<", "<") s = strings.ReplaceAll(s, ">", ">") s = strings.ReplaceAll(s, "'", "'") s = strings.ReplaceAll(s, "\"", """) return s}
func (h *Handler) CreateCheckout(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
if !h.stripe.IsEnabled() { WriteBadRequest(w, "Billing is not configured") return }
var input struct { Plan string `json:"plan"` } json.NewDecoder(r.Body).Decode(&input) plan := "monthly" if input.Plan == "yearly" { plan = "yearly" }
priceID := h.stripe.PriceID(plan) if priceID == "" { WriteBadRequest(w, "Price ID not configured") return }
sub, _ := h.db.GetSubscription(r.Context(), session.DID) customerID := "" if sub != nil && sub.StripeCustomerID != "" { customerID = sub.StripeCustomerID }
baseURL := config.Get().BaseURL if baseURL == "" { baseURL = "https://margin.at" } successURL := baseURL + "/settings?billing=success" cancelURL := baseURL + "/settings?billing=canceled"
if customerID == "" { customerID, err = h.stripe.CreateCustomer(session.DID) if err != nil { fmt.Printf("[CreateCheckout] Stripe create customer failed: %v\n", err) WriteInternalError(w, "Failed to create customer") return } h.db.UpsertSubscription(r.Context(), &db.ReadingRoomSubscription{ DID: session.DID, StripeCustomerID: customerID, Status: "incomplete", Plan: plan, }) }
checkout, err := h.stripe.CreateCheckoutSession(customerID, priceID, successURL, cancelURL) if err != nil { fmt.Printf("[CreateCheckout] Stripe checkout session failed: %v\n", err) WriteInternalError(w, "Failed to create checkout session") return }
WriteSuccess(w, map[string]string{"url": checkout.URL})}
func (h *Handler) CreatePortal(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
if !h.stripe.IsEnabled() { WriteBadRequest(w, "Billing is not configured") return }
sub, _ := h.db.GetSubscription(r.Context(), session.DID) if sub == nil || sub.StripeCustomerID == "" { WriteBadRequest(w, "No subscription found") return }
baseURL := config.Get().BaseURL if baseURL == "" { baseURL = "https://margin.at" }
portalURL, err := h.stripe.CreatePortalSession(sub.StripeCustomerID, baseURL+"/settings") if err != nil { WriteInternalError(w, "Failed to create portal session") return }
WriteSuccess(w, map[string]string{"url": portalURL})}
func (h *Handler) GetBillingStatus(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
sub, err := h.db.GetSubscription(r.Context(), session.DID) if err != nil { logger.Error("GetBillingStatus: failed to read subscription for %s: %v", session.DID, err) WriteJSONError(w, http.StatusServiceUnavailable, "billing temporarily unavailable") return } resp := BillingStatusResponse{} if sub != nil { resp.Status = sub.Status resp.Plan = sub.Plan resp.CurrentPeriodEnd = sub.CurrentPeriodEnd resp.HasSubscription = sub.Status == "active" || sub.Status == "trialing" }
w.Header().Set("Cache-Control", "no-store") WriteSuccess(w, resp)}
func (h *Handler) HandleStripeWebhook(w http.ResponseWriter, r *http.Request) { if !h.stripe.IsEnabled() { w.WriteHeader(http.StatusServiceUnavailable) return }
payload, err := io.ReadAll(r.Body) if err != nil { w.WriteHeader(http.StatusBadRequest) return }
sig := r.Header.Get("Stripe-Signature") event, err := h.stripe.ConstructWebhookEvent(payload, sig) if err != nil { fmt.Printf("[StripeWebhook] Signature verification failed: %v\n", err) w.WriteHeader(http.StatusBadRequest) return }
switch event.Type { case "checkout.session.completed": customerID := event.GetString("customer") subID := event.GetString("subscription") if customerID == "" || subID == "" { break } stripeSub, _ := h.stripe.GetSubscription(subID) if stripeSub == nil { break } periodEnd := time.Unix(stripeSub.CurrentPeriodEnd, 0) existingSub, _ := h.db.GetSubscriptionByCustomerID(r.Context(), customerID) if existingSub == nil { break } h.db.UpsertSubscription(r.Context(), &db.ReadingRoomSubscription{ DID: existingSub.DID, StripeCustomerID: customerID, StripeSubscriptionID: subID, Status: stripeSub.Status, Plan: existingSub.Plan, CurrentPeriodEnd: &periodEnd, })
case "customer.subscription.updated": subID := event.GetString("id") customerID := event.GetString("customer") if customerID == "" || subID == "" { break } existingSub, _ := h.db.GetSubscriptionByCustomerID(r.Context(), customerID) if existingSub == nil { break } stripeSub, _ := h.stripe.GetSubscription(subID) if stripeSub == nil { break } pe := time.Unix(stripeSub.CurrentPeriodEnd, 0) plan := existingSub.Plan if stripeSub.Plan.ID == h.stripe.PriceID("yearly") { plan = "yearly" } else if stripeSub.Plan.ID == h.stripe.PriceID("monthly") { plan = "monthly" } h.db.UpsertSubscription(r.Context(), &db.ReadingRoomSubscription{ DID: existingSub.DID, StripeCustomerID: customerID, StripeSubscriptionID: subID, Status: stripeSub.Status, Plan: plan, CurrentPeriodEnd: &pe, })
case "customer.subscription.deleted": customerID := event.GetString("customer") if customerID == "" { break } existingSub, _ := h.db.GetSubscriptionByCustomerID(r.Context(), customerID) if existingSub == nil { break } h.db.UpsertSubscription(r.Context(), &db.ReadingRoomSubscription{ DID: existingSub.DID, StripeCustomerID: customerID, Status: "canceled", Plan: existingSub.Plan, }) }
w.WriteHeader(http.StatusOK) w.Write([]byte(`{"received":true}`))}
func (h *Handler) AddCustomDomain(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
if !h.db.HasActiveSubscription(r.Context(), session.DID) { WriteForbidden(w, "Margin Pro required") return }
if !h.cloudflare.IsEnabled() { WriteBadRequest(w, "Custom domain management is not configured") return }
var input struct { Domain string `json:"domain"` } if err := json.NewDecoder(r.Body).Decode(&input); err != nil { WriteBadRequest(w, "Invalid input") return }
domain := strings.ToLower(strings.TrimSpace(input.Domain)) if domain == "" { WriteBadRequest(w, "Domain required") return }
rootDomain := h.cloudflare.RootDomain() if rootDomain != "" && (domain == rootDomain || strings.HasSuffix(domain, "."+rootDomain)) { WriteBadRequest(w, "Cannot use root domain") return }
zoneID, err := h.cloudflare.GetZoneID(rootDomain) if err != nil { WriteInternalError(w, "Failed to find zone") return }
h.cloudflare.EnsureFallbackOrigin(zoneID)
result, err := h.cloudflare.CreateCustomHostname(zoneID, domain) if err != nil { WriteBadRequest(w, "Failed to create custom hostname: "+err.Error()) return }
records := cloudflare.ExtractVerificationRecords(result) recordsJSON, _ := json.Marshal(records) status := cloudflare.CombinedStatus(result)
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), session.DID) if rrConfig == nil { rrConfig = &db.ReadingRoomConfig{DID: session.DID} } rrConfig.CustomDomain = domain rrConfig.CFHostnameID = result.ID rrConfig.DomainStatus = status rrConfig.DomainVerificationRecords = string(recordsJSON)
h.db.UpsertReadingRoomConfig(r.Context(), rrConfig)
if status == "active" { var handle string h.db.Pool().QueryRow(r.Context(), "SELECT handle FROM oauth_sessions WHERE did = $1 LIMIT 1", session.DID).Scan(&handle) if handle == "" { handle = session.DID } h.cloudflare.EnsureRouting(domain, handle) }
WriteSuccess(w, CustomDomainResponse{ Domain: domain, Status: status, VerificationRecords: records, })}
func (h *Handler) PollCustomDomain(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
if !h.db.HasActiveSubscription(r.Context(), session.DID) { WriteForbidden(w, "Margin Pro required") return }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), session.DID) if rrConfig == nil || rrConfig.CFHostnameID == "" { WriteNotFound(w, "No custom domain configured") return }
zoneID, err := h.cloudflare.GetZoneID(h.cloudflare.RootDomain()) if err != nil { WriteInternalError(w, "Failed to find zone") return }
result, err := h.cloudflare.GetCustomHostname(zoneID, rrConfig.CFHostnameID) if err != nil { WriteInternalError(w, "Failed to poll domain status") return }
records := cloudflare.ExtractVerificationRecords(result) recordsJSON, _ := json.Marshal(records) status := cloudflare.CombinedStatus(result)
h.db.UpdateReadingRoomDomain(r.Context(), session.DID, rrConfig.CustomDomain, rrConfig.CFHostnameID, status, string(recordsJSON))
if status == "active" && rrConfig.DomainStatus != "active" { var handle string h.db.Pool().QueryRow(r.Context(), "SELECT handle FROM oauth_sessions WHERE did = $1 LIMIT 1", session.DID).Scan(&handle) if handle == "" { handle = session.DID } h.cloudflare.EnsureRouting(rrConfig.CustomDomain, handle) rrConfig.DomainStatus = "active" h.writeReadingRoomPublication(r, session, rrConfig.Title, rrConfig.Description, rrConfig) }
WriteSuccess(w, CustomDomainResponse{ Domain: rrConfig.CustomDomain, Status: status, VerificationRecords: records, })}
func (h *Handler) RemoveCustomDomain(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
if !h.db.HasActiveSubscription(r.Context(), session.DID) { WriteForbidden(w, "Margin Pro required") return }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), session.DID) if rrConfig == nil || rrConfig.CustomDomain == "" { w.WriteHeader(http.StatusOK) return }
if rrConfig.CFHostnameID != "" && h.cloudflare.IsEnabled() { zoneID, _ := h.cloudflare.GetZoneID(h.cloudflare.RootDomain()) if zoneID != "" { h.cloudflare.DeleteCustomHostname(zoneID, rrConfig.CFHostnameID) } }
if h.cloudflare.IsEnabled() { h.cloudflare.RemoveRouting(rrConfig.CustomDomain) }
h.db.UpdateReadingRoomDomain(r.Context(), session.DID, "", "", "", "[]")
rrConfig.CustomDomain = "" rrConfig.DomainStatus = "" h.writeReadingRoomPublication(r, session, rrConfig.Title, rrConfig.Description, rrConfig)
WriteSuccess(w, map[string]string{"status": "removed"})}
func (h *Handler) GetCustomDomainStatus(w http.ResponseWriter, r *http.Request) { session, err := h.refresher.GetSessionWithAutoRefresh(r) if err != nil { WriteUnauthorized(w, "Unauthorized") return }
rrConfig, _ := h.db.GetReadingRoomConfig(r.Context(), session.DID) if rrConfig == nil || rrConfig.CustomDomain == "" { WriteSuccess(w, CustomDomainResponse{}) return }
var records interface{} if rrConfig.DomainVerificationRecords != "" && rrConfig.DomainVerificationRecords != "[]" { json.Unmarshal([]byte(rrConfig.DomainVerificationRecords), &records) } else { records = []interface{}{} }
WriteSuccess(w, CustomDomainResponse{ Domain: rrConfig.CustomDomain, Status: rrConfig.DomainStatus, VerificationRecords: records, })}
func (h *Handler) GetPublicationVerification(w http.ResponseWriter, r *http.Request) { handle := chi.URLParam(r, "handle") if handle == "" { w.WriteHeader(http.StatusNotFound) return }
did := h.resolveHandleOrDID(r, handle) if did == "" { w.WriteHeader(http.StatusNotFound) return }
if !h.db.HasActiveSubscription(r.Context(), did) { w.WriteHeader(http.StatusNotFound) return }
w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Header().Set("Cache-Control", "public, max-age=300") w.Write([]byte(fmt.Sprintf("at://%s/site.standard.publication/reading-room", did)))}