diff --git a/internal/api/apidocs.go b/internal/api/apidocs.go index 0afb13d..fed53f2 100644 --- a/internal/api/apidocs.go +++ b/internal/api/apidocs.go @@ -22,6 +22,9 @@ func paged(o obj) obj { // show them. var endpoints = []endpoint{ // Account + {method: "GET", path: "/api/v1/public/regions", tag: "Public", summary: "Platform regions with their locations", public: true, + description: "For websites showing where the platform checks from: no authentication, any origin (CORS), cached for up to a minute. Lists platform regions only; `latitude`/`longitude` are absent for regions without a location, and `online` is set while a checker of the region is connected.", + resp: obj{"regions": []publicRegion{}}}, {method: "POST", path: "/api/v1/auth/signup", tag: "Account", summary: "Create an account", public: true, description: "Depending on the installation, sign-up is open, limited to the first user, or closed. Where addresses are confirmed, answers `{\"status\": \"verification_sent\"}` and mails a link; the account signs in after confirming. Otherwise starts a session, and `org_name`/`org_slug`, if given, create a first organization. One account per mailbox (+suffixes and Gmail dots count as the same address); a client address may create only a few accounts a day (`429 signup_limit`).", req: signupRequest{}, resp: sessionStarted}, diff --git a/internal/api/publicregions.go b/internal/api/publicregions.go new file mode 100644 index 0000000..9d8801e --- /dev/null +++ b/internal/api/publicregions.go @@ -0,0 +1,82 @@ +package api + +import ( + "encoding/json" + "net/http" + "sync" + "time" + + "github.com/gin-gonic/gin" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +// publicRegionsTTL is how long an instance serves the platform regions +// from memory, so the endpoint costs the database next to nothing however +// often a front page asks. +const publicRegionsTTL = 30 * time.Second + +// publicRegion is a platform region as anyone may see it. Organizations' +// own regions are never listed. +type publicRegion struct { + Key string `json:"key"` + Name string `json:"name"` + // Latitude and longitude are absent for regions without a location. + Latitude *float64 `json:"latitude,omitempty"` + Longitude *float64 `json:"longitude,omitempty"` + // Online is set while at least one checker of the region is connected. + Online bool `json:"online"` +} + +type publicRegionsCache struct { + mu sync.Mutex + body []byte + expires time.Time +} + +// listPublicRegions answers without authentication and to any origin, for +// a website showing where the platform checks from. +func (s *Server) listPublicRegions(c *gin.Context) { + c.Header("Access-Control-Allow-Origin", "*") + c.Header("Cache-Control", "public, max-age=60") + body, err := s.publicRegionsBody(c) + if err != nil { + internalError(c, err) + return + } + c.Data(http.StatusOK, "application/json; charset=utf-8", body) +} + +func (s *Server) publicRegionsBody(c *gin.Context) ([]byte, error) { + cache := &s.publicRegions + cache.mu.Lock() + defer cache.mu.Unlock() + if cache.body != nil && time.Now().Before(cache.expires) { + return cache.body, nil + } + ctx := c.Request.Context() + var rows []store.Region + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.ListPlatformRegions(ctx) + return err + }) + if err != nil { + return nil, err + } + out := make([]publicRegion, len(rows)) + for i, r := range rows { + n, err := s.sched.Instances(ctx, r.ID.String()) + if err != nil { + return nil, err + } + out[i] = publicRegion{Key: r.Key, Name: r.Name, Latitude: r.Latitude, Longitude: r.Longitude, Online: n > 0} + } + body, err := json.Marshal(gin.H{"regions": out}) + if err != nil { + return nil, err + } + cache.body, cache.expires = body, time.Now().Add(publicRegionsTTL) + return body, nil +} diff --git a/internal/api/regions_test.go b/internal/api/regions_test.go index 258c287..9a68e62 100644 --- a/internal/api/regions_test.go +++ b/internal/api/regions_test.go @@ -2,6 +2,7 @@ package api_test import ( "context" + "encoding/json" "net/http" "net/http/httptest" "strings" @@ -278,6 +279,41 @@ func TestRegionLocations(t *testing.T) { t.Errorf("platform location seen by org B = %v, %v", lat, lon) } + t.Run("public list", func(t *testing.T) { + req, _ := http.NewRequest(http.MethodGet, a.base+"/api/v1/public/regions", nil) + req.Header.Set("Origin", "https://www.example.org") + // The browser's transport trusts the test server; no cookie jar, so no session. + resp, err := (&http.Client{Transport: a.hc.Transport}).Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = resp.Body.Close() }() + var body struct { + Regions []map[string]any `json:"regions"` + } + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil || resp.StatusCode != http.StatusOK { + t.Fatalf("GET public regions = %d %v", resp.StatusCode, err) + } + if got := resp.Header.Get("Access-Control-Allow-Origin"); got != "*" { + t.Errorf("CORS header = %q, want *", got) + } + var found map[string]any + for _, r := range body.Regions { + if r["name"] == "Office plain" || r["key"] == "berlin" { + t.Errorf("public list shows an org region: %v", r) + } + if _, leaked := r["id"]; leaked { + t.Errorf("public list exposes region ids: %v", r) + } + if r["latitude"] == 50.1109 { + found = r + } + } + if _, isBool := found["online"].(bool); found == nil || found["longitude"] != 8.6821 || !isBool { + t.Errorf("platform region in public list = %v, want its location and online state", found) + } + }) + _, _, html := a.page("/monitors/new") if !strings.Contains(html, `data-region-map="select"`) || !strings.Contains(html, `data-lat="50.1109"`) || !strings.Contains(html, `data-lat="-33.8688"`) { t.Errorf("monitor form lacks the region map or markers") diff --git a/internal/api/server.go b/internal/api/server.go index a2a9884..61c1004 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -67,6 +67,9 @@ type Server struct { // snapshots lets status page servers asking for the same page at once // share one build of it. snapshots singleflight.Group + + // publicRegions caches the answer of the public region list. + publicRegions publicRegionsCache } // Deps are the external resources a Server needs. @@ -127,6 +130,8 @@ func (s *Server) Mount(r gin.IRouter) { g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit(), s.accountGate()) r.GET("/api/openapi.json", s.openAPIJSON) + // Public data for websites: no session, no CSRF. + r.GET("/api/v1/public/regions", s.listPublicRegions) r.GET("/install.sh", s.installScript) g.GET("/api/docs", s.apiDocsPage) diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 3353474..f92a669 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -1371,6 +1371,9 @@ "regions.location_pick_hint": "Ein Klick auf die Karte setzt die Koordinaten einer neuen Region oder der Region, deren Standort du gerade setzt.", "regions.location_set": "Setzen", "regions.longitude": "Längengrad", + "regions.map_ctrl_key": "Strg", + "regions.map_scroll_hint": "{{.Key}} + Scrollen zoomt die Karte.", + "regions.map_touch_hint": "Mit zwei Fingern verschiebst du die Karte.", "regions.own": "diese Organisation", "regions.owner": "Besitzer", "regions.platform": "Plattform", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 45f1375..6d49a05 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -1371,6 +1371,9 @@ "regions.location_pick_hint": "Click the map to fill in the coordinates of a new region, or of the region whose location you are setting.", "regions.location_set": "Set", "regions.longitude": "Longitude", + "regions.map_ctrl_key": "Ctrl", + "regions.map_scroll_hint": "Use {{.Key}} + scroll to zoom the map.", + "regions.map_touch_hint": "Use two fingers to move the map.", "regions.own": "this organization", "regions.owner": "Owner", "regions.platform": "platform", diff --git a/internal/web/assets/app.css b/internal/web/assets/app.css index e394993..f03fea0 100644 --- a/internal/web/assets/app.css +++ b/internal/web/assets/app.css @@ -158,6 +158,12 @@ transform: scale(1.1); box-shadow: 0 2px 8px rgb(0 0 0 / 0.35); } +@media (pointer: coarse) { + .region-pin { + padding: 6px 11px 6px 8px; + font-size: 12px; + } +} .region-pin:focus-visible { outline: 2px solid var(--color-maintenance); outline-offset: 2px; } .region-pick { width: 14px; diff --git a/internal/web/assets/app.js b/internal/web/assets/app.js index 7489a8a..829da5a 100644 --- a/internal/web/assets/app.js +++ b/internal/web/assets/app.js @@ -648,8 +648,24 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) { let map; try { // Scrolling the page must not zoom the map; the buttons, a double - // click and pinching do. - map = new gl.Map({ container: box, style: mapStyle(server), center: [10.45, 51.17], zoom: 3, scrollZoom: false, attributionControl: { compact: true } }); + // click and pinching do. On touch screens one finger scrolls the page + // and two move the map. + const touch = window.matchMedia?.("(pointer: coarse)").matches ?? false; + map = new gl.Map({ + container: box, + style: mapStyle(server), + center: [10.45, 51.17], + zoom: 3, + // With cooperative gestures, scrolling zooms only with Ctrl or ⌘. + scrollZoom: touch, + cooperativeGestures: touch, + locale: { + "CooperativeGesturesHandler.MobileHelpText": box.dataset.touchHint, + "CooperativeGesturesHandler.WindowsHelpText": box.dataset.scrollHint.replace("{key}", box.dataset.ctrlKey), + "CooperativeGesturesHandler.MacHelpText": box.dataset.scrollHint.replace("{key}", "⌘"), + }, + attributionControl: { compact: true }, + }); } catch { box.hidden = true; return; @@ -696,9 +712,10 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) { holder.classList.toggle("is-hover", on); row.classList.toggle("is-hover", on); }; + // Mouse only: a tap would leave the highlight behind. for (const el of [pin, row]) { - el.addEventListener("mouseenter", () => hover(true)); - el.addEventListener("mouseleave", () => hover(false)); + el.addEventListener("pointerenter", (ev) => ev.pointerType === "mouse" && hover(true)); + el.addEventListener("pointerleave", () => hover(false)); } if (selecting) { // The checkbox stays the source of truth; its change event keeps diff --git a/internal/web/regionmap.templ b/internal/web/regionmap.templ index f103a5f..e6e1ad9 100644 --- a/internal/web/regionmap.templ +++ b/internal/web/regionmap.templ @@ -33,8 +33,11 @@ templ regionMap(mode, items string) { data-region-map={ mode } data-region-items={ items } data-map-server={ MapServer } + data-touch-hint={ i18n.T(ctx, "regions.map_touch_hint") } + data-scroll-hint={ i18n.T(ctx, "regions.map_scroll_hint", "Key", "{key}") } + data-ctrl-key={ i18n.T(ctx, "regions.map_ctrl_key") } hidden - class="region-map mb-3 h-72 w-full overflow-hidden border border-rule" + class="region-map mb-3 h-60 w-full overflow-hidden border border-rule sm:h-72" > } diff --git a/internal/web/regionmap_templ.go b/internal/web/regionmap_templ.go index 8671e05..2270a6a 100644 --- a/internal/web/regionmap_templ.go +++ b/internal/web/regionmap_templ.go @@ -93,7 +93,46 @@ func regionMap(mode, items string) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\" hidden class=\"region-map mb-3 h-72 w-full overflow-hidden border border-rule\">") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\" data-touch-hint=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var5 string + templ_7745c5c3_Var5, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_touch_hint")).Resolve(ctx) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 36, Col: 57} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var5) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "\" data-scroll-hint=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var6 string + templ_7745c5c3_Var6, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_scroll_hint", "Key", "{key}")).Resolve(ctx) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 37, Col: 75} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var6) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "\" data-ctrl-key=\"") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var7 string + templ_7745c5c3_Var7, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "regions.map_ctrl_key")).Resolve(ctx) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regionmap.templ`, Line: 38, Col: 53} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var7) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "\" hidden class=\"region-map mb-3 h-60 w-full overflow-hidden border border-rule sm:h-72\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -120,7 +159,7 @@ func locationFields(lat, lon *float64) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "