aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/browser_account.go (4665B)


      1 package main
      2 
      3 import (
      4 	"crypto/rand"
      5 	"crypto/sha256"
      6 	"crypto/subtle"
      7 	"database/sql"
      8 	"encoding/json"
      9 	"errors"
     10 	"fmt"
     11 	"net/http"
     12 )
     13 
     14 func (server *server) setBrowserCookie(w http.ResponseWriter, r *http.Request, token string) {
     15 	http.SetCookie(w, &http.Cookie{Name: "ao_client", Value: token, Path: server.baseURL,
     16 		HttpOnly: true, Secure: r.TLS != nil, SameSite: http.SameSiteLaxMode, MaxAge: 31536000})
     17 }
     18 
     19 func (server *server) browserAccountInfo(w http.ResponseWriter, r *http.Request) {
     20 	w.Header().Set("Cache-Control", "no-store")
     21 	cookie, err := r.Cookie("ao_client")
     22 	if err != nil {
     23 		http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
     24 		return
     25 	}
     26 
     27 	// Account identity and credentials commit atomically; reading them needs no simulation lock.
     28 	credential := fmt.Sprintf("%x", sha256.Sum256([]byte(cookie.Value)))
     29 	var name string
     30 	var claimed bool
     31 	err = server.db.QueryRow("SELECT name, length(password_hash)>0 FROM characters WHERE id<1000000 AND browser_token_hash=?", credential).Scan(&name, &claimed)
     32 	if err == sql.ErrNoRows {
     33 		http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
     34 		return
     35 	}
     36 	if err != nil {
     37 		http.Error(w, err.Error(), http.StatusInternalServerError)
     38 		return
     39 	}
     40 	w.Header().Set("Content-Type", "application/json")
     41 	json.NewEncoder(w).Encode(map[string]any{"name": name, "visitor": !claimed, "adopted": claimed})
     42 }
     43 
     44 func (server *server) browserAccount(w http.ResponseWriter, r *http.Request) {
     45 	w.Header().Set("Cache-Control", "no-store")
     46 	action := r.PathValue("action")
     47 	if action == "password" {
     48 		server.changeBrowserPassword(w, r)
     49 		return
     50 	}
     51 	if action != "claim" && action != "login" && action != "create" {
     52 		http.NotFound(w, r)
     53 		return
     54 	}
     55 	r.Body = http.MaxBytesReader(w, r.Body, 4096)
     56 	if err := r.ParseForm(); err != nil {
     57 		http.Error(w, "Invalid account form.", http.StatusBadRequest)
     58 		return
     59 	}
     60 	name, validName := browserPlayerName(r.PostForm.Get("name"))
     61 	password := r.PostForm.Get("password")
     62 	if !validName || len(password) > 1024 {
     63 		http.Error(w, "Use a name of 4-12 letters or digits, with at least four initial letters and digits only at the end, and a password up to 1024 bytes.", http.StatusBadRequest)
     64 		return
     65 	}
     66 	if action != "login" && !validNewPassword(password) {
     67 		http.Error(w, "Use a password of at least 5 characters and at most 1024 bytes.", http.StatusBadRequest)
     68 		return
     69 	}
     70 	var created *character
     71 	if action == "create" {
     72 		var err error
     73 		created, err = server.browserCreation(r)
     74 		if err != nil {
     75 			http.Error(w, err.Error(), http.StatusBadRequest)
     76 			return
     77 		}
     78 	}
     79 	previous := browserCredential(r)
     80 	currentID, err := server.browserPlayerID(previous)
     81 	if err != nil {
     82 		http.Error(w, err.Error(), http.StatusInternalServerError)
     83 		return
     84 	}
     85 	if currentID == 0 {
     86 		http.Error(w, "Your browser session has ended. Reconnect to continue.", http.StatusUnauthorized)
     87 		return
     88 	}
     89 
     90 	// Derive a new salted hash, or verify the existing hash before changing state.
     91 	id := currentID
     92 	salt, expected := make([]byte, 16), make([]byte, 32)
     93 	if action != "login" {
     94 		rand.Read(salt)
     95 	} else {
     96 		err = server.db.QueryRow("SELECT id, password_salt, password_hash FROM characters WHERE name=? COLLATE NOCASE AND length(password_hash)>0", name).Scan(&id, &salt, &expected)
     97 		if err != nil && err != sql.ErrNoRows {
     98 			http.Error(w, err.Error(), http.StatusInternalServerError)
     99 			return
    100 		}
    101 		if err == sql.ErrNoRows {
    102 			id = 0
    103 		}
    104 	}
    105 	hash := server.browserPassword(password, salt)
    106 	if action == "login" && (id == 0 || subtle.ConstantTimeCompare(hash, expected) != 1) {
    107 		http.Error(w, "Incorrect player name or password.", http.StatusUnauthorized)
    108 		return
    109 	}
    110 
    111 	// Only the affected owners pause while SQLite commits the account change.
    112 	token := rand.Text()
    113 	change := &browserAccountChange{action: action, current: currentID, target: id, previous: previous,
    114 		credential: fmt.Sprintf("%x", sha256.Sum256([]byte(token))),
    115 		abandoned:  fmt.Sprintf("%x", sha256.Sum256([]byte(rand.Text()))),
    116 		name:       name, salt: salt, hash: hash, created: created}
    117 	if err := server.changeBrowserAccount(change); err != nil {
    118 		status := http.StatusInternalServerError
    119 		if errors.Is(err, errGameBanned) {
    120 			status = http.StatusForbidden
    121 		} else if errors.Is(err, errBrowserSessionChanged) || errors.Is(err, errBrowserLogin) {
    122 			status = http.StatusUnauthorized
    123 		} else if errors.Is(err, errBrowserNameTaken) || errors.Is(err, errBrowserAdopted) {
    124 			status = http.StatusConflict
    125 		}
    126 		http.Error(w, err.Error(), status)
    127 		return
    128 	}
    129 	server.setBrowserCookie(w, r, token)
    130 	w.WriteHeader(http.StatusNoContent)
    131 }