Fix critical and high audit findings

Fixed findings from the audit reports (SECURITY, QUALITY, PERFORMANCE):
- P-001 · Dashboard re-downloads the entire dataset every 5 seconds

Re-synced the vendored shared/ snapshot from shared commit 199a5ef.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
Gabriel20xxandClaude Haiku 5.5 committed 2026-10-19 07:48:07 +00:00
1 parent 7dd0d34383
commit a84a36349b
31 files changed
+653 -6055

No files matched your search

+4 -4
View File
@@ -79,7 +79,7 @@ func (d *DB) queryLists(ctx context.Context, includeDeleted bool, since *int64)
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += " ORDER BY updatedat DESC"
query += " ORDER BY updatedat DESC, id"
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
@@ -116,7 +116,7 @@ func (d *DB) queryFields(ctx context.Context, includeDeleted bool, since *int64,
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += ` ORDER BY "order" ASC`
query += ` ORDER BY "order" ASC, id`
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
@@ -152,7 +152,7 @@ func (d *DB) queryItems(ctx context.Context, includeDeleted bool, since *int64,
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += " ORDER BY updatedat DESC"
query += " ORDER BY updatedat DESC, id"
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
@@ -185,7 +185,7 @@ func (d *DB) queryValues(ctx context.Context, since *int64, itemID string) ([]It
if len(conditions) > 0 {
query += " WHERE " + strings.Join(conditions, " AND ")
}
query += " ORDER BY updatedat ASC"
query += " ORDER BY updatedat ASC, id"
rows, err := d.pool.Query(ctx, query, args...)
if err != nil {
+62 -12
View File
@@ -1,7 +1,7 @@
package main
import (
"errors"
"context"
"fmt"
"net/http"
"time"
@@ -42,6 +42,55 @@ func normalizeEntityTimestamps(createdAt, updatedAt, now int64) (int64, int64) {
return created, updated
}
// valueReferences returns the list ID of each field and the existence of each
// item that the values refer to, using one statement per table.
func valueReferences(ctx context.Context, tx pgx.Tx, values []ItemValue) (map[string]string, map[string]bool, error) {
fieldLists := make(map[string]string)
existingItems := make(map[string]bool)
if len(values) == 0 {
return fieldLists, existingItems, nil
}
fieldIDs := make([]string, 0, len(values))
itemIDs := make([]string, 0, len(values))
for _, value := range values {
fieldIDs = append(fieldIDs, value.FieldID)
itemIDs = append(itemIDs, value.ItemID)
}
fieldRows, err := tx.Query(ctx, `SELECT id, listid FROM fields WHERE id = ANY($1)`, fieldIDs)
if err != nil {
return nil, nil, err
}
defer fieldRows.Close()
for fieldRows.Next() {
var fieldID, listID string
if err := fieldRows.Scan(&fieldID, &listID); err != nil {
return nil, nil, err
}
fieldLists[fieldID] = listID
}
if err := fieldRows.Err(); err != nil {
return nil, nil, err
}
itemRows, err := tx.Query(ctx, `SELECT id FROM items WHERE id = ANY($1)`, itemIDs)
if err != nil {
return nil, nil, err
}
defer itemRows.Close()
for itemRows.Next() {
var itemID string
if err := itemRows.Scan(&itemID); err != nil {
return nil, nil, err
}
existingItems[itemID] = true
}
if err := itemRows.Err(); err != nil {
return nil, nil, err
}
return fieldLists, existingItems, nil
}
func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
var request SyncRequest
if err := decodeJSON(r, &request); err != nil {
@@ -169,23 +218,23 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
}
}
// Resolve the fields and items the values refer to once per request, not once
// per value. Items are read after the item loop above, so this request's own
// item inserts are visible.
fieldLists, existingItems, err := valueReferences(r.Context(), tx, request.ItemValues)
if err != nil {
return err
}
for _, value := range request.ItemValues {
updatedAt := normalizeTimestamp(int64(value.UpdatedAt), now, now)
var listID string
fieldErr := tx.QueryRow(r.Context(), `SELECT listid FROM fields WHERE id = $1`, value.FieldID).Scan(&listID)
if errors.Is(fieldErr, pgx.ErrNoRows) {
listID, ok := fieldLists[value.FieldID]
if !ok {
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "missingField"})
continue
}
if fieldErr != nil {
return fieldErr
}
var itemExists bool
if err := tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM items WHERE id = $1)`, value.ItemID).Scan(&itemExists); err != nil {
return err
}
if !itemExists {
if !existingItems[value.ItemID] {
if _, err := tx.Exec(r.Context(), `
INSERT INTO items (id, listid, createdat, updatedat, isdeleted)
VALUES ($1, $2, $3, $3, 0)
@@ -194,6 +243,7 @@ func (s *Server) handleSync(w http.ResponseWriter, r *http.Request) {
orphans = append(orphans, OrphanValue{ID: value.ID, ItemID: value.ItemID, FieldID: value.FieldID, Reason: "failedCreateStubItem"})
continue
}
existingItems[value.ItemID] = true
}
if _, err := tx.Exec(r.Context(), `
INSERT INTO item_values (id, itemid, fieldid, value, updatedat)
+40 -6
View File
@@ -1,8 +1,12 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
)
@@ -71,10 +75,7 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
webLists = append(webLists, webList{List: list, EffectiveUpdatedAt: effective})
}
w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
writeJSON(w, http.StatusOK, map[string]any{
payload := map[string]any{
"lists": webLists,
"fields": fields,
"items": items,
@@ -85,8 +86,41 @@ func (s *Server) handleWebData(w http.ResponseWriter, r *http.Request) {
"items": len(items),
"values": len(values),
},
"timestamp": time.Now().UnixMilli(),
})
}
// The ETag covers the data only; the timestamp is added after hashing because
// it changes on every request.
body, err := json.Marshal(payload)
if err != nil {
writeJSONError(w, http.StatusInternalServerError, "Failed to fetch data")
return
}
digest := sha256.Sum256(body)
etag := `W/"` + hex.EncodeToString(digest[:]) + `"`
// Browsers may keep this per-user response, but revalidate it on every poll,
// so an unchanged dashboard gets a 304 instead of the full body.
w.Header().Set("Cache-Control", "private, no-cache")
w.Header().Set("ETag", etag)
if etagMatches(r.Header.Get("If-None-Match"), etag) {
w.WriteHeader(http.StatusNotModified)
return
}
payload["timestamp"] = time.Now().UnixMilli()
writeJSON(w, http.StatusOK, payload)
}
// etagMatches reports whether an If-None-Match header matches etag under the
// weak comparison of RFC 9110, which ignores the W/ prefix.
func etagMatches(ifNoneMatch, etag string) bool {
if strings.TrimSpace(ifNoneMatch) == "*" {
return true
}
want := strings.TrimPrefix(etag, "W/")
for _, candidate := range strings.Split(ifNoneMatch, ",") {
if strings.TrimPrefix(strings.TrimSpace(candidate), "W/") == want {
return true
}
}
return false
}
func (s *Server) handleNotificationPoll(w http.ResponseWriter, r *http.Request) {
+26
View File
@@ -0,0 +1,26 @@
package main
import "testing"
func TestEtagMatchesUsesWeakComparison(t *testing.T) {
const etag = `W/"abc"`
cases := []struct {
name string
ifNoneMatch string
want bool
}{
{name: "missing header", ifNoneMatch: "", want: false},
{name: "same weak tag", ifNoneMatch: `W/"abc"`, want: true},
{name: "strong form of same tag", ifNoneMatch: `"abc"`, want: true},
{name: "one of several tags", ifNoneMatch: `"x", W/"abc"`, want: true},
{name: "different tag", ifNoneMatch: `W/"def"`, want: false},
{name: "wildcard", ifNoneMatch: "*", want: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := etagMatches(tc.ifNoneMatch, etag); got != tc.want {
t.Fatalf("etagMatches(%q) = %v, want %v", tc.ifNoneMatch, got, tc.want)
}
})
}
}