diff --git a/.air.toml b/.air.toml new file mode 100644 index 0000000..2214178 --- /dev/null +++ b/.air.toml @@ -0,0 +1,33 @@ +# Hot reload for local development: air +# https://github.com/air-verse/air + +root = "." +tmp_dir = "tmp" + +[build] + cmd = "go build -o ./tmp/server ./cmd/server" + bin = "./tmp/server" + full_bin = "./tmp/server" + include_ext = ["go", "html", "css", "js", "sql"] + exclude_dir = ["tmp", "vendor", "testdata", "bin"] + exclude_file = [] + exclude_regex = ["_test\\.go"] + exclude_unchanged = true + follow_symlink = false + delay = 500 + stop_on_error = true + send_interrupt = true + kill_delay = "1s" + +[log] + time = false + main_only = false + +[color] + main = "magenta" + watcher = "cyan" + build = "yellow" + runner = "green" + +[misc] + clean_on_exit = true diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e6941bb --- /dev/null +++ b/.env.example @@ -0,0 +1,18 @@ +# Local listen address (ignored when PORT is set, e.g. on App Platform) +LISTEN=:8080 +DATA_PATH=data.db +# Optional: first matching registrant becomes admin only if no admin exists yet. +# Later promote/demote via /admin/users (admins only). +ADMIN_USERNAME=yourusername +# Set to 1 when serving over HTTPS +SECURE_COOKIE=0 +# Prod (PlanetScale Postgres): paste the dashboard URI. When set, SQLite is ignored. +# Use port 5432 so the app can create tables on boot. Switch to 6432 (PgBouncer) later if you need pooling. +# DATABASE_URL=postgresql://user:password@host.example.com:5432/postgres?sslmode=verify-full +# DigitalOcean Spaces (profile avatars). Leave unset to disable uploads. +# SPACES_KEY= +# SPACES_SECRET= +# SPACES_REGION=nyc3 +# SPACES_BUCKET=your-bucket +# SPACES_ENDPOINT=https://nyc3.digitaloceanspaces.com +# SPACES_CDN_BASE=https://your-bucket.nyc3.cdn.digitaloceanspaces.com diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3f6b01e --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +/data.db +/data.db-* +/.test.db +/.test.db-* +/bin/ +/tmp/ +.env +*.exe diff --git a/cmd/server/main.go b/cmd/server/main.go new file mode 100644 index 0000000..169fa9a --- /dev/null +++ b/cmd/server/main.go @@ -0,0 +1,74 @@ +package main + +import ( + "log" + "net/http" + "os" + "strings" + + "github.com/joho/godotenv" + + "plumber" + "plumber/internal/blob" + "plumber/internal/store" + "plumber/internal/web" +) + +func main() { + _ = godotenv.Load() + listen := listenAddr() + st, err := store.Connect(os.Getenv("DATABASE_URL"), env("DATA_PATH", "data.db"), plumber.SchemaSQL) + if err != nil { + log.Fatalf("database: %v", err) + } + defer st.Close() + if os.Getenv("DATABASE_URL") != "" { + log.Printf("database: postgres") + } else { + log.Printf("database: sqlite") + } + uploader := blob.NewSpaces(blob.SpacesConfig{ + Key: os.Getenv("SPACES_KEY"), + Secret: os.Getenv("SPACES_SECRET"), + Region: os.Getenv("SPACES_REGION"), + Bucket: os.Getenv("SPACES_BUCKET"), + Endpoint: os.Getenv("SPACES_ENDPOINT"), + CDNBase: os.Getenv("SPACES_CDN_BASE"), + }) + if uploader.Enabled() { + log.Printf("avatars: digitalocean spaces") + } else { + log.Printf("avatars: uploads disabled (set SPACES_* to enable)") + } + srv, err := web.New(st, st.SessionStore(), plumber.TemplateFS, plumber.StaticFS, web.Config{ + AdminUsername: os.Getenv("ADMIN_USERNAME"), + SecureCookie: os.Getenv("SECURE_COOKIE") == "1", + Blob: uploader, + }) + if err != nil { + log.Fatalf("server: %v", err) + } + log.Printf("listening on %s", listen) + if err := http.ListenAndServe(listen, srv.Handler()); err != nil { + log.Fatal(err) + } +} + +// listenAddr prefers PORT (App Platform / PaaS), then LISTEN, then :8080. +func listenAddr() string { + if p := strings.TrimSpace(os.Getenv("PORT")); p != "" { + if strings.HasPrefix(p, ":") { + return p + } + return ":" + p + } + return env("LISTEN", ":8080") +} + +func env(key, fallback string) string { + v := strings.TrimSpace(os.Getenv(key)) + if v == "" { + return fallback + } + return v +} diff --git a/embed.go b/embed.go new file mode 100644 index 0000000..d74be85 --- /dev/null +++ b/embed.go @@ -0,0 +1,12 @@ +package plumber + +import "embed" + +//go:embed templates/*.html templates/partials/*.html +var TemplateFS embed.FS + +//go:embed static +var StaticFS embed.FS + +//go:embed schema.sql +var SchemaSQL string diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a4ba585 --- /dev/null +++ b/go.mod @@ -0,0 +1,42 @@ +module plumber + +go 1.25.0 + +require ( + github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de + github.com/alexedwards/scs/v2 v2.9.0 + github.com/aws/aws-sdk-go-v2 v1.43.7 + github.com/aws/aws-sdk-go-v2/credentials v1.19.37 + github.com/aws/aws-sdk-go-v2/service/s3 v1.107.3 + github.com/go-chi/chi/v5 v5.3.1 + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.10.0 + github.com/joho/godotenv v1.5.1 + golang.org/x/crypto v0.55.0 + modernc.org/sqlite v1.57.0 +) + +require ( + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.18 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.38 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.38 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.39 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.17 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.31 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.38 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.39 // indirect + github.com/aws/smithy-go v1.27.8 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/puddle/v2 v2.2.2 // indirect + github.com/mattn/go-isatty v0.0.24 // indirect + github.com/ncruces/go-strftime v1.0.0 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sync v0.22.0 // indirect + golang.org/x/sys v0.47.0 // indirect + golang.org/x/text v0.41.0 // indirect + modernc.org/libc v1.74.4 // indirect + modernc.org/mathutil v1.7.1 // indirect + modernc.org/memory v1.11.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..66a4c4b --- /dev/null +++ b/go.sum @@ -0,0 +1,110 @@ +github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de h1:LDrMkjj4OCCQsq9SvIPQV1l3leMxqXZTCTxDFwMrqTE= +github.com/alexedwards/scs/postgresstore v0.0.0-20251002162104-209de6e426de/go.mod h1:TDDdV/xnjj+/4zBQ9a2k+i2AbuAdY7SQjPUh5zoTZ3M= +github.com/alexedwards/scs/v2 v2.9.0 h1:xa05mVpwTBm1iLeTMNFfAWpKUm4fXAW7CeAViqBVS90= +github.com/alexedwards/scs/v2 v2.9.0/go.mod h1:ToaROZxyKukJKT/xLcVQAChi5k6+Pn1Gvmdl7h3RRj8= +github.com/aws/aws-sdk-go-v2 v1.43.7 h1:msCzvkeYJA9ehbV8mRRmkZLo/zJg/+yDVLNtflg83hQ= +github.com/aws/aws-sdk-go-v2 v1.43.7/go.mod h1:tXpPM+v0D1lndmga+HqqLDIzUFJlEeR21aspVklHF00= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.18 h1:LAfOuhAH331fmOjTQpAaOlH+Ftn7RzSDJ2VFwjdMMy4= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.18/go.mod h1:4e5xhuXHx1e4U9EthvbPP1r/DIMp5c2823OL8karzcM= +github.com/aws/aws-sdk-go-v2/credentials v1.19.37 h1:FJ8Iz4/xISMB/rwLlgfWujfGDFWr0oneQgtA6KPcYLY= +github.com/aws/aws-sdk-go-v2/credentials v1.19.37/go.mod h1:Q6pWOgVUp49x4g5QVi29wHofUoICnZ+Zq4jHbRN/7ec= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.38 h1:MBMg0zJ6i4TkAJ0dVFLKKn2cOkY6FkicmUDM67BRr6g= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.38/go.mod h1:9MWuJbyiUyj6eA7W1/zm1zuePDPSB3g+xcgRQeMWsXc= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.38 h1:lHm4jPf3k1Lz5ZWc+Vcn3MKVwym+26kWCba9FkJ4f0Y= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.38/go.mod h1:Rn+P2XR+FbyZzjmWKjg/KUZNxmGfr5oZwh5jQiE+CzI= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.39 h1:vo4xvMRs/F6h1E52qsgLqCQgWIQXgIJUauG6rlZEh4U= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.39/go.mod h1:jB03R1ij/A+OE2e1dz6vgj076gd7vlYcfstAzj3HcnU= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.17 h1:OvYZOB3qA6zvfdRFiRFRzVSiElMYrz3GdntkXZxlp1o= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.17/go.mod h1:JgR/2Ew50ACfIWau1oeMRX59tMtC0kM+PYQGEaT04cY= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.31 h1:uZOinZb+h7lZw8IYzP1z1IuEnueB76/EFkcf/fEW4Ag= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.31/go.mod h1:NRtwAM/p5VRt03TlEUs0pH3TeWamWdf4YyJpSrzPYLc= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.38 h1:H/5TI1jqaHsNoDQ60UwvPvJBg4GURkinXI3Qga29t2w= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.38/go.mod h1:PTVFf+XH++7NJOky+RLBYQx0QA5NcaeEYFQ2fsi0nwo= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.39 h1:HLPAVrlLDaN2boN0xJx7MgaQDNEO3Q+c9L6kl/8m47Q= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.39/go.mod h1:Pg/dVfsNkm1hsIDK/gMvCKtmyNfNTV12mrgHqVE/6Oo= +github.com/aws/aws-sdk-go-v2/service/s3 v1.107.3 h1:IKoCZqfWfZzSBi16QFQ+QcbQ3LRQ7QgB1S5tDAyPBQQ= +github.com/aws/aws-sdk-go-v2/service/s3 v1.107.3/go.mod h1:RBpRcXiM4s2pOInVs32GsBonnje+fiAj4mcrStRmlCA= +github.com/aws/smithy-go v1.27.8 h1:FR0dxZfIlV7Z8eh2iHfIofdunw382XsDV3Mxt9nUvRY= +github.com/aws/smithy-go v1.27.8/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/go-chi/chi/v5 v5.3.1 h1:3j4HZLGZQ3JpMCrPJF/Jl3mYJfWLKBfNJ6quurUGCf8= +github.com/go-chi/chi/v5 v5.3.1/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 h1:LMLX+LgTNWpfvCBdFebv6EsYotImrt/Ppc5cXIriCSo= +github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3/go.mod h1:jl5iWTm0/hd5PjEYEOuwAJ57L/CibdZfrqZ5XA5GrCk= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= +github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= +github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= +github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= +github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/lib/pq v1.4.0 h1:TmtCFbH+Aw0AixwyttznSMQDgbR5Yed/Gg6S8Funrhc= +github.com/lib/pq v1.4.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= +github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= +github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M= +golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis= +golang.org/x/mod v0.38.0 h1:MECBjubtXD7yj4HrhIUcywNaGeNVUdfVnxmPajOk4yk= +golang.org/x/mod v0.38.0/go.mod h1:V6Xz0pq8TQ3dGqVQ1FVHuelZpAL0uNhSkk9ogYP3c40= +golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= +golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= +golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8= +golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M= +golang.org/x/tools v0.48.0 h1:3+hClM1aLL5mjMKm5ovokw9epgRXPuu2tILgismM6RE= +golang.org/x/tools v0.48.0/go.mod h1:08xX0orndb/F7jJxGDicx061tyd5pcMto75YMAXr6lk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +modernc.org/cc/v4 v4.29.1 h1:MKgdCV3WykTSPqpVrnxdEDS0HEd2FHpKZDzxzU5LyeI= +modernc.org/cc/v4 v4.29.1/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= +modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU= +modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk= +modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= +modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= +modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= +modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= +modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI= +modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= +modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= +modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= +modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k= +modernc.org/libc v1.74.4/go.mod h1:eeQAS9W3sZeKYMFubydxJpII9ybHWshk+7or7bLG9co= +modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= +modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= +modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= +modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= +modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= +modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= +modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= +modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= +modernc.org/sqlite v1.57.0 h1:qNQP6xnx5M0ISNtlnxoOX0+cD5bJ0/gr9aMmndFczzg= +modernc.org/sqlite v1.57.0/go.mod h1:yCJ2cmAaIkHQ25oXWrF8H4O1lIfPYPR26yCEDj2P3pQ= +modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= +modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/internal/blob/spaces.go b/internal/blob/spaces.go new file mode 100644 index 0000000..69df506 --- /dev/null +++ b/internal/blob/spaces.go @@ -0,0 +1,88 @@ +package blob + +import ( + "context" + "fmt" + "io" + "strings" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" +) + +// Uploader stores public avatar objects. +type Uploader interface { + Enabled() bool + Upload(ctx context.Context, key string, body io.Reader, contentType string, size int64) (publicURL string, err error) +} + +// Disabled is a no-op uploader used when Spaces is not configured. +type Disabled struct{} + +func (Disabled) Enabled() bool { return false } + +func (Disabled) Upload(context.Context, string, io.Reader, string, int64) (string, error) { + return "", fmt.Errorf("avatar uploads are not configured") +} + +// SpacesConfig holds DigitalOcean Spaces settings. +type SpacesConfig struct { + Key string + Secret string + Region string + Bucket string + Endpoint string // e.g. https://nyc3.digitaloceanspaces.com + CDNBase string // optional public base URL without trailing slash +} + +// NewSpaces returns an Uploader when required env is present; otherwise Disabled. +func NewSpaces(cfg SpacesConfig) Uploader { + cfg.Key = strings.TrimSpace(cfg.Key) + cfg.Secret = strings.TrimSpace(cfg.Secret) + cfg.Region = strings.TrimSpace(cfg.Region) + cfg.Bucket = strings.TrimSpace(cfg.Bucket) + cfg.Endpoint = strings.TrimSpace(cfg.Endpoint) + cfg.CDNBase = strings.TrimRight(strings.TrimSpace(cfg.CDNBase), "/") + if cfg.Key == "" || cfg.Secret == "" || cfg.Region == "" || cfg.Bucket == "" || cfg.Endpoint == "" { + return Disabled{} + } + client := s3.New(s3.Options{ + Region: cfg.Region, + Credentials: credentials.NewStaticCredentialsProvider(cfg.Key, cfg.Secret, ""), + BaseEndpoint: aws.String(cfg.Endpoint), + }) + return &spaces{client: client, cfg: cfg} +} + +type spaces struct { + client *s3.Client + cfg SpacesConfig +} + +func (s *spaces) Enabled() bool { return true } + +func (s *spaces) Upload(ctx context.Context, key string, body io.Reader, contentType string, size int64) (string, error) { + key = strings.TrimPrefix(key, "/") + input := &s3.PutObjectInput{ + Bucket: aws.String(s.cfg.Bucket), + Key: aws.String(key), + Body: body, + ContentType: aws.String(contentType), + ACL: types.ObjectCannedACLPublicRead, + } + if size > 0 { + input.ContentLength = aws.Int64(size) + } + if _, err := s.client.PutObject(ctx, input); err != nil { + return "", err + } + if s.cfg.CDNBase != "" { + return s.cfg.CDNBase + "/" + key, nil + } + // Virtual-hosted–style Spaces URL. + host := strings.TrimPrefix(s.cfg.Endpoint, "https://") + host = strings.TrimPrefix(host, "http://") + return fmt.Sprintf("https://%s.%s/%s", s.cfg.Bucket, host, key), nil +} diff --git a/internal/geo/us.go b/internal/geo/us.go new file mode 100644 index 0000000..ff77702 --- /dev/null +++ b/internal/geo/us.go @@ -0,0 +1,56 @@ +package geo + +import "strings" + +// States is the US states + DC allowlist (code -> name). +var States = []struct { + Code string + Name string +}{ + {"AL", "Alabama"}, {"AK", "Alaska"}, {"AZ", "Arizona"}, {"AR", "Arkansas"}, {"CA", "California"}, + {"CO", "Colorado"}, {"CT", "Connecticut"}, {"DE", "Delaware"}, {"DC", "District of Columbia"}, + {"FL", "Florida"}, {"GA", "Georgia"}, {"HI", "Hawaii"}, {"ID", "Idaho"}, {"IL", "Illinois"}, + {"IN", "Indiana"}, {"IA", "Iowa"}, {"KS", "Kansas"}, {"KY", "Kentucky"}, {"LA", "Louisiana"}, + {"ME", "Maine"}, {"MD", "Maryland"}, {"MA", "Massachusetts"}, {"MI", "Michigan"}, {"MN", "Minnesota"}, + {"MS", "Mississippi"}, {"MO", "Missouri"}, {"MT", "Montana"}, {"NE", "Nebraska"}, {"NV", "Nevada"}, + {"NH", "New Hampshire"}, {"NJ", "New Jersey"}, {"NM", "New Mexico"}, {"NY", "New York"}, + {"NC", "North Carolina"}, {"ND", "North Dakota"}, {"OH", "Ohio"}, {"OK", "Oklahoma"}, {"OR", "Oregon"}, + {"PA", "Pennsylvania"}, {"RI", "Rhode Island"}, {"SC", "South Carolina"}, {"SD", "South Dakota"}, + {"TN", "Tennessee"}, {"TX", "Texas"}, {"UT", "Utah"}, {"VT", "Vermont"}, {"VA", "Virginia"}, + {"WA", "Washington"}, {"WV", "West Virginia"}, {"WI", "Wisconsin"}, {"WY", "Wyoming"}, +} + +var codes map[string]struct{} + +func init() { + codes = make(map[string]struct{}, len(States)) + for _, s := range States { + codes[s.Code] = struct{}{} + } +} + +// ValidState reports whether state is empty or a known US code. +func ValidState(state string) bool { + state = strings.ToUpper(strings.TrimSpace(state)) + if state == "" { + return true + } + _, ok := codes[state] + return ok +} + +// NormalizeState returns "" or an uppercase 2-letter code. +func NormalizeState(state string) string { + return strings.ToUpper(strings.TrimSpace(state)) +} + +// StateName returns the full name for a US state code, or "" if unknown. +func StateName(code string) string { + code = NormalizeState(code) + for _, s := range States { + if s.Code == code { + return s.Name + } + } + return "" +} diff --git a/internal/pacific/pacific.go b/internal/pacific/pacific.go new file mode 100644 index 0000000..ab7eae1 --- /dev/null +++ b/internal/pacific/pacific.go @@ -0,0 +1,53 @@ +package pacific + +import ( + "time" + + _ "time/tzdata" +) + +const Layout = "2006-01-02" + +var Loc *time.Location + +func init() { + loc, err := time.LoadLocation("America/Los_Angeles") + if err != nil { + panic(err) + } + Loc = loc +} + +func HuntDate(t time.Time) string { + return t.In(Loc).Format(Layout) +} + +func Today() string { + return HuntDate(time.Now()) +} + +func Yesterday() string { + now := time.Now().In(Loc) + y := time.Date(now.Year(), now.Month(), now.Day()-1, 0, 0, 0, 0, Loc) + return y.Format(Layout) +} + +func Parse(date string) (time.Time, error) { + return time.ParseInLocation(Layout, date, Loc) +} + +func Label(date string) string { + t, err := Parse(date) + if err != nil { + return date + } + return t.Format("January 2, 2006") +} + +func IsToday(date string) bool { + return date == Today() +} + +func IsYesterday(date string) bool { + return date == Yesterday() +} diff --git a/internal/store/db.go b/internal/store/db.go new file mode 100644 index 0000000..00febb9 --- /dev/null +++ b/internal/store/db.go @@ -0,0 +1,33 @@ +package store + +import ( + "context" + "errors" +) + +// ErrLastAdmin is returned when demoting the only remaining admin. +var ErrLastAdmin = errors.New("cannot demote the last admin") + +// DB is the persistence API used by the web layer. +// Named DB to avoid colliding with scs.Store. +type DB interface { + CreateUser(ctx context.Context, username, passwordHash string, asAdmin bool) (*User, error) + UserByID(ctx context.Context, id string) (*User, error) + UserByUsername(ctx context.Context, username string) (*User, error) + CountAdmins(ctx context.Context) (int, error) + ListUsers(ctx context.Context) ([]User, error) + SetRole(ctx context.Context, userID, role string) error + CreateQuestion(ctx context.Context, authorID, title, body, city string) (*RankedQuestion, error) + ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) + GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) + Vote(ctx context.Context, userID, questionID string, value int) error + GetAnswer(ctx context.Context, questionID string) (*Answer, error) + UpsertAnswer(ctx context.Context, questionID, authorID, body string) error + HideQuestion(ctx context.Context, id string) error + UpdateProfile(ctx context.Context, userID, state, avatarURL string) error + ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) + ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) +} + +// Compile-time check: *Store implements DB. +var _ DB = (*Store)(nil) diff --git a/internal/store/migrate.go b/internal/store/migrate.go new file mode 100644 index 0000000..0c247cb --- /dev/null +++ b/internal/store/migrate.go @@ -0,0 +1,28 @@ +package store + +import ( + "database/sql" + "fmt" + "strings" +) + +func migrateUserProfileColumns(db *sql.DB, dialect string) error { + cols := []string{"avatar_url", "state"} + for _, col := range cols { + var stmt string + switch dialect { + case dialectPostgres: + stmt = fmt.Sprintf(`ALTER TABLE users ADD COLUMN IF NOT EXISTS %s TEXT NOT NULL DEFAULT ''`, col) + default: + stmt = fmt.Sprintf(`ALTER TABLE users ADD COLUMN %s TEXT NOT NULL DEFAULT ''`, col) + } + if _, err := db.Exec(stmt); err != nil { + // SQLite errors when the column already exists. + if dialect == dialectSQLite && strings.Contains(strings.ToLower(err.Error()), "duplicate column") { + continue + } + return fmt.Errorf("add column %s: %w", col, err) + } + } + return nil +} diff --git a/internal/store/postgres.go b/internal/store/postgres.go new file mode 100644 index 0000000..878e2d0 --- /dev/null +++ b/internal/store/postgres.go @@ -0,0 +1,130 @@ +package store + +import ( + "database/sql" + "fmt" + "net/url" + "strconv" + "strings" + "time" + + _ "github.com/jackc/pgx/v5/stdlib" +) + +const ( + dialectSQLite = "sqlite" + dialectPostgres = "postgres" +) + +func rebind(query string) string { + n := 0 + var b strings.Builder + for i := 0; i < len(query); i++ { + if query[i] == '?' { + n++ + b.WriteByte('$') + b.WriteString(strconv.Itoa(n)) + continue + } + b.WriteByte(query[i]) + } + return b.String() +} + +func (s *Store) q(query string) string { + if s.dialect == dialectPostgres { + return rebind(query) + } + return query +} + +func applySchema(db *sql.DB, schema string) error { + for _, stmt := range strings.Split(schema, ";") { + stmt = strings.TrimSpace(stmt) + if stmt == "" { + continue + } + upper := strings.ToUpper(stmt) + if strings.HasPrefix(upper, "PRAGMA") { + continue + } + if _, err := db.Exec(stmt); err != nil { + return fmt.Errorf("%w: %s", err, stmt) + } + } + return nil +} + +func postgresDSN(raw string) (string, error) { + u, err := url.Parse(raw) + if err != nil { + return "", fmt.Errorf("DATABASE_URL: %w", err) + } + switch u.Scheme { + case "postgres", "postgresql": + default: + return "", fmt.Errorf("DATABASE_URL must be a postgres URL") + } + q := u.Query() + if strings.EqualFold(q.Get("sslrootcert"), "system") { + q.Del("sslrootcert") + } + q.Del("sslnegotiation") + if q.Get("sslmode") == "" { + q.Set("sslmode", "verify-full") + } + u.RawQuery = q.Encode() + return u.String(), nil +} + +func OpenPostgres(databaseURL, schema string) (*Store, error) { + return openPostgres(databaseURL, schema, 5*time.Minute) +} + +// OpenPostgresWithoutSessionCleanup opens Postgres without a session cleanup goroutine (for tests). +func OpenPostgresWithoutSessionCleanup(databaseURL, schema string) (*Store, error) { + return openPostgres(databaseURL, schema, 0) +} + +func openPostgres(databaseURL, schema string, sessionCleanup time.Duration) (*Store, error) { + dsn, err := postgresDSN(databaseURL) + if err != nil { + return nil, err + } + db, err := sql.Open("pgx", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(20) + db.SetMaxIdleConns(5) + if err := db.Ping(); err != nil { + _ = db.Close() + return nil, fmt.Errorf("postgres ping: %w", err) + } + if err := applySchema(db, schema); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply schema: %w", err) + } + if err := applySessionsSchema(db, dialectPostgres); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply sessions schema: %w", err) + } + if err := migrateUserProfileColumns(db, dialectPostgres); err != nil { + _ = db.Close() + return nil, fmt.Errorf("migrate profile columns: %w", err) + } + st := &Store{db: db, dialect: dialectPostgres} + st.initSessionStore(sessionCleanup) + return st, nil +} + +// Connect uses PlanetScale Postgres when DATABASE_URL is set, otherwise SQLite. +func Connect(databaseURL, sqlitePath, schema string) (*Store, error) { + if strings.TrimSpace(databaseURL) != "" { + return OpenPostgres(databaseURL, schema) + } + if sqlitePath == "" { + sqlitePath = "data.db" + } + return Open(sqlitePath, schema) +} diff --git a/internal/store/postgres_test.go b/internal/store/postgres_test.go new file mode 100644 index 0000000..f297d14 --- /dev/null +++ b/internal/store/postgres_test.go @@ -0,0 +1,41 @@ +package store + +import "testing" + +func TestRebindPostgresPlaceholders(t *testing.T) { + got := rebind(`SELECT a FROM t WHERE x = ? AND y = ?`) + want := `SELECT a FROM t WHERE x = $1 AND y = $2` + if got != want { + t.Fatalf("got %q", got) + } +} + +func TestNormalizeUsername(t *testing.T) { + if got := NormalizeUsername(" Alice_1 "); got != "alice_1" { + t.Fatalf("got %q", got) + } +} + +func TestPostgresDSNDefaultsSSLMode(t *testing.T) { + in := "postgresql://user:pass@db.example.com:5432/postgres" + out, err := postgresDSN(in) + if err != nil { + t.Fatal(err) + } + if !containsAny(out, "sslmode=verify-full") { + t.Fatalf("missing default sslmode: %s", out) + } +} + +func containsAny(s string, parts ...string) bool { + for _, p := range parts { + if len(p) > 0 && (len(s) >= len(p)) { + for i := 0; i+len(p) <= len(s); i++ { + if s[i:i+len(p)] == p { + return true + } + } + } + } + return false +} diff --git a/internal/store/sessions.go b/internal/store/sessions.go new file mode 100644 index 0000000..1e4041f --- /dev/null +++ b/internal/store/sessions.go @@ -0,0 +1,154 @@ +package store + +import ( + "database/sql" + "log" + "time" + + "github.com/alexedwards/scs/postgresstore" + "github.com/alexedwards/scs/v2" +) + +const sessionsSchemaSQLite = ` +CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + data BLOB NOT NULL, + expiry REAL NOT NULL +); +CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions(expiry); +` + +const sessionsSchemaPostgres = ` +CREATE TABLE IF NOT EXISTS sessions ( + token TEXT PRIMARY KEY, + data BYTEA NOT NULL, + expiry TIMESTAMPTZ NOT NULL +); +CREATE INDEX IF NOT EXISTS sessions_expiry_idx ON sessions (expiry); +` + +func applySessionsSchema(db *sql.DB, dialect string) error { + schema := sessionsSchemaSQLite + if dialect == dialectPostgres { + schema = sessionsSchemaPostgres + } + return applySchema(db, schema) +} + +type sessionStopper interface { + StopCleanup() +} + +// SessionStore returns the scs store backed by this database. +func (s *Store) SessionStore() scs.Store { + return s.sessionStore +} + +func (s *Store) initSessionStore(cleanupInterval time.Duration) { + switch s.dialect { + case dialectPostgres: + ps := postgresstore.NewWithCleanupInterval(s.db, cleanupInterval) + s.sessionStore = ps + s.sessionStopper = ps + default: + ss := newSQLiteSessionStore(s.db, cleanupInterval) + s.sessionStore = ss + s.sessionStopper = ss + } +} + +// sqliteSessionStore is a modernc-safe scs.Store (uses ? placeholders). +type sqliteSessionStore struct { + db *sql.DB + stopCleanup chan bool +} + +func newSQLiteSessionStore(db *sql.DB, cleanupInterval time.Duration) *sqliteSessionStore { + s := &sqliteSessionStore{db: db} + if cleanupInterval > 0 { + s.stopCleanup = make(chan bool) + go s.startCleanup(cleanupInterval) + } + return s +} + +func (s *sqliteSessionStore) Find(token string) ([]byte, bool, error) { + var b []byte + err := s.db.QueryRow( + `SELECT data FROM sessions WHERE token = ? AND julianday('now') < expiry`, + token, + ).Scan(&b) + if err == sql.ErrNoRows { + return nil, false, nil + } + if err != nil { + return nil, false, err + } + return b, true, nil +} + +func (s *sqliteSessionStore) Commit(token string, b []byte, expiry time.Time) error { + _, err := s.db.Exec( + `REPLACE INTO sessions (token, data, expiry) VALUES (?, ?, julianday(?))`, + token, + b, + expiry.UTC().Format("2006-01-02T15:04:05.999"), + ) + return err +} + +func (s *sqliteSessionStore) Delete(token string) error { + _, err := s.db.Exec(`DELETE FROM sessions WHERE token = ?`, token) + return err +} + +func (s *sqliteSessionStore) All() (map[string][]byte, error) { + rows, err := s.db.Query(`SELECT token, data FROM sessions WHERE julianday('now') < expiry`) + if err != nil { + return nil, err + } + defer rows.Close() + out := make(map[string][]byte) + for rows.Next() { + var token string + var data []byte + if err := rows.Scan(&token, &data); err != nil { + return nil, err + } + out[token] = data + } + return out, rows.Err() +} + +func (s *sqliteSessionStore) startCleanup(interval time.Duration) { + ticker := time.NewTicker(interval) + for { + select { + case <-ticker.C: + if err := s.deleteExpired(); err != nil { + log.Println(err) + } + case <-s.stopCleanup: + ticker.Stop() + return + } + } +} + +func (s *sqliteSessionStore) StopCleanup() { + if s.stopCleanup != nil { + s.stopCleanup <- true + } +} + +func (s *sqliteSessionStore) deleteExpired() error { + _, err := s.db.Exec(`DELETE FROM sessions WHERE expiry < julianday('now')`) + return err +} + +// Ensure interface compliance. +var ( + _ scs.Store = (*sqliteSessionStore)(nil) + _ scs.IterableStore = (*sqliteSessionStore)(nil) + _ sessionStopper = (*sqliteSessionStore)(nil) +) diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..778dfc8 --- /dev/null +++ b/internal/store/store.go @@ -0,0 +1,406 @@ +package store + +import ( + "context" + "database/sql" + "fmt" + "strings" + "time" + + "github.com/alexedwards/scs/v2" + "github.com/google/uuid" + _ "modernc.org/sqlite" + + "plumber/internal/pacific" +) + +type Store struct { + db *sql.DB + dialect string + sessionStore scs.Store + sessionStopper sessionStopper +} + +type User struct { + ID string + Username string + Name string + Role string + AvatarURL string + State string + CreatedAt string + PasswordHash string +} + +func (u *User) Admin() bool { + return u != nil && u.Role == "admin" +} + +type RankedQuestion struct { + ID string + AuthorID string + AuthorName string + Title string + Body string + City string + HuntDate string + Hidden bool + CreatedAt string + Score int + Answered bool + UserVote int +} + +type Answer struct { + QuestionID string + AuthorID string + AuthorName string + Body string + CreatedAt string + UpdatedAt string +} + +func Open(path, schema string) (*Store, error) { + return openSQLite(path, schema, 5*time.Minute) +} + +// OpenWithoutSessionCleanup opens SQLite without a session cleanup goroutine (for tests). +func OpenWithoutSessionCleanup(path, schema string) (*Store, error) { + return openSQLite(path, schema, 0) +} + +func openSQLite(path, schema string, sessionCleanup time.Duration) (*Store, error) { + dsn := path + if !strings.Contains(dsn, "?") { + dsn += "?_pragma=foreign_keys(1)&_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)" + } + db, err := sql.Open("sqlite", dsn) + if err != nil { + return nil, err + } + db.SetMaxOpenConns(1) + if _, err := db.Exec(schema); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply schema: %w", err) + } + if err := applySessionsSchema(db, dialectSQLite); err != nil { + _ = db.Close() + return nil, fmt.Errorf("apply sessions schema: %w", err) + } + if err := migrateUserProfileColumns(db, dialectSQLite); err != nil { + _ = db.Close() + return nil, fmt.Errorf("migrate profile columns: %w", err) + } + st := &Store{db: db, dialect: dialectSQLite} + st.initSessionStore(sessionCleanup) + return st, nil +} + +func (s *Store) Close() error { + if s.sessionStopper != nil { + s.sessionStopper.StopCleanup() + s.sessionStopper = nil + } + return s.db.Close() +} + +func (s *Store) CreateUser(ctx context.Context, username, passwordHash string, asAdmin bool) (*User, error) { + username = NormalizeUsername(username) + role := "user" + if asAdmin { + role = "admin" + } + u := &User{ + ID: uuid.NewString(), + Username: username, + Name: username, + Role: role, + PasswordHash: passwordHash, + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + _, err := s.db.ExecContext(ctx, s.q(`INSERT INTO users (id, username, name, password_hash, role, avatar_url, state, created_at) VALUES (?, ?, ?, ?, ?, '', '', ?)`), + u.ID, u.Username, u.Name, u.PasswordHash, u.Role, u.CreatedAt) + if err != nil { + return nil, err + } + return u, nil +} + +func (s *Store) CountAdmins(ctx context.Context) (int, error) { + var n int + err := s.db.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), "admin").Scan(&n) + return n, err +} + +func (s *Store) ListUsers(ctx context.Context) ([]User, error) { + rows, err := s.db.QueryContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at FROM users ORDER BY created_at ASC`)) + if err != nil { + return nil, err + } + defer rows.Close() + var out []User + for rows.Next() { + var u User + if err := rows.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt); err != nil { + return nil, err + } + out = append(out, u) + } + return out, rows.Err() +} + +func (s *Store) SetRole(ctx context.Context, userID, role string) error { + if role != "user" && role != "admin" { + return fmt.Errorf("invalid role") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + + var current string + err = tx.QueryRowContext(ctx, s.q(`SELECT role FROM users WHERE id = ?`), userID).Scan(¤t) + if err != nil { + return err + } + if current == "admin" && role == "user" { + var n int + if err := tx.QueryRowContext(ctx, s.q(`SELECT COUNT(*) FROM users WHERE role = ?`), "admin").Scan(&n); err != nil { + return err + } + if n <= 1 { + return ErrLastAdmin + } + } + res, err := tx.ExecContext(ctx, s.q(`UPDATE users SET role = ? WHERE id = ?`), role, userID) + if err != nil { + return err + } + aff, err := res.RowsAffected() + if err != nil { + return err + } + if aff == 0 { + return sql.ErrNoRows + } + return tx.Commit() +} + +func (s *Store) UserByID(ctx context.Context, id string) (*User, error) { + return scanUser(s.db.QueryRowContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at FROM users WHERE id = ?`), id), false) +} + +func (s *Store) UserByUsername(ctx context.Context, username string) (*User, error) { + return scanUser(s.db.QueryRowContext(ctx, s.q(`SELECT id, username, name, role, avatar_url, state, created_at, password_hash FROM users WHERE username = ?`), NormalizeUsername(username)), true) +} + +func scanUser(row *sql.Row, withSecrets bool) (*User, error) { + var u User + var err error + if withSecrets { + err = row.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt, &u.PasswordHash) + } else { + err = row.Scan(&u.ID, &u.Username, &u.Name, &u.Role, &u.AvatarURL, &u.State, &u.CreatedAt) + } + if err != nil { + return nil, err + } + return &u, nil +} + +func NormalizeUsername(s string) string { + return strings.ToLower(strings.TrimSpace(s)) +} + +func (s *Store) CreateQuestion(ctx context.Context, authorID, title, body, city string) (*RankedQuestion, error) { + q := &RankedQuestion{ + ID: uuid.NewString(), + AuthorID: authorID, + Title: strings.TrimSpace(title), + Body: strings.TrimSpace(body), + City: strings.TrimSpace(city), + HuntDate: pacific.Today(), + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + _, err := s.db.ExecContext(ctx, s.q(`INSERT INTO questions (id, author_id, title, body, city, hunt_date, hidden, created_at) VALUES (?, ?, ?, ?, ?, ?, 0, ?)`), + q.ID, q.AuthorID, q.Title, q.Body, q.City, q.HuntDate, q.CreatedAt) + if err != nil { + return nil, err + } + return q, nil +} + +func (s *Store) ListHunt(ctx context.Context, huntDate, viewerID string) ([]RankedQuestion, error) { + rows, err := s.db.QueryContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE(SUM(v.value), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + COALESCE((SELECT value FROM votes WHERE user_id = ? AND question_id = q.id), 0) AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN votes v ON v.question_id = q.id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.hunt_date = ? AND q.hidden = 0 +GROUP BY q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, a.question_id +ORDER BY score DESC, q.created_at ASC`), viewerID, huntDate) + if err != nil { + return nil, err + } + defer rows.Close() + var out []RankedQuestion + for rows.Next() { + q, err := scanRanked(rows) + if err != nil { + return nil, err + } + out = append(out, q) + } + return out, rows.Err() +} + +func (s *Store) GetQuestion(ctx context.Context, id, viewerID string) (*RankedQuestion, error) { + row := s.db.QueryRowContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + COALESCE((SELECT value FROM votes WHERE user_id = ? AND question_id = q.id), 0) AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.id = ?`), viewerID, id) + q, err := scanRankedRow(row) + if err != nil { + return nil, err + } + return &q, nil +} + +type scanned interface { + Scan(dest ...any) error +} + +func scanRanked(rows scanned) (RankedQuestion, error) { + var q RankedQuestion + var hidden, answered int + err := rows.Scan(&q.ID, &q.AuthorID, &q.AuthorName, &q.Title, &q.Body, &q.City, &q.HuntDate, &hidden, &q.CreatedAt, &q.Score, &answered, &q.UserVote) + q.Hidden = hidden != 0 + q.Answered = answered != 0 + return q, err +} + +func scanRankedRow(row *sql.Row) (RankedQuestion, error) { + return scanRanked(row) +} + +func (s *Store) Vote(ctx context.Context, userID, questionID string, value int) error { + if value != 1 && value != -1 { + return fmt.Errorf("invalid vote") + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + var current sql.NullInt64 + err = tx.QueryRowContext(ctx, s.q(`SELECT value FROM votes WHERE user_id = ? AND question_id = ?`), userID, questionID).Scan(¤t) + if err != nil && err != sql.ErrNoRows { + return err + } + if err == nil && current.Valid && int(current.Int64) == value { + _, err = tx.ExecContext(ctx, s.q(`DELETE FROM votes WHERE user_id = ? AND question_id = ?`), userID, questionID) + } else { + _, err = tx.ExecContext(ctx, s.q(`INSERT INTO votes (user_id, question_id, value) VALUES (?, ?, ?) +ON CONFLICT (user_id, question_id) DO UPDATE SET value = excluded.value`), userID, questionID, value) + } + if err != nil { + return err + } + return tx.Commit() +} + +func (s *Store) GetAnswer(ctx context.Context, questionID string) (*Answer, error) { + var a Answer + err := s.db.QueryRowContext(ctx, s.q(` +SELECT a.question_id, a.author_id, u.name, a.body, a.created_at, a.updated_at +FROM answers a +JOIN users u ON u.id = a.author_id +WHERE a.question_id = ?`), questionID).Scan(&a.QuestionID, &a.AuthorID, &a.AuthorName, &a.Body, &a.CreatedAt, &a.UpdatedAt) + if err != nil { + return nil, err + } + return &a, nil +} + +func (s *Store) UpsertAnswer(ctx context.Context, questionID, authorID, body string) error { + body = strings.TrimSpace(body) + now := time.Now().UTC().Format(time.RFC3339) + _, err := s.db.ExecContext(ctx, s.q(` +INSERT INTO answers (question_id, author_id, body, created_at, updated_at) VALUES (?, ?, ?, ?, ?) +ON CONFLICT (question_id) DO UPDATE SET body = excluded.body, author_id = excluded.author_id, updated_at = excluded.updated_at`), + questionID, authorID, body, now, now) + return err +} + +func (s *Store) HideQuestion(ctx context.Context, id string) error { + _, err := s.db.ExecContext(ctx, s.q(`UPDATE questions SET hidden = 1 WHERE id = ?`), id) + return err +} + +func (s *Store) UpdateProfile(ctx context.Context, userID, state, avatarURL string) error { + state = strings.TrimSpace(state) + if avatarURL == "" { + _, err := s.db.ExecContext(ctx, s.q(`UPDATE users SET state = ? WHERE id = ?`), state, userID) + return err + } + _, err := s.db.ExecContext(ctx, s.q(`UPDATE users SET state = ?, avatar_url = ? WHERE id = ?`), state, avatarURL, userID) + return err +} + +func (s *Store) ListQuestionsByAuthor(ctx context.Context, authorID string) ([]RankedQuestion, error) { + rows, err := s.db.QueryContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + CASE WHEN a.question_id IS NULL THEN 0 ELSE 1 END AS answered, + 0 AS user_vote +FROM questions q +JOIN users u ON u.id = q.author_id +LEFT JOIN answers a ON a.question_id = q.id +WHERE q.author_id = ? AND q.hidden = 0 +ORDER BY q.created_at DESC`), authorID) + if err != nil { + return nil, err + } + defer rows.Close() + return scanRankedList(rows) +} + +func (s *Store) ListQuestionsAnsweredBy(ctx context.Context, adminID string) ([]RankedQuestion, error) { + rows, err := s.db.QueryContext(ctx, s.q(` +SELECT q.id, q.author_id, u.name, q.title, q.body, q.city, q.hunt_date, q.hidden, q.created_at, + COALESCE((SELECT SUM(value) FROM votes WHERE question_id = q.id), 0) AS score, + 1 AS answered, + 0 AS user_vote +FROM answers ans +JOIN questions q ON q.id = ans.question_id +JOIN users u ON u.id = q.author_id +WHERE ans.author_id = ? AND q.hidden = 0 +ORDER BY ans.updated_at DESC`), adminID) + if err != nil { + return nil, err + } + defer rows.Close() + return scanRankedList(rows) +} + +func scanRankedList(rows *sql.Rows) ([]RankedQuestion, error) { + var out []RankedQuestion + for rows.Next() { + q, err := scanRanked(rows) + if err != nil { + return nil, err + } + out = append(out, q) + } + return out, rows.Err() +} diff --git a/internal/web/admin.go b/internal/web/admin.go new file mode 100644 index 0000000..2e955d3 --- /dev/null +++ b/internal/web/admin.go @@ -0,0 +1,70 @@ +package web + +import ( + "errors" + "net/http" + + "github.com/go-chi/chi/v5" + + "plumber/internal/store" +) + +type adminUsersPage struct { + page + Users []store.User + Error string +} + +func (s *Server) requireAdmin(w http.ResponseWriter, r *http.Request) *store.User { + u := currentUser(r) + if !u.Admin() { + http.Error(w, "forbidden", http.StatusForbidden) + return nil + } + return u +} + +func (s *Server) handleAdminUsers(w http.ResponseWriter, r *http.Request) { + if s.requireAdmin(w, r) == nil { + return + } + users, err := s.store.ListUsers(r.Context()) + if err != nil { + http.Error(w, "could not load users", http.StatusInternalServerError) + return + } + s.exec(w, "admin-users", adminUsersPage{ + page: s.basePage(r, "Users"), + Users: users, + }) +} + +func (s *Server) handleAdminSetRole(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + if s.requireAdmin(w, r) == nil { + return + } + id := chi.URLParam(r, "id") + role := r.PostFormValue("role") + err := s.store.SetRole(r.Context(), id, role) + if errors.Is(err, store.ErrLastAdmin) { + users, listErr := s.store.ListUsers(r.Context()) + if listErr != nil { + http.Error(w, "could not demote last admin", http.StatusBadRequest) + return + } + s.exec(w, "admin-users", adminUsersPage{ + page: s.basePage(r, "Users"), + Users: users, + Error: "Cannot demote the last admin.", + }) + return + } + if err != nil { + http.Error(w, "could not update role", http.StatusBadRequest) + return + } + http.Redirect(w, r, "/admin/users", http.StatusSeeOther) +} diff --git a/internal/web/auth.go b/internal/web/auth.go new file mode 100644 index 0000000..4bfcb00 --- /dev/null +++ b/internal/web/auth.go @@ -0,0 +1,112 @@ +package web + +import ( + "net/http" + "net/url" + "regexp" + "strings" + "unicode/utf8" + + "golang.org/x/crypto/bcrypt" + + "plumber/internal/store" +) + +var usernameRe = regexp.MustCompile(`^[a-zA-Z0-9_]{3,20}$`) + +func safeNext(raw string) string { + if raw == "" { + return "/" + } + u, err := url.Parse(raw) + if err != nil || u.IsAbs() || !strings.HasPrefix(u.Path, "/") || strings.HasPrefix(u.Path, "//") { + return "/" + } + return u.RequestURI() +} + +func (s *Server) handleLoginForm(w http.ResponseWriter, r *http.Request) { + if currentUser(r) != nil { + http.Redirect(w, r, safeNext(r.URL.Query().Get("next")), http.StatusSeeOther) + return + } + s.exec(w, "login", authPage{ + page: s.basePage(r, "Sign in"), + Next: r.URL.Query().Get("next"), + }) +} + +func (s *Server) handleLogin(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + username := strings.TrimSpace(r.PostFormValue("username")) + password := r.PostFormValue("password") + next := safeNext(r.PostFormValue("next")) + u, err := s.store.UserByUsername(r.Context(), username) + if err != nil || bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)) != nil { + w.WriteHeader(http.StatusUnauthorized) + s.exec(w, "login", authPage{ + page: s.basePage(r, "Sign in"), + Username: username, + Next: next, + Error: "Wrong username or password.", + }) + return + } + s.sessions.Put(r.Context(), "user_id", u.ID) + http.Redirect(w, r, next, http.StatusSeeOther) +} + +func (s *Server) handleRegisterForm(w http.ResponseWriter, r *http.Request) { + if currentUser(r) != nil { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + s.exec(w, "register", authPage{page: s.basePage(r, "Create account")}) +} + +func (s *Server) handleRegister(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + username := strings.TrimSpace(r.PostFormValue("username")) + password := r.PostFormValue("password") + p := authPage{page: s.basePage(r, "Create account"), Username: username} + if !usernameRe.MatchString(username) { + p.Error = "Username must be 3–20 letters, numbers, or underscores." + s.exec(w, "register", p) + return + } + if utf8.RuneCountInString(password) < 8 { + p.Error = "Password must be at least 8 characters." + s.exec(w, "register", p) + return + } + hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + http.Error(w, "could not save password", http.StatusInternalServerError) + return + } + asAdmin := false + if s.cfg.AdminUsername != "" && store.NormalizeUsername(username) == store.NormalizeUsername(s.cfg.AdminUsername) { + n, err := s.store.CountAdmins(r.Context()) + if err != nil { + http.Error(w, "could not create account", http.StatusInternalServerError) + return + } + asAdmin = n == 0 + } + u, err := s.store.CreateUser(r.Context(), username, string(hash), asAdmin) + if err != nil { + p.Error = "That username is taken." + s.exec(w, "register", p) + return + } + s.sessions.Put(r.Context(), "user_id", u.ID) + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) handleAuthPrompt(w http.ResponseWriter, r *http.Request) { + s.exec(w, "signin-prompt", s.basePage(r, "")) +} diff --git a/internal/web/memstore_test.go b/internal/web/memstore_test.go new file mode 100644 index 0000000..0eb62d4 --- /dev/null +++ b/internal/web/memstore_test.go @@ -0,0 +1,330 @@ +package web + +import ( + "context" + "database/sql" + "fmt" + "sort" + "strings" + "sync" + "time" + + "github.com/google/uuid" + + "plumber/internal/pacific" + "plumber/internal/store" +) + +// memDB is an in-memory store.DB for tests. +type memDB struct { + mu sync.Mutex + users map[string]*store.User // id -> user + byName map[string]string // username -> id + questions map[string]*store.RankedQuestion // id -> question + votes map[string]int // userID|questionID -> value + answers map[string]*store.Answer // questionID -> answer +} + +func newMemDB() *memDB { + return &memDB{ + users: map[string]*store.User{}, + byName: map[string]string{}, + questions: map[string]*store.RankedQuestion{}, + votes: map[string]int{}, + answers: map[string]*store.Answer{}, + } +} + +func voteKey(userID, questionID string) string { + return userID + "|" + questionID +} + +func (m *memDB) CreateUser(_ context.Context, username, passwordHash string, asAdmin bool) (*store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + username = store.NormalizeUsername(username) + if _, ok := m.byName[username]; ok { + return nil, fmt.Errorf("username taken") + } + role := "user" + if asAdmin { + role = "admin" + } + u := &store.User{ + ID: uuid.NewString(), + Username: username, + Name: username, + Role: role, + PasswordHash: passwordHash, + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + m.users[u.ID] = u + m.byName[username] = u.ID + cp := *u + return &cp, nil +} + +func (m *memDB) UserByID(_ context.Context, id string) (*store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + u, ok := m.users[id] + if !ok { + return nil, sql.ErrNoRows + } + cp := *u + cp.PasswordHash = "" + return &cp, nil +} + +func (m *memDB) UserByUsername(_ context.Context, username string) (*store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + id, ok := m.byName[store.NormalizeUsername(username)] + if !ok { + return nil, sql.ErrNoRows + } + cp := *m.users[id] + return &cp, nil +} + +func (m *memDB) CountAdmins(_ context.Context) (int, error) { + m.mu.Lock() + defer m.mu.Unlock() + n := 0 + for _, u := range m.users { + if u.Role == "admin" { + n++ + } + } + return n, nil +} + +func (m *memDB) ListUsers(_ context.Context) ([]store.User, error) { + m.mu.Lock() + defer m.mu.Unlock() + out := make([]store.User, 0, len(m.users)) + for _, u := range m.users { + cp := *u + cp.PasswordHash = "" + out = append(out, cp) + } + sort.Slice(out, func(i, j int) bool { + return out[i].CreatedAt < out[j].CreatedAt + }) + return out, nil +} + +func (m *memDB) SetRole(_ context.Context, userID, role string) error { + if role != "user" && role != "admin" { + return fmt.Errorf("invalid role") + } + m.mu.Lock() + defer m.mu.Unlock() + u, ok := m.users[userID] + if !ok { + return sql.ErrNoRows + } + if u.Role == "admin" && role == "user" { + n := 0 + for _, x := range m.users { + if x.Role == "admin" { + n++ + } + } + if n <= 1 { + return store.ErrLastAdmin + } + } + u.Role = role + return nil +} + +func (m *memDB) CreateQuestion(_ context.Context, authorID, title, body, city string) (*store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + author, ok := m.users[authorID] + if !ok { + return nil, fmt.Errorf("unknown author") + } + q := &store.RankedQuestion{ + ID: uuid.NewString(), + AuthorID: authorID, + AuthorName: author.Name, + Title: strings.TrimSpace(title), + Body: strings.TrimSpace(body), + City: strings.TrimSpace(city), + HuntDate: pacific.Today(), + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + m.questions[q.ID] = q + cp := *q + return &cp, nil +} + +func (m *memDB) rankedLocked(q *store.RankedQuestion, viewerID string) store.RankedQuestion { + out := *q + score := 0 + for k, v := range m.votes { + _, qid, ok := strings.Cut(k, "|") + if ok && qid == q.ID { + score += v + } + } + out.Score = score + out.Answered = m.answers[q.ID] != nil + if viewerID != "" { + out.UserVote = m.votes[voteKey(viewerID, q.ID)] + } + if u, ok := m.users[q.AuthorID]; ok { + out.AuthorName = u.Name + } + return out +} + +func (m *memDB) ListHunt(_ context.Context, huntDate, viewerID string) ([]store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + var out []store.RankedQuestion + for _, q := range m.questions { + if q.HuntDate != huntDate || q.Hidden { + continue + } + out = append(out, m.rankedLocked(q, viewerID)) + } + sort.Slice(out, func(i, j int) bool { + if out[i].Score != out[j].Score { + return out[i].Score > out[j].Score + } + return out[i].CreatedAt < out[j].CreatedAt + }) + return out, nil +} + +func (m *memDB) GetQuestion(_ context.Context, id, viewerID string) (*store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + q, ok := m.questions[id] + if !ok { + return nil, sql.ErrNoRows + } + out := m.rankedLocked(q, viewerID) + return &out, nil +} + +func (m *memDB) Vote(_ context.Context, userID, questionID string, value int) error { + if value != 1 && value != -1 { + return fmt.Errorf("invalid vote") + } + m.mu.Lock() + defer m.mu.Unlock() + if _, ok := m.questions[questionID]; !ok { + return fmt.Errorf("unknown question") + } + k := voteKey(userID, questionID) + if cur, ok := m.votes[k]; ok && cur == value { + delete(m.votes, k) + return nil + } + m.votes[k] = value + return nil +} + +func (m *memDB) GetAnswer(_ context.Context, questionID string) (*store.Answer, error) { + m.mu.Lock() + defer m.mu.Unlock() + a, ok := m.answers[questionID] + if !ok { + return nil, sql.ErrNoRows + } + cp := *a + if u, ok := m.users[a.AuthorID]; ok { + cp.AuthorName = u.Name + } + return &cp, nil +} + +func (m *memDB) UpsertAnswer(_ context.Context, questionID, authorID, body string) error { + m.mu.Lock() + defer m.mu.Unlock() + body = strings.TrimSpace(body) + now := time.Now().UTC().Format(time.RFC3339) + if existing, ok := m.answers[questionID]; ok { + existing.Body = body + existing.AuthorID = authorID + existing.UpdatedAt = now + return nil + } + m.answers[questionID] = &store.Answer{ + QuestionID: questionID, + AuthorID: authorID, + Body: body, + CreatedAt: now, + UpdatedAt: now, + } + return nil +} + +func (m *memDB) HideQuestion(_ context.Context, id string) error { + m.mu.Lock() + defer m.mu.Unlock() + q, ok := m.questions[id] + if !ok { + return sql.ErrNoRows + } + q.Hidden = true + return nil +} + +func (m *memDB) UpdateProfile(_ context.Context, userID, state, avatarURL string) error { + m.mu.Lock() + defer m.mu.Unlock() + u, ok := m.users[userID] + if !ok { + return sql.ErrNoRows + } + u.State = state + if avatarURL != "" { + u.AvatarURL = avatarURL + } + return nil +} + +func (m *memDB) ListQuestionsByAuthor(_ context.Context, authorID string) ([]store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + var out []store.RankedQuestion + for _, q := range m.questions { + if q.AuthorID != authorID || q.Hidden { + continue + } + out = append(out, m.rankedLocked(q, "")) + } + sort.Slice(out, func(i, j int) bool { + return out[i].CreatedAt > out[j].CreatedAt + }) + return out, nil +} + +func (m *memDB) ListQuestionsAnsweredBy(_ context.Context, adminID string) ([]store.RankedQuestion, error) { + m.mu.Lock() + defer m.mu.Unlock() + var out []store.RankedQuestion + for qid, a := range m.answers { + if a.AuthorID != adminID { + continue + } + q, ok := m.questions[qid] + if !ok || q.Hidden { + continue + } + rq := m.rankedLocked(q, "") + rq.Answered = true + out = append(out, rq) + } + sort.Slice(out, func(i, j int) bool { + return out[i].CreatedAt > out[j].CreatedAt + }) + return out, nil +} + +var _ store.DB = (*memDB)(nil) diff --git a/internal/web/profile.go b/internal/web/profile.go new file mode 100644 index 0000000..1c214ec --- /dev/null +++ b/internal/web/profile.go @@ -0,0 +1,142 @@ +package web + +import ( + "io" + "net/http" + "path" + "strings" + + "github.com/google/uuid" + + "plumber/internal/geo" + "plumber/internal/store" +) + +type profilePage struct { + page + States []struct{ Code, Name string } + Questions []store.RankedQuestion + QuestionsLabel string + UploadsEnabled bool + Error string + StateVal string +} + +func (s *Server) handleProfileForm(w http.ResponseWriter, r *http.Request) { + u := currentUser(r) + if u == nil { + http.Redirect(w, r, "/login?next=/profile", http.StatusSeeOther) + return + } + s.renderProfile(w, r, u, "", u.State) +} + +func (s *Server) handleProfile(w http.ResponseWriter, r *http.Request) { + u := currentUser(r) + if u == nil { + http.Redirect(w, r, "/login?next=/profile", http.StatusSeeOther) + return + } + if err := r.ParseMultipartForm(3 << 20); err != nil { + s.renderProfile(w, r, u, "Could not read form (max 2MB for images).", u.State) + return + } + want := s.sessions.GetString(r.Context(), "csrf") + got := r.FormValue("_csrf") + if want == "" || got != want { + http.Error(w, "invalid csrf token", http.StatusForbidden) + return + } + + state := geo.NormalizeState(r.FormValue("state")) + if !geo.ValidState(state) { + s.renderProfile(w, r, u, "Choose a valid US state or leave it blank.", state) + return + } + + avatarURL := "" + file, hdr, err := r.FormFile("avatar") + if err == nil { + defer file.Close() + if !s.cfg.Blob.Enabled() { + s.renderProfile(w, r, u, "Avatar uploads are not configured on this server.", state) + return + } + ct := hdr.Header.Get("Content-Type") + ext, contentType, ok := avatarType(hdr.Filename, ct) + if !ok { + s.renderProfile(w, r, u, "Avatar must be a JPEG, PNG, or WebP image.", state) + return + } + if hdr.Size > 2<<20 { + s.renderProfile(w, r, u, "Avatar must be 2MB or smaller.", state) + return + } + key := path.Join("avatars", u.ID, uuid.NewString()+ext) + limited := io.LimitReader(file, (2<<20)+1) + url, upErr := s.cfg.Blob.Upload(r.Context(), key, limited, contentType, hdr.Size) + if upErr != nil { + s.renderProfile(w, r, u, "Could not upload avatar. Try again later.", state) + return + } + avatarURL = url + } else if err != http.ErrMissingFile { + s.renderProfile(w, r, u, "Could not read avatar file.", state) + return + } + + if err := s.store.UpdateProfile(r.Context(), u.ID, state, avatarURL); err != nil { + http.Error(w, "could not save profile", http.StatusInternalServerError) + return + } + s.sessions.Put(r.Context(), "flash", "Profile saved.") + http.Redirect(w, r, "/profile", http.StatusSeeOther) +} + +func avatarType(filename, contentType string) (ext, normalized string, ok bool) { + contentType = strings.ToLower(strings.TrimSpace(contentType)) + filename = strings.ToLower(filename) + switch { + case strings.HasPrefix(contentType, "image/jpeg"), strings.HasSuffix(filename, ".jpg"), strings.HasSuffix(filename, ".jpeg"): + return ".jpg", "image/jpeg", true + case strings.HasPrefix(contentType, "image/png"), strings.HasSuffix(filename, ".png"): + return ".png", "image/png", true + case strings.HasPrefix(contentType, "image/webp"), strings.HasSuffix(filename, ".webp"): + return ".webp", "image/webp", true + default: + return "", "", false + } +} + +func (s *Server) renderProfile(w http.ResponseWriter, r *http.Request, u *store.User, errMsg, stateVal string) { + var ( + questions []store.RankedQuestion + label string + err error + ) + if u.Admin() { + label = "Questions you answered" + questions, err = s.store.ListQuestionsAnsweredBy(r.Context(), u.ID) + } else { + label = "Your questions" + questions, err = s.store.ListQuestionsByAuthor(r.Context(), u.ID) + } + if err != nil { + http.Error(w, "could not load questions", http.StatusInternalServerError) + return + } + if fresh, e := s.store.UserByID(r.Context(), u.ID); e == nil { + u = fresh + } + p := s.basePage(r, "Profile") + p.User = u + s.exec(w, "profile", profilePage{ + page: p, + States: geo.States, + Questions: questions, + QuestionsLabel: label, + UploadsEnabled: s.cfg.Blob.Enabled(), + Error: errMsg, + StateVal: stateVal, + }) +} diff --git a/internal/web/server.go b/internal/web/server.go new file mode 100644 index 0000000..154515c --- /dev/null +++ b/internal/web/server.go @@ -0,0 +1,518 @@ +package web + +import ( + "context" + "crypto/rand" + "encoding/hex" + "fmt" + "html/template" + "io/fs" + "log" + "net/http" + "net/url" + "strings" + "time" + + "github.com/alexedwards/scs/v2" + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + + "plumber/internal/blob" + "plumber/internal/geo" + "plumber/internal/pacific" + "plumber/internal/store" +) + +type Config struct { + AdminUsername string + SecureCookie bool + Blob blob.Uploader +} + +type Server struct { + store store.DB + sessions *scs.SessionManager + tmpl *template.Template + cfg Config + static http.Handler +} + +type page struct { + User *store.User + CSRF string + Flash string + Title string + Today string + Yesterday string +} + +type huntPage struct { + page + Date string + Label string + IsToday bool + IsYesterday bool + Questions []store.RankedQuestion +} + +type questionPage struct { + page + Question *store.RankedQuestion + Answer *store.Answer +} + +type submitPage struct { + page + TitleVal string + BodyVal string + CityVal string + Error string +} + +type authPage struct { + page + Username string + Error string + Next string +} + +type voteCtx struct { + User *store.User + CSRF string + View string + Date string + Question store.RankedQuestion +} + +func New(st store.DB, sessionStore scs.Store, templateFS fs.FS, staticFS fs.FS, cfg Config) (*Server, error) { + if cfg.Blob == nil { + cfg.Blob = blob.Disabled{} + } + funcMap := template.FuncMap{ + "voteCtx": func(user *store.User, csrf, view, date string, q store.RankedQuestion) voteCtx { + return voteCtx{User: user, CSRF: csrf, View: view, Date: date, Question: q} + }, + "add": func(a, b int) int { return a + b }, + "rank": func(i int) int { return i + 1 }, + "isAdmin": func(u *store.User) bool { return u.Admin() }, + "pacificLabel": pacific.Label, + "locationTag": func(u *store.User) string { + if u != nil { + if name := geo.StateName(u.State); name != "" { + return name + } + } + return "Bay Area" + }, + } + tmpl, err := template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/*.html", "templates/partials/*.html") + if err != nil { + return nil, fmt.Errorf("parse templates: %w", err) + } + sessions := scs.New() + sessions.Store = sessionStore + sessions.Lifetime = 30 * 24 * time.Hour + sessions.Cookie.Name = "plumber_session" + sessions.Cookie.HttpOnly = true + sessions.Cookie.SameSite = http.SameSiteLaxMode + sessions.Cookie.Secure = cfg.SecureCookie + sessions.Cookie.Path = "/" + + sub, err := fs.Sub(staticFS, "static") + if err != nil { + return nil, err + } + + return &Server{ + store: st, + sessions: sessions, + tmpl: tmpl, + cfg: cfg, + static: http.StripPrefix("/static/", http.FileServer(http.FS(sub))), + }, nil +} + +func (s *Server) Handler() http.Handler { + r := chi.NewRouter() + r.Use(middleware.RequestID) + r.Use(middleware.RealIP) + r.Use(middleware.Logger) + r.Use(middleware.Recoverer) + r.Use(func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, 3<<20) + next.ServeHTTP(w, r) + }) + }) + r.Use(s.sessions.LoadAndSave) + r.Use(s.withUser) + r.Handle("/static/*", s.static) + r.Get("/", s.handleToday) + r.Get("/archive", s.handleArchive) + r.Get("/hunt/{date}", s.handleHunt) + r.Get("/submit", s.handleSubmitForm) + r.Post("/submit", s.handleSubmit) + r.Get("/questions/{id}", s.handleQuestion) + r.Post("/questions/{id}/vote", s.handleVote) + r.Post("/questions/{id}/answer", s.handleAnswer) + r.Post("/questions/{id}/hide", s.handleHide) + r.Get("/login", s.handleLoginForm) + r.Post("/login", s.handleLogin) + r.Get("/register", s.handleRegisterForm) + r.Post("/register", s.handleRegister) + r.Get("/auth/prompt", s.handleAuthPrompt) + r.Post("/logout", s.handleLogout) + r.Get("/admin/users", s.handleAdminUsers) + r.Post("/admin/users/{id}/role", s.handleAdminSetRole) + r.Get("/profile", s.handleProfileForm) + r.Post("/profile", s.handleProfile) + return r +} + +type ctxKey int + +const userKey ctxKey = 1 + +func (s *Server) withUser(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if s.sessions.GetString(r.Context(), "csrf") == "" { + s.sessions.Put(r.Context(), "csrf", randomHex(16)) + } + id := s.sessions.GetString(r.Context(), "user_id") + if id != "" { + u, err := s.store.UserByID(r.Context(), id) + if err == nil { + r = r.WithContext(context.WithValue(r.Context(), userKey, u)) + } + } + next.ServeHTTP(w, r) + }) +} + +func currentUser(r *http.Request) *store.User { + u, _ := r.Context().Value(userKey).(*store.User) + return u +} + +func (s *Server) basePage(r *http.Request, title string) page { + return page{ + User: currentUser(r), + CSRF: s.sessions.GetString(r.Context(), "csrf"), + Flash: s.sessions.PopString(r.Context(), "flash"), + Title: title, + Today: pacific.Today(), + Yesterday: pacific.Yesterday(), + } +} + +func isHTMX(r *http.Request) bool { + return r.Header.Get("HX-Request") == "true" +} + +func (s *Server) requireCSRF(w http.ResponseWriter, r *http.Request) bool { + if err := r.ParseForm(); err != nil { + http.Error(w, "bad form", http.StatusBadRequest) + return false + } + want := s.sessions.GetString(r.Context(), "csrf") + got := r.PostFormValue("_csrf") + if want == "" || got != want { + http.Error(w, "invalid csrf token", http.StatusForbidden) + return false + } + return true +} + +func (s *Server) handleToday(w http.ResponseWriter, r *http.Request) { + s.renderHunt(w, r, pacific.Today()) +} + +func (s *Server) handleArchive(w http.ResponseWriter, r *http.Request) { + date := r.URL.Query().Get("date") + if date == "" || date == pacific.Today() { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + if _, err := pacific.Parse(date); err != nil || date > pacific.Today() { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + http.Redirect(w, r, "/hunt/"+url.PathEscape(date), http.StatusSeeOther) +} + +func (s *Server) handleHunt(w http.ResponseWriter, r *http.Request) { + date := chi.URLParam(r, "date") + if _, err := pacific.Parse(date); err != nil { + http.NotFound(w, r) + return + } + if date >= pacific.Today() { + http.Redirect(w, r, "/", http.StatusSeeOther) + return + } + s.renderHunt(w, r, date) +} + +func (s *Server) renderHunt(w http.ResponseWriter, r *http.Request, date string) { + viewer := "" + if u := currentUser(r); u != nil { + viewer = u.ID + } + questions, err := s.store.ListHunt(r.Context(), date, viewer) + if err != nil { + http.Error(w, "could not load questions", http.StatusInternalServerError) + return + } + label := pacific.Label(date) + title := label + if pacific.IsToday(date) { + title = "Today" + } + s.exec(w, "hunt", huntPage{ + page: s.basePage(r, title), + Date: date, + Label: label, + IsToday: pacific.IsToday(date), + IsYesterday: pacific.IsYesterday(date), + Questions: questions, + }) +} + +func (s *Server) handleSubmitForm(w http.ResponseWriter, r *http.Request) { + if currentUser(r) == nil { + s.sessions.Put(r.Context(), "flash", "Sign in to ask a question.") + http.Redirect(w, r, "/login?next=/submit", http.StatusSeeOther) + return + } + s.exec(w, "submit", submitPage{page: s.basePage(r, "Ask a question")}) +} + +func (s *Server) handleSubmit(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if u == nil { + http.Redirect(w, r, "/login?next=/submit", http.StatusSeeOther) + return + } + title := strings.TrimSpace(r.PostFormValue("title")) + body := strings.TrimSpace(r.PostFormValue("body")) + city := strings.TrimSpace(r.PostFormValue("city")) + if title == "" || body == "" { + s.exec(w, "submit", submitPage{ + page: s.basePage(r, "Ask a question"), + TitleVal: title, + BodyVal: body, + CityVal: city, + Error: "Title and description are required.", + }) + return + } + if len(title) > 120 { + title = title[:120] + } + if len(body) > 8000 { + body = body[:8000] + } + if len(city) > 80 { + city = city[:80] + } + q, err := s.store.CreateQuestion(r.Context(), u.ID, title, body, city) + if err != nil { + http.Error(w, "could not save question", http.StatusInternalServerError) + return + } + http.Redirect(w, r, "/questions/"+url.PathEscape(q.ID), http.StatusSeeOther) +} + +func (s *Server) handleQuestion(w http.ResponseWriter, r *http.Request) { + id := chi.URLParam(r, "id") + viewer := "" + if u := currentUser(r); u != nil { + viewer = u.ID + } + q, err := s.store.GetQuestion(r.Context(), id, viewer) + if err != nil || (q.Hidden && !currentUser(r).Admin()) { + http.NotFound(w, r) + return + } + var ans *store.Answer + if q.Answered { + ans, _ = s.store.GetAnswer(r.Context(), q.ID) + } + s.exec(w, "question", questionPage{ + page: s.basePage(r, q.Title), + Question: q, + Answer: ans, + }) +} + +func (s *Server) handleVote(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if u == nil { + if isHTMX(r) { + s.exec(w, "signin-prompt", s.basePage(r, "")) + return + } + http.Redirect(w, r, "/login", http.StatusSeeOther) + return + } + id := chi.URLParam(r, "id") + value := 0 + switch r.PostFormValue("value") { + case "1": + value = 1 + case "-1": + value = -1 + default: + http.Error(w, "invalid vote", http.StatusBadRequest) + return + } + if err := s.store.Vote(r.Context(), u.ID, id, value); err != nil { + http.Error(w, "could not vote", http.StatusInternalServerError) + return + } + view := r.PostFormValue("view") + date := r.PostFormValue("date") + if isHTMX(r) { + if view == "list" { + s.renderLeaderboard(w, r, date) + return + } + q, err := s.store.GetQuestion(r.Context(), id, u.ID) + if err != nil { + http.Error(w, "not found", http.StatusNotFound) + return + } + s.exec(w, "vote", voteCtx{ + User: u, + CSRF: s.sessions.GetString(r.Context(), "csrf"), + View: "question", + Date: q.HuntDate, + Question: *q, + }) + return + } + if view == "question" { + http.Redirect(w, r, "/questions/"+url.PathEscape(id), http.StatusSeeOther) + return + } + if date != "" && date != pacific.Today() { + http.Redirect(w, r, "/hunt/"+url.PathEscape(date), http.StatusSeeOther) + return + } + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) renderLeaderboard(w http.ResponseWriter, r *http.Request, date string) { + if date == "" { + date = pacific.Today() + } + viewer := "" + if u := currentUser(r); u != nil { + viewer = u.ID + } + questions, err := s.store.ListHunt(r.Context(), date, viewer) + if err != nil { + http.Error(w, "could not load questions", http.StatusInternalServerError) + return + } + s.exec(w, "leaderboard", huntPage{ + page: s.basePage(r, ""), + Date: date, + Questions: questions, + }) +} + +func (s *Server) handleAnswer(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if !u.Admin() { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + id := chi.URLParam(r, "id") + body := strings.TrimSpace(r.PostFormValue("body")) + if body == "" { + http.Error(w, "answer required", http.StatusBadRequest) + return + } + if len(body) > 12000 { + body = body[:12000] + } + if err := s.store.UpsertAnswer(r.Context(), id, u.ID, body); err != nil { + http.Error(w, "could not save answer", http.StatusInternalServerError) + return + } + ans, err := s.store.GetAnswer(r.Context(), id) + if err != nil { + http.Error(w, "could not load answer", http.StatusInternalServerError) + return + } + if isHTMX(r) { + s.exec(w, "answer", questionPage{page: s.basePage(r, ""), Answer: ans}) + return + } + http.Redirect(w, r, "/questions/"+url.PathEscape(id), http.StatusSeeOther) +} + +func (s *Server) handleHide(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + u := currentUser(r) + if !u.Admin() { + http.Error(w, "forbidden", http.StatusForbidden) + return + } + id := chi.URLParam(r, "id") + q, err := s.store.GetQuestion(r.Context(), id, u.ID) + if err != nil { + http.NotFound(w, r) + return + } + if err := s.store.HideQuestion(r.Context(), id); err != nil { + http.Error(w, "could not hide", http.StatusInternalServerError) + return + } + if isHTMX(r) && r.PostFormValue("view") == "list" { + s.renderLeaderboard(w, r, q.HuntDate) + return + } + if isHTMX(r) { + w.Header().Set("HX-Redirect", "/") + w.WriteHeader(http.StatusSeeOther) + return + } + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) handleLogout(w http.ResponseWriter, r *http.Request) { + if !s.requireCSRF(w, r) { + return + } + s.sessions.Remove(r.Context(), "user_id") + http.Redirect(w, r, "/", http.StatusSeeOther) +} + +func (s *Server) exec(w http.ResponseWriter, name string, data any) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil { + log.Printf("template %s: %v", name, err) + http.Error(w, "template error", http.StatusInternalServerError) + } +} + +func randomHex(n int) string { + b := make([]byte, n) + if _, err := rand.Read(b); err != nil { + panic(err) + } + return hex.EncodeToString(b) +} diff --git a/internal/web/server_test.go b/internal/web/server_test.go new file mode 100644 index 0000000..aa6f849 --- /dev/null +++ b/internal/web/server_test.go @@ -0,0 +1,468 @@ +package web + +import ( + "bytes" + "context" + "io" + "mime/multipart" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/alexedwards/scs/v2" + + "plumber" +) + +func newTestServer(t *testing.T) (*Server, *memDB, scs.Store) { + t.Helper() + fake := newMemDB() + sessions := scs.New() + srv, err := New(fake, sessions.Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + if err != nil { + t.Fatal(err) + } + return srv, fake, sessions.Store +} + +func TestHomeEmptyAndViewport(t *testing.T) { + srv, _, _ := newTestServer(t) + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/", nil) + srv.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("status %d: %s", rec.Code, rec.Body.String()) + } + body := rec.Body.String() + if !strings.Contains(body, "No questions yet") { + t.Fatal("missing empty state") + } + if !strings.Contains(body, "width=device-width") { + t.Fatal("missing mobile viewport") + } + if !strings.Contains(body, "not a substitute for a licensed plumber") { + t.Fatal("missing disclaimer") + } +} + +func TestRegisterLoginAsk(t *testing.T) { + srv, _, _ := newTestServer(t) + h := srv.Handler() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) + cookie := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + if csrf == "" { + t.Fatal("no csrf") + } + form := strings.NewReader("_csrf=" + csrf + "&username=hub&password=hunter22") + req := httptest.NewRequest(http.MethodPost, "/register", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range cookie { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("register status %d %s", rec.Code, rec.Body.String()) + } + session := rec.Result().Cookies() + req = httptest.NewRequest(http.MethodGet, "/submit", nil) + for _, c := range session { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("submit form %d", rec.Code) + } + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&title=Leaky+faucet&body=Drip+all+night.&city=Oakland") + req = httptest.NewRequest(http.MethodPost, "/submit", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range session { + req.AddCookie(c) + } + for _, c := range rec.Result().Cookies() { + req.AddCookie(c) + } + rec2 := httptest.NewRecorder() + h.ServeHTTP(rec2, req) + if rec2.Code != http.StatusSeeOther { + t.Fatalf("submit %d %s", rec2.Code, rec2.Body.String()) + } +} + +func TestSessionSurvivesServerRestart(t *testing.T) { + fake := newMemDB() + sessionStore := scs.New().Store + + srv1, err := New(fake, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + if err != nil { + t.Fatal(err) + } + h1 := srv1.Handler() + + rec := httptest.NewRecorder() + h1.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) + preCookies := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + if csrf == "" { + t.Fatal("no csrf") + } + form := strings.NewReader("_csrf=" + csrf + "&username=hub&password=hunter22") + req := httptest.NewRequest(http.MethodPost, "/register", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range preCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h1.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("register status %d %s", rec.Code, rec.Body.String()) + } + sessionCookies := mergeCookies(preCookies, rec.Result().Cookies()) + + srv2, err := New(fake, sessionStore, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "hub"}) + if err != nil { + t.Fatal(err) + } + req = httptest.NewRequest(http.MethodGet, "/submit", nil) + for _, c := range sessionCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + srv2.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("expected authenticated submit form after restart, got %d: %s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "Ask a question") { + t.Fatal("session did not survive restart") + } +} + +func registerUser(t *testing.T, h http.Handler, username, password string) []*http.Cookie { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/register", nil)) + cookies := rec.Result().Cookies() + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf + "&username=" + username + "&password=" + password) + req := httptest.NewRequest(http.MethodPost, "/register", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("register %s: %d %s", username, rec.Code, rec.Body.String()) + } + return mergeCookies(cookies, rec.Result().Cookies()) +} + +func TestAdminSeedOnlyWhenNoAdmins(t *testing.T) { + srv, fake, _ := newTestServer(t) + h := srv.Handler() + registerUser(t, h, "hub", "hunter22") + u, err := fake.UserByUsername(context.Background(), "hub") + if err != nil || !u.Admin() { + t.Fatalf("hub should be first admin: %+v %v", u, err) + } + registerUser(t, h, "hub2", "hunter22") + // Create another account that also matches AdminUsername after an admin exists — use a fresh server config with AdminUsername hub2 after hub exists + srv2, err := New(fake, scs.New().Store, plumber.TemplateFS, plumber.StaticFS, Config{AdminUsername: "lateradmin"}) + if err != nil { + t.Fatal(err) + } + registerUser(t, srv2.Handler(), "lateradmin", "hunter22") + u2, err := fake.UserByUsername(context.Background(), "lateradmin") + if err != nil { + t.Fatal(err) + } + if u2.Admin() { + t.Fatal("lateradmin must stay user when an admin already exists") + } +} + +func TestAdminUsersPageAccessAndRoles(t *testing.T) { + srv, fake, _ := newTestServer(t) + h := srv.Handler() + adminCookies := registerUser(t, h, "hub", "hunter22") + registerUser(t, h, "bob", "hunter22") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("admin list %d", rec.Code) + } + if !strings.Contains(rec.Body.String(), "bob") { + t.Fatal("missing bob on admin page") + } + + bob, err := fake.UserByUsername(context.Background(), "bob") + if err != nil { + t.Fatal(err) + } + csrf := csrfFrom(rec.Body.String()) + form := strings.NewReader("_csrf=" + csrf + "&role=admin") + req = httptest.NewRequest(http.MethodPost, "/admin/users/"+bob.ID+"/role", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("promote %d %s", rec.Code, rec.Body.String()) + } + bob, _ = fake.UserByUsername(context.Background(), "bob") + if !bob.Admin() { + t.Fatal("bob should be admin") + } + + // Non-admin forbidden + bobCookies := registerUser(t, h, "carol", "hunter22") + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range bobCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("non-admin expected 403, got %d", rec.Code) + } + + // Demote last remaining admin after demoting bob first — leave only hub, then demote hub + hub, err := fake.UserByUsername(context.Background(), "hub") + if err != nil { + t.Fatal(err) + } + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&role=user") + req = httptest.NewRequest(http.MethodPost, "/admin/users/"+bob.ID+"/role", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("demote bob %d", rec.Code) + } + + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/admin/users", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + form = strings.NewReader("_csrf=" + csrf + "&role=user") + req = httptest.NewRequest(http.MethodPost, "/admin/users/"+hub.ID+"/role", form) + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("demote last admin expected page with error, got %d", rec.Code) + } + if !strings.Contains(rec.Body.String(), "Cannot demote the last admin") { + t.Fatalf("missing last-admin error: %s", rec.Body.String()) + } + hub, _ = fake.UserByUsername(context.Background(), "hub") + if !hub.Admin() { + t.Fatal("hub must remain admin") + } +} + +type fakeBlob struct { + calls int + last string +} + +func (f *fakeBlob) Enabled() bool { return true } + +func (f *fakeBlob) Upload(_ context.Context, key string, _ io.Reader, _ string, _ int64) (string, error) { + f.calls++ + f.last = key + return "https://cdn.example.com/" + key, nil +} + +func TestProfilePageAndState(t *testing.T) { + srv, fake, _ := newTestServer(t) + h := srv.Handler() + cookies := registerUser(t, h, "alice", "hunter22") + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range cookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("profile %d", rec.Code) + } + if !strings.Contains(rec.Body.String(), "Your questions") { + t.Fatal("expected user questions label") + } + if !strings.Contains(rec.Body.String(), "local plumbing codes") { + t.Fatal("missing state helper copy") + } + + csrf := csrfFrom(rec.Body.String()) + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + _ = w.WriteField("_csrf", csrf) + _ = w.WriteField("state", "CA") + _ = w.Close() + req = httptest.NewRequest(http.MethodPost, "/profile", &buf) + req.Header.Set("Content-Type", w.FormDataContentType()) + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("save profile %d %s", rec.Code, rec.Body.String()) + } + u, err := fake.UserByUsername(context.Background(), "alice") + if err != nil || u.State != "CA" { + t.Fatalf("state not saved: %+v %v", u, err) + } + + // invalid state + rec = httptest.NewRecorder() + req = httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range cookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + csrf = csrfFrom(rec.Body.String()) + buf.Reset() + w = multipart.NewWriter(&buf) + _ = w.WriteField("_csrf", csrf) + _ = w.WriteField("state", "ZZ") + _ = w.Close() + req = httptest.NewRequest(http.MethodPost, "/profile", &buf) + req.Header.Set("Content-Type", w.FormDataContentType()) + for _, c := range cookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 || !strings.Contains(rec.Body.String(), "valid US state") { + t.Fatalf("expected invalid state error, got %d %s", rec.Code, rec.Body.String()) + } +} + +func TestProfileAdminAnsweredListAndAvatarUpload(t *testing.T) { + fake := newMemDB() + blob := &fakeBlob{} + sessions := scs.New() + srv, err := New(fake, sessions.Store, plumber.TemplateFS, plumber.StaticFS, Config{ + AdminUsername: "hub", + Blob: blob, + }) + if err != nil { + t.Fatal(err) + } + h := srv.Handler() + adminCookies := registerUser(t, h, "hub", "hunter22") + userCookies := registerUser(t, h, "alice", "hunter22") + + alice, _ := fake.UserByUsername(context.Background(), "alice") + hub, _ := fake.UserByUsername(context.Background(), "hub") + q, err := fake.CreateQuestion(context.Background(), alice.ID, "Drip", "Under sink", "Oakland") + if err != nil { + t.Fatal(err) + } + if err := fake.UpsertAnswer(context.Background(), q.ID, hub.ID, "Replace the cartridge."); err != nil { + t.Fatal(err) + } + + rec := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/profile", nil) + for _, c := range adminCookies { + req.AddCookie(c) + } + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("admin profile %d", rec.Code) + } + body := rec.Body.String() + if !strings.Contains(body, "Questions you answered") || !strings.Contains(body, "Drip") { + t.Fatalf("admin answered list missing: %s", body) + } + + csrf := csrfFrom(body) + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + _ = w.WriteField("_csrf", csrf) + _ = w.WriteField("state", "OR") + part, err := w.CreateFormFile("avatar", "pic.png") + if err != nil { + t.Fatal(err) + } + _, _ = part.Write([]byte("fakepngbytes")) + _ = w.Close() + req = httptest.NewRequest(http.MethodPost, "/profile", &buf) + req.Header.Set("Content-Type", w.FormDataContentType()) + for _, c := range adminCookies { + req.AddCookie(c) + } + rec = httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != http.StatusSeeOther { + t.Fatalf("avatar upload %d %s", rec.Code, rec.Body.String()) + } + if blob.calls != 1 { + t.Fatalf("expected 1 upload, got %d", blob.calls) + } + hub, _ = fake.UserByUsername(context.Background(), "hub") + if !strings.Contains(hub.AvatarURL, "cdn.example.com/avatars/") { + t.Fatalf("avatar url %q", hub.AvatarURL) + } + _ = userCookies +} + +func mergeCookies(sets ...[]*http.Cookie) []*http.Cookie { + byName := map[string]*http.Cookie{} + for _, set := range sets { + for _, c := range set { + byName[c.Name] = c + } + } + out := make([]*http.Cookie, 0, len(byName)) + for _, c := range byName { + out = append(out, c) + } + return out +} + +func csrfFrom(html string) string { + const needle = `name="_csrf" value="` + i := strings.Index(html, needle) + if i < 0 { + return "" + } + html = html[i+len(needle):] + j := strings.Index(html, `"`) + if j < 0 { + return "" + } + return html[:j] +} diff --git a/schema.sql b/schema.sql new file mode 100644 index 0000000..29bd809 --- /dev/null +++ b/schema.sql @@ -0,0 +1,40 @@ +PRAGMA foreign_keys = ON; + +CREATE TABLE IF NOT EXISTS users ( + id TEXT PRIMARY KEY, + username TEXT NOT NULL UNIQUE, + name TEXT NOT NULL, + password_hash TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'user' CHECK (role IN ('user', 'admin')), + avatar_url TEXT NOT NULL DEFAULT '', + state TEXT NOT NULL DEFAULT '', + created_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS questions ( + id TEXT PRIMARY KEY, + author_id TEXT NOT NULL REFERENCES users(id), + title TEXT NOT NULL, + body TEXT NOT NULL, + city TEXT NOT NULL DEFAULT '', + hunt_date TEXT NOT NULL, + hidden INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL +); + +CREATE INDEX IF NOT EXISTS idx_questions_hunt_date ON questions(hunt_date, hidden); + +CREATE TABLE IF NOT EXISTS votes ( + user_id TEXT NOT NULL REFERENCES users(id), + question_id TEXT NOT NULL REFERENCES questions(id) ON DELETE CASCADE, + value INTEGER NOT NULL CHECK (value IN (-1, 1)), + PRIMARY KEY (user_id, question_id) +); + +CREATE TABLE IF NOT EXISTS answers ( + question_id TEXT PRIMARY KEY REFERENCES questions(id) ON DELETE CASCADE, + author_id TEXT NOT NULL REFERENCES users(id), + body TEXT NOT NULL, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL +); diff --git a/static/app.css b/static/app.css new file mode 100644 index 0000000..7fec899 --- /dev/null +++ b/static/app.css @@ -0,0 +1,789 @@ +:root { + --bg: #161719; + --panel: #1e2023; + --ink: #ecebe7; + --muted: #8d9096; + --line: #2e3136; + --zinc: #6b7078; + --signal: #e96a26; + --signal-ink: #161719; + --err: #e24b4b; + --err-bg: #2a1a1a; + --ok: #e96a26; + --sans: "Archivo", "Helvetica Neue", sans-serif; + --mono: "IBM Plex Mono", ui-monospace, monospace; + --pad: env(safe-area-inset-bottom, 0px); +} + +* { box-sizing: border-box; } + +html, body { + margin: 0; + padding: 0; + min-height: 100%; + background: var(--bg); + color: var(--ink); + font: 16px/1.45 var(--sans); + -webkit-text-size-adjust: 100%; + color-scheme: dark; +} + +body { + background-image: + linear-gradient(180deg, #1a1c1f 0%, var(--bg) 180px), + repeating-linear-gradient( + 90deg, + transparent, + transparent 47px, + #1c1e21 47px, + #1c1e21 48px + ); + background-size: 100% 100%, 48px 48px; +} + +img, svg { display: block; } + +a { + color: var(--signal); + text-underline-offset: 0.18em; +} + +.skip { + position: absolute; + left: -999px; +} +.skip:focus { + left: 12px; + top: 12px; + z-index: 20; + background: var(--panel); + padding: 8px 12px; +} + +.top { + position: sticky; + top: 0; + z-index: 20; + background: #141516; + border-bottom: 1px solid var(--line); + box-shadow: inset 0 2px 0 var(--signal); +} + +.top-inner { + width: min(840px, calc(100% - 32px)); + margin: 0 auto; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 12px 16px; + padding: calc(12px + env(safe-area-inset-top, 0px)) 0 12px; +} + +.logo { + display: flex; + align-items: center; + gap: 12px; + color: var(--signal); + text-decoration: none; +} + +.mark { + width: 32px; + height: 32px; + flex: none; +} + +.logo-text { + display: flex; + flex-direction: column; + gap: 3px; +} + +.logo-name { + font-size: 0.95rem; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; + color: var(--ink); + line-height: 1.15; +} + +.tagline { + color: var(--muted); + font-family: var(--mono); + font-size: 0.65rem; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.top-nav { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.who { + color: var(--muted); + font-family: var(--mono); + font-size: 0.75rem; + max-width: 9rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + letter-spacing: 0.04em; +} + +.account-menu { + position: relative; +} + +.account-menu-toggle { + gap: 8px; + list-style: none; + padding-left: 10px; + border-color: transparent; +} + +.account-menu-toggle:hover { + border-color: transparent; +} + +.account-menu-toggle::-webkit-details-marker { display: none; } +.account-menu-toggle::marker { content: ""; } + +.nav-avatar { + width: 28px; + height: 28px; + border-radius: 50%; + object-fit: cover; + flex: none; + border: 1px solid var(--line); + background: var(--panel); +} + +.nav-avatar-ghost { + display: inline-flex; + align-items: center; + justify-content: center; + font-family: var(--mono); + font-size: 0.7rem; + font-weight: 600; + letter-spacing: 0; + text-transform: uppercase; + color: var(--signal); +} + +.account-menu-caret { + width: 0; + height: 0; + border-left: 4px solid transparent; + border-right: 4px solid transparent; + border-top: 5px solid var(--muted); +} + +.account-menu[open] .account-menu-caret { + border-top: none; + border-bottom: 5px solid var(--muted); +} + +.account-menu-panel { + position: absolute; + right: 0; + top: calc(100% + 6px); + z-index: 10; + min-width: 10.5rem; + padding: 6px; + background: var(--panel); + border: 1px solid var(--line); + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35); +} + +.account-menu-item { + display: flex; + align-items: center; + width: 100%; + min-height: 40px; + padding: 0 12px; + border: 0; + border-radius: 2px; + background: transparent; + color: var(--ink); + font: inherit; + font-weight: 600; + font-size: 0.75rem; + letter-spacing: 0.08em; + text-transform: uppercase; + text-decoration: none; + text-align: left; + cursor: pointer; +} + +.account-menu-item:hover, +.account-menu-item:focus-visible { + background: #26282c; + outline: none; +} + +.logout { margin: 0; } + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 44px; + padding: 0 16px; + border-radius: 3px; + border: 1px solid transparent; + font: inherit; + font-weight: 600; + font-size: 0.8rem; + letter-spacing: 0.08em; + text-transform: uppercase; + text-decoration: none; + cursor: pointer; + touch-action: manipulation; +} + +.btn-primary { + background: var(--signal); + color: var(--signal-ink); +} + +.btn-primary:hover { filter: brightness(1.08); } + +.btn-ghost { + background: transparent; + color: var(--ink); + border-color: var(--line); +} + +.btn-ghost:hover { border-color: var(--zinc); } + +.wrap { + width: min(840px, calc(100% - 32px)); + margin: 28px auto 56px; +} + +#flash:empty { display: none; } + +.banner { + width: min(840px, calc(100% - 32px)); + margin: 16px auto 0; + padding: 12px 16px; + background: var(--panel); + border: 1px solid var(--line); + border-left: 3px solid var(--signal); + color: var(--ink); +} + +.banner.error { + background: var(--err-bg); + border-left-color: var(--err); + color: #ffd0d0; +} + +.hunt-head { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + align-items: end; + gap: 20px; + margin-bottom: 8px; + padding-bottom: 20px; + border-bottom: 1px solid var(--line); +} + +.eyebrow { + margin: 0; + font-family: var(--mono); + text-transform: uppercase; + letter-spacing: 0.16em; + font-size: 0.68rem; + font-weight: 500; + color: var(--signal); +} + +h1 { + margin: 10px 0 0; + font-size: clamp(1.8rem, 4.5vw, 2.75rem); + font-weight: 500; + letter-spacing: -0.03em; + line-height: 1.05; + text-wrap: pretty; +} + +.date-nav { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; +} + +.chip { + min-height: 40px; + padding: 8px 12px; + border-radius: 3px; + border: 1px solid var(--line); + background: transparent; + color: var(--ink); + text-decoration: none; + font-family: var(--mono); + font-weight: 500; + font-size: 0.72rem; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.chip.is-on { + background: var(--signal); + border-color: var(--signal); + color: var(--signal-ink); +} + +.date-form { + display: flex; + gap: 6px; + align-items: center; +} + +.date-form input[type="date"] { + min-height: 44px; + padding: 0 10px; + border: 1px solid var(--line); + border-radius: 3px; + font: inherit; + font-family: var(--mono); + font-size: 0.8rem; + background: var(--panel); + color: var(--ink); + color-scheme: dark; +} + +.board { + list-style: none; + margin: 0; + padding: 0; + background: var(--panel); + border: 1px solid var(--line); +} + +.row { + display: grid; + grid-template-columns: 2.8rem 3.25rem 1fr; + gap: 4px 8px; + align-items: start; + padding: 14px 12px; + border-bottom: 1px solid var(--line); +} + +.row:last-child { border-bottom: 0; } + +.row:hover { background: #24262b; } + +.rank { + font-family: var(--mono); + font-weight: 500; + font-size: 1.15rem; + line-height: 1; + color: var(--zinc); + text-align: right; + padding-top: 12px; +} + +.row:first-child .rank { color: var(--signal); } + +.vote { + display: flex; + flex-direction: column; + align-items: center; + gap: 0; +} + +.vote form { margin: 0; } + +.vote-btn { + width: 44px; + height: 40px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 0; + background: transparent; + color: var(--zinc); + cursor: pointer; + text-decoration: none; + touch-action: manipulation; + border-radius: 3px; +} + +.vote-btn:hover { color: var(--ink); background: #2a2d32; } + +.vote-btn.is-up { color: var(--signal); } +.vote-btn.is-down { color: var(--muted); } + +.score { + font-family: var(--mono); + font-variant-numeric: tabular-nums; + font-weight: 500; + font-size: 0.85rem; +} + +.q-title { + color: var(--ink); + font-weight: 500; + text-decoration: none; + font-size: 1.05rem; + text-wrap: pretty; +} + +.q-title:hover { color: var(--signal); } + +.meta { + margin: 6px 0 0; + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.02em; +} + +.dot { margin: 0 0.35em; } + +.badge { + display: inline-block; + margin-left: 8px; + padding: 2px 6px; + border: 1px solid var(--signal); + color: var(--signal); + font-size: 0.62rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.empty { + padding: 48px 16px; + text-align: left; + color: var(--muted); +} + +.empty-kicker { + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.16em; + text-transform: uppercase; + color: var(--signal); + margin: 0 0 8px; +} + +.inline-hide { margin: 6px 0 0; } + +.linkish { + background: none; + border: 0; + padding: 0; + color: var(--muted); + font: inherit; + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.06em; + text-transform: uppercase; + text-decoration: underline; + cursor: pointer; + min-height: 44px; +} + +.lede, .hint, .switch { + color: var(--muted); +} + +.lede { margin: 8px 0 0; max-width: 38rem; text-wrap: pretty; } + +.ask, .answer-form { + display: flex; + flex-direction: column; + gap: 8px; + margin-top: 20px; +} + +label { + font-family: var(--mono); + font-weight: 500; + font-size: 0.68rem; + letter-spacing: 0.12em; + text-transform: uppercase; + color: var(--muted); +} + +input[type="text"], +input[type="password"], +textarea { + width: 100%; + font: inherit; + font-size: 16px; + padding: 12px 12px; + border: 1px solid var(--line); + border-radius: 3px; + background: #141516; + color: var(--ink); +} + +input:focus, textarea:focus, .btn:focus-visible, .chip:focus-visible, .vote-btn:focus-visible { + outline: 2px solid var(--signal); + outline-offset: 2px; +} + +.optional { font-weight: 400; letter-spacing: 0.04em; } + +.panel-wrap, .auth-wrap { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 3px; + padding: 24px 20px 28px; +} + +.question-page .q-detail { + display: grid; + grid-template-columns: 3.25rem 1fr; + gap: 8px 14px; + background: var(--panel); + border: 1px solid var(--line); + padding: 18px 14px; +} + +.question-page h1 { + font-size: clamp(1.5rem, 3.5vw, 2.1rem); + line-height: 1.15; +} + +.q-body, .answer-body { + white-space: pre-wrap; + margin: 14px 0 0; + text-wrap: pretty; +} + +.crumb { margin: 0 0 20px; } +.crumb a { + color: var(--muted); + text-decoration: none; + font-family: var(--mono); + font-size: 0.72rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} +.crumb a:hover { color: var(--signal); } + +.answer { + margin-top: 16px; + padding: 20px 18px; + background: var(--panel); + border: 1px solid var(--line); +} + +.answer.is-in { + border-color: var(--signal); +} + +.answer-kicker { + margin: 0 0 6px; + font-family: var(--mono); + text-transform: uppercase; + letter-spacing: 0.16em; + font-size: 0.68rem; + font-weight: 500; + color: var(--signal); +} + +.answer h2 { + margin: 0; + font-size: 1.15rem; + font-weight: 500; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.byline { + margin: 6px 0 0; + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; +} + +.waiting { color: var(--muted); margin: 0; font-family: var(--mono); font-size: 0.8rem; } + +.auth-wrap { + width: min(420px, calc(100% - 32px)); +} + +.auth-wrap h1 { font-size: 1.7rem; } + +.site-footer { + width: min(840px, calc(100% - 32px)); + margin: 0 auto; + padding: 20px 0 calc(36px + var(--pad)); + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; + line-height: 1.55; + border-top: 1px solid var(--line); +} + +.sr-only { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + border: 0; +} + +@media (min-width: 640px) { + .row { + grid-template-columns: 3.4rem 3.5rem 1fr; + padding: 16px 18px; + } + .rank { font-size: 1.35rem; } + .panel-wrap { padding: 32px; } +} + +@media (prefers-reduced-motion: reduce) { + .btn-primary:hover { filter: none; } +} + +.admin-users { margin-top: 20px; overflow-x: auto; } + +.user-table { + width: 100%; + border-collapse: collapse; + font-size: 0.95rem; +} + +.user-table th, +.user-table td { + text-align: left; + padding: 12px 10px; + border-bottom: 1px solid var(--line); + vertical-align: middle; +} + +.user-table th { + color: var(--muted); + font-family: var(--mono); + font-size: 0.7rem; + font-weight: 500; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.user-table .mono { + font-family: var(--mono); + font-size: 0.85rem; +} + +.user-actions form { margin: 0; display: inline; } + +.user-actions .btn { + min-height: 36px; + padding: 0 12px; + font-size: 0.7rem; +} + +.profile-page h2 { + margin: 40px 0 16px; + font-size: 1.15rem; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.profile-form { + display: flex; + flex-direction: column; + gap: 10px; + max-width: 28rem; + margin-top: 24px; +} + +.profile-avatar { + display: flex; + align-items: center; + gap: 16px; + margin-bottom: 8px; +} + +.avatar { + width: 96px; + height: 96px; + border-radius: 50%; + object-fit: cover; + border: 1px solid var(--line); + background: var(--panel); +} + +.avatar-empty { + display: flex; + align-items: center; + justify-content: center; + font-family: var(--mono); + font-size: 1.6rem; + font-weight: 600; + color: var(--signal); + text-transform: uppercase; +} + +.avatar-fields label { margin-bottom: 6px; display: block; } + +.hint, .muted { + margin: 0; + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; + line-height: 1.45; +} + +.profile-form select, +.profile-form input[type="file"] { + width: 100%; + min-height: 44px; + padding: 8px 12px; + border: 1px solid var(--line); + border-radius: 3px; + background: var(--panel); + color: var(--ink); + font: inherit; +} + +.profile-form .btn { align-self: flex-start; margin-top: 8px; } + +.profile-q-list { + list-style: none; + margin: 0; + padding: 0; + border-top: 1px solid var(--line); +} + +.profile-q-list li { + display: flex; + flex-wrap: wrap; + justify-content: space-between; + gap: 8px 16px; + padding: 14px 0; + border-bottom: 1px solid var(--line); +} + +.profile-q-list a { + color: var(--ink); + text-decoration: none; + font-weight: 500; +} + +.profile-q-list a:hover { color: var(--signal); } + +.profile-q-list .meta { + color: var(--muted); + font-family: var(--mono); + font-size: 0.72rem; +} diff --git a/static/htmx.min.js b/static/htmx.min.js new file mode 100644 index 0000000..59937d7 --- /dev/null +++ b/static/htmx.min.js @@ -0,0 +1 @@ +var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=cn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true},parseInterval:null,_:null,version:"2.0.4"};Q.onLoad=j;Q.process=kt;Q.on=ye;Q.off=be;Q.trigger=he;Q.ajax=Rn;Q.find=u;Q.findAll=x;Q.closest=g;Q.remove=z;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=$e;Q.defineExtension=Fn;Q.removeExtension=Bn;Q.logAll=V;Q.logNone=_;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:le,canAccessLocalStorage:B,findThisElement:Se,filterValues:hn,swap:$e,hasAttribute:s,getAttributeValue:te,getClosestAttributeValue:re,getClosestMatch:o,getExpressionVars:En,getHeaders:fn,getInputValues:cn,getInternalData:ie,getSwapSpecification:gn,getTriggerSpecs:st,getTarget:Ee,makeFragment:P,mergeObjects:ce,makeSettleInfo:xn,oobSwap:He,querySelectorExt:ae,settleImmediately:Kt,shouldCancel:ht,triggerEvent:he,triggerErrorEvent:fe,withExtensions:Ft};const r=["get","post","put","delete","patch"];const H=r.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function te(e,t){return ee(e,t)||ee(e,"data-"+t)}function c(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function ne(){return document}function m(e,t){return e.getRootNode?e.getRootNode({composed:t}):ne()}function o(e,t){while(e&&!t(e)){e=c(e)}return e||null}function i(e,t,n){const r=te(t,n);const o=te(t,"hx-disinherit");var i=te(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function re(t,n){let r=null;o(t,function(e){return!!(r=i(t,ue(e),n))});if(r!=="unset"){return r}}function h(e,t){const n=e instanceof Element&&(e.matches||e.matchesSelector||e.msMatchesSelector||e.mozMatchesSelector||e.webkitMatchesSelector||e.oMatchesSelector);return!!n&&n.call(e,t)}function T(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function q(e){const t=new DOMParser;return t.parseFromString(e,"text/html")}function L(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function A(e){const t=ne().createElement("script");se(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function N(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(N(e)){const t=A(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){O(e)}finally{e.remove()}}})}function P(e){const t=e.replace(/]*)?>[\s\S]*?<\/head>/i,"");const n=T(t);let r;if(n==="html"){r=new DocumentFragment;const i=q(e);L(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=q(t);L(r,i.body);r.title=i.title}else{const i=q('");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function oe(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function k(e){return typeof e==="function"}function D(e){return t(e,"Object")}function ie(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function le(e){return e.getRootNode({composed:true})===document}function F(e){return e.trim().split(/\s+/)}function ce(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function S(e){try{return JSON.parse(e)}catch(e){O(e);return null}}function B(){const e="htmx:localStorageTest";try{localStorage.setItem(e,e);localStorage.removeItem(e);return true}catch(e){return false}}function U(t){try{const e=new URL(t);if(e){t=e.pathname+e.search}if(!/^\/$/.test(t)){t=t.replace(/\/+$/,"")}return t}catch(e){return t}}function e(e){return vn(ne().body,function(){return eval(e)})}function j(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function V(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function _(){Q.logger=null}function u(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return u(ne(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(ne(),e)}}function E(){return window}function z(e,t){e=y(e);if(t){E().setTimeout(function(){z(e);e=null},t)}else{c(e).removeChild(e)}}function ue(e){return e instanceof Element?e:null}function $(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function f(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ue(y(e));if(!e){return}if(n){E().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ue(y(e));if(!r){return}if(n){E().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=y(e);e.classList.toggle(t)}function Z(e,t){e=y(e);se(e.parentElement.children,function(e){G(e,t)});K(ue(e),t)}function g(e,t){e=ue(y(e));if(e&&e.closest){return e.closest(t)}else{do{if(e==null||h(e,t)){return e}}while(e=e&&ue(c(e)));return null}}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function ge(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function p(t,r,n){if(r.indexOf("global ")===0){return p(t,r.slice(7),true)}t=y(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=ge(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ue(t),ge(r.substr(8)))}else if(r.indexOf("find ")===0){e=u(f(t),ge(r.substr(5)))}else if(r==="next"||r==="nextElementSibling"){e=ue(t).nextElementSibling}else if(r.indexOf("next ")===0){e=pe(t,ge(r.substr(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ue(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,ge(r.substr(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=m(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=f(m(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var pe=function(t,e,n){const r=f(m(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ae(e,t){if(typeof e!=="string"){return p(e,t)[0]}else{return p(ne().body,e)[0]}}function y(e,t){if(typeof e==="string"){return u(f(t)||document,e)}else{return e}}function xe(e,t,n,r){if(k(t)){return{target:ne().body,event:J(e),listener:t,options:n}}else{return{target:y(e),event:J(t),listener:n,options:r}}}function ye(t,n,r,o){Vn(function(){const e=xe(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=k(n);return e?n:r}function be(t,n,r){Vn(function(){const e=xe(t,n,r);e.target.removeEventListener(e.event,e.listener)});return k(n)?n:r}const ve=ne().createElement("output");function we(e,t){const n=re(e,t);if(n){if(n==="this"){return[Se(e,t)]}else{const r=p(e,n);if(r.length===0){O('The selector "'+n+'" on '+t+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ue(o(e,function(e){return te(ue(e),t)!=null}))}function Ee(e){const t=re(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ae(e,t)}}else{const n=ie(e);if(n.boosted){return ne().body}else{return e}}}function Ce(t){const n=Q.config.attributesToSettle;for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=p(t,n,false);if(r){se(r,function(e){let t;const n=o.cloneNode(true);t=ne().createDocumentFragment();t.appendChild(n);if(!Re(s,e)){t=f(n)}const r={shouldSwap:true,target:e,fragment:t};if(!he(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);_e(s,e,e,t,i);Te()}se(i.elts,function(e){he(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(ne().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Te(){const e=u("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=u("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){se(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=te(e,"id");const n=ne().getElementById(t);if(n!=null){if(e.moveBefore){let e=u("#--htmx-preserve-pantry--");if(e==null){ne().body.insertAdjacentHTML("afterend","
");e=u("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Le(l,e,c){se(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=f(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Ae(e){return function(){G(e,Q.config.addedClass);kt(ue(e));Ne(f(e));he(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=$(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function a(e,t,n,r){Le(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ue(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Ae(o))}}}function Ie(e,t){let n=0;while(n0}function $e(e,t,r,o){if(!o){o={}}e=y(e);const i=o.contextElement?m(o.contextElement,false):ne();const n=document.activeElement;let s={};try{s={elt:n,start:n?n.selectionStart:null,end:n?n.selectionEnd:null}}catch(e){}const l=xn(e);if(r.swapStyle==="textContent"){e.textContent=t}else{let n=P(t);l.title=n.title;if(o.selectOOB){const u=o.selectOOB.split(",");for(let t=0;t0){E().setTimeout(c,r.settleDelay)}else{c()}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=S(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(D(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}he(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=vn(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(ne().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function C(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=C(e,Qe).trim();e.shift()}else{t=C(e,v)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{C(o,w);const l=o.length;const c=C(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};C(o,w);u.pollInterval=d(C(o,/[,\[\s]/));C(o,w);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const a={trigger:c};var i=nt(e,o,"event");if(i){a.eventFilter=i}C(o,w);while(o.length>0&&o[0]!==","){const f=o.shift();if(f==="changed"){a.changed=true}else if(f==="once"){a.once=true}else if(f==="consume"){a.consume=true}else if(f==="delay"&&o[0]===":"){o.shift();a.delay=d(C(o,v))}else if(f==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=C(o,v);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}a.from=s}else if(f==="target"&&o[0]===":"){o.shift();a.target=rt(o)}else if(f==="throttle"&&o[0]===":"){o.shift();a.throttle=d(C(o,v))}else if(f==="queue"&&o[0]===":"){o.shift();a.queue=C(o,v)}else if(f==="root"&&o[0]===":"){o.shift();a[f]=rt(o)}else if(f==="threshold"&&o[0]===":"){o.shift();a[f]=C(o,v)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}r.push(a)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}C(o,w)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=te(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){ie(e).cancelled=true}function ct(e,t,n){const r=ie(e);r.timeout=E().setTimeout(function(){if(le(e)&&r.cancelled!==true){if(!gt(n,e,Mt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function at(e){return g(e,Q.config.disableSelector)}function ft(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=ne().location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){pt(t,function(e,t){const n=ue(e);if(at(n)){b(n);return}de(r,o,n,t)},n,e,true)})}}function ht(e,t){const n=ue(t);if(!n){return false}if(e.type==="submit"||e.type==="click"){if(n.tagName==="FORM"){return true}if(h(n,'input[type="submit"], button')&&(h(n,"[form]")||g(n,"form")!==null)){return true}if(n instanceof HTMLAnchorElement&&n.href&&(n.getAttribute("href")==="#"||n.getAttribute("href").indexOf("#")!==0)){return true}}return false}function dt(e,t){return ie(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function gt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(ne().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function pt(l,c,e,u,a){const f=ie(l);let t;if(u.from){t=p(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in f)){f.lastValue=new WeakMap}t.forEach(function(e){if(!f.lastValue.has(u)){f.lastValue.set(u,new WeakMap)}f.lastValue.get(u).set(e,e.value)})}se(t,function(i){const s=function(e){if(!le(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(a||ht(e,l)){e.preventDefault()}if(gt(u,l,e)){return}const t=ie(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ue(e.target),u.target)){return}}if(u.once){if(f.triggeredOnce){return}else{f.triggeredOnce=true}}if(u.changed){const n=event.target;const r=n.value;const o=f.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(f.delayed){clearTimeout(f.delayed)}if(f.throttle){return}if(u.throttle>0){if(!f.throttle){he(l,"htmx:trigger");c(l,e);f.throttle=E().setTimeout(function(){f.throttle=null},u.throttle)}}else if(u.delay>0){f.delayed=E().setTimeout(function(){he(l,"htmx:trigger");c(l,e)},u.delay)}else{he(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let xt=null;function yt(){if(!xt){xt=function(){mt=true};window.addEventListener("scroll",xt);window.addEventListener("resize",xt);setInterval(function(){if(mt){mt=false;se(ne().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&X(e)){e.setAttribute("data-hx-revealed","true");const t=ie(e);if(t.initHash){he(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){he(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;he(e,"htmx:trigger");t(e)}};if(r>0){E().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;se(r,function(r){if(s(t,"hx-"+r)){const o=te(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ue(e);if(g(n,Q.config.disableSelector)){b(n);return}de(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){yt();pt(r,n,t,e);bt(ue(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ae(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ue(r),n,e)}else{pt(r,n,t,e)}}function Et(e){const t=ue(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Tt(e){const t=g(ue(e.target),"button, input[type='submit']");const n=Lt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Lt(e);if(t){t.lastButtonClicked=null}}function Lt(e){const t=g(ue(e.target),"button, input[type='submit']");if(!t){return}const n=y("#"+ee(t,"form"),t.getRootNode())||g(t,"form");if(!n){return}return ie(n)}function At(e){e.addEventListener("click",Tt);e.addEventListener("focusin",Tt);e.addEventListener("focusout",qt)}function Nt(t,e,n){const r=ie(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){vn(t,function(){if(at(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function It(t){ke(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{localStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(ne().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Vt(t){if(!B()){return null}t=U(t);const n=S(localStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){he(ne().body,"htmx:historyCacheMissLoad",i);const e=P(this.response);const t=e.querySelector("[hx-history-elt],[data-hx-history-elt]")||e;const n=Ut();const r=xn(n);kn(e.title);qe(e);Ve(n,t,r);Te();Kt(r.tasks);Bt=o;he(ne().body,"htmx:historyRestore",{path:o,cacheMiss:true,serverResponse:this.response})}else{fe(ne().body,"htmx:historyCacheMissLoadError",i)}};e.send()}function Wt(e){zt();e=e||location.pathname+location.search;const t=Vt(e);if(t){const n=P(t.content);const r=Ut();const o=xn(r);kn(t.title);qe(n);Ve(r,n,o);Te();Kt(o.tasks);E().setTimeout(function(){window.scrollTo(0,t.scroll)},0);Bt=e;he(ne().body,"htmx:historyRestore",{path:e,item:t})}else{if(Q.config.refreshOnHistoryMiss){window.location.reload(true)}else{Gt(e)}}}function Zt(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function Yt(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}se(t,function(e){const t=ie(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function Qt(e,t){se(e.concat(t),function(e){const t=ie(e);t.requestCount=(t.requestCount||1)-1});se(e,function(e){const t=ie(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});se(t,function(e){const t=ie(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function en(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);se(e,e=>r.append(t,e))}}function on(t,n,r,o,i){if(o==null||en(t,o)){return}else{t.push(o)}if(tn(o)){const s=ee(o,"name");let e=o.value;if(o instanceof HTMLSelectElement&&o.multiple){e=M(o.querySelectorAll("option:checked")).map(function(e){return e.value})}if(o instanceof HTMLInputElement&&o.files){e=M(o.files)}nn(s,e,n);if(i){sn(o,r)}}if(o instanceof HTMLFormElement){se(o.elements,function(e){if(t.indexOf(e)>=0){rn(e.name,e.value,n)}else{t.push(e)}if(i){sn(e,r)}});new FormData(o).forEach(function(e,t){if(e instanceof File&&e.name===""){return}nn(t,e,n)})}}function sn(e,t){const n=e;if(n.willValidate){he(n,"htmx:validation:validate");if(!n.checkValidity()){t.push({elt:n,message:n.validationMessage,validity:n.validity});he(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})}}}function ln(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function cn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=ie(e);if(s.lastButtonClicked&&!le(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||te(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){on(n,o,i,g(e,"form"),l)}on(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const a=ee(u,"name");nn(a,u.value,o)}const c=we(e,"hx-include");se(c,function(e){on(n,r,i,ue(e),l);if(!h(e,"form")){se(f(e).querySelectorAll(ot),function(e){on(n,r,i,e,l)})}});ln(r,o);return{errors:i,formData:r,values:An(r)}}function un(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function an(e){e=qn(e);let n="";e.forEach(function(e,t){n=un(n,t,e)});return n}function fn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":te(t,"id"),"HX-Current-URL":ne().location.href};bn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(ie(e).boosted){r["HX-Boosted"]="true"}return r}function hn(n,e){const t=re(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){se(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;se(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function dn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function gn(e,t){const n=t||re(e,"hx-swap");const r={swapStyle:ie(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&ie(e).boosted&&!dn(e)){r.show="top"}if(n){const s=F(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const a=l.slice(5);var o=a.split(":");const f=o.pop();var i=o.length>0?o.join(":"):null;r.show=f;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{O("Unknown modifier in hx-swap: "+l)}}}}return r}function pn(e){return re(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function mn(t,n,r){let o=null;Ft(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(pn(n)){return ln(new FormData,qn(r))}else{return an(r)}}}function xn(e){return{tasks:[],elts:[e]}}function yn(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ue(ae(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ue(ae(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function bn(r,e,o,i){if(i==null){i={}}if(r==null){return i}const s=te(r,e);if(s){let e=s.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=vn(r,function(){return Function("return ("+e+")")()},{})}else{n=S(e)}for(const l in n){if(n.hasOwnProperty(l)){if(i[l]==null){i[l]=n[l]}}}}return bn(ue(c(r)),e,o,i)}function vn(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function wn(e,t){return bn(e,"hx-vars",true,t)}function Sn(e,t){return bn(e,"hx-vals",false,t)}function En(e){return ce(wn(e),Sn(e))}function Cn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function On(t){if(t.responseURL&&typeof URL!=="undefined"){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(ne().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function R(e,t){return t.test(e.getAllResponseHeaders())}function Rn(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return de(t,n,null,null,{targetOverride:y(r)||ve,returnPromise:true})}else{let e=y(r.target);if(r.target&&!e||r.source&&!e&&!y(r.source)){e=ve}return de(t,n,y(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true})}}else{return de(t,n,null,null,{returnPromise:true})}}function Hn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function Tn(e,t,n){let r;let o;if(typeof URL==="function"){o=new URL(t,document.location.href);const i=document.location.origin;r=i===o.origin}else{o=t;r=l(t,document.location.origin)}if(Q.config.selfRequestsOnly){if(!r){return false}}return he(e,"htmx:validateUrl",ce({url:o,sameHost:r},n))}function qn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Ln(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function An(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}else{return e[t]}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Ln(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function de(t,n,r,o,i,D){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=ne().body}const M=i.handler||Dn;const X=i.select||null;if(!le(r)){oe(s);return e}const c=i.targetOverride||ue(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:te(r,"hx-target")});oe(l);return e}let u=ie(r);const a=u.lastButtonClicked;if(a){const L=ee(a,"formaction");if(L!=null){n=L}const A=ee(a,"formmethod");if(A!=null){if(A.toLowerCase()!=="dialog"){t=A}}}const f=re(r,"hx-confirm");if(D===undefined){const K=function(e){return de(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:f};if(he(r,"htmx:confirm",G)===false){oe(s);return e}}let h=r;let d=re(r,"hx-sync");let g=null;let F=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ue(ae(r,I))}d=(N[1]||"drop").trim();u=ie(h);if(d==="drop"&&u.xhr&&u.abortable!==true){oe(s);return e}else if(d==="abort"){if(u.xhr){oe(s);return e}else{F=true}}else if(d==="replace"){he(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");g=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){he(h,"htmx:abort")}else{if(g==null){if(o){const P=ie(o);if(P&&P.triggerSpec&&P.triggerSpec.queue){g=P.triggerSpec.queue}}if(g==null){g="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(g==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="all"){u.queuedRequests.push(function(){de(t,n,r,o,i)})}else if(g==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){de(t,n,r,o,i)})}oe(s);return e}}const p=new XMLHttpRequest;u.xhr=p;u.abortable=F;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const B=re(r,"hx-prompt");if(B){var x=prompt(B);if(x===null||!he(r,"htmx:prompt",{prompt:x,target:c})){oe(s);m();return e}}if(f&&!D){if(!confirm(f)){oe(s);m();return e}}let y=fn(r,c,x);if(t!=="get"&&!pn(r)){y["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){y=ce(y,i.headers)}const U=cn(r,t);let b=U.errors;const j=U.formData;if(i.values){ln(j,qn(i.values))}const V=qn(En(r));const v=ln(j,V);let w=hn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=ne().location.href}const S=bn(r,"hx-request");const _=ie(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:_,useUrlParams:E,formData:w,parameters:An(w),unfilteredFormData:v,unfilteredParameters:An(v),headers:y,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!he(r,"htmx:configRequest",C)){oe(s);m();return e}n=C.path;t=C.verb;y=C.headers;w=qn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){he(r,"htmx:validation:halted",C);oe(s);m();return e}const z=n.split("#");const $=z[0];const O=z[1];let R=n;if(E){R=$;const Z=!w.keys().next().done;if(Z){if(R.indexOf("?")<0){R+="?"}else{R+="&"}R+=an(w);if(O){R+="#"+O}}}if(!Tn(r,R,C)){fe(r,"htmx:invalidPath",C);oe(l);return e}p.open(t.toUpperCase(),R,true);p.overrideMimeType("text/html");p.withCredentials=C.withCredentials;p.timeout=C.timeout;if(S.noHeaders){}else{for(const k in y){if(y.hasOwnProperty(k)){const Y=y[k];Cn(p,k,Y)}}}const H={xhr:p,target:c,requestConfig:C,etc:i,boosted:_,select:X,pathInfo:{requestPath:n,finalRequestPath:R,responsePath:null,anchor:O}};p.onload=function(){try{const t=Hn(r);H.pathInfo.responsePath=On(p);M(r,H);if(H.keepIndicators!==true){Qt(T,q)}he(r,"htmx:afterRequest",H);he(r,"htmx:afterOnLoad",H);if(!le(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(le(n)){e=n}}if(e){he(e,"htmx:afterRequest",H);he(e,"htmx:afterOnLoad",H)}}oe(s);m()}catch(e){fe(r,"htmx:onLoadError",ce({error:e},H));throw e}};p.onerror=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendError",H);oe(l);m()};p.onabort=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:sendAbort",H);oe(l);m()};p.ontimeout=function(){Qt(T,q);fe(r,"htmx:afterRequest",H);fe(r,"htmx:timeout",H);oe(l);m()};if(!he(r,"htmx:beforeRequest",H)){oe(s);m();return e}var T=Zt(r);var q=Yt(r);se(["loadstart","loadend","progress","abort"],function(t){se([p,p.upload],function(e){e.addEventListener(t,function(e){he(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});he(r,"htmx:beforeSend",H);const J=E?null:mn(p,r,w);p.send(J);return e}function Nn(e,t){const n=t.xhr;let r=null;let o=null;if(R(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(R(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(R(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=re(e,"hx-push-url");const c=re(e,"hx-replace-url");const u=ie(e).boosted;let a=null;let f=null;if(l){a="push";f=l}else if(c){a="replace";f=c}else if(u){a="push";f=s||i}if(f){if(f==="false"){return{}}if(f==="true"){f=s||i}if(t.pathInfo.anchor&&f.indexOf("#")===-1){f=f+"#"+t.pathInfo.anchor}return{type:a,path:f}}else{return{}}}function In(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Pn(e){for(var t=0;t0){E().setTimeout(e,x.swapDelay)}else{e()}}if(f){fe(o,"htmx:responseError",ce({error:"Response Status Error Code "+s.status+" from "+i.pathInfo.requestPath},i))}}const Mn={};function Xn(){return{init:function(e){return null},getSelectors:function(){return null},onEvent:function(e,t){return true},transformResponse:function(e,t,n){return e},isInlineSwap:function(e){return false},handleSwap:function(e,t,n,r){return false},encodeParameters:function(e,t,n){return null}}}function Fn(e,t){if(t.init){t.init(n)}Mn[e]=ce(Xn(),t)}function Bn(e){delete Mn[e]}function Un(e,n,r){if(n==undefined){n=[]}if(e==undefined){return n}if(r==undefined){r=[]}const t=te(e,"hx-ext");if(t){se(t.split(","),function(e){e=e.replace(/ /g,"");if(e.slice(0,7)=="ignore:"){r.push(e.slice(7));return}if(r.indexOf(e)<0){const t=Mn[e];if(t&&n.indexOf(t)<0){n.push(t)}}})}return Un(ue(c(e)),n,r)}var jn=false;ne().addEventListener("DOMContentLoaded",function(){jn=true});function Vn(e){if(jn||ne().readyState==="complete"){e()}else{ne().addEventListener("DOMContentLoaded",e)}}function _n(){if(Q.config.includeIndicatorStyles!==false){const e=Q.config.inlineStyleNonce?` nonce="${Q.config.inlineStyleNonce}"`:"";ne().head.insertAdjacentHTML("beforeend"," ."+Q.config.indicatorClass+"{opacity:0} ."+Q.config.requestClass+" ."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ."+Q.config.requestClass+"."+Q.config.indicatorClass+"{opacity:1; transition: opacity 200ms ease-in;} ")}}function zn(){const e=ne().querySelector('meta[name="htmx-config"]');if(e){return S(e.content)}else{return null}}function $n(){const e=zn();if(e){Q.config=ce(Q.config,e)}}Vn(function(){$n();_n();let e=ne().body;kt(e);const t=ne().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.target;const n=ie(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){Wt();se(t,function(e){he(e,"htmx:restored",{document:ne(),triggerEvent:he})})}else{if(n){n(e)}}};E().setTimeout(function(){he(e,"htmx:load",{});e=null},0)});return Q}(); \ No newline at end of file diff --git a/templates/admin_users.html b/templates/admin_users.html new file mode 100644 index 0000000..d15e846 --- /dev/null +++ b/templates/admin_users.html @@ -0,0 +1,45 @@ +{{define "admin-users"}} +{{template "header" .}} +
+

Admin

+

Users

+ {{if .Error}}{{end}} +
+ + + + + + + + + + {{range .Users}} + + + + + + {{else}} + + {{end}} + +
UsernameRoleActions
{{.Username}}{{.Role}}
No users yet.
+
+
+{{template "footer" .}} +{{end}} diff --git a/templates/base.html b/templates/base.html new file mode 100644 index 0000000..f7a32d0 --- /dev/null +++ b/templates/base.html @@ -0,0 +1,73 @@ +{{define "header"}} + + + + + + {{if .Title}}{{.Title}} · {{end}}Ask a Plumber First + + + + + + + + + +
+
+ + +
+
+
+ {{if .Flash}}{{end}} +
+{{end}} + +{{define "footer"}} +
+

This site is not a substitute for a licensed plumber. Advice is general and based on the question as written. If you have a gas leak, flooding, or another emergency, leave the area if needed and call 911.

+
+ + +{{end}} diff --git a/templates/hunt.html b/templates/hunt.html new file mode 100644 index 0000000..fc939ca --- /dev/null +++ b/templates/hunt.html @@ -0,0 +1,21 @@ +{{define "hunt"}} +{{template "header" .}} +
+
+
+

{{if .IsToday}}Live board{{else if .IsYesterday}}Prior board{{else}}Archive{{end}}

+

{{.Label}}

+
+ +
+ {{template "leaderboard" .}} +
+{{template "footer" .}} +{{end}} diff --git a/templates/login.html b/templates/login.html new file mode 100644 index 0000000..e1dc202 --- /dev/null +++ b/templates/login.html @@ -0,0 +1,19 @@ +{{define "login"}} +{{template "header" .}} +
+

Access

+

Sign in

+ {{if .Error}}{{end}} +
+ + + + + + + +
+

New here? Create an account

+
+{{template "footer" .}} +{{end}} diff --git a/templates/partials/_answer.html b/templates/partials/_answer.html new file mode 100644 index 0000000..f50904a --- /dev/null +++ b/templates/partials/_answer.html @@ -0,0 +1,12 @@ +{{define "answer"}} +
+ {{if .Answer}} +

Shop response

+

Answer

+ +

{{.Answer.Body}}

+ {{else}} +

No answer yet. Check back after the hunt.

+ {{end}} +
+{{end}} diff --git a/templates/partials/_list.html b/templates/partials/_list.html new file mode 100644 index 0000000..5b8bb4a --- /dev/null +++ b/templates/partials/_list.html @@ -0,0 +1,37 @@ +{{define "leaderboard"}} +
    + {{if not .Questions}} +
  1. + {{if eq .Date .Today}} +

    Queue empty

    +

    No questions yet. Be the first to ask.

    + {{else}} +

    No questions on this day.

    + {{end}} +
  2. + {{else}} + {{range $i, $q := .Questions}} +
  3. + + {{template "vote" (voteCtx $.User $.CSRF "list" $.Date $q)}} +
    + {{$q.Title}} +

    + {{$q.AuthorName}} + {{if $q.City}}{{$q.City}}{{end}} + {{if $q.Answered}}Answered{{end}} +

    + {{if isAdmin $.User}} +
    + + + +
    + {{end}} +
    +
  4. + {{end}} + {{end}} +
+{{end}} diff --git a/templates/partials/_signin.html b/templates/partials/_signin.html new file mode 100644 index 0000000..0ba989f --- /dev/null +++ b/templates/partials/_signin.html @@ -0,0 +1,8 @@ +{{define "signin-prompt"}} + +{{end}} diff --git a/templates/partials/_vote.html b/templates/partials/_vote.html new file mode 100644 index 0000000..7b40010 --- /dev/null +++ b/templates/partials/_vote.html @@ -0,0 +1,37 @@ +{{define "vote"}} +
+ {{if .User}} +
+ + + + + +
+ {{.Question.Score}} +
+ + + + + +
+ {{else}} + + + + {{.Question.Score}} + + + + {{end}} +
+{{end}} diff --git a/templates/profile.html b/templates/profile.html new file mode 100644 index 0000000..2bd4176 --- /dev/null +++ b/templates/profile.html @@ -0,0 +1,57 @@ +{{define "profile"}} +{{template "header" .}} +
+

Account

+

Profile

+ {{if .Error}}{{end}} + +
+ + +
+ {{if .User.AvatarURL}} + + {{else}} + + {{end}} +
+ + {{if .UploadsEnabled}} + +

JPEG, PNG, or WebP · max 2MB

+ {{else}} +

Avatar uploads are not configured on this server.

+ {{end}} +
+
+ + + +

Optional. Sharing your state helps answers line up with local plumbing codes.

+ + +
+ +
+

{{.QuestionsLabel}}

+ {{if .Questions}} +
    + {{range .Questions}} +
  • + {{.Title}} + {{.HuntDate}} +
  • + {{end}} +
+ {{else}} +

Nothing here yet.

+ {{end}} +
+
+{{template "footer" .}} +{{end}} diff --git a/templates/question.html b/templates/question.html new file mode 100644 index 0000000..4f83855 --- /dev/null +++ b/templates/question.html @@ -0,0 +1,37 @@ +{{define "question"}} +{{template "header" .}} +
+

← {{pacificLabel .Question.HuntDate}}

+
+ {{template "vote" (voteCtx .User .CSRF "question" .Question.HuntDate .Question)}} +
+

{{.Question.Title}}

+

+ {{.Question.AuthorName}} + {{if .Question.City}}{{.Question.City}}{{end}} + + {{.Question.HuntDate}} +

+

{{.Question.Body}}

+ {{if isAdmin .User}} +
+ + +
+ {{end}} +
+
+ {{template "answer" .}} + {{if isAdmin .User}} +
+ + + + +
+ {{end}} +
+{{template "footer" .}} +{{end}} diff --git a/templates/register.html b/templates/register.html new file mode 100644 index 0000000..1e2c273 --- /dev/null +++ b/templates/register.html @@ -0,0 +1,20 @@ +{{define "register"}} +{{template "header" .}} +
+

New account

+

Create an account

+ {{if .Error}}{{end}} +
+ + + +

3–20 letters, numbers, or underscores.

+ + +

At least 8 characters.

+ +
+

Already have an account? Sign in

+
+{{template "footer" .}} +{{end}} diff --git a/templates/submit.html b/templates/submit.html new file mode 100644 index 0000000..ce8668f --- /dev/null +++ b/templates/submit.html @@ -0,0 +1,19 @@ +{{define "submit"}} +{{template "header" .}} +
+

Ask a question

+

It lands on today’s hunt (Pacific time). People vote; the ranking resets at midnight PT.

+ {{if .Error}}{{end}} +
+ + + + + + + + +
+
+{{template "footer" .}} +{{end}} diff --git a/todo.md b/todo.md new file mode 100644 index 0000000..b4d0601 --- /dev/null +++ b/todo.md @@ -0,0 +1,33 @@ +# Plumber — follow-ups + +From the project review. Priority order within each section. + +## Fix soon + +- [x] **Persist sessions** — Sessions live in the app DB (`sessions` table): SQLite locally, `postgresstore` when `DATABASE_URL` is set. Opaque cookie unchanged; unused `SESSION_SECRET` removed from config / `.env.example`. +- [x] **Drop Dockerfile** — Deploying on DigitalOcean App Platform (buildpack from `go.mod`); no container image needed. +- [ ] **Rune-safe truncation** — `title[:120]`, `body[:8000]`, `city[:80]`, answer body, etc. can split multi-byte UTF-8. Truncate by runes (or safely). +- [x] **Admin bootstrap** — `ADMIN_USERNAME` seeds the first admin on register only when no admin exists. Promote/demote via `/admin/users` (admins only); roles stay in `users.role`. + +## Docs & ops + +- [ ] **README** — How to run locally, env vars (from `.env.example`), admin bootstrap, SQLite vs PlanetScale `DATABASE_URL`, App Platform notes (`PORT`, `SECURE_COOKIE=1`). +- [ ] **Migrations story** — Schema is applied on boot from `schema.sql` (+ sessions DDL). OK for v1; plan real migrations before schema drifts between SQLite and Postgres. +- [x] **App Platform listen port** — Prefers `PORT`, then `LISTEN`, then `:8080`. +- [x] **Prod DB = PlanetScale Postgres** — App already opens Postgres when `DATABASE_URL` is set; DSN cleanup strips PlanetScale/libpq-only params (`sslrootcert=system`, `sslnegotiation`). Use dashboard URI on **5432** for boot schema create; **6432** (PgBouncer) later if you need pooling. + +## Smaller / later + +- [ ] Rate-limit login/register (bcrypt helps; still open to brute-force). +- [ ] Graceful shutdown instead of bare `ListenAndServe`. +- [ ] More tests: vote HTMX paths, admin answer/hide, archive redirects; optional Postgres integration test. +- [ ] Watch dual-dialect schema — one SQL file works now; expect divergence later. + +## Suggested order of attack + +1. ~~Persist sessions~~ done. +2. ~~Drop Dockerfile~~ done (App Platform). +3. ~~Wire `PORT`~~ done. +4. ~~Admin roles page~~ done. +5. Short README (run, env, admin, App Platform + PlanetScale). +6. Rune-safe truncation + a couple of handler tests (vote, admin hide).