app.go (18483B)
1 // Package web contains the HTTP applications for the Taler merchant demos. 2 package web 3 4 import ( 5 "bytes" 6 "crypto/rand" 7 "encoding/hex" 8 "encoding/json" 9 "errors" 10 "fmt" 11 "html" 12 "html/template" 13 "io/fs" 14 "log" 15 "net/http" 16 "net/url" 17 "path" 18 "regexp" 19 "sort" 20 "strconv" 21 "strings" 22 "sync/atomic" 23 24 "git.taler.net/taler-merchant-demos/internal/backend" 25 ) 26 27 const ( 28 sessionCookieName = "taler_demo_session" 29 orderCookieName = "order_id" 30 articlePriceUnits = "0.5" 31 subscriptionUnits = "10" 32 subscriptionPrefix = "blog_abo_" 33 ) 34 35 // PublicURLs contains the externally visible entry points linked by the demos. 36 type PublicURLs struct { 37 Landing string 38 Bank string 39 Blog string 40 Donations string 41 } 42 43 // Options configures one of the three demo HTTP applications. 44 type Options struct { 45 Shop string 46 Currency string 47 PublicURLs PublicURLs 48 BlogBackend *backend.Client 49 SamplesBackend *backend.Client 50 DonationBackends map[string]*backend.Client 51 DonauURL string 52 EnableTokens bool 53 } 54 55 // App serves one configured demo. 56 type App struct { 57 samplesReady atomic.Bool 58 samplesLandingURL *url.URL 59 opts Options 60 catalogs catalogs 61 articles articleLibrary 62 templates map[string]*template.Template 63 static http.Handler 64 mux *http.ServeMux 65 routes *http.ServeMux 66 } 67 68 type language struct { 69 Code string 70 Name template.HTML 71 } 72 73 var languages = []language{ 74 {"en", "English [en]"}, {"de", "Deutsch [de]"}, 75 {"fr", "Français [fr]"}, {"it", "Italiano [it]"}, 76 {"pt", "Português [pt]"}, {"es", "Español [es]"}, 77 {"ru", "Русский [ru]"}, {"tr", "Türkçe [tr]"}, 78 {"uk", "Українська [uk]"}, 79 } 80 81 var supportedLocales = func() map[string]bool { 82 result := make(map[string]bool, len(languages)) 83 for _, language := range languages { 84 result[language.Code] = true 85 } 86 return result 87 }() 88 89 var localePattern = regexp.MustCompile(`^[A-Za-z]{2,3}([_-][A-Za-z0-9]{2,8})*$`) 90 91 // resolveLocale returns a supported locale or its closest supported parent. 92 // Separators and case do not affect matching, but the returned spelling is 93 // always the one used by the application. 94 func resolveLocale(requested string, supported map[string]bool) string { 95 if !localePattern.MatchString(requested) { 96 return "" 97 } 98 normalize := func(value string) string { 99 return strings.ToLower(strings.ReplaceAll(value, "_", "-")) 100 } 101 for candidate := normalize(requested); candidate != ""; { 102 for locale, enabled := range supported { 103 if enabled && normalize(locale) == candidate { 104 return locale 105 } 106 } 107 index := strings.LastIndexByte(candidate, '-') 108 if index < 0 { 109 break 110 } 111 candidate = candidate[:index] 112 } 113 return "" 114 } 115 116 type links struct { 117 Landing string 118 Bank string 119 Blog string 120 Donations string 121 } 122 123 type page struct { 124 LanguagePath string 125 Lang string 126 Title string 127 Active string 128 HeaderTitle string 129 HeaderURL string 130 HeaderText template.HTML 131 Styles []string 132 Prefix string 133 StaticPrefix string 134 Links links 135 Languages []language 136 LanguageName template.HTML 137 Content any 138 } 139 140 type errorContent struct { 141 Message string 142 Details string 143 Status int 144 JSON string 145 } 146 147 // New loads embedded resources and constructs an application. 148 func New(opts Options) (*App, error) { 149 if opts.Currency == "" { 150 return nil, errors.New("currency is required") 151 } 152 if opts.Shop != "landing" && opts.Shop != "blog" && opts.Shop != "donations" { 153 return nil, fmt.Errorf("unknown shop %q", opts.Shop) 154 } 155 if opts.Shop == "blog" && opts.BlogBackend == nil { 156 return nil, errors.New("blog backend is required") 157 } 158 if opts.Shop == "donations" { 159 for _, receiver := range []string{"gnunet", "taler", "tor"} { 160 if opts.DonationBackends[receiver] == nil { 161 return nil, fmt.Errorf("donation backend %q is required", receiver) 162 } 163 } 164 } 165 cats, err := loadCatalogs(supportedLocales) 166 if err != nil { 167 return nil, err 168 } 169 a := &App{ 170 opts: opts, catalogs: cats, templates: make(map[string]*template.Template), 171 mux: http.NewServeMux(), routes: http.NewServeMux(), 172 } 173 if opts.SamplesBackend != nil { 174 base, err := url.Parse(opts.PublicURLs.Landing) 175 if err != nil || base.Host == "" || (base.Scheme != "http" && base.Scheme != "https") { 176 return nil, errors.New("merchant samples require an absolute HTTP or HTTPS landing_url") 177 } 178 a.samplesLandingURL = base 179 } 180 if opts.Shop == "blog" { 181 a.articles, err = loadArticles() 182 if err != nil { 183 return nil, err 184 } 185 } 186 staticFS, err := fs.Sub(Assets, "assets/static") 187 if err != nil { 188 return nil, err 189 } 190 a.static = http.FileServer(http.FS(staticFS)) 191 if err := a.loadTemplates(); err != nil { 192 return nil, err 193 } 194 a.registerRoutes() 195 return a, nil 196 } 197 198 func (a *App) loadTemplates() error { 199 base, err := Assets.ReadFile("templates/base.gohtml") 200 if err != nil { 201 return err 202 } 203 names := []string{"error", "landing", "merchant-samples", "sample-receipt", "donations-index", "donations-checkout", "donations-provider", "donations-fulfillment", "blog-index", "blog-article", "blog-confirm-refund", "blog-refunded"} 204 funcs := template.FuncMap{ 205 "tr": func(lang, message string) string { return a.catalogs.translate(lang, message) }, 206 "trHTML": func(lang, message string) template.HTML { 207 return template.HTML(a.catalogs.translate(lang, message)) 208 }, 209 "trf": func(lang, message string, values ...any) string { 210 return formatNamed(a.catalogs.translate(lang, message), values...) 211 }, 212 "trfHTML": func(lang, message string, values ...any) template.HTML { 213 escaped := make([]any, len(values)) 214 copy(escaped, values) 215 for i := 1; i < len(escaped); i += 2 { 216 escaped[i] = html.EscapeString(fmt.Sprint(escaped[i])) 217 } 218 return template.HTML(formatNamed(a.catalogs.translate(lang, message), escaped...)) 219 }, 220 "pathEscape": url.PathEscape, 221 "talerURL": func(lang string) string { return "https://taler.net/" + url.PathEscape(lang) + "/" }, 222 "localIndex": func(prefix, lang string) string { return prefix + "/" + url.PathEscape(lang) + "/" }, 223 } 224 for _, name := range names { 225 body, err := Assets.ReadFile("templates/" + name + ".gohtml") 226 if err != nil { 227 return err 228 } 229 t, err := template.New("base.gohtml").Funcs(funcs).Parse(string(base) + "\n" + string(body)) 230 if err != nil { 231 return fmt.Errorf("parse template %s: %w", name, err) 232 } 233 a.templates[name] = t 234 } 235 return nil 236 } 237 238 // ServeHTTP adds common recovery and response tracking around the standard 239 // library request multiplexer. 240 func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) { 241 tracked := &trackingResponseWriter{ResponseWriter: w} 242 defer func() { 243 if recovered := recover(); recovered != nil { 244 log.Printf("request panic: %v", recovered) 245 if !tracked.wroteHeader { 246 a.renderError(tracked, r, http.StatusInternalServerError, requestLang(r), "Internal error", nil) 247 } 248 } 249 }() 250 a.mux.ServeHTTP(tracked, r) 251 } 252 253 func (a *App) registerRoutes() { 254 a.mux.HandleFunc("GET /{$}", a.redirectRoot) 255 a.mux.HandleFunc("/{$}", a.methodNotAllowed) 256 a.mux.HandleFunc("GET /static/", a.serveStatic) 257 a.mux.HandleFunc("/static/", a.methodNotAllowed) 258 a.mux.HandleFunc("GET /{lang}", a.redirectLanguage) 259 a.mux.HandleFunc("/{lang}", a.methodNotAllowed) 260 261 switch a.opts.Shop { 262 case "landing": 263 a.registerLandingRoutes() 264 case "donations": 265 a.registerDonationRoutes() 266 case "blog": 267 a.registerBlogRoutes() 268 } 269 a.routes.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 270 a.renderError(w, r, http.StatusNotFound, requestLang(r), "Page not found", nil) 271 }) 272 a.mux.HandleFunc("/{lang}/{path...}", func(w http.ResponseWriter, r *http.Request) { 273 if a.redirectLocale(w, r) { 274 return 275 } 276 a.routes.ServeHTTP(w, r) 277 }) 278 a.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 279 a.renderError(w, r, http.StatusNotFound, requestLang(r), "Page not found", nil) 280 }) 281 } 282 283 func (a *App) handleGet(pattern string, handler http.HandlerFunc) { 284 a.routes.HandleFunc("GET "+pattern, handler) 285 a.routes.HandleFunc(pattern, a.methodNotAllowed) 286 } 287 288 func (a *App) handlePost(pattern string, handler http.HandlerFunc) { 289 a.routes.HandleFunc("POST "+pattern, handler) 290 a.routes.HandleFunc(pattern, a.methodNotAllowed) 291 } 292 293 func (a *App) methodNotAllowed(w http.ResponseWriter, r *http.Request) { 294 a.renderError(w, r, http.StatusMethodNotAllowed, requestLang(r), "HTTP method not allowed for this page", nil) 295 } 296 297 func (a *App) serveStatic(w http.ResponseWriter, r *http.Request) { 298 w.Header().Set("Cache-Control", "public, max-age=3600") 299 http.StripPrefix("/static/", a.static).ServeHTTP(w, r) 300 } 301 302 func (a *App) redirectLanguage(w http.ResponseWriter, r *http.Request) { 303 if a.redirectLocale(w, r) { 304 return 305 } 306 target := forwardedPrefix(r) + "/" + url.PathEscape(r.PathValue("lang")) + "/" 307 if r.URL.RawQuery != "" { 308 target += "?" + r.URL.RawQuery 309 } 310 http.Redirect(w, r, target, http.StatusPermanentRedirect) 311 } 312 313 // redirectLocale handles language aliases before any page or payment handler 314 // runs. It reports whether it has already answered the request. 315 func (a *App) redirectLocale(w http.ResponseWriter, r *http.Request) bool { 316 requested := r.PathValue("lang") 317 if validLocale(requested) { 318 return false 319 } 320 if !localePattern.MatchString(requested) { 321 a.renderError(w, r, http.StatusNotFound, "en", "Page not found", nil) 322 return true 323 } 324 lang := resolveLocale(requested, supportedLocales) 325 if lang == "" { 326 lang = "en" 327 } 328 // Split the escaped path to retain encoded separators in article/file IDs. 329 _, rest, _ := strings.Cut(strings.TrimPrefix(r.URL.EscapedPath(), "/"), "/") 330 target := forwardedPrefix(r) + "/" + url.PathEscape(lang) + "/" + rest 331 if r.URL.RawQuery != "" { 332 target += "?" + r.URL.RawQuery 333 } 334 http.Redirect(w, r, target, http.StatusTemporaryRedirect) 335 return true 336 } 337 338 type trackingResponseWriter struct { 339 http.ResponseWriter 340 wroteHeader bool 341 } 342 343 func (w *trackingResponseWriter) WriteHeader(status int) { 344 if !w.wroteHeader { 345 w.wroteHeader = true 346 w.ResponseWriter.WriteHeader(status) 347 } 348 } 349 350 func (w *trackingResponseWriter) Write(data []byte) (int, error) { 351 if !w.wroteHeader { 352 w.WriteHeader(http.StatusOK) 353 } 354 return w.ResponseWriter.Write(data) 355 } 356 357 func requestLang(r *http.Request) string { 358 if lang := r.PathValue("lang"); validLocale(lang) { 359 return lang 360 } 361 first, _, _ := strings.Cut(strings.TrimPrefix(r.URL.Path, "/"), "/") 362 if validLocale(first) { 363 return first 364 } 365 return "en" 366 } 367 368 func validLocale(lang string) bool { 369 return supportedLocales[lang] 370 } 371 372 func (a *App) redirectRoot(w http.ResponseWriter, r *http.Request) { 373 lang := a.bestLanguage(r.Header.Get("Accept-Language")) 374 http.Redirect(w, r, forwardedPrefix(r)+"/"+lang+"/", http.StatusFound) 375 } 376 377 func (a *App) bestLanguage(header string) string { 378 type preference struct { 379 lang string 380 q float64 381 order int 382 } 383 var preferences []preference 384 for order, weighted := range strings.Split(header, ",") { 385 parts := strings.Split(weighted, ";") 386 candidate := strings.TrimSpace(parts[0]) 387 candidate = strings.ReplaceAll(candidate, "-", "_") 388 quality := 1.0 389 for _, parameter := range parts[1:] { 390 key, value, ok := strings.Cut(strings.TrimSpace(parameter), "=") 391 if ok && strings.EqualFold(key, "q") { 392 if parsed, err := strconv.ParseFloat(value, 64); err == nil { 393 quality = parsed 394 } 395 } 396 } 397 if candidate == "" || candidate == "*" || quality <= 0 { 398 continue 399 } 400 preferences = append(preferences, preference{candidate, quality, order}) 401 } 402 sort.SliceStable(preferences, func(i, j int) bool { 403 if preferences[i].q == preferences[j].q { 404 return preferences[i].order < preferences[j].order 405 } 406 return preferences[i].q > preferences[j].q 407 }) 408 for _, preferred := range preferences { 409 if lang := resolveLocale(preferred.lang, supportedLocales); lang != "" { 410 return lang 411 } 412 } 413 return "en" 414 } 415 416 func (a *App) makePage(r *http.Request, lang, title string, content any) page { 417 prefix := forwardedPrefix(r) 418 p := page{ 419 Lang: lang, Title: a.catalogs.translate(lang, title), Active: a.opts.Shop, 420 Prefix: prefix, StaticPrefix: prefix + "/static/", Languages: languages, 421 LanguageName: template.HTML("en"), Content: content, 422 Links: links{ 423 Landing: appLanguageURL(a.opts.PublicURLs.Landing, lang), 424 Bank: appLanguageURL(a.opts.PublicURLs.Bank, lang), 425 Blog: appLanguageURL(a.opts.PublicURLs.Blog, lang), 426 Donations: appLanguageURL(a.opts.PublicURLs.Donations, lang), 427 }, 428 } 429 for _, language := range languages { 430 if language.Code == lang { 431 p.LanguageName = language.Name 432 break 433 } 434 } 435 switch a.opts.Shop { 436 case "landing": 437 p.HeaderTitle = a.catalogs.translate(lang, "Introduction") 438 p.HeaderURL = configuredURL(a.opts.PublicURLs.Landing) 439 p.HeaderText = a.translatedHTML(lang, "Try GNU Taler with a toy currency.") 440 case "donations": 441 p.HeaderTitle = a.catalogs.translate(lang, "Donations") 442 p.HeaderURL = configuredURL(a.opts.PublicURLs.Donations) 443 p.HeaderText = a.translatedHTML(lang, "Support Free Software projects with a toy currency.") 444 p.Styles = []string{"colors-donations.css"} 445 case "blog": 446 p.HeaderTitle = a.catalogs.translate(lang, "Essay Shop") 447 p.HeaderURL = configuredURL(a.opts.PublicURLs.Blog) 448 p.HeaderText = a.translatedHTML(lang, "Buy chapters from <cite>Free Software, Free Society</cite> with a toy currency.") 449 p.Styles = []string{"blog.css", "colors-blog.css"} 450 } 451 return p 452 } 453 454 func (a *App) translatedHTML(lang, message string) template.HTML { 455 return template.HTML(a.catalogs.translate(lang, message)) 456 } 457 458 func (a *App) translatedHTMLf(lang, message string, values ...any) template.HTML { 459 escaped := make([]any, len(values)) 460 copy(escaped, values) 461 for i := 1; i < len(escaped); i += 2 { 462 escaped[i] = html.EscapeString(fmt.Sprint(escaped[i])) 463 } 464 return template.HTML(formatNamed(a.catalogs.translate(lang, message), escaped...)) 465 } 466 467 func (a *App) render(w http.ResponseWriter, name string, p page, status int) { 468 var output bytes.Buffer 469 if err := a.templates[name].ExecuteTemplate(&output, "base", p); err != nil { 470 log.Printf("render %s: %v", name, err) 471 http.Error(w, a.catalogs.translate(p.Lang, "Internal server error"), http.StatusInternalServerError) 472 return 473 } 474 w.Header().Set("Content-Type", "text/html; charset=utf-8") 475 w.Header().Set("Cache-Control", "private, no-store") 476 w.Header().Set("Content-Security-Policy", "default-src 'self'; img-src 'self' https://taler.net; style-src 'self' 'unsafe-inline'; script-src 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'") 477 w.Header().Set("X-Content-Type-Options", "nosniff") 478 w.WriteHeader(status) 479 _, _ = w.Write(output.Bytes()) 480 } 481 482 func (a *App) renderError(w http.ResponseWriter, r *http.Request, status int, lang, message string, err error) { 483 a.renderErrorf(w, r, status, lang, message, err) 484 } 485 486 func (a *App) renderErrorf(w http.ResponseWriter, r *http.Request, status int, lang, message string, err error, values ...any) { 487 content := errorContent{Message: formatNamed(a.catalogs.translate(lang, message), values...)} 488 var be *backend.Error 489 if errors.As(err, &be) { 490 content.Status = be.Status 491 if be.Body != nil { 492 encoded, _ := json.MarshalIndent(be.Body, "", " ") 493 content.JSON = string(encoded) 494 } 495 } 496 if err != nil { 497 content.Details = err.Error() 498 log.Printf("%s: %v", message, err) 499 } 500 a.render(w, "error", a.makePage(r, lang, "GNU Taler Demo: Error", content), status) 501 } 502 503 func configuredURL(value string) string { 504 if value = strings.TrimSpace(value); value != "" { 505 return value 506 } 507 return "#" 508 } 509 510 func appLanguageURL(base, lang string) string { 511 base = configuredURL(base) 512 if base == "#" { 513 return "#" 514 } 515 target, err := url.Parse(base) 516 if err != nil { 517 return "#" 518 } 519 return target.JoinPath(url.PathEscape(lang) + "/").String() 520 } 521 522 func forwardedPrefix(r *http.Request) string { 523 value := strings.TrimSpace(strings.SplitN(r.Header.Get("X-Forwarded-Prefix"), ",", 2)[0]) 524 if value == "" || !strings.HasPrefix(value, "/") || strings.HasPrefix(value, "//") { 525 return "" 526 } 527 raw := strings.TrimRight(value, "/") 528 value = path.Clean(value) 529 if value == "/" || value != raw { 530 return "" 531 } 532 return strings.TrimRight(value, "/") 533 } 534 535 func externalURL(r *http.Request) string { 536 scheme := "http" 537 if r.TLS != nil { 538 scheme = "https" 539 } 540 if forwarded := strings.TrimSpace(strings.SplitN(r.Header.Get("X-Forwarded-Proto"), ",", 2)[0]); forwarded == "http" || forwarded == "https" { 541 scheme = forwarded 542 } 543 host := r.Host 544 if forwarded := strings.TrimSpace(strings.SplitN(r.Header.Get("X-Forwarded-Host"), ",", 2)[0]); forwarded != "" { 545 host = forwarded 546 } 547 return (&url.URL{Scheme: scheme, Host: host, Path: forwardedPrefix(r) + r.URL.Path}).String() 548 } 549 550 func externalOrigin(r *http.Request) string { 551 parsed, _ := url.Parse(externalURL(r)) 552 return parsed.Scheme + "://" + parsed.Host 553 } 554 555 func externalURLWithQuery(r *http.Request) string { 556 result := externalURL(r) 557 if r.URL.RawQuery != "" { 558 result += "?" + r.URL.RawQuery 559 } 560 return result 561 } 562 563 func randomID() (string, error) { 564 var raw [16]byte 565 if _, err := rand.Read(raw[:]); err != nil { 566 return "", err 567 } 568 return hex.EncodeToString(raw[:]), nil 569 } 570 571 func cookieSecure(r *http.Request) bool { 572 return r.TLS != nil || strings.EqualFold(strings.TrimSpace(strings.SplitN(r.Header.Get("X-Forwarded-Proto"), ",", 2)[0]), "https") 573 } 574 575 func setSessionCookie(w http.ResponseWriter, r *http.Request, sessionID string) { 576 http.SetCookie(w, &http.Cookie{Name: sessionCookieName, Value: sessionID, Path: forwardedPrefix(r) + "/", HttpOnly: true, Secure: cookieSecure(r), SameSite: http.SameSiteLaxMode, MaxAge: 86400}) 577 } 578 579 func sessionID(r *http.Request) string { 580 cookie, err := r.Cookie(sessionCookieName) 581 if err != nil { 582 return "" 583 } 584 return cookie.Value 585 } 586 587 func setOrderCookie(w http.ResponseWriter, r *http.Request, lang, article, orderID string) { 588 http.SetCookie(w, &http.Cookie{Name: orderCookieName, Value: orderID, Path: forwardedPrefix(r) + "/" + url.PathEscape(lang) + "/essay/" + url.PathEscape(article), HttpOnly: true, Secure: cookieSecure(r), SameSite: http.SameSiteLaxMode, MaxAge: 86400}) 589 } 590 591 func orderID(r *http.Request) string { 592 cookie, err := r.Cookie(orderCookieName) 593 if err != nil { 594 return "" 595 } 596 return cookie.Value 597 } 598 599 func queryRedirect(r *http.Request, mutate func(url.Values)) string { 600 target := *r.URL 601 query := target.Query() 602 mutate(query) 603 target.RawQuery = query.Encode() 604 return forwardedPrefix(r) + target.RequestURI() 605 }