diff --git a/cmd/ingestor/accounts.go b/cmd/ingestor/accounts.go index c7feeb81b..70fe966a2 100644 --- a/cmd/ingestor/accounts.go +++ b/cmd/ingestor/accounts.go @@ -403,6 +403,10 @@ func (s *Store) applyAccountWrite(ctx context.Context, cmd account.Command, l ac if err := applyLinkWrite(ctx, tx, cmd, l, nowMs); err != nil { return err } + case account.OpStationSet: + if err := applyStationEdit(ctx, tx, cmd, l, nowMs); err != nil { + return err + } default: return account.ErrInvalidCommand } diff --git a/cmd/ingestor/accounts_links.go b/cmd/ingestor/accounts_links.go index 332a08504..3f4c42055 100644 --- a/cmd/ingestor/accounts_links.go +++ b/cmd/ingestor/accounts_links.go @@ -52,7 +52,7 @@ var ( func isLinkOutcome(err error) bool { for _, e := range []error{errTooManyLinks, errTooManyAcctLinks, errTooManyNodeLinks, errTooManyLinkedNodes, errNotLinkable, errAlreadyOwner, errNodeFull, errNodeRate, errNotVerifiedOwner, errCannotObject, errTooManyObjections, errAlreadyObjected, - errObjectionNotOpen, errLinkNotActive, errRelinkTooSoon} { + errObjectionNotOpen, errLinkNotActive, errRelinkTooSoon, errNotAnOwner, errNoPosition, errTooManyEdits} { if errors.Is(err, e) { return true } @@ -192,6 +192,15 @@ func (s *Store) proveLink(ctx context.Context, proofID, pubkey, hash string, l a VALUES (?, ?, ?, 'verified', 'manual', 'active', ?, ?, ?)`, linkID, aid, pubkey, proofID, hash, nowMs); err != nil { return "", err } + if ownID != "" { + // Open objections follow the owner to the new link (review + // PR#1095 F1): proving the node by advert does not settle them, so + // they keep forcing review and an uphold removes the active link. + if _, err := tx.ExecContext(ctx, `UPDATE link_objections SET link_id = ? WHERE link_id = ? AND status = 'open'`, + linkID, ownID); err != nil { + return "", err + } + } if err := noticeOtherOwners(ctx, tx, pubkey, aid, notice{kind: account.NoticeCoOwnerAdded, linkID: linkID, tier: account.TierVerified}, nowMs); err != nil { return "", err } diff --git a/cmd/ingestor/accounts_station.go b/cmd/ingestor/accounts_station.go new file mode 100644 index 000000000..b95357620 --- /dev/null +++ b/cmd/ingestor/accounts_station.go @@ -0,0 +1,212 @@ +package main + +// Station data through owner links (#1018 M2d) — the writer side. The rules +// shared with the server are in internal/channelregistry/account +// (station.go). +// +// applyStationEdit runs inside the account write's transaction (the account +// and its session generation are checked): it finds the sender's active +// link to the node, stores the edit as node_antenna_claims rows with +// account_id, link_id and via = 'link', and decides them: +// - review (probation or an open objection): one row, the whole edit, +// proven and flagged, waiting for the administrator; +// - otherwise the edit is approved at once ('auto'; a clear-only edit +// 'owner'), except new free text: the edit with its free text kept at +// what is in force is approved, and the whole edit waits for review as +// a second row (account.ReviewClaimID), which the administrator's +// approval puts in force through the claim queue as any proven claim. +// +// Last write wins by edit time: the approved row takes a part only when no +// row in force for that part has a later (created_at, request_id); an edit +// that takes no part is superseded at once. A direct advert claim is not +// touched by any of this. + +import ( + "context" + "database/sql" + "errors" + "strings" + + "github.com/meshcore-analyzer/channelregistry/account" + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// User-facing outcomes of a station edit. +var ( + errNotAnOwner = errors.New("you are not an owner of this node") + errNoPosition = errors.New("this node has no position yet, so its station data cannot be placed: let it send an advert with its position first") + errTooManyEdits = errors.New("this node has had too many station changes today, please try again tomorrow") +) + +// applyStationEdit applies OpStationSet inside tx. A replayed command (its +// request id is stored) adds nothing. +func applyStationEdit(ctx context.Context, tx *sql.Tx, cmd account.Command, l account.Limits, nowMs int64) error { + e, pk, id := *cmd.Station, cmd.PubKey, cmd.RequestID + var n int + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM node_antenna_claims WHERE request_id = ?`, id).Scan(&n); err != nil { + return err + } + if n > 0 { + return nil + } + var linkID string + err := tx.QueryRowContext(ctx, `SELECT link_id FROM account_node_links WHERE account_id = ? AND pubkey = ? AND status = 'active'`, + cmd.AccountID, pk).Scan(&linkID) + if err == sql.ErrNoRows { + return errNotAnOwner + } + if err != nil { + return err + } + if err := tx.QueryRowContext(ctx, `SELECT COUNT(*) FROM node_antenna_claims WHERE pubkey = ? AND via = 'link' AND created_at > ?`, + pk, nowMs-dayMs).Scan(&n); err != nil { + return err + } + if n >= account.MaxStationEditsPerNodePerDay { + return errTooManyEdits + } + // The node's position now is where the values stand: the public reads + // serve them only there, and withhold them once the node moves away + // (staleMoveM), as for an advert claim's proof position. + var lat, lon sql.NullFloat64 + if err := tx.QueryRowContext(ctx, `SELECT lat, lon FROM nodes WHERE public_key = ?`, pk).Scan(&lat, &lon); err != nil && err != sql.ErrNoRows { + return err + } + if !lat.Valid || !lon.Valid || (lat.Float64 == 0 && lon.Float64 == 0) { + if !e.ClearOnly() { + return errNoPosition + } + lat, lon = sql.NullFloat64{}, sql.NullFloat64{} + } + review, err := mustReview(ctx, tx, linkID, l, nowMs) + if err != nil { + return err + } + at := cmd.CreatedAt + if at <= 0 { + at = nowMs + } + row := linkRow{pk: pk, account: cmd.AccountID, link: linkID, at: at, lat: lat, lon: lon} + if review { + return row.insert(ctx, tx, id, e, antennaclaim.StatusProven, nowMs) + } + structured, held, err := holdFreeText(ctx, tx, pk, e) + if err != nil { + return err + } + if err := row.insert(ctx, tx, id, structured, antennaclaim.StatusApproved, nowMs); err != nil { + return err + } + if err := putInForceByEditTime(ctx, tx, pk, id, at, nowMs); err != nil { + return err + } + if held { + return row.insert(ctx, tx, account.ReviewClaimID(id), e, antennaclaim.StatusProven, nowMs) + } + return nil +} + +// mustReview: the link is on probation or has an open objection. +func mustReview(ctx context.Context, tx *sql.Tx, linkID string, l account.Limits, nowMs int64) (bool, error) { + var probation, objected bool + if l.Probation > 0 { + if err := tx.QueryRowContext(ctx, account.ProbationSQL, linkID, nowMs, l.Probation.Milliseconds()).Scan(&probation); err != nil { + return false, err + } + } + if err := tx.QueryRowContext(ctx, account.ObjectedSQL, linkID).Scan(&objected); err != nil { + return false, err + } + return probation || objected, nil +} + +// holdFreeText returns e with its free text (contactPublic, a hardware +// model under "other") kept at what is in force for the node, and whether +// e changed any of it: that part waits for the administrator. Removing free +// text is no risk and applies at once. +func holdFreeText(ctx context.Context, tx *sql.Tx, pk string, e antennaclaim.Edit) (antennaclaim.Edit, bool, error) { + if e.Details == nil { + return e, false, nil + } + var contact, model sql.NullString + err := tx.QueryRowContext(ctx, `SELECT contact_public, hardware_model FROM node_antenna_claims + WHERE pubkey = ? AND status = 'approved' AND details_op = 'set' AND details_in_force = 1`, pk).Scan(&contact, &model) + if err != nil && err != sql.ErrNoRows { + return e, false, err + } + d := *e.Details + held := false + if d.ContactPublic != "" && d.ContactPublic != contact.String { + d.ContactPublic, held = contact.String, true + } + if d.HardwareModel != "" && d.HardwareModel != model.String { + d.HardwareModel, held = model.String, true + } + if !held { + return e, false, nil + } + e.Details = &d + return e, true, nil +} + +// linkRow is what every row of one link edit shares. +type linkRow struct { + pk, account, link string + at int64 + lat, lon sql.NullFloat64 +} + +// insert stores e as row id in status: approved ('owner' for a clear-only +// edit, else 'auto') or proven, flagged for the administrator's review. +// Its edit time is both created_at and proven_at, so the claim queue's +// rule for an administrator's approval (antennaclaim.NewerApprovedQuery, +// by proven_at) orders it with every other edit. +func (r linkRow) insert(ctx context.Context, tx *sql.Tx, id string, e antennaclaim.Edit, status string, nowMs int64) error { + review := status == antennaclaim.StatusProven + if err := insertClaimRow(ctx, tx, id, r.pk, "", e, review, r.at, r.at); err != nil { + return err + } + var approvedBy sql.NullString + var reviewedAt sql.NullInt64 + if !review { + by := antennaclaim.ApprovedByAuto + if e.ClearOnly() { + by = antennaclaim.ApprovedByOwner + } + approvedBy, reviewedAt = sql.NullString{String: by, Valid: true}, sql.NullInt64{Int64: nowMs, Valid: true} + } + _, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET status = ?, proven_at = ?, proof_lat = ?, proof_lon = ?, + reviewed_at = ?, approved_by = ?, via = 'link', account_id = ?, link_id = ? WHERE request_id = ?`, + status, r.at, r.lat, r.lon, reviewedAt, approvedBy, r.account, r.link, id) + return err +} + +// putInForceByEditTime runs after approved row id (edit time at) was +// stored: it takes each part it carries unless a row in force for that part +// was edited later (created_at as proven_at, then request_id), retires that +// part from the other rows, and supersedes the rows left with nothing in +// force, itself included. +func putInForceByEditTime(ctx context.Context, tx *sql.Tx, pk, id string, at, nowMs int64) error { + const newer = `SELECT EXISTS(SELECT 1 FROM node_antenna_claims WHERE pubkey = ?1 AND status = 'approved' AND request_id != ?2 + AND %s = 1 AND (proven_at > ?3 OR (proven_at = ?3 AND request_id > ?2)))` + var newerHeight, newerDetails bool + if err := tx.QueryRowContext(ctx, strings.Replace(newer, "%s", "height_in_force", 1), pk, id, at).Scan(&newerHeight); err != nil { + return err + } + if err := tx.QueryRowContext(ctx, strings.Replace(newer, "%s", "details_in_force", 1), pk, id, at).Scan(&newerDetails); err != nil { + return err + } + var takesHeight, takesDetails bool + if err := tx.QueryRowContext(ctx, `UPDATE node_antenna_claims + SET height_in_force = (height_op IS NOT NULL AND NOT ?), details_in_force = (details_op IS NOT NULL AND NOT ?) + WHERE request_id = ? RETURNING height_in_force, details_in_force`, newerHeight, newerDetails, id).Scan(&takesHeight, &takesDetails); err != nil { + return err + } + if !takesHeight && !takesDetails { + if _, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET status = 'superseded' WHERE request_id = ?`, id); err != nil { + return err + } + return dropContacts(ctx, tx, id) + } + return retireOthers(ctx, tx, pk, id, takesHeight, takesDetails, nowMs) +} diff --git a/cmd/ingestor/accounts_station_test.go b/cmd/ingestor/accounts_station_test.go new file mode 100644 index 000000000..63be2ef37 --- /dev/null +++ b/cmd/ingestor/accounts_station_test.go @@ -0,0 +1,526 @@ +package main + +import ( + "context" + "database/sql" + "fmt" + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/channelregistry/account" + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// #1018 M2d — station data through owner links, the writer side. A linked +// owner (verified or self-reported, owner decision 2026-12-02) edits the +// node's station data with no advert claim: every edit is a claim row with +// account_id, link_id and via = 'link'; the last write wins by created_at, +// then request_id; structured values apply at once; new free text waits for +// the administrator; a new co-owner's probation and an open objection send +// the whole edit to review. + +var probationOff = 0 +var probationOn = 72 + +func stationRig(t *testing.T, probation *int) *linkRig { + t.Helper() + return newLinkRig(t, &account.Config{ProbationHours: probation}) +} + +func heightEdit(h float64) *antennaclaim.Edit { return &antennaclaim.Edit{HeightM: &h} } + +func detailsEdit(d antennaclaim.StationDetails, admin string) *antennaclaim.Edit { + return &antennaclaim.Edit{Details: &antennaclaim.DetailsInput{StationDetails: d, ContactAdmin: admin}} +} + +// edit sends OpStationSet for node from aid with request id id (random +// when empty) and edit time at (the clock when 0). +func (r *linkRig) edit(aid string, node int, e *antennaclaim.Edit, id string, at int64) account.Result { + r.t.Helper() + if id == "" { + id = r.id() + } + if at == 0 { + at = r.clock.UnixMilli() + } + r.send(account.Command{RequestID: id, Op: account.OpStationSet, AccountID: aid, Gen: 1, PubKey: r.nodes[node].pk, Station: e, CreatedAt: at}) + res := r.res(id) + r.clock = r.clock.Add(time.Second) + return res +} + +func (r *linkRig) mustEdit(aid string, node int, e *antennaclaim.Edit) string { + r.t.Helper() + id := r.id() + if res := r.edit(aid, node, e, id, 0); res.Status != account.RequestDone { + r.t.Fatalf("edit by %s: %+v", aid, res) + } + return id +} + +type claimState struct { + status, approvedBy, via, account, link string + heightInForce, detailsInForce bool + contact string +} + +func (r *linkRig) stationRow(id string) claimState { + r.t.Helper() + var c claimState + var by, via, acc, link, contact sql.NullString + if err := r.store.db.QueryRow(`SELECT status, approved_by, via, account_id, link_id, height_in_force, details_in_force, contact_public + FROM node_antenna_claims WHERE request_id = ?`, id).Scan(&c.status, &by, &via, &acc, &link, &c.heightInForce, &c.detailsInForce, &contact); err != nil { + r.t.Fatalf("claim %s: %v", id, err) + } + c.approvedBy, c.via, c.account, c.link, c.contact = by.String, via.String, acc.String, link.String, contact.String + return c +} + +// heightInForce is node i's height in force, or -1. +func (r *linkRig) heightInForce(i int) float64 { + r.t.Helper() + var h float64 + err := r.store.db.QueryRow(`SELECT height_m FROM node_antenna_claims WHERE pubkey = ? AND status = 'approved' AND height_in_force = 1`, + r.nodes[i].pk).Scan(&h) + if err == sql.ErrNoRows { + return -1 + } + if err != nil { + r.t.Fatal(err) + } + return h +} + +func (r *linkRig) detailsInForce(i int) (typ, contact string) { + r.t.Helper() + var t, c sql.NullString + err := r.store.db.QueryRow(`SELECT antenna_type, contact_public FROM node_antenna_claims WHERE pubkey = ? AND status = 'approved' AND details_in_force = 1`, + r.nodes[i].pk).Scan(&t, &c) + if err != nil && err != sql.ErrNoRows { + r.t.Fatal(err) + } + return t.String, c.String +} + +// Two co-owners edit one after the other: the later edit is in force, and +// both rows stay, each naming its account and link. +func TestStation1018_LastWriteWinsAcrossCoOwners(t *testing.T) { + r := stationRig(t, &probationOff) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + r.linked(b, 0) + first := r.mustEdit(a, 0, heightEdit(10)) + if h := r.heightInForce(0); h != 10 { + t.Fatalf("after a's edit: %v", h) + } + second := r.mustEdit(b, 0, heightEdit(12)) + if h := r.heightInForce(0); h != 12 { + t.Fatalf("after b's edit: %v", h) + } + ca, cb := r.stationRow(first), r.stationRow(second) + if ca.status != antennaclaim.StatusSuperseded || cb.status != antennaclaim.StatusApproved || cb.approvedBy != antennaclaim.ApprovedByAuto { + t.Fatalf("rows %+v %+v", ca, cb) + } + if ca.via != account.ViaLink || ca.account != a || ca.link != r.linkID(a, 0) || cb.account != b || cb.link != r.linkID(b, 0) { + t.Fatalf("who: %+v %+v", ca, cb) + } + if n := r.count(`SELECT COUNT(*) FROM node_antenna_claims WHERE pubkey = ? AND via = 'link'`, r.nodes[0].pk); n != 2 { + t.Fatalf("%d link rows, want both edits kept", n) + } +} + +// An edit applied after a newer one (the queue's order is not the edit +// order) takes no part from it: last write wins by edit time. +func TestStation1018_AnOlderEditAppliedLaterLoses(t *testing.T) { + r := stationRig(t, &probationOff) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + r.linked(b, 0) + t0 := r.clock.UnixMilli() + newer := r.id() + if res := r.edit(b, 0, heightEdit(12), newer, t0+5000); res.Status != account.RequestDone { + t.Fatal(res) + } + older := r.id() + if res := r.edit(a, 0, &antennaclaim.Edit{HeightM: ptrF(10), Details: &antennaclaim.DetailsInput{StationDetails: antennaclaim.StationDetails{AntennaType: "yagi"}}}, older, t0); res.Status != account.RequestDone { + t.Fatal(res) + } + if h := r.heightInForce(0); h != 12 { + t.Fatalf("height %v, want the newer edit's 12", h) + } + // The older edit still takes the part the newer one did not carry. + if typ, _ := r.detailsInForce(0); typ != "yagi" { + t.Fatalf("details %q, want the older edit's, which nothing newer replaced", typ) + } + if c := r.stationRow(older); c.status != antennaclaim.StatusApproved || c.heightInForce || !c.detailsInForce { + t.Fatalf("older edit %+v", c) + } + // One carrying only what a newer edit holds is superseded at once. + oldest := r.id() + if res := r.edit(a, 0, heightEdit(8), oldest, t0-1000); res.Status != account.RequestDone { + t.Fatal(res) + } + if c := r.stationRow(oldest); c.status != antennaclaim.StatusSuperseded || c.heightInForce { + t.Fatalf("oldest edit %+v", c) + } + if h := r.heightInForce(0); h != 12 { + t.Fatalf("height %v", h) + } +} + +// The tie-break: two edits with the same edit time; the greater request id +// wins, whichever the ingestor applies first. +func TestStation1018_TieBreakByRequestID(t *testing.T) { + for _, order := range []string{"low first", "high first"} { + t.Run(order, func(t *testing.T) { + r := stationRig(t, &probationOff) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + r.linked(b, 0) + at := r.clock.UnixMilli() + low, high := strings.Repeat("1", 32), strings.Repeat("9", 32) + if order == "low first" { + r.edit(a, 0, heightEdit(10), low, at) + r.edit(b, 0, heightEdit(12), high, at) + } else { + r.edit(b, 0, heightEdit(12), high, at) + r.edit(a, 0, heightEdit(10), low, at) + } + if h := r.heightInForce(0); h != 12 { + t.Fatalf("height %v, want the greater request id's 12", h) + } + if c := r.stationRow(low); c.status != antennaclaim.StatusSuperseded { + t.Fatalf("low %+v", c) + } + }) + } +} + +// Owner decision 2026-12-02: a self-reported owner (the one-click admin +// login) writes structured station data like a verified one: approved at +// once, by 'auto'. +func TestStation1018_SelfReportedStructuredFieldsAutoApproved(t *testing.T) { + r := stationRig(t, nil) + a := r.acct(1) + r.heard(0, advRepeater) + if res := r.adminLogin(a, 0); res.Status != account.RequestDone { + t.Fatal(res) + } + gain, tx := 6.0, 22.0 + id := r.mustEdit(a, 0, &antennaclaim.Edit{HeightM: ptrF(18.5), Details: &antennaclaim.DetailsInput{StationDetails: antennaclaim.StationDetails{ + AntennaType: "omni", GainDBi: &gain, Hardware: "heltec-mesh-solar", TxPowerDbm: &tx, Power: []string{"mains"}, Installation: "mast"}}}) + c := r.stationRow(id) + if c.status != antennaclaim.StatusApproved || c.approvedBy != antennaclaim.ApprovedByAuto || !c.heightInForce || !c.detailsInForce { + t.Fatalf("self-reported edit %+v", c) + } + if h := r.heightInForce(0); h != 18.5 { + t.Fatalf("height %v", h) + } + // The node page reads it: a position to serve it at. + var lat sql.NullFloat64 + if err := r.store.db.QueryRow(`SELECT proof_lat FROM node_antenna_claims WHERE request_id = ?`, id).Scan(&lat); err != nil || !lat.Valid { + t.Fatalf("no position on the row: %v %v", lat, err) + } +} + +// Probation: for probationHours after joining a node that already had an +// owner, a new co-owner's edits go to review whole, whatever the tier. The +// first owner is never on probation; after the window the new one is not. +func TestStation1018_ProbationForcesReview(t *testing.T) { + for _, tier := range []string{account.TierVerified, account.TierSelfReported} { + t.Run(tier, func(t *testing.T) { + r := stationRig(t, &probationOn) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + if tier == account.TierVerified { + r.linked(b, 0) + } else if res := r.adminLogin(b, 0); res.Status != account.RequestDone { + t.Fatal(res) + } + r.mustEdit(a, 0, heightEdit(10)) + id := r.mustEdit(b, 0, heightEdit(30)) + if c := r.stationRow(id); c.status != antennaclaim.StatusProven || c.heightInForce || c.approvedBy != "" { + t.Fatalf("on probation: %+v", c) + } + if h := r.heightInForce(0); h != 10 { + t.Fatalf("height %v, want the first owner's 10 still", h) + } + if n := r.count(`SELECT needs_review FROM node_antenna_claims WHERE request_id = ?`, id); n != 1 { + t.Fatal("not flagged for review") + } + // The administrator approves it through the claim queue. + r.decide898(antennaclaim.OpApprove, id) + if h := r.heightInForce(0); h != 30 { + t.Fatalf("after approval: %v", h) + } + r.clock = r.clock.Add(time.Duration(probationOn) * time.Hour) + later := r.mustEdit(b, 0, heightEdit(31)) + if c := r.stationRow(later); c.status != antennaclaim.StatusApproved { + t.Fatalf("after probation: %+v", c) + } + }) + } +} + +// The first owner of a node, and a co-owner who joined after every earlier +// owner had left, are not on probation. Probation is on here, or nothing +// would be tested: earlier links that had ended must not count (review +// PR#1095 F4). +func TestStation1018_NoProbationWithoutAnEarlierOwner(t *testing.T) { + r := stationRig(t, &probationOn) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + if c := r.stationRow(r.mustEdit(a, 0, heightEdit(10))); c.status != antennaclaim.StatusApproved { + t.Fatalf("first owner: %+v", c) + } + // A co-owner joining later puts the first owner on no probation. + c3 := r.acct(3) + r.linked(c3, 0) + if c := r.stationRow(r.mustEdit(a, 0, heightEdit(10.5))); c.status != antennaclaim.StatusApproved { + t.Fatalf("first owner after a co-owner joined: %+v", c) + } + r.cmd(account.Command{Op: account.OpLeave, AccountID: c3, PubKey: r.nodes[0].pk}) + r.cmd(account.Command{Op: account.OpLeave, AccountID: a, PubKey: r.nodes[0].pk}) + r.linked(b, 0) + if c := r.stationRow(r.mustEdit(b, 0, heightEdit(11))); c.status != antennaclaim.StatusApproved { + t.Fatalf("after the earlier owner left: %+v", c) + } +} + +// Probation counts from when the account joined the node, not from its +// newest link: proving a self-reported link by advert (the M2a upgrade) +// does not start it again (review PR#1095 F3), and does not end it early. +func TestStation1018_ProbationSurvivesUpgrade(t *testing.T) { + r := stationRig(t, &probationOn) + a, b, c := r.acct(1), r.acct(2), r.acct(3) + r.heard(0, advRepeater) + r.linked(a, 0) + if res := r.adminLogin(b, 0); res.Status != account.RequestDone { + t.Fatal(res) + } + if res := r.adminLogin(c, 0); res.Status != account.RequestDone { + t.Fatal(res) + } + // c upgrades inside the window: still on probation, until the window + // from its first link ends. + r.linked(c, 0) + if st := r.stationRow(r.mustEdit(c, 0, heightEdit(9))); st.status != antennaclaim.StatusProven { + t.Fatalf("upgraded inside the window: %+v", st) + } + // b upgrades long after its window: no new probation. + r.clock = r.clock.Add(100 * time.Hour) + r.linked(b, 0) + if st := r.stationRow(r.mustEdit(b, 0, heightEdit(10))); st.status != antennaclaim.StatusApproved { + t.Fatalf("upgraded after the window: %+v", st) + } + if st := r.stationRow(r.mustEdit(c, 0, heightEdit(11))); st.status != antennaclaim.StatusApproved { + t.Fatalf("window from the first link over: %+v", st) + } +} + +// An open objection follows the objected owner's link when they prove it +// by advert (review PR#1095 F1): their edits still wait for review, and an +// administrator upholding the objection removes the new link. +func TestStation1018_ObjectionSurvivesUpgrade(t *testing.T) { + r := stationRig(t, &probationOff) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + if res := r.adminLogin(b, 0); res.Status != account.RequestDone { + t.Fatal(res) + } + if res := r.cmd(account.Command{Op: account.OpObject, AccountID: a, LinkID: r.linkID(b, 0), Reason: account.ObjectionDefaultPassword}); res.Status != account.RequestDone { + t.Fatalf("objection: %+v", res) + } + obj := r.objection(a, r.linkID(b, 0)) + r.linked(b, 0) // the upgrade: a new verified link + if st := r.stationRow(r.mustEdit(b, 0, heightEdit(30))); st.status != antennaclaim.StatusProven { + t.Fatalf("after the upgrade, with the objection open: %+v", st) + } + if h := r.heightInForce(0); h != -1 { + t.Fatalf("height in force %v", h) + } + if res := r.cmd(account.Command{Op: account.OpAdminObjectionDecide, ObjectionID: obj, Decision: account.ObjectionUpheld}); res.Status != account.RequestDone { + t.Fatalf("uphold: %+v", res) + } + if n := r.count(`SELECT COUNT(*) FROM account_node_links WHERE account_id = ? AND status = 'active'`, b); n != 0 { + t.Fatalf("upholding left %d active links of the objected owner", n) + } +} + +// An open objection against an owner's link sends their edits to review, +// verified or self-reported; once withdrawn, they apply again. +func TestStation1018_ObjectionForcesReview(t *testing.T) { + for _, tier := range []string{account.TierVerified, account.TierSelfReported} { + t.Run(tier, func(t *testing.T) { + r := stationRig(t, &probationOff) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + if tier == account.TierVerified { + r.linked(b, 0) + } else { + r.adminLogin(b, 0) + } + if res := r.cmd(account.Command{Op: account.OpObject, AccountID: a, LinkID: r.linkID(b, 0), Reason: account.ObjectionNotAnOwner}); res.Status != account.RequestDone { + t.Fatalf("objection: %+v", res) + } + obj := r.objection(a, r.linkID(b, 0)) + id := r.mustEdit(b, 0, heightEdit(30)) + if c := r.stationRow(id); c.status != antennaclaim.StatusProven { + t.Fatalf("with an open objection: %+v", c) + } + if h := r.heightInForce(0); h != -1 { + t.Fatalf("height in force %v", h) + } + if res := r.cmd(account.Command{Op: account.OpObjectionWithdraw, AccountID: a, ObjectionID: obj}); res.Status != account.RequestDone { + t.Fatal(res) + } + if c := r.stationRow(r.mustEdit(b, 0, heightEdit(31))); c.status != antennaclaim.StatusApproved { + t.Fatalf("after the withdrawal: %+v", c) + } + }) + } +} + +// Free text waits for the administrator for everyone (decision 7): an edit +// with a new public contact applies its structured part now and keeps the +// whole edit for review; approving it puts the contact in force. A contact +// already in force does not wait again. The admin contact stays admin-only. +func TestStation1018_FreeTextGoesToReview(t *testing.T) { + r := stationRig(t, nil) + a := r.acct(1) + r.heard(0, advRepeater) + r.linked(a, 0) + id := r.mustEdit(a, 0, detailsEdit(antennaclaim.StationDetails{AntennaType: "yagi", ContactPublic: "OZ1ABC"}, "ring me")) + review := account.ReviewClaimID(id) + if c := r.stationRow(id); c.status != antennaclaim.StatusApproved || !c.detailsInForce || c.contact != "" { + t.Fatalf("structured part %+v", c) + } + if c := r.stationRow(review); c.status != antennaclaim.StatusProven || c.contact != "OZ1ABC" || c.account != a || c.via != account.ViaLink { + t.Fatalf("review part %+v", c) + } + if typ, contact := r.detailsInForce(0); typ != "yagi" || contact != "" { + t.Fatalf("in force %q %q, want the type without the unreviewed contact", typ, contact) + } + if n := r.count(`SELECT COUNT(*) FROM node_claim_admin_contacts WHERE contact = 'ring me' AND request_id IN (?, ?)`, id, review); n != 2 { + t.Fatalf("admin contact on %d rows", n) + } + r.decide898(antennaclaim.OpApprove, review) + if typ, contact := r.detailsInForce(0); typ != "yagi" || contact != "OZ1ABC" { + t.Fatalf("after approval %q %q", typ, contact) + } + // The same contact again: nothing waits. + again := r.mustEdit(a, 0, detailsEdit(antennaclaim.StationDetails{AntennaType: "panel", ContactPublic: "OZ1ABC"}, "")) + if n := r.count(`SELECT COUNT(*) FROM node_antenna_claims WHERE request_id = ?`, account.ReviewClaimID(again)); n != 0 { + t.Fatal("an unchanged contact went to review") + } + if typ, contact := r.detailsInForce(0); typ != "panel" || contact != "OZ1ABC" { + t.Fatalf("unchanged contact: %q %q", typ, contact) + } + // A hardware model typed under "other" is free text too. + model := r.mustEdit(a, 0, detailsEdit(antennaclaim.StationDetails{Hardware: "other", HardwareModel: "Homebrew 1"}, "")) + if c := r.stationRow(account.ReviewClaimID(model)); c.status != antennaclaim.StatusProven { + t.Fatalf("model review %+v", c) + } + var hwModel sql.NullString + if err := r.store.db.QueryRow(`SELECT hardware_model FROM node_antenna_claims WHERE request_id = ?`, model).Scan(&hwModel); err != nil || hwModel.Valid { + t.Fatalf("structured part carries the model %v %v", hwModel, err) + } +} + +// Only an active owner of the node edits; a node without a position takes +// no values (only clears); a node's link edits per day are bounded; a +// replayed command adds nothing. +func TestStation1018_Refusals(t *testing.T) { + r := stationRig(t, &probationOff) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.heard(1, advRepeater) + r.linked(a, 0) + if res := r.edit(b, 0, heightEdit(10), "", 0); res.Status != account.RequestError || res.Error != errNotAnOwner.Error() { + t.Fatalf("not an owner: %+v", res) + } + if res := r.edit(a, 1, heightEdit(10), "", 0); res.Status != account.RequestError || res.Error != errNotAnOwner.Error() { + t.Fatalf("another node: %+v", res) + } + if res := r.cmd(account.Command{Op: account.OpStationSet, AccountID: a, Gen: 2, PubKey: r.nodes[0].pk, Station: heightEdit(10)}); res.Error != errSessionEnded.Error() { + t.Fatalf("old generation: %+v", res) + } + if _, err := r.store.db.Exec(`UPDATE nodes SET lat = NULL, lon = NULL WHERE public_key = ?`, r.nodes[0].pk); err != nil { + t.Fatal(err) + } + if res := r.edit(a, 0, heightEdit(10), "", 0); res.Status != account.RequestError || res.Error != errNoPosition.Error() { + t.Fatalf("no position: %+v", res) + } + if res := r.edit(a, 0, &antennaclaim.Edit{Clear: true}, "", 0); res.Status != account.RequestDone { + t.Fatalf("a clear needs no position: %+v", res) + } + if _, err := r.store.db.Exec(`UPDATE nodes SET lat = ?, lon = ? WHERE public_key = ?`, claimLat, claimLon, r.nodes[0].pk); err != nil { + t.Fatal(err) + } + // Replay: the same command applied twice is one row. + cmd := account.Command{RequestID: strings.Repeat("e", 32), Op: account.OpStationSet, AccountID: a, Gen: 1, PubKey: r.nodes[0].pk, + Station: heightEdit(15), CreatedAt: r.clock.UnixMilli()} + for i := 0; i < 2; i++ { + if err := r.store.applyAccountWrite(context.Background(), cmd, r.acc.limits, r.clock.UnixMilli()); err != nil { + t.Fatalf("apply %d: %v", i, err) + } + } + if n := r.count(`SELECT COUNT(*) FROM node_antenna_claims WHERE request_id = ?`, cmd.RequestID); n != 1 { + t.Fatalf("%d rows after a replay", n) + } + // The per-node day bound, all owners together. + for i := r.count(`SELECT COUNT(*) FROM node_antenna_claims WHERE pubkey = ? AND via = 'link'`, r.nodes[0].pk); i < account.MaxStationEditsPerNodePerDay; i++ { + if _, err := r.store.db.Exec(`INSERT INTO node_antenna_claims (request_id, pubkey, height_m, height_op, code, status, created_at, expires_at, via, account_id, link_id) + VALUES (?, ?, 1, 'set', '', 'superseded', ?, ?, 'link', ?, ?)`, fmt.Sprintf("%032x", 0xf00000+i), r.nodes[0].pk, r.clock.UnixMilli(), r.clock.UnixMilli(), a, r.linkID(a, 0)); err != nil { + t.Fatal(err) + } + } + if res := r.edit(a, 0, heightEdit(10), "", 0); res.Status != account.RequestError || res.Error != errTooManyEdits.Error() { + t.Fatalf("over the day bound: %+v", res) + } + r.clock = r.clock.Add(25 * time.Hour) + if res := r.edit(a, 0, heightEdit(10), "", 0); res.Status != account.RequestDone { + t.Fatalf("next day: %+v", res) + } +} + +// A direct advert claim is unchanged: no via, no account, no link. +func TestStation1018_AdvertClaimUnchanged(t *testing.T) { + r := stationRig(t, nil) + r.claim("1111111111111111", 12, "7KX9QM") + var via, acc sql.NullString + if err := r.store.db.QueryRow(`SELECT via, account_id FROM node_antenna_claims WHERE request_id = '1111111111111111'`).Scan(&via, &acc); err != nil { + t.Fatal(err) + } + if via.Valid || acc.Valid { + t.Fatalf("advert claim via=%v account=%v", via, acc) + } +} + +func ptrF(f float64) *float64 { return &f } + +// The default is off: a new co-owner's edit applies at once, with no +// probationHours in the config. +func TestStation1018_ProbationOffByDefault(t *testing.T) { + r := stationRig(t, nil) + a, b := r.acct(1), r.acct(2) + r.heard(0, advRepeater) + r.linked(a, 0) + r.linked(b, 0) + r.mustEdit(a, 0, heightEdit(10)) + id := r.mustEdit(b, 0, heightEdit(30)) + if c := r.stationRow(id); !c.heightInForce { + t.Fatalf("default config held a co-owner's edit: %+v", c) + } + if h := r.heightInForce(0); h != 30 { + t.Fatalf("height %v, want 30", h) + } +} diff --git a/cmd/ingestor/antenna_claims.go b/cmd/ingestor/antenna_claims.go index 71f46cf3a..ee6828f05 100644 --- a/cmd/ingestor/antenna_claims.go +++ b/cmd/ingestor/antenna_claims.go @@ -236,13 +236,21 @@ func putInForce(ctx context.Context, tx *sql.Tx, pubkey, id string, nowMs int64) WHERE request_id = ? RETURNING height_in_force, details_in_force`, id).Scan(&carriesHeight, &carriesDetails); err != nil { return err } + return retireOthers(ctx, tx, pubkey, id, carriesHeight, carriesDetails, nowMs) +} + +// retireOthers runs after claim id of pubkey took the parts it holds in +// force (height, details): every other approved claim loses those parts (a +// part replaced by details also loses its contacts), and one left with no +// part in force is superseded. +func retireOthers(ctx context.Context, tx *sql.Tx, pubkey, id string, height, details bool, nowMs int64) error { const others = ` WHERE pubkey = ? AND status = 'approved' AND request_id != ?` - if carriesHeight { + if height { if _, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET height_in_force = 0`+others+` AND height_in_force = 1`, pubkey, id); err != nil { return err } } - if carriesDetails { + if details { if _, err := tx.ExecContext(ctx, `DELETE FROM node_claim_admin_contacts WHERE request_id IN (SELECT request_id FROM node_antenna_claims`+others+` AND details_in_force = 1)`, pubkey, id); err != nil { return err @@ -301,7 +309,17 @@ func (s *Store) insertAntennaClaim(ctx context.Context, cmd antennaclaim.Command if created <= 0 { created = nowMs } - parts := cmd.Parts() + if err := insertClaimRow(ctx, tx, cmd.RequestID, cmd.PubKey, cmd.Code, cmd.Edit(), cmd.NeedsReview, created, created+l.RequestTTL.Milliseconds()); err != nil { + return "", err + } + return antennaclaim.StatusPending, tx.Commit() +} + +// insertClaimRow stores one pending claim row carrying e, and its admin +// contact, inside tx. An advert claim (insertAntennaClaim) and an owner's +// edit through a link (applyStationEdit, which then moves it on) share it. +func insertClaimRow(ctx context.Context, tx *sql.Tx, id, pubkey, code string, e antennaclaim.Edit, needsReview bool, created, expires int64) error { + parts := e.Parts() var ( d antennaclaim.DetailsInput antennaType, installation sql.NullString @@ -309,8 +327,8 @@ func (s *Store) insertAntennaClaim(ctx context.Context, cmd antennaclaim.Command hardware, hardwareModel sql.NullString powerMask sql.NullInt64 ) - if cmd.Details != nil { - d = *cmd.Details + if e.Details != nil { + d = *e.Details antennaType, installation = nullString(d.AntennaType), nullString(d.Installation) hardware, hardwareModel = nullString(d.Hardware), nullString(d.HardwareModel) contactPublic, contactAdmin = nullString(d.ContactPublic), nullString(d.ContactAdmin) @@ -324,19 +342,19 @@ func (s *Store) insertAntennaClaim(ctx context.Context, cmd antennaclaim.Command hardware, hardware_model, tx_power_dbm, cable_loss_db, azimuth_deg, beamwidth_deg, battery_wh, solar_w, code, status, needs_review, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)`, - cmd.RequestID, cmd.PubKey, cmd.HeightM, nullString(parts.Height), nullString(parts.Details), + id, pubkey, e.HeightM, nullString(parts.Height), nullString(parts.Details), antennaType, d.GainDBi, powerMask, installation, contactPublic, hardware, hardwareModel, d.TxPowerDbm, d.CableLossDb, d.AzimuthDeg, d.BeamwidthDeg, d.BatteryWh, d.SolarW, - cmd.Code, cmd.NeedsReview, created, created+l.RequestTTL.Milliseconds()); err != nil { - return "", err + code, needsReview, created, expires); err != nil { + return err } if contactAdmin.Valid { if _, err := tx.ExecContext(ctx, `INSERT INTO node_claim_admin_contacts (request_id, contact) VALUES (?, ?)`, - cmd.RequestID, contactAdmin); err != nil { - return "", err + id, contactAdmin); err != nil { + return err } } - return antennaclaim.StatusPending, tx.Commit() + return nil } func nullString(s string) sql.NullString { return sql.NullString{String: s, Valid: s != ""} } diff --git a/cmd/server/accounts.go b/cmd/server/accounts.go index eb6a4e124..2aa66ef5c 100644 --- a/cmd/server/accounts.go +++ b/cmd/server/accounts.go @@ -215,6 +215,11 @@ type accountService struct { linkOwners map[string]string // linkOwnerOrder holds linkOwners' ids oldest first, for the eviction. linkOwnerOrder []string + // stationEdits holds the queued station edits (#1018 M2d) whose "done" + // has not been answered yet: the first one drops the claim snapshots, + // so the node page shows the edit at once. Bounded (rememberStationEdit). + stationEdits map[string]bool + stationEditsOrder []string keyMu sync.Mutex key []byte @@ -234,7 +239,8 @@ func newAccountService(cfg *Config, db *sql.DB, dbPath string) *accountService { trusted = cfg.WSTrustedProxies() } svc := &accountService{limits: ac.Limits(), db: db, now: time.Now, trusted: parseCIDRListQuiet(trusted), - redeemed: map[string]int64{}, revocations: map[string]string{}, linkOwners: map[string]string{}} + redeemed: map[string]int64{}, revocations: map[string]string{}, linkOwners: map[string]string{}, + stationEdits: map[string]bool{}} svc.acctWrites = newKeyedRateLimiter(svc.limits.WritesPerHourPerAcct, time.Hour) svc.acctWrites.now = func() time.Time { return svc.now() } svc.linkCodes = newKeyedRateLimiter(svc.limits.LinkCodesPerHourPerAcct, time.Hour) @@ -635,6 +641,9 @@ func (s *Server) writeQueuedAccountStatus(w http.ResponseWriter, id string) { case queued: writeJSON(w, AccountRequestStatusResponse{Status: account.RequestQueued}) default: + if res.Status == account.RequestDone && a.takeStationEdit(id) { + s.antennaClaims().invalidateOwners() + } writeJSON(w, AccountRequestStatusResponse{Status: res.Status, Error: res.Error}) } } diff --git a/cmd/server/accounts_station.go b/cmd/server/accounts_station.go new file mode 100644 index 000000000..e11055164 --- /dev/null +++ b/cmd/server/accounts_station.go @@ -0,0 +1,319 @@ +package main + +// Station data through owner links (#1018 M2d) — the read-only server side. +// +// A signed-in owner of a repeater or room server (an active link of either +// tier) edits its station data (#1017) from the account, with no advert +// claim: POST /api/account/nodes/{pubkey}/station checks the body with the +// claim's own rules (checkEdit), the node (hidden, unknown and unpositioned +// nodes answer the claim's one 404) and the link, and queues +// account.OpStationSet. The ingestor writes and decides the claim rows +// (cmd/ingestor/accounts_station.go); the node page serves them as any +// approved claim. The write is charged to the account write windows; the +// ingestor also bounds a node's link edits per day. +// +// GET /api/account/nodes/{pubkey}/history is the change log, for the node's +// owners only: every decided claim row of the node, newest first (edit +// time, then request id), who made it ("You", "Co-owner A" in the owner +// card's order, "A former owner", or "Advert claim"), what it carried and +// its status. It never carries contactAdmin: no type it uses has a field +// for it, and the query never reads node_claim_admin_contacts. Other owners +// are never named by key, account or display name. + +import ( + "context" + "database/sql" + "log" + "net/http" + + "github.com/meshcore-analyzer/channelregistry/account" + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// Review reasons of an owner's station edits. +const ( + ReviewProbation = "probation" // a new co-owner of a node that already had an owner + ReviewObjection = "objection" // another owner objected to this owner's link +) + +// AccountStationResponse is the 202 body of a queued station edit. Review +// says why the whole edit will wait for the administrator, when it will; +// new free text (contactPublic, a hardware model) waits whatever it says. +type AccountStationResponse struct { + RequestID string `json:"requestId"` + Review string `json:"review,omitempty"` +} + +// AccountStationHistoryEntry is one change of a node's station data. +type AccountStationHistoryEntry struct { + At int64 `json:"at"` + By string `json:"by"` + Mine bool `json:"mine,omitempty"` + Via string `json:"via"` + Tier string `json:"tier,omitempty"` + HeightOp string `json:"heightOp,omitempty"` + HeightM *float64 `json:"heightM,omitempty"` + DetailsOp string `json:"detailsOp,omitempty"` + Details *antennaclaim.StationDetails `json:"details,omitempty"` + Status string `json:"status"` + InForce bool `json:"inForce"` +} + +// AccountStationHistoryResponse is GET /api/account/nodes/{pubkey}/history. +// Review and ReviewUntil say whether this account's edits wait for the +// administrator now (probation ends at ReviewUntil; an objection has no end +// date). +type AccountStationHistoryResponse struct { + PubKey string `json:"pubkey"` + Entries []AccountStationHistoryEntry `json:"entries"` + Review string `json:"review,omitempty"` + ReviewUntil *int64 `json:"reviewUntil,omitempty"` +} + +// History labels. +const ( + historyYou = "You" + historyFormerOwner = "A former owner" + historyAdvertClaim = "Advert claim" +) + +// ownedNodeLink reads {pubkey}, and answers 404 unless the account has an +// active link to it (either tier) and the node is not hidden. It returns +// the node and the account's link. +func (s *Server) ownedNodeLink(w http.ResponseWriter, r *http.Request, aid string) (pk, linkID string, ok bool) { + pk, ok = linkPubKey(w, r) + if !ok { + return "", "", false + } + a := s.accountsSvc() + var name string + err := a.db.QueryRowContext(r.Context(), `SELECT l.link_id, COALESCE(n.name, '') FROM account_node_links l + LEFT JOIN nodes n ON n.public_key = l.pubkey + WHERE l.account_id = ? AND l.pubkey = ? AND l.status = 'active'`, aid, pk).Scan(&linkID, &name) + if err == nil { + var hidden map[string][]string + if hidden, err = s.hiddenIdentityNames(r.Context(), []string{pk}); err == nil && identityHidden(s.cfg, pk, append(hidden[pk], name)...) { + err = sql.ErrNoRows + } + } + if err == sql.ErrNoRows || isMissingAccountTable(err) { + writeError(w, http.StatusNotFound, "Not found") + return "", "", false + } + if err != nil { + log.Printf("[accounts] owner check failed: %v", err) + writeError(w, http.StatusInternalServerError, "could not read the link") + return "", "", false + } + return pk, linkID, true +} + +// reviewOf is why link linkID's edits go to review now: an open objection, +// or probation (until when); "" when they apply at once. The ingestor +// decides by the same SQL. +func (a *accountService) reviewOf(ctx context.Context, linkID string) (string, *int64, error) { + var objected bool + if err := a.db.QueryRowContext(ctx, account.ObjectedSQL, linkID).Scan(&objected); err != nil { + return "", nil, err + } + if objected { + return ReviewObjection, nil, nil + } + p := a.limits.Probation.Milliseconds() + if p <= 0 { + return "", nil, nil + } + nowMs := a.now().UnixMilli() + var probation bool + if err := a.db.QueryRowContext(ctx, account.ProbationSQL, linkID, nowMs, p).Scan(&probation); err != nil { + return "", nil, err + } + if !probation { + return "", nil, nil + } + var joined int64 + if err := a.db.QueryRowContext(ctx, account.JoinedSQL, linkID).Scan(&joined); err != nil { + return "", nil, err + } + until := joined + p + return ReviewProbation, &until, nil +} + +// POST /api/account/nodes/{pubkey}/station +func (s *Server) handleAccountStation(w http.ResponseWriter, r *http.Request) { + a, c := s.accountsSvc(), s.antennaClaims() + if !a.enabled || !c.enabled { + noStore(w) + writeError(w, http.StatusForbidden, "station data is closed on this site") + return + } + review := "" + s.accountWrite(w, r, true, false, func(cmd *account.Command) bool { + var body AntennaClaimRequest + if err := decodeSingleJSONObject(http.MaxBytesReader(w, r.Body, maxClaimBodyBytes), &body); err != nil { + writeError(w, http.StatusBadRequest, "invalid request body") + return false + } + e := antennaclaim.Edit(body) + if !c.checkEdit(w, e) { + return false + } + pk, linkID, ok := s.ownedNodeLink(w, r, cmd.AccountID) + if !ok { + return false + } + // Hidden, unknown and unpositioned nodes: the claim's one 404. A + // clear-only edit needs no position (the ingestor takes it without + // one), so an owner can withdraw their data from a node that no + // longer reports one (review PR#1095 F5); ownedNodeLink has + // already refused a hidden node. + if _, ok := s.resolveTerrainEnd(r.Context(), terrainRef{pubkey: pk}); !ok && !e.ClearOnly() { + writeError(w, http.StatusNotFound, "Not found") + return false + } + var err error + if review, _, err = a.reviewOf(r.Context(), linkID); err != nil { + log.Printf("[accounts] review check failed: %v", err) + writeError(w, http.StatusInternalServerError, "could not read the link") + return false + } + cmd.Op, cmd.PubKey, cmd.Station = account.OpStationSet, pk, &e + return true + }, func(cmd account.Command) interface{} { + a.rememberStationEdit(cmd.RequestID) + return AccountStationResponse{RequestID: cmd.RequestID, Review: review} + }) +} + +// rememberStationEdit records a queued station edit. At the cap +// (linkOwnerCap) the older half is dropped: an edit nobody polls any more +// only waits for the snapshots' own expiry. +func (a *accountService) rememberStationEdit(id string) { + a.claimMu.Lock() + defer a.claimMu.Unlock() + if limit := a.linkOwnerCap(); len(a.stationEditsOrder) >= limit { + drop := len(a.stationEditsOrder) - limit/2 + for _, old := range a.stationEditsOrder[:drop] { + delete(a.stationEdits, old) + } + a.stationEditsOrder = append([]string(nil), a.stationEditsOrder[drop:]...) + } + a.stationEdits[id] = true + a.stationEditsOrder = append(a.stationEditsOrder, id) +} + +// takeStationEdit reports whether id is a remembered station edit, and +// forgets it: its "done" drops the snapshots once. +func (a *accountService) takeStationEdit(id string) bool { + a.claimMu.Lock() + defer a.claimMu.Unlock() + if !a.stationEdits[id] { + return false + } + delete(a.stationEdits, id) + return true +} + +// GET /api/account/nodes/{pubkey}/history +func (s *Server) handleAccountStationHistory(w http.ResponseWriter, r *http.Request) { + noStore(w) + sess, ok := s.requireSession(w, r) + if !ok { + return + } + aid := sess.claims.AccountID + pk, linkID, ok := s.ownedNodeLink(w, r, aid) + if !ok { + return + } + resp, err := s.readStationHistory(r.Context(), aid, pk, linkID) + if err != nil { + log.Printf("[accounts] station history failed: %v", err) + writeError(w, http.StatusInternalServerError, "could not read the change log") + return + } + writeJSON(w, resp) +} + +// readStationHistory is three indexed reads: the node's active links (for +// the co-owner labels, at most HardMaxOwnersPerNode), the link tiers of the +// edits, and the node's last MaxHistoryEntries decided claim rows. +func (s *Server) readStationHistory(ctx context.Context, aid, pk, linkID string) (AccountStationHistoryResponse, error) { + a := s.accountsSvc() + resp := AccountStationHistoryResponse{PubKey: pk, Entries: []AccountStationHistoryEntry{}} + var err error + if resp.Review, resp.ReviewUntil, err = a.reviewOf(ctx, linkID); err != nil { + return resp, err + } + // The owner card's labels: the other active owners in the order they + // joined (readLinks). + labels := map[string]string{} + rows, err := a.db.QueryContext(ctx, `SELECT link_id, account_id = ? FROM account_node_links + WHERE pubkey = ? AND status = 'active' ORDER BY created_at, link_id LIMIT ?`, aid, pk, account.HardMaxOwnersPerNode) + if err != nil { + return resp, err + } + for rows.Next() { + var id string + var mine bool + if err := rows.Scan(&id, &mine); err != nil { + rows.Close() + return resp, err + } + if !mine { + labels[id] = account.CoOwnerLabel(len(labels)) + } + } + rows.Close() + if err := rows.Err(); err != nil { + return resp, err + } + hr, err := a.db.QueryContext(ctx, `SELECT COALESCE(c.proven_at, c.created_at), c.status, COALESCE(c.via, ''), COALESCE(c.account_id, ''), + COALESCE(c.link_id, ''), COALESCE(l.tier, ''), COALESCE(c.height_op, ''), c.height_m, COALESCE(c.details_op, ''), + c.height_in_force OR c.details_in_force, + c.antenna_type, c.gain_dbi, c.power_mask, c.installation, c.contact_public, c.hardware, c.hardware_model, `+stationFieldsSQL+` + FROM node_antenna_claims c LEFT JOIN account_node_links l ON l.link_id = c.link_id + WHERE c.pubkey = ? AND c.status NOT IN ('pending', 'expired') + ORDER BY 1 DESC, c.request_id DESC LIMIT ?`, pk, account.MaxHistoryEntries) + if err != nil { + return resp, err + } + defer hr.Close() + for hr.Next() { + var ( + e AccountStationHistoryEntry + acc, link string + h, gain sql.NullFloat64 + mask sql.NullInt64 + typ, inst, contact, hw, hwModel sql.NullString + sf stationFieldsScan + ) + dest := []interface{}{&e.At, &e.Status, &e.Via, &acc, &link, &e.Tier, &e.HeightOp, &h, &e.DetailsOp, &e.InForce, + &typ, &gain, &mask, &inst, &contact, &hw, &hwModel} + if err := hr.Scan(append(dest, sf.dest()...)...); err != nil { + return resp, err + } + e.InForce = e.InForce && e.Status == antennaclaim.StatusApproved + e.HeightM = claimFloat(h) + if e.DetailsOp == antennaclaim.PartSet { + e.Details = claimDetails(typ, gain, mask, inst, contact, hw, hwModel, sf) + } + switch { + case e.Via != account.ViaLink: + e.Via, e.By, e.Tier = account.ViaAdvert, historyAdvertClaim, "" + case acc == aid: + e.By, e.Mine = historyYou, true + case labels[link] != "": + e.By = labels[link] + default: + e.By = historyFormerOwner + } + // A public contact waiting for review has not passed it (decision + // 7): only its author sees it before approval (review PR#1095 F6). + if e.Details != nil && e.Status == antennaclaim.StatusProven && !e.Mine { + e.Details.ContactPublic = "" + } + resp.Entries = append(resp.Entries, e) + } + return resp, hr.Err() +} diff --git a/cmd/server/accounts_station_1018_test.go b/cmd/server/accounts_station_1018_test.go new file mode 100644 index 000000000..a5aa27f70 --- /dev/null +++ b/cmd/server/accounts_station_1018_test.go @@ -0,0 +1,465 @@ +package main + +import ( + "encoding/json" + "net/http" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/channelregistry/account" + "github.com/meshcore-analyzer/channelregistry/antennaclaim" + "github.com/meshcore-analyzer/dbschema" +) + +// #1018 M2d — station data through owner links, the read-only server side: +// POST /api/account/nodes/{pubkey}/station queues OpStationSet for an owner +// of either tier; GET /api/account/nodes/{pubkey}/history is the change log, +// owners only, never with the administrator contact. + +func stationPath(pk string) string { return "/api/account/nodes/" + pk + "/station" } +func historyPath(pk string) string { return "/api/account/nodes/" + pk + "/history" } + +// addPlacedNode adds a node the in-memory store knows at once (the claim's +// position check reads it). +func (e *acc1018Env) addPlacedNode(pk, name string, withPos bool) { + e.t.Helper() + e.addNode(pk, name, "repeater", withPos) + if e.srv.store != nil { + e.srv.store.InvalidateNodeCache() + } +} + +// stationEnv is linksEnv with antenna claims (and station details) on. +func stationEnv(t *testing.T, mod func(*account.Config), cc *antennaclaim.Config) (*acc1018Env, string) { + t.Helper() + e, tok := linksEnv(t, mod) + e.srv.cfg.AntennaClaims = cc + // Test fixture only: the ingestor creates and writes the claim tables. + if err := dbschema.EnsureNodeAntennaClaims(e.srv.db.conn); err != nil { + t.Fatal(err) + } + svc := newAntennaClaimService(e.srv.cfg, e.srv.db.conn, filepath.Join(t.TempDir(), antennaclaim.QueueDirName)) + svc.now = func() time.Time { return e.now } + e.srv.claims = svc + return e, tok +} + +func TestStation1018_EditQueuedForAnOwner(t *testing.T) { + for _, tier := range []string{account.TierVerified, account.TierSelfReported} { + t.Run(tier, func(t *testing.T) { + e, tok := stationEnv(t, nil, detailsOn(nil)) + hill := pk789("1") + e.addPlacedNode(hill, "Hilltop", true) + e.linkFixture(lnkID(1), accAID, hill, tier, e.now.Add(-time.Hour)) + body := `{"heightM":18.5,"details":{"antennaType":"omni","gainDbi":6,"hardware":"heltec-mesh-solar","txPowerDbm":22,"contactAdmin":"ring me"}}` + w := e.req("POST", stationPath(hill), body, withCookie(tok)) + if w.Code != http.StatusAccepted { + t.Fatalf("edit: %d %s", w.Code, w.Body) + } + var got AccountStationResponse + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil || got.RequestID == "" || got.Review != "" { + t.Fatalf("response %s", w.Body) + } + c := e.lastQueued(account.OpStationSet) + if c.PubKey != hill || c.AccountID != accAID || c.Gen != 1 || c.RequestID != got.RequestID || c.Station == nil || + *c.Station.HeightM != 18.5 || c.Station.Details.AntennaType != "omni" || c.Station.Details.ContactAdmin != "ring me" || + c.Code != "" || c.CreatedAt != e.now.UnixMilli() { + t.Fatalf("queued %+v", c) + } + }) + } +} + +// Everything the claim route refuses, this route refuses the same way; a +// node the account does not own answers the claim's one 404. +func TestStation1018_EditRefusals(t *testing.T) { + e, tok := stationEnv(t, nil, detailsOn(nil)) + mine, theirs, hidden, nopos := pk789("1"), pk789("2"), pk789("3"), pk789("4") + e.addPlacedNode(mine, "Mine", true) + e.addPlacedNode(theirs, "Theirs", true) + e.addPlacedNode(hidden, "Hidden", true) + e.addPlacedNode(nopos, "Nowhere", false) + e.linkFixture(lnkID(1), accAID, mine, account.TierVerified, e.now) + e.linkFixture(lnkID(2), accAID, hidden, account.TierVerified, e.now) + e.linkFixture(lnkID(3), accAID, nopos, account.TierVerified, e.now) + e.srv.cfg.SetNodeBlacklist([]string{hidden}) + ok := `{"heightM":10}` + if w := e.req("POST", stationPath(mine), ok); w.Code != http.StatusUnauthorized { + t.Fatalf("signed out: %d", w.Code) + } + if w := e.req("POST", stationPath(mine), ok, withCookie(tok), func(r *http.Request) { r.Header.Set("Origin", "https://evil.example") }); w.Code != http.StatusForbidden { + t.Fatalf("cross-site: %d", w.Code) + } + want := e.req("POST", stationPath(pk789("9")), ok, withCookie(tok)) + if want.Code != http.StatusNotFound { + t.Fatalf("unknown node: %d", want.Code) + } + for _, pk := range []string{theirs, hidden, nopos} { + if w := e.req("POST", stationPath(pk), ok, withCookie(tok)); w.Code != http.StatusNotFound || w.Body.String() != want.Body.String() { + t.Errorf("%s…: %d %s", pk[:4], w.Code, w.Body) + } + } + for name, b := range map[string]string{ + "no part": `{}`, + "both": `{"heightM":10,"clear":true}`, + "too high": `{"heightM":100.5}`, + "bad details": `{"details":{"antennaType":"dish"}}`, + "unknown field": `{"heightM":10,"code":"7KX9QM"}`, + "not json": `height`, + } { + if w := e.req("POST", stationPath(mine), b, withCookie(tok)); w.Code != http.StatusBadRequest { + t.Errorf("%s: %d %s", name, w.Code, w.Body) + } + } + if n := e.countOp(account.OpStationSet); n != 0 { + t.Fatalf("%d queued", n) + } +} + +// A clear-only edit needs no position: an owner withdraws their data from +// a node that no longer reports one (review PR#1095 F5). A hidden node +// still answers 404, and a set still needs the position. +func TestStation1018_ClearOnlyWithoutPosition(t *testing.T) { + e, tok := stationEnv(t, nil, detailsOn(nil)) + nopos, hidden := pk789("4"), pk789("3") + e.addPlacedNode(nopos, "Nowhere", false) + e.addPlacedNode(hidden, "Hidden", false) + e.linkFixture(lnkID(1), accAID, nopos, account.TierVerified, e.now) + e.linkFixture(lnkID(2), accAID, hidden, account.TierSelfReported, e.now) + e.srv.cfg.SetNodeBlacklist([]string{hidden}) + for _, b := range []string{`{"clear":true}`, `{"clearDetails":true}`, `{"clear":true,"clearDetails":true}`} { + if w := e.req("POST", stationPath(nopos), b, withCookie(tok)); w.Code != http.StatusAccepted { + t.Fatalf("clear %s: %d %s", b, w.Code, w.Body) + } + if c := e.lastQueued(account.OpStationSet); c.PubKey != nopos || c.Station == nil || !c.Station.ClearOnly() { + t.Fatalf("queued %+v", c) + } + if w := e.req("POST", stationPath(hidden), b, withCookie(tok)); w.Code != http.StatusNotFound { + t.Fatalf("hidden, clear %s: %d", b, w.Code) + } + } + if w := e.req("POST", stationPath(nopos), `{"heightM":10,"clearDetails":true}`, withCookie(tok)); w.Code != http.StatusNotFound { + t.Fatalf("a set without a position: %d %s", w.Code, w.Body) + } + if n := e.countOp(account.OpStationSet); n != 3 { + t.Fatalf("%d queued, want 3", n) + } +} + +// The site's switches: accounts and antenna claims on, station details for +// a details part. +func TestStation1018_EditSwitches(t *testing.T) { + hill := pk789("1") + setup := func(cc *antennaclaim.Config) (*acc1018Env, string) { + e, tok := stationEnv(t, nil, cc) + e.addPlacedNode(hill, "Hilltop", true) + e.linkFixture(lnkID(1), accAID, hill, account.TierVerified, e.now) + return e, tok + } + e, tok := setup(nil) + if w := e.req("POST", stationPath(hill), `{"heightM":10}`, withCookie(tok)); w.Code != http.StatusForbidden { + t.Fatalf("claims off: %d", w.Code) + } + e, tok = setup(claimsOn(nil)) + if w := e.req("POST", stationPath(hill), `{"details":{"antennaType":"omni"}}`, withCookie(tok)); w.Code != http.StatusForbidden { + t.Fatalf("details off: %d", w.Code) + } + if w := e.req("POST", stationPath(hill), `{"heightM":10}`, withCookie(tok)); w.Code != http.StatusAccepted { + t.Fatalf("a height with details off: %d %s", w.Code, w.Body) + } + off := newAcc1018Env(t, accountAdminKey, nil) + off.addNode(hill, "N", "repeater", true) + if w := off.req("POST", stationPath(hill), `{"heightM":10}`); w.Code != http.StatusForbidden { + t.Fatalf("accounts off: %d", w.Code) + } +} + +// The answer says why the edit will wait: probation (a new co-owner of a +// node that had an owner, within probationHours) or an open objection. +func TestStation1018_EditSaysWhyItWaits(t *testing.T) { + // Probation is off by default; an operator turns it on with probationHours. + e, tok := stationEnv(t, func(c *account.Config) { on := 72; c.ProbationHours = &on }, detailsOn(nil)) + hill, solo := pk789("1"), pk789("2") + e.addPlacedNode(hill, "Hilltop", true) + e.addPlacedNode(solo, "Solo", true) + e.linkFixture(lnkID(1), accOtherAID, hill, account.TierVerified, e.now.Add(-48*time.Hour)) + e.linkFixture(lnkID(2), accAID, hill, account.TierSelfReported, e.now.Add(-time.Hour)) + e.linkFixture(lnkID(3), accAID, solo, account.TierSelfReported, e.now.Add(-time.Hour)) + review := func(pk string) string { + t.Helper() + w := e.req("POST", stationPath(pk), `{"heightM":10}`, withCookie(tok)) + if w.Code != http.StatusAccepted { + t.Fatalf("%d %s", w.Code, w.Body) + } + var got AccountStationResponse + json.Unmarshal(w.Body.Bytes(), &got) + return got.Review + } + if r := review(hill); r != ReviewProbation { + t.Fatalf("new co-owner: %q", r) + } + if r := review(solo); r != "" { + t.Fatalf("first owner: %q", r) + } + h := e.history(tok, hill) + if h.Review != ReviewProbation || h.ReviewUntil == nil || *h.ReviewUntil != e.now.Add(-time.Hour).Add(72*time.Hour).UnixMilli() { + t.Fatalf("history review %q %v", h.Review, h.ReviewUntil) + } + // An upgrade does not start probation again: it ends where the first + // link's window ends (review PR#1095 F3). + if _, err := e.srv.db.conn.Exec(`UPDATE account_node_links SET status = 'upgraded', ended_at = ?, ended_by = 'upgrade' WHERE link_id = ?`, + e.now.UnixMilli(), lnkID(2)); err != nil { + t.Fatal(err) + } + e.linkFixture(lnkID(4), accAID, hill, account.TierVerified, e.now) + if r := review(hill); r != ReviewProbation { + t.Fatalf("upgraded inside the window: %q", r) + } + if h := e.history(tok, hill); h.ReviewUntil == nil || *h.ReviewUntil != e.now.Add(-time.Hour).Add(72*time.Hour).UnixMilli() { + t.Fatalf("after the upgrade, review until %v", h.ReviewUntil) + } + e.now = e.now.Add(72 * time.Hour) + if r := review(hill); r != "" { + t.Fatalf("after probation: %q", r) + } + if _, err := e.srv.db.conn.Exec(`INSERT INTO link_objections (objection_id, link_id, by_account, reason, status, created_at) + VALUES (?, ?, ?, 'not_an_owner', 'open', ?)`, lnkID(9), lnkID(3), accOtherAID, e.now.UnixMilli()); err != nil { + t.Fatal(err) + } + if r := review(solo); r != ReviewObjection { + t.Fatalf("objected: %q", r) + } + // The default (probationHours unset) is off, and so is an explicit 0. + for name, mod := range map[string]func(*account.Config){ + "default": nil, + "zero": func(c *account.Config) { zero := 0; c.ProbationHours = &zero }, + } { + e2, tok2 := stationEnv(t, mod, detailsOn(nil)) + e2.addPlacedNode(hill, "Hilltop", true) + e2.linkFixture(lnkID(1), accOtherAID, hill, account.TierVerified, e2.now.Add(-48*time.Hour)) + e2.linkFixture(lnkID(2), accAID, hill, account.TierVerified, e2.now.Add(-time.Hour)) + if w := e2.req("POST", stationPath(hill), `{"heightM":10}`, withCookie(tok2)); !strings.Contains(w.Body.String(), `"requestId"`) || strings.Contains(w.Body.String(), "review") { + t.Fatalf("probation off (%s): %s", name, w.Body) + } + } +} + +// histRow is a claim row fixture for the change log. +type histRow struct { + id, status, via, acc, link string + at int64 + height float64 + inForce bool + contactPublic, admin string +} + +func (e *acc1018Env) histFixture(pk string, r histRow) { + e.t.Helper() + var via, acc, link interface{} + if r.via != "" { + via = r.via + } + if r.acc != "" { + acc, link = r.acc, r.link + } + detailsOp, typ, contact := interface{}(nil), interface{}(nil), interface{}(nil) + if r.contactPublic != "" { + detailsOp, typ, contact = "set", "omni", r.contactPublic + } + if _, err := e.srv.db.conn.Exec(`INSERT INTO node_antenna_claims (request_id, pubkey, height_m, height_op, details_op, antenna_type, contact_public, + code, status, created_at, expires_at, proven_at, height_in_force, via, account_id, link_id) + VALUES (?, ?, ?, 'set', ?, ?, ?, '', ?, ?, ?, ?, ?, ?, ?, ?)`, r.id, pk, r.height, detailsOp, typ, contact, r.status, r.at, r.at, r.at, + r.inForce, via, acc, link); err != nil { + e.t.Fatal(err) + } + if r.admin != "" { + if _, err := e.srv.db.conn.Exec(`INSERT INTO node_claim_admin_contacts (request_id, contact) VALUES (?, ?)`, r.id, r.admin); err != nil { + e.t.Fatal(err) + } + } +} + +func (e *acc1018Env) history(tok, pk string) AccountStationHistoryResponse { + e.t.Helper() + w := e.req("GET", historyPath(pk), "", withCookie(tok)) + if w.Code != http.StatusOK { + e.t.Fatalf("history: %d %s", w.Code, w.Body) + } + var h AccountStationHistoryResponse + if err := json.Unmarshal(w.Body.Bytes(), &h); err != nil { + e.t.Fatal(err) + } + return h +} + +// The change log lists both co-owners' edits, newest first with the +// request id breaking a tie, labels the other owners as the owner card does, +// shows an advert claim and a former owner, leaves out pending and expired +// rows, and never carries the administrator contact. +func TestStation1018_HistoryListsBothCoOwners(t *testing.T) { + e, tok := stationEnv(t, nil, detailsOn(nil)) + hill := pk789("1") + e.addPlacedNode(hill, "Hilltop", true) + third := strings.Repeat("7c", 16) + e.srv.db.conn.Exec(`INSERT INTO accounts (account_id, identity_pubkey, created_at, last_login_at) VALUES (?, ?, 1, 1)`, third, pk789("9")) + t0 := e.now.Add(-10 * time.Hour) + e.linkFixture(lnkID(1), accOtherAID, hill, account.TierVerified, t0) + e.linkFixture(lnkID(2), accAID, hill, account.TierSelfReported, t0.Add(-time.Hour)) // the viewer joined first: the labels skip them + e.linkFixture(lnkID(3), third, hill, account.TierVerified, t0.Add(2*time.Hour)) + if _, err := e.srv.db.conn.Exec(`UPDATE account_node_links SET status = 'left', ended_at = ? WHERE link_id = ?`, e.now.UnixMilli(), lnkID(3)); err != nil { + t.Fatal(err) + } + ms := e.now.UnixMilli() + e.histFixture(hill, histRow{id: "a000000000000001", status: "approved", at: ms - 5000, height: 7}) + e.histFixture(hill, histRow{id: "a000000000000002", status: "superseded", via: "link", acc: accOtherAID, link: lnkID(1), at: ms - 4000, height: 10, admin: "ZZADMINSECRET1"}) + e.histFixture(hill, histRow{id: "a000000000000003", status: "superseded", via: "link", acc: accAID, link: lnkID(2), at: ms - 3000, height: 11}) + e.histFixture(hill, histRow{id: "a000000000000005", status: "approved", via: "link", acc: accAID, link: lnkID(2), at: ms - 2000, height: 12, inForce: true, admin: "ZZADMINSECRET2"}) + e.histFixture(hill, histRow{id: "a000000000000004", status: "superseded", via: "link", acc: third, link: lnkID(3), at: ms - 2000, height: 9}) + e.histFixture(hill, histRow{id: "a000000000000006", status: "proven", via: "link", acc: accOtherAID, link: lnkID(1), at: ms - 1000, height: 13, contactPublic: "OZ1ABC", admin: "ZZADMINSECRET3"}) + e.histFixture(hill, histRow{id: "a000000000000009", status: "proven", via: "link", acc: accAID, link: lnkID(2), at: ms - 500, height: 14, contactPublic: "OZ9MINE"}) + e.histFixture(hill, histRow{id: "a000000000000007", status: "pending", at: ms, height: 99, admin: "ZZADMINSECRET4"}) + e.histFixture(hill, histRow{id: "a000000000000008", status: "expired", at: ms, height: 98}) + w := e.req("GET", historyPath(hill), "", withCookie(tok)) + if w.Code != http.StatusOK { + t.Fatalf("%d %s", w.Code, w.Body) + } + body := w.Body.String() + // "OZ1ABC" is a co-owner's public contact still waiting for review. + for _, leak := range []string{"ZZADMIN", "contactAdmin", accOtherAID, third, lnkID(1), lnkID(3), "a00000000000000", "OZ1ABC"} { + if strings.Contains(body, leak) { + t.Fatalf("history carries %q: %s", leak, body) + } + } + h := e.history(tok, hill) + type got struct { + by string + h float64 + status string + inForce bool + via string + tier string + } + var list []got + for _, x := range h.Entries { + list = append(list, got{x.By, *x.HeightM, x.Status, x.InForce, x.Via, x.Tier}) + } + want := []got{ + {"You", 14, "proven", false, "link", "self_reported"}, + {"Co-owner A", 13, "proven", false, "link", "verified"}, + {"You", 12, "approved", true, "link", "self_reported"}, + {"A former owner", 9, "superseded", false, "link", "verified"}, + {"You", 11, "superseded", false, "link", "self_reported"}, + {"Co-owner A", 10, "superseded", false, "link", "verified"}, + {"Advert claim", 7, "approved", false, "advert", ""}, + } + if !reflect.DeepEqual(list, want) { + t.Fatalf("history\n got %+v\nwant %+v", list, want) + } + if !h.Entries[2].Mine || h.Entries[1].Mine || h.Entries[1].Details == nil || h.Entries[1].Details.ContactPublic != "" { + t.Fatalf("entries %+v", h.Entries[:3]) + } + // The author sees their own contact while it waits. + if !h.Entries[0].Mine || h.Entries[0].Details == nil || h.Entries[0].Details.ContactPublic != "OZ9MINE" { + t.Fatalf("own entry %+v", h.Entries[0]) + } +} + +// Only the node's owners read it; another account and a hidden node get +// 404, a signed-out browser 401. +func TestStation1018_HistoryOwnersOnly(t *testing.T) { + e, tok := stationEnv(t, nil, detailsOn(nil)) + mine, theirs := pk789("1"), pk789("2") + e.addPlacedNode(mine, "Mine", true) + e.addPlacedNode(theirs, "Theirs", true) + e.linkFixture(lnkID(1), accAID, mine, account.TierVerified, e.now) + e.linkFixture(lnkID(2), accOtherAID, theirs, account.TierVerified, e.now) + if w := e.req("GET", historyPath(mine), ""); w.Code != http.StatusUnauthorized { + t.Fatalf("signed out: %d", w.Code) + } + if w := e.req("GET", historyPath(theirs), "", withCookie(tok)); w.Code != http.StatusNotFound { + t.Fatalf("not an owner: %d", w.Code) + } + if w := e.req("GET", historyPath("zz"), "", withCookie(tok)); w.Code != http.StatusBadRequest { + t.Fatalf("bad key: %d", w.Code) + } + e.srv.cfg.SetNodeBlacklist([]string{mine}) + if w := e.req("GET", historyPath(mine), "", withCookie(tok)); w.Code != http.StatusNotFound { + t.Fatalf("hidden: %d", w.Code) + } +} + +// Reflection: no type of the two routes can carry the administrator +// contact, nor an account id or a link id of another owner. +func TestStation1018_HistoryTypesHaveNoAdminContact(t *testing.T) { + for _, v := range []interface{}{AccountStationHistoryResponse{}, AccountStationResponse{}} { + for _, tag := range jsonTags(reflect.TypeOf(v), map[reflect.Type]bool{}) { + switch strings.ToLower(tag) { + case "contactadmin", "accountid", "linkid", "requestid": + if tag == "requestId" && reflect.TypeOf(v) == reflect.TypeOf(AccountStationResponse{}) { + continue // the edit's own request id + } + t.Errorf("%T can carry %s", v, tag) + } + } + } + // The walk must see what it is looking for. + found := false + for _, tag := range jsonTags(reflect.TypeOf(antennaclaim.DetailsInput{}), map[reflect.Type]bool{}) { + found = found || tag == "contactAdmin" + } + if !found { + t.Fatal("the walk misses DetailsInput.contactAdmin") + } +} + +// Once the ingestor applied an edit, the first "done" the owner's page +// reads drops the 30 s claim snapshots: the node page shows the new station +// data at once. Only a station edit's "done" does, and only once. +func TestStation1018_DoneShowsTheEditAtOnce(t *testing.T) { + e, tok := stationEnv(t, nil, detailsOn(nil)) + hill := pk789("1") + e.addPlacedNode(hill, "Hilltop", true) + e.linkFixture(lnkID(1), accAID, hill, account.TierVerified, e.now) + station := func() *antennaclaim.StationDetails { + t.Helper() + w := e.req("GET", "/api/nodes/"+hill+"/station", "") + var r NodeStationResponse + if w.Code != http.StatusOK || json.Unmarshal(w.Body.Bytes(), &r) != nil { + t.Fatalf("station: %d %s", w.Code, w.Body) + } + return r.Details + } + if d := station(); d != nil { + t.Fatalf("before: %+v", d) + } + w := e.req("POST", stationPath(hill), `{"details":{"antennaType":"yagi"}}`, withCookie(tok)) + var got AccountStationResponse + if w.Code != http.StatusAccepted || json.Unmarshal(w.Body.Bytes(), &got) != nil { + t.Fatalf("edit: %d %s", w.Code, w.Body) + } + // What the ingestor writes for it. + if _, err := e.srv.db.conn.Exec(`INSERT INTO node_antenna_claims (request_id, pubkey, details_op, antenna_type, code, status, created_at, expires_at, + proven_at, proof_lat, proof_lon, reviewed_at, approved_by, details_in_force, via, account_id, link_id) + VALUES (?, ?, 'set', 'yagi', '', 'approved', ?, ?, ?, 55.6761, 12.5683, ?, 'auto', 1, 'link', ?, ?)`, + got.RequestID, hill, e.now.UnixMilli(), e.now.UnixMilli(), e.now.UnixMilli(), e.now.UnixMilli(), accAID, lnkID(1)); err != nil { + t.Fatal(err) + } + if d := station(); d != nil { + t.Fatalf("the snapshot is still the old one until done is read: %+v", d) + } + if err := e.svc.queue.CompleteValue(got.RequestID, account.Result{RequestID: got.RequestID, Status: account.RequestDone}); err != nil { + t.Fatal(err) + } + if w := e.req("GET", "/api/account/requests/"+got.RequestID, ""); !strings.Contains(w.Body.String(), `"done"`) { + t.Fatalf("status %s", w.Body) + } + if d := station(); d == nil || d.AntennaType != "yagi" { + t.Fatalf("after done: %+v", d) + } + if e.svc.takeStationEdit(got.RequestID) { + t.Fatal("the edit is remembered after its done was read") + } +} diff --git a/cmd/server/antenna_claims.go b/cmd/server/antenna_claims.go index cc3c7eed3..cc7258c3d 100644 --- a/cmd/server/antenna_claims.go +++ b/cmd/server/antenna_claims.go @@ -352,7 +352,8 @@ func (c *antennaClaimService) ownerStations(ctx context.Context) map[string]owne return c.stations.get(ctx, c.now, "station details", c.readOwnerStations) } -// invalidateOwners drops the snapshots (tests). +// invalidateOwners drops the snapshots: an owner's station edit through a +// link was applied (#1018 M2d), and tests. func (c *antennaClaimService) invalidateOwners() { c.owners.invalidate() c.stations.invalidate() @@ -536,34 +537,9 @@ func (s *Server) handleAntennaClaimSubmit(w http.ResponseWriter, r *http.Request writeError(w, http.StatusBadRequest, "invalid request body") return } - if body.HeightM != nil && body.Clear { - writeError(w, http.StatusBadRequest, "give either heightM or clear:true, not both") - return - } - if body.Details != nil && body.ClearDetails { - writeError(w, http.StatusBadRequest, "give either details or clearDetails:true, not both") - return - } - if body.HeightM == nil && !body.Clear && body.Details == nil && !body.ClearDetails { - writeError(w, http.StatusBadRequest, "give heightM, clear:true, details or clearDetails:true") - return - } - if body.HeightM != nil && !antennaclaim.ValidHeight(*body.HeightM) { - writeError(w, http.StatusBadRequest, "heightM must be 0-100 m in steps of 0.1 m") + if !c.checkEdit(w, antennaclaim.Edit(body)) { return } - // Setting details needs detailsEnabled; clearing them stays open while - // claims are enabled, so an owner can always remove their data (N4). - if body.Details != nil && !c.detailsEnabled { - writeError(w, http.StatusForbidden, "station details are disabled") - return - } - if body.Details != nil { - if err := body.Details.Validate(); err != nil { - writeError(w, http.StatusBadRequest, err.Error()) - return - } - } pk := strings.ToLower(mux.Vars(r)["pubkey"]) if !antennaclaim.ValidPubKey(pk) { writeError(w, http.StatusBadRequest, "invalid public key") @@ -619,6 +595,41 @@ func (s *Server) handleAntennaClaimSubmit(w http.ResponseWriter, r *http.Request }) } +// checkEdit answers 400, or 403 for details with station details off, for +// an edit the shared rules refuse, and reports whether it passed. A claim +// and an owner's edit through a link (#1018 M2d) share it. +func (c *antennaClaimService) checkEdit(w http.ResponseWriter, e antennaclaim.Edit) bool { + if e.HeightM != nil && e.Clear { + writeError(w, http.StatusBadRequest, "give either heightM or clear:true, not both") + return false + } + if e.Details != nil && e.ClearDetails { + writeError(w, http.StatusBadRequest, "give either details or clearDetails:true, not both") + return false + } + if e.HeightM == nil && !e.Clear && e.Details == nil && !e.ClearDetails { + writeError(w, http.StatusBadRequest, "give heightM, clear:true, details or clearDetails:true") + return false + } + if e.HeightM != nil && !antennaclaim.ValidHeight(*e.HeightM) { + writeError(w, http.StatusBadRequest, "heightM must be 0-100 m in steps of 0.1 m") + return false + } + // Setting details needs detailsEnabled; clearing them stays open while + // claims are enabled, so an owner can always remove their data (N4). + if e.Details != nil && !c.detailsEnabled { + writeError(w, http.StatusForbidden, "station details are disabled") + return false + } + if e.Details != nil { + if err := e.Details.Validate(); err != nil { + writeError(w, http.StatusBadRequest, err.Error()) + return false + } + } + return true +} + // cachedSurfaceOnly is the M1 surface under node e from the estimate's // cache, never upstream; nil when unknown or the estimate is off. func (s *Server) cachedSurfaceOnly(e terrainEnd) *float64 { @@ -701,10 +712,7 @@ func scanClaim(sc interface{ Scan(...interface{}) error }, l antennaclaim.Limits r.ContactAdmin = contactAdmin.String if r.DetailsOp == antennaclaim.PartSet { // The admin sees the stored key as is, known to this server or not. - r.Details = &antennaclaim.StationDetails{AntennaType: typ.String, GainDBi: claimFloat(gain), - Power: antennaclaim.PowerList(int(mask.Int64)), Installation: inst.String, ContactPublic: contactPublic.String, - Hardware: hw.String, HardwareModel: hwModel.String} - sf.apply(r.Details) + r.Details = claimDetails(typ, gain, mask, inst, contactPublic, hw, hwModel, sf) } r.HeightM = claimFloat(h) r.ProofLat, r.ProofLon = claimFloat(plat), claimFloat(plon) @@ -717,6 +725,17 @@ func scanClaim(sc interface{ Scan(...interface{}) error }, l antennaclaim.Limits return r, nil } +// claimDetails builds a details set from a claim row's columns, as stored +// (the stored hardware key as is). It has no admin contact: StationDetails +// has no field for one. +func claimDetails(typ sql.NullString, gain sql.NullFloat64, mask sql.NullInt64, inst, contactPublic, hw, hwModel sql.NullString, sf stationFieldsScan) *antennaclaim.StationDetails { + d := &antennaclaim.StationDetails{AntennaType: typ.String, GainDBi: claimFloat(gain), + Power: antennaclaim.PowerList(int(mask.Int64)), Installation: inst.String, ContactPublic: contactPublic.String, + Hardware: hw.String, HardwareModel: hwModel.String} + sf.apply(d) + return d +} + // stationFieldsSQL are the #1017 M3 columns, in stationFieldsScan's order. const stationFieldsSQL = `tx_power_dbm, cable_loss_db, azimuth_deg, beamwidth_deg, battery_wh, solar_w` diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index 72c1b9b4b..0573c379b 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -447,6 +447,8 @@ func routeDescriptions() map[string]routeMeta { "GET /api/admin/region-scopes/requests/{id}": {Summary: "Region-scope decision status", Description: "Returns queued, approved, rejected, revoked, or error from the ingestor-owned decision queue.", Tag: "admin", Auth: true}, // Node links (#1018 M2a) "POST /api/account/links": {Summary: "Get one code to link repeaters and room servers", Description: "Body {pubkeys: [...]}: 1 to accounts.maxNodesPerCode (20) distinct keys. Returns 202 {requestId, code, expiresAt, nodes: [{pubkey, name, nameBudgetBytes, suggestedName}]}: put the code in each node's name (set name ) as a whole word within nameBudgetBytes (23 with a position, 31 without) and send an advert from each; each node is proven by its own new, signature-valid advert that is newer than the last one applied for it. The code lasts 24 hours. An unknown node, a node that is not a repeater or room server, and a hidden one all answer the same 404; 409 when the node has accounts.maxOwnersPerNode owners and none is self-reported, or the account already owns it. Bounded by accounts.linkCodesPerHourPerAccount and the account write windows (429). Same-origin JSON only (403); 401 without a session.", Tag: "account"}, + "POST /api/account/nodes/{pubkey}/station": {Summary: "Edit a linked node's station data", Description: "#1018 M2d. Body as POST /api/nodes/{pubkey}/antenna-claims (a height part {heightM} | {clear:true} and/or a details part {details} | {clearDetails:true}), with no code and no advert: the account must have an active link to the node (verified or self-reported). Returns 202 {requestId, review?}; poll GET /api/account/requests/{requestId}. Structured values apply at once; a new contactPublic or hardware model waits for the administrator; review is probation (for accounts.probationHours after joining a node that already had an owner) or objection (an open objection against the link), and then the whole edit waits. The last write wins by edit time. 403 when accounts or antenna claims are off (details: when station details are off); 404 for a node the account does not own, or a hidden, unknown or unpositioned node; 429 over the account write windows. Same-origin JSON only; 401 without a session.", Tag: "account"}, + "GET /api/account/nodes/{pubkey}/history": {Summary: "Change log of a linked node's station data", Description: "#1018 M2d, the node's owners only. {pubkey, entries: [{at, by, mine?, via: link|advert, tier?, heightOp?, heightM?, detailsOp?, details?, status, inForce}], review?, reviewUntil?}: the last 50 decided changes, newest first (edit time, then request id). by is You, Co-owner A… (the owner card's order), A former owner, or Advert claim: other owners are never named. Never carries the administrator contact. 404 for a node the account does not own or a hidden node; 401 without a session.", Tag: "account"}, "POST /api/account/admin-login-links": {Summary: "Link a node after an admin login to it", Description: "Body {pubkey, perms, fwLevel}: the browser logged in to the repeater or room server as admin through the owner's companion (the one-click flow) and reports the login answer's permissions byte (admin role required) and firmware level; never the password. The server cannot check the login, so the node is linked self-reported (method admin_login), which never counts as a verified owner. Returns 202 {requestId}; poll GET /api/account/requests/{requestId}. An unknown, hidden or non-repeater/room node answers the same 404 as a code; 409 when the account already owns the node or it has accounts.maxOwnersPerNode owners. Shares accounts.linkCodesPerHourPerAccount with the codes, on top of the account write windows (429). Same-origin JSON only (403); 401 without a session.", Tag: "account"}, "GET /api/account/links/requests/{requestId}": {Summary: "Status of a link code", Description: "Returns {status: queued|pending|error, error, expiresAt, nodes: [{pubkey, status: pending|linked|expired|refused, refusal: cap|rate}]} for the session's own link code; another account gets 404. refused: the advert came, but the node had the maximum number of owners (cap) or had gained accounts.newOwnersPerNodePerDay owners in 24 hours (rate).", Tag: "account"}, "DELETE /api/account/links/{pubkey}": {Summary: "Leave a node", Description: "Ends the account's own link to the node; the other owners are told. No owner can remove another. Returns 202 {requestId}; 404 when the account does not own the node. Never counted against the write windows. Same-origin only (403); 401 without a session.", Tag: "account"}, diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 4ea377251..00332e539 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -551,6 +551,8 @@ func (s *Server) RegisterRoutes(r *mux.Router) { r.HandleFunc("/api/account/notices/read", s.handleAccountNoticesRead).Methods("POST") r.HandleFunc("/api/account/objections", s.handleAccountObject).Methods("POST") r.HandleFunc("/api/account/objections/{id}/withdraw", s.handleAccountObjectionWithdraw).Methods("POST") + r.HandleFunc("/api/account/nodes/{pubkey}/station", s.handleAccountStation).Methods("POST") + r.HandleFunc("/api/account/nodes/{pubkey}/history", s.handleAccountStationHistory).Methods("GET") r.HandleFunc("/api/nodes/{pubkey}/owners", s.handleNodeOwners).Methods("GET") r.HandleFunc("/api/known-channels", s.handleKnownChannels).Methods("GET") r.HandleFunc("/api/observers/metrics/summary", s.handleMetricsSummary).Methods("GET") diff --git a/config.example.json b/config.example.json index 3f2e093ee..f6382f206 100644 --- a/config.example.json +++ b/config.example.json @@ -514,9 +514,10 @@ "maxNodesPerCode": 20, "maxLinkedNodes": 200, "linkCodesPerHourPerAccount": 30, - "newOwnersPerNodePerDay": 3 + "newOwnersPerNodePerDay": 3, + "probationHours": 0 }, - "_comment_accounts": "Owner accounts (#1018 M1): an owner signs in with their companion radio (no password, no e-mail) and gets a My Mesh list that follows them to every device. The page (#/account) issues a 6-character code bound to the companion's key; the owner puts it in the companion's name (appended, within the first 31 bytes, 23 when the companion shares its position) and sends a FLOOD advert. A new, signature-valid companion advert with the code proves the sign-in; repeater, room and sensor adverts never do, and a blacklisted key is refused like an unknown node. The browser then gets an HttpOnly, Secure, SameSite=Strict session cookie (__Host-mv_session): it lasts sessionDays (default 30, at most 90), is renewed on use, and never lasts past sessionMaxDays (default 90) after the sign-in; both are clamped to the 90-day hard cap. Serve the site over HTTPS (or localhost): browsers drop a Secure cookie on plain http. Sign-in opens only when enabled is true AND apiKey is strong; enabled is read by its exact spelling. The ingestor creates the signing key account-session.key (0600) next to the database when enabled is true; the server only reads it, and replacing it signs everyone out. It is not in GET /api/backup. Limits: loginCodeMinutes (default 15, at most 60) is a code's lifetime; loginsPerHour is a global sliding window on new sign-ins and loginsPerMinutePerIP a per-client one that only works behind webSocket.trustedProxies; writesPerHour is a global window on account changes and writesPerHourPerAccount the same per account (sign out everywhere and delete are never counted, so an owner can always revoke a stolen session); maxPendingLogins and maxPendingPerKey bound unproven sign-ins; maxQueuedRequests bounds the account-requests queue next to the database; maxMyNodes (default 200, at most 1000) bounds one account's list. Accounts without a sign-in for inactiveMonths (default 24, at most 120) are deleted with their list. A value out of its range is the default (sessionDays and sessionMaxDays are clamped to 90 instead). Node links (#1018 M2a): an owner links repeaters and room servers to the account with one code for up to maxNodesPerCode nodes (default 20, at most 50; also the account's waiting link codes), each proven by its own advert carrying the code; a node has at most maxOwnersPerNode owners (default 5, at most 20), a new owner never removes a verified one, and a node gains at most newOwnersPerNodePerDay owners per 24 h (default 3). The existing owners get a notice, and those linked before the new one may object to the administrator within objectionDays (default 30, at most 365). maxLinkedNodes (default 200, at most 1000) bounds one account's links and linkCodesPerHourPerAccount (default 30) its link codes per hour. Read by both server and ingestor; changes need a restart of both. Owner guide: docs/user-guide/owner-account.md.", + "_comment_accounts": "Owner accounts (#1018 M1): an owner signs in with their companion radio (no password, no e-mail) and gets a My Mesh list that follows them to every device. The page (#/account) issues a 6-character code bound to the companion's key; the owner puts it in the companion's name (appended, within the first 31 bytes, 23 when the companion shares its position) and sends a FLOOD advert. A new, signature-valid companion advert with the code proves the sign-in; repeater, room and sensor adverts never do, and a blacklisted key is refused like an unknown node. The browser then gets an HttpOnly, Secure, SameSite=Strict session cookie (__Host-mv_session): it lasts sessionDays (default 30, at most 90), is renewed on use, and never lasts past sessionMaxDays (default 90) after the sign-in; both are clamped to the 90-day hard cap. Serve the site over HTTPS (or localhost): browsers drop a Secure cookie on plain http. Sign-in opens only when enabled is true AND apiKey is strong; enabled is read by its exact spelling. The ingestor creates the signing key account-session.key (0600) next to the database when enabled is true; the server only reads it, and replacing it signs everyone out. It is not in GET /api/backup. Limits: loginCodeMinutes (default 15, at most 60) is a code's lifetime; loginsPerHour is a global sliding window on new sign-ins and loginsPerMinutePerIP a per-client one that only works behind webSocket.trustedProxies; writesPerHour is a global window on account changes and writesPerHourPerAccount the same per account (sign out everywhere and delete are never counted, so an owner can always revoke a stolen session); maxPendingLogins and maxPendingPerKey bound unproven sign-ins; maxQueuedRequests bounds the account-requests queue next to the database; maxMyNodes (default 200, at most 1000) bounds one account's list. Accounts without a sign-in for inactiveMonths (default 24, at most 120) are deleted with their list. A value out of its range is the default (sessionDays and sessionMaxDays are clamped to 90 instead). Node links (#1018 M2a): an owner links repeaters and room servers to the account with one code for up to maxNodesPerCode nodes (default 20, at most 50; also the account's waiting link codes), each proven by its own advert carrying the code; a node has at most maxOwnersPerNode owners (default 5, at most 20), a new owner never removes a verified one, and a node gains at most newOwnersPerNodePerDay owners per 24 h (default 3). The existing owners get a notice, and those linked before the new one may object to the administrator within objectionDays (default 30, at most 365). maxLinkedNodes (default 200, at most 1000) bounds one account's links and linkCodesPerHourPerAccount (default 30) its link codes per hour. Station data (#1018 M2d): a linked owner, verified or self-reported, edits the node's station data from the account with no advert claim; structured values apply at once, a new public contact or hardware model text waits for the administrator, and for probationHours (default 0, which is off; at most 720, e.g. 72 to turn it on) after joining a node that already had an owner, a new co-owner's edits all wait for the administrator when it is on, as do the edits of an owner with an open objection. Read by both server and ingestor; changes need a restart of both. Owner guide: docs/user-guide/owner-account.md.", "healthThresholds": { "infraDegradedHours": 24, "infraSilentHours": 72, diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index 869ff2cc2..ca9d68219 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -261,8 +261,9 @@ An approved height ranks below a per-node height in `radio.antennaHeightsM` and | `maxLinkedNodes` | `200` | Nodes one account owns, with its waiting link codes. At most 1000. | | `linkCodesPerHourPerAccount` | `30` | Link codes one account can ask for per hour. Leaving a node is never counted. | | `newOwnersPerNodePerDay` | `3` | Owners one node can gain in 24 hours; a proof over it is refused, so nobody fills the cap with fresh companions in one go. At most 20. | +| `probationHours` | `0` (off) | Station data through links (#1018 M2d): when set above `0` (e.g. `72`), a new co-owner's station edits wait for the administrator instead of applying at once for this many hours after joining a node that already had an owner. It protects the owners who were there first. Off by default, to keep it easy for owners. At most 720. | -A value outside its range falls back to its default, except `sessionDays` and `sessionMaxDays`, which are clamped to the 90-day cap. +A value outside its range falls back to its default, except `sessionDays` and `sessionMaxDays`, which are clamped to the 90-day cap, and `probationHours`, where `0` (the default) means off. **The session.** The cookie is `__Host-mv_session`: `HttpOnly`, `Secure`, `SameSite=Strict`, `Path=/`. Browsers drop a `Secure` cookie on plain `http://` (except `localhost`), so serve the site over HTTPS. Every change (`POST`, `DELETE`) must come from the site itself: a missing or foreign `Origin` is refused with 403. Behind a proxy that rewrites `Host`, pass `X-Forwarded-Host`. diff --git a/docs/user-guide/owner-account.md b/docs/user-guide/owner-account.md index 3095b5e6b..5b75ba340 100644 --- a/docs/user-guide/owner-account.md +++ b/docs/user-guide/owner-account.md @@ -99,6 +99,21 @@ A node can have up to 5 owners (the operator may set another limit), for a club - **Object.** If you were an owner before someone joined and do not know them, tap **Object** next to them within 30 days, choose a reason and, if you like, add a note. The note is only shown to the administrator, who decides: the co-owner is removed or kept, and you get a notice either way. - A node that already has the maximum number of owners takes no new one; a code for it is refused. A node can also gain at most 3 new owners in 24 hours. +### Station data for your nodes + +Once a node is linked to your account, you fill in its station data on the node page, with no code and no advert: + +1. On the account page, tap **Edit station data** on the node's card (or open the node page while signed in). +2. The owner section says **You own this node** and its button is **Save**. Choose **Set the height** and **Set the details**, fill in what you know: the hardware, the antenna (type, gain, direction and beamwidth for a yagi or panel), the installation, the power sources (battery and solar panel size), the TX power at the antenna port and the cable loss, and a public contact if you want one. +3. Tap **Save**. The page waits a moment until it is stored and then shows the new values in the **Station** block straight away. + +This works the same whether you linked the node with a code in its name (verified owner) or in one go with Bluetooth or USB (admin login). + +- **What waits for the administrator:** a new public contact and a hardware model typed in by hand. Everything else is used at once; the page says when something waits. The contact for the administrator is never shown publicly or to other owners. +- **A new co-owner:** probation is off unless the operator turns it on (`probationHours`, e.g. 72). When it is on, and you joined a node that already had an owner, your changes are checked by an administrator for that many hours after you joined. Proving a self-reported link later does not start it again. If another owner objects to you, your changes wait for the administrator's decision, also after you prove the node. +- **Several owners:** the newest change wins. The node page's **Change log**, which only the owners see, lists every change, who made it (*You*, *Co-owner A*, …, never a name) and whether it is in use, replaced or waiting. +- The node needs a position (it sends one in its adverts) before station data can be set. + ### What is public Nothing, unless you choose it: tick **Show "N verified owners" on the node page** on the node's card. Once at least one owner has, the node page shows how many verified owners the node has, never who they are. diff --git a/internal/channelregistry/account/account.go b/internal/channelregistry/account/account.go index 8bb3f0270..0be3acbb0 100644 --- a/internal/channelregistry/account/account.go +++ b/internal/channelregistry/account/account.go @@ -207,6 +207,8 @@ type Command struct { // M2b admin-login link: what the node's login answer reported. Perms *int `json:"perms,omitempty"` // OpLinkAdminLogin: the ACL permissions byte (admin role) FwLevel *int `json:"fwLevel,omitempty"` // OpLinkAdminLogin: FIRMWARE_VER_LEVEL, when reported + // M2d station data through a link. + Station *antennaclaim.Edit `json:"station,omitempty"` // OpStationSet // M1b signed sign-in. Challenge string `json:"challenge,omitempty"` // OpLoginSigned: the signed message Signature string `json:"signature,omitempty"` // OpLoginSigned: hex ed25519 @@ -238,6 +240,7 @@ const ( fSignature fPerms fFwLevel + fStation ) func (c Command) fields() cmdField { @@ -265,6 +268,7 @@ func (c Command) fields() cmdField { set(c.Signature != "", fSignature) set(c.Perms != nil, fPerms) set(c.FwLevel != nil, fFwLevel) + set(c.Station != nil, fStation) return f } @@ -289,6 +293,7 @@ var opFields = map[string]cmdField{ OpObjectionWithdraw: fObjectionID, OpAdminLinkRemove: fLinkID, OpAdminObjectionDecide: fObjectionID | fDecision, + OpStationSet: fPubKey | fStation, } // Validate checks c against the shared rules. The ingestor runs it again on @@ -330,6 +335,8 @@ func (c Command) Validate() error { ok = antennaclaim.ValidPubKey(c.PubKey) && c.Perms != nil && AdminPerms(*c.Perms) && validByte(c.FwLevel) case OpLinkVisibility: ok = antennaclaim.ValidPubKey(c.PubKey) && c.ShowPublic != nil + case OpStationSet: + ok = antennaclaim.ValidPubKey(c.PubKey) && validStationEdit(c.Station) case OpNoticesRead: ok = ValidAccountID(c.NoticeID) case OpObject: @@ -432,6 +439,9 @@ type Config struct { MaxLinkedNodes int `json:"maxLinkedNodes,omitempty"` LinkCodesPerHourPerAcct int `json:"linkCodesPerHourPerAccount,omitempty"` NewOwnersPerNodePerDay int `json:"newOwnersPerNodePerDay,omitempty"` + // Station data through links (#1018 M2d): a new co-owner's probation; + // unset is DefaultProbationHours (0, off); a positive value turns it on. + ProbationHours *int `json:"probationHours,omitempty"` } // Requested reports whether the operator switched accounts on. Callers must @@ -476,6 +486,8 @@ type Limits struct { MaxPendingLinksPerAcct int // one account's unproven link codes: one full code MaxPendingLinksPerNode int // one node's unproven link codes, all accounts MaxPendingLinks int // unproven link codes in all + // Station data through links (#1018 M2d). + Probation time.Duration // a new co-owner's edits go to review this long; 0 is off } // Limits resolves the configured limits. Safe on a nil *Config. @@ -513,6 +525,7 @@ func (c *Config) Limits() Limits { l.MaxPendingLinksPerAcct = l.MaxNodesPerCode l.MaxPendingLinksPerNode = MaxPendingLinksPerNode l.MaxPendingLinks = MaxPendingLinks + l.Probation = probationLimit(in.ProbationHours) return l } diff --git a/internal/channelregistry/account/links.go b/internal/channelregistry/account/links.go index 8c45fac79..4f566d81d 100644 --- a/internal/channelregistry/account/links.go +++ b/internal/channelregistry/account/links.go @@ -174,7 +174,7 @@ func SkipsWriteBudget(op string) bool { // AccountOps lists every op a signed-in account can send. func AccountOps() []string { return []string{OpLogin, OpMyNodesSet, OpMyNodeAdd, OpMyNodeRemove, OpProfileSet, OpSignOutAll, OpDelete, OpRedeem, - OpLink, OpLinkAdminLogin, OpLeave, OpLinkVisibility, OpNoticesRead, OpObject, OpObjectionWithdraw} + OpLink, OpLinkAdminLogin, OpLeave, OpLinkVisibility, OpNoticesRead, OpObject, OpObjectionWithdraw, OpStationSet} } // ValidObjectionReason accepts the fixed reasons. diff --git a/internal/channelregistry/account/links_test.go b/internal/channelregistry/account/links_test.go index 502c10a45..2e6878e00 100644 --- a/internal/channelregistry/account/links_test.go +++ b/internal/channelregistry/account/links_test.go @@ -6,6 +6,8 @@ import ( "strings" "testing" "time" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" ) // #1018 M2a — linking repeaters and room servers to accounts: the shared @@ -39,6 +41,9 @@ func lnkCmd(op string) Command { c.LinkID, c.Reason = lnkLink, ObjectionNotAnOwner case OpObjectionWithdraw: c.ObjectionID = lnkObj + case OpStationSet: + h := 12.5 + c.PubKey, c.Station = lnkPK, &antennaclaim.Edit{HeightM: &h} case OpAdminLinkRemove: c.AccountID, c.Gen, c.LinkID = "", 0, lnkLink case OpAdminObjectionDecide: diff --git a/internal/channelregistry/account/station.go b/internal/channelregistry/account/station.go new file mode 100644 index 000000000..482f19aa6 --- /dev/null +++ b/internal/channelregistry/account/station.go @@ -0,0 +1,108 @@ +package account + +// Station data through owner links (#1018 M2d). +// +// An owner linked to a repeater or room server (either tier) edits the +// node's station data (#1017: height, antenna, hardware, TX, power, …) from +// the account, with no advert claim: the server queues OpStationSet, and the +// ingestor checks the link and writes one node_antenna_claims row per edit +// with account_id, link_id and via = 'link', in one transaction. A direct +// advert claim (#789/#898) stays exactly as it was (via = 'advert' or NULL). +// +// Order: last write wins by edit time, created_at (the server's clock when +// it queued the edit), then request_id: an edit the ingestor applies after a +// newer one never takes a part from it. +// +// Approval (owner decisions 7 of 2026-11-28 and 2026-12-02): +// - structured fields from any linked owner, verified or self-reported, +// are approved at once (approved_by 'auto'; a clear-only edit 'owner'); +// - free text (a new contactPublic or a new hardware model under "other") +// waits for the administrator for everyone: the edit is split into the +// structured part, approved now, and the whole edit, waiting for review; +// - a new co-owner of a node that already had another owner is on +// probation for ProbationHours, and an owner with an open objection +// against their link waits for the administrator's decision: every edit +// of theirs goes to review whole. Both protect the owners who were there +// first, and both apply to self-reported owners exactly as to verified +// ones. + +import ( + "crypto/sha256" + "encoding/hex" + "time" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// OpStationSet edits the station data of PubKey through the sender's link. +const OpStationSet = "station-set" + +// How a claim row came: an advert claim (the code in the name) or an +// owner's edit through an account link. Older rows have NULL: an advert. +const ( + ViaAdvert = "advert" + ViaLink = "link" +) + +// Bounds of the station edits. +const ( + // DefaultProbationHours is a new co-owner's probation; MaxProbationHours + // bounds it. The default is 0 (off): owners keep it easy, and an operator + // turns the mechanism on with probationHours (e.g. 72). + DefaultProbationHours = 0 + MaxProbationHours = 720 + // MaxStationEditsPerNodePerDay bounds the claim rows link edits add for + // one node in 24 h, all owners together, on top of the account write + // windows: the table stays bounded by it and the claim retention. + MaxStationEditsPerNodePerDay = 100 + // MaxHistoryEntries bounds GET /api/account/nodes/{pubkey}/history. + MaxHistoryEntries = 50 +) + +// joinedCTE is l: link ?1's account, node and when the account joined the +// node, its first link in an unbroken chain. An upgrade (a self-reported +// link proven by advert) ends the old link at the very millisecond the new +// one is made, so it does not count as joining again (review PR#1095 F3). +const joinedCTE = `WITH l AS (SELECT n.account_id, n.pubkey, + COALESCE((SELECT MIN(p.created_at) FROM account_node_links p + WHERE p.account_id = n.account_id AND p.pubkey = n.pubkey + AND p.status = 'upgraded' AND p.ended_at = n.created_at), n.created_at) AS joined + FROM account_node_links n WHERE n.link_id = ?1) ` + +// JoinedSQL is when link ?1's account joined the node (see joinedCTE). +const JoinedSQL = joinedCTE + `SELECT joined FROM l` + +// ProbationSQL is 1 when link ?1 is on probation at ?2 (Unix ms) with a +// window of ?3 ms: its account joined the node less than the window ago, +// and another account had a link to the node, of either tier, that was made +// before it joined and had not ended then. The server shows it, the +// ingestor decides by it. +const ProbationSQL = joinedCTE + `SELECT EXISTS(SELECT 1 FROM l + JOIN account_node_links o ON o.pubkey = l.pubkey AND o.account_id != l.account_id + WHERE ?2 - l.joined < ?3 + AND o.created_at < l.joined AND (o.ended_at IS NULL OR o.ended_at > l.joined))` + +// ObjectedSQL is 1 when link ?1 has an open objection. An upgrade carries +// the open objections of the old link to the new one (review PR#1095 F1). +const ObjectedSQL = `SELECT EXISTS(SELECT 1 FROM link_objections WHERE link_id = ?1 AND status = 'open')` + +// ReviewClaimID is the id of the review row of edit requestID: the whole +// edit, when its free text waits for the administrator while its +// structured part is approved. Derived, so a replayed command finds it. +func ReviewClaimID(requestID string) string { + h := sha256.Sum256([]byte(requestID + ":review")) + return hex.EncodeToString(h[:16]) +} + +// probationLimit resolves probationHours: nil or out of range is the default +// (0, off); a value from 1 to MaxProbationHours turns probation on. +func probationLimit(p *int) time.Duration { + h := DefaultProbationHours + if p != nil && *p >= 0 && *p <= MaxProbationHours { + h = *p + } + return time.Duration(h) * time.Hour +} + +// validStationEdit accepts an edit with at least one valid part. +func validStationEdit(e *antennaclaim.Edit) bool { return e != nil && e.Validate() == nil } diff --git a/internal/channelregistry/account/station_test.go b/internal/channelregistry/account/station_test.go new file mode 100644 index 000000000..039df7080 --- /dev/null +++ b/internal/channelregistry/account/station_test.go @@ -0,0 +1,92 @@ +package account + +import ( + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// #1018 M2d — station data through links: the shared command rules. + +func TestStation1018_ValidCommand(t *testing.T) { + h := 12.5 + gain := 6.0 + for name, e := range map[string]*antennaclaim.Edit{ + "height": {HeightM: &h}, + "clear height": {Clear: true}, + "details": {Details: &antennaclaim.DetailsInput{StationDetails: antennaclaim.StationDetails{AntennaType: "omni", GainDBi: &gain}}}, + "clear details": {ClearDetails: true}, + "both": {HeightM: &h, ClearDetails: true}, + } { + c := lnkCmd(OpStationSet) + c.Station = e + if err := c.Validate(); err != nil { + t.Errorf("%s: %v", name, err) + } + } +} + +func TestStation1018_InvalidCommands(t *testing.T) { + h, bad := 12.5, 100.5 + for name, mod := range map[string]func(*Command){ + "no station": func(c *Command) { c.Station = nil }, + "no part": func(c *Command) { c.Station = &antennaclaim.Edit{} }, + "height and clear": func(c *Command) { c.Station = &antennaclaim.Edit{HeightM: &h, Clear: true} }, + "height too high": func(c *Command) { c.Station = &antennaclaim.Edit{HeightM: &bad} }, + "bad details": func(c *Command) { + c.Station = &antennaclaim.Edit{Details: &antennaclaim.DetailsInput{StationDetails: antennaclaim.StationDetails{AntennaType: "dish"}}} + }, + "details and clear": func(c *Command) { + c.Station = &antennaclaim.Edit{ClearDetails: true, Details: &antennaclaim.DetailsInput{StationDetails: antennaclaim.StationDetails{AntennaType: "omni"}}} + }, + "no pubkey": func(c *Command) { c.PubKey = "" }, + "no account": func(c *Command) { c.AccountID, c.Gen = "", 0 }, + "with a link": func(c *Command) { c.LinkID = lnkLink }, + "with a code": func(c *Command) { c.Code = "3HQ7ZB" }, + "station on a leave": func(c *Command) { + c.Op = OpLeave + }, + } { + c := lnkCmd(OpStationSet) + mod(&c) + if c.Validate() == nil { + t.Errorf("%s: accepted", name) + } + } +} + +// probationHours: unset is the default (off), 0 is off, a value in range +// turns it on, out of range is the default. +func TestStation1018_ProbationLimit(t *testing.T) { + zero, ten, huge, neg := 0, 10, MaxProbationHours+1, -1 + for _, c := range []struct { + in *int + want time.Duration + }{ + {nil, 0}, + {&zero, 0}, + {&ten, 10 * time.Hour}, + {&huge, 0}, + {&neg, 0}, + } { + if got := (&Config{ProbationHours: c.in}).Limits().Probation; got != c.want { + t.Errorf("probationHours %v: %v, want %v", c.in, got, c.want) + } + } + if DefaultProbationHours != 0 { + t.Errorf("DefaultProbationHours = %d, want 0 (off)", DefaultProbationHours) + } + if got := (*Config)(nil).Limits().Probation; got != 0 { + t.Errorf("nil config: %v", got) + } +} + +func TestStation1018_ReviewClaimID(t *testing.T) { + id := strings.Repeat("ab", 16) + r := ReviewClaimID(id) + if len(r) != 32 || r == id || ReviewClaimID(id) != r || ReviewClaimID(strings.Repeat("cd", 16)) == r { + t.Fatalf("review id %q", r) + } +} diff --git a/internal/channelregistry/antennaclaim/antennaclaim.go b/internal/channelregistry/antennaclaim/antennaclaim.go index 1619cf062..0df7991b0 100644 --- a/internal/channelregistry/antennaclaim/antennaclaim.go +++ b/internal/channelregistry/antennaclaim/antennaclaim.go @@ -287,23 +287,64 @@ const ContactLiveSQL = `(status IN ('pending','proven') OR (status = 'approved' type Parts struct{ Height, Details string } // Parts returns what c carries. -func (c Command) Parts() Parts { +func (c Command) Parts() Parts { return c.Edit().Parts() } + +// Edit is the station data one change carries: a height part (heightM or +// clear) and a details part (details or clearDetails), each optional, at +// least one. A claim carries one (Command.Edit), and so does an owner's +// edit through an account link (#1018 M2d, account.OpStationSet). +type Edit struct { + HeightM *float64 `json:"heightM,omitempty"` + Clear bool `json:"clear,omitempty"` + Details *DetailsInput `json:"details,omitempty"` + ClearDetails bool `json:"clearDetails,omitempty"` +} + +// Edit is the station data c carries. +func (c Command) Edit() Edit { + return Edit{HeightM: c.HeightM, Clear: c.Clear, Details: c.Details, ClearDetails: c.ClearDetails} +} + +// Parts is which parts e carries and how. +func (e Edit) Parts() Parts { var p Parts switch { - case c.HeightM != nil: + case e.HeightM != nil: p.Height = PartSet - case c.Clear: + case e.Clear: p.Height = PartClear } switch { - case c.Details != nil: + case e.Details != nil: p.Details = PartSet - case c.ClearDetails: + case e.ClearDetails: p.Details = PartClear } return p } +// Validate accepts at least one part, each a set or a clear but not both, +// with a valid height and valid details. +func (e Edit) Validate() error { + if (e.HeightM != nil && e.Clear) || (e.Details != nil && e.ClearDetails) || (e.Parts() == Parts{}) { + return ErrInvalidCommand + } + if e.HeightM != nil && !ValidHeight(*e.HeightM) { + return ErrInvalidCommand + } + if e.Details != nil && e.Details.Validate() != nil { + return ErrInvalidCommand + } + return nil +} + +// ClearOnly reports whether every part e carries is a clear: the owner +// withdraws their own data, which needs no position. +func (e Edit) ClearOnly() bool { + p := e.Parts() + return p.Height != PartSet && p.Details != PartSet +} + // Validate checks c against the shared rules. The ingestor runs it again on // every file it reads: it never trusts the queue. func (c Command) Validate() error { @@ -312,14 +353,7 @@ func (c Command) Validate() error { } switch c.Op { case OpClaim: - if !ValidPubKey(c.PubKey) || !ValidCode(c.Code) || (c.HeightM != nil && c.Clear) || - (c.Details != nil && c.ClearDetails) || (c.Parts() == Parts{}) { - return ErrInvalidCommand - } - if c.HeightM != nil && !ValidHeight(*c.HeightM) { - return ErrInvalidCommand - } - if c.Details != nil && c.Details.Validate() != nil { + if !ValidPubKey(c.PubKey) || !ValidCode(c.Code) || c.Edit().Validate() != nil { return ErrInvalidCommand } case OpApprove, OpReject, OpRevoke: diff --git a/internal/dbschema/antenna_claim_link_columns_test.go b/internal/dbschema/antenna_claim_link_columns_test.go new file mode 100644 index 000000000..ced53e5aa --- /dev/null +++ b/internal/dbschema/antenna_claim_link_columns_test.go @@ -0,0 +1,95 @@ +package dbschema + +import ( + "fmt" + "strings" + "testing" +) + +// #1018 M2d — node_antenna_claims says how a row came (via) and, for an +// owner's edit through an account link, which account and link: ADD COLUMN +// in the ingestor's Apply (the server stays read-only, #1283), old rows +// unchanged and read as advert claims, idempotent, CHECKs, AssertReady. + +const linkCols = "via, account_id, link_id" + +func TestAntennaClaimLinkColumns1018_MigrationKeepsOldRows(t *testing.T) { + db := pre1017ClaimsDB(t) + before := dumpClaims(t, db, pre1017Cols) + var logs []string + logf := Logger(func(f string, a ...interface{}) { logs = append(logs, fmt.Sprintf(f, a...)) }) + if err := Apply(db, logf); err != nil { + t.Fatalf("Apply: %v", err) + } + if after := dumpClaims(t, db, pre1017Cols); fmt.Sprint(after) != fmt.Sprint(before) { + t.Fatalf("old rows changed") + } + var n int + if err := db.QueryRow(`SELECT COUNT(*) FROM node_antenna_claims WHERE COALESCE(` + linkCols + `) IS NOT NULL`).Scan(&n); err != nil || n != 0 { + t.Fatalf("new columns on old rows: %d (%v)", n, err) + } + if countLogs(logs, "#1018 M2d") != 1 { + t.Fatalf("migration log lines: %v", logs) + } + if err := AssertReady(db); err != nil { + t.Fatalf("AssertReady: %v", err) + } + logs = nil + if err := Apply(db, logf); err != nil { + t.Fatal(err) + } + if countLogs(logs, "#1018 M2d") != 0 { + t.Fatalf("second Apply logged the migration: %v", logs) + } + fresh := minimalDB(t) + defer fresh.Close() + if err := EnsureNodeAntennaClaims(fresh); err != nil { + t.Fatal(err) + } + for _, c := range antennaClaimLinkColumns { + if has, err := TableHasColumn(fresh, "node_antenna_claims", c.name); err != nil || !has { + t.Fatalf("EnsureNodeAntennaClaims lacks %s (%v)", c.name, err) + } + } +} + +// Until the ingestor recorded the migration, the server is not ready: it +// reads the columns. +func TestAntennaClaimLinkColumns1018_AssertReadyNeedsThem(t *testing.T) { + db := minimalDB(t) + defer db.Close() + if err := Apply(db, nil); err != nil { + t.Fatal(err) + } + if _, err := db.Exec(`DELETE FROM _migrations WHERE name = ?`, AntennaClaimLinkMigration); err != nil { + t.Fatal(err) + } + err := AssertReady(db) + if err == nil || !strings.Contains(err.Error(), AntennaClaimLinkMigration) { + t.Fatalf("AssertReady without the M2d migration: %v", err) + } +} + +func TestAntennaClaimLinkColumns1018_Checks(t *testing.T) { + db := minimalDB(t) + defer db.Close() + if err := Apply(db, nil); err != nil { + t.Fatal(err) + } + ins := func(vals string) error { + _, err := db.Exec(`INSERT INTO node_antenna_claims (request_id, pubkey, code, status, created_at, expires_at, height_m, height_op, ` + linkCols + `) + VALUES (lower(hex(randomblob(8))), 'ab', '', 'approved', 1, 2, 10, 'set', ` + vals + `)`) + return err + } + id := "'" + strings.Repeat("a", 32) + "'" + for _, ok := range []string{"NULL, NULL, NULL", "'advert', NULL, NULL", "'link', " + id + ", " + id} { + if err := ins(ok); err != nil { + t.Errorf("refused %s: %v", ok, err) + } + } + for _, bad := range []string{"'radio', NULL, NULL", "'advert', " + id + ", NULL", "NULL, NULL, " + id, "'link', 'short', " + id} { + if err := ins(bad); err == nil { + t.Errorf("accepted %s", bad) + } + } +} diff --git a/internal/dbschema/dbschema.go b/internal/dbschema/dbschema.go index 6dc702ca4..dff2c5ffa 100644 --- a/internal/dbschema/dbschema.go +++ b/internal/dbschema/dbschema.go @@ -153,6 +153,9 @@ func Apply(rw *sql.DB, logf Logger) error { if err := ensureAntennaClaimStationFields(rw, logf); err != nil { return fmt.Errorf("ensure node_antenna_claims station fields: %w", err) } + if err := ensureAntennaClaimLinkColumns(rw, logf); err != nil { + return fmt.Errorf("ensure node_antenna_claims link columns: %w", err) + } if err := EnsureAccounts(rw); err != nil { return fmt.Errorf("ensure accounts: %w", err) } @@ -454,6 +457,17 @@ func assertReady(ro *sql.DB, probed func(item string)) error { for _, c := range antennaClaimStationFieldColumns { mustCol("node_antenna_claims", c.name) } + // #1018 M2d: who edited through an account link. + lc, err := migrationRecorded(tx, AntennaClaimLinkMigration) + if err != nil { + probeFailed(AntennaClaimLinkItem, err) + } else if !lc { + missing = append(missing, AntennaClaimLinkItem) + } else { + for _, c := range antennaClaimLinkColumns { + mustCol("node_antenna_claims", c.name) + } + } } } var partless bool @@ -1498,7 +1512,10 @@ func EnsureNodeAntennaClaims(rw *sql.DB) error { if err := ensureAntennaClaimHardware(rw, func(string, ...interface{}) {}); err != nil { return err } - return ensureAntennaClaimStationFields(rw, func(string, ...interface{}) {}) + if err := ensureAntennaClaimStationFields(rw, func(string, ...interface{}) {}); err != nil { + return err + } + return ensureAntennaClaimLinkColumns(rw, func(string, ...interface{}) {}) } // AccountTables are the owner-account tables (#1018 M1), in creation order. @@ -1795,6 +1812,37 @@ func ensureAntennaClaimStationFields(rw *sql.DB, logf Logger) error { return addAntennaClaimColumns(rw, logf, AntennaClaimStationFieldsMigration, antennaClaimStationFieldColumns, "#1017 M3 station-field") } +// AntennaClaimLinkMigration records the #1018 M2d columns: an owner's edit +// through an account link names the account and the link, and every row +// says how it came (via). +const AntennaClaimLinkMigration = "antenna_claim_link_columns_v1" + +// AntennaClaimLinkItem is AssertReady's item for a claims table the ingestor +// has not given the M2d columns yet: transient. +const AntennaClaimLinkItem = "migration:" + AntennaClaimLinkMigration + +// antennaClaimLinkColumns are the #1018 M2d columns. via is NULL on older +// rows (an advert claim); a link edit names its account and link, an advert +// claim names neither. The account and link ids are not foreign keys: the +// change log keeps an edit after its account or link is gone, as "a former +// owner". +var antennaClaimLinkColumns = []struct{ name, ddl string }{ + {"via", `via TEXT NULL CHECK(via IS NULL OR via IN ('advert','link'))`}, + {"account_id", `account_id TEXT NULL CHECK(account_id IS NULL OR (via IS 'link' AND length(account_id) = 32))`}, + {"link_id", `link_id TEXT NULL CHECK(link_id IS NULL OR (via IS 'link' AND length(link_id) = 32))`}, +} + +// ensureAntennaClaimLinkColumns adds the #1018 M2d columns and their index +// (the change log reads one node's rows; the per-node edit limit counts +// them), and records AntennaClaimLinkMigration. +func ensureAntennaClaimLinkColumns(rw *sql.DB, logf Logger) error { + if err := addAntennaClaimColumns(rw, logf, AntennaClaimLinkMigration, antennaClaimLinkColumns, "#1018 M2d link"); err != nil { + return err + } + _, err := rw.Exec(`CREATE INDEX IF NOT EXISTS idx_node_antenna_claims_pubkey_created ON node_antenna_claims(pubkey, created_at)`) + return err +} + // addAntennaClaimColumns adds cols to node_antenna_claims in one transaction // and records migration. Each column is guarded by tableHasColumn, so it is // idempotent and also repairs a table that was rebuilt under a recorded diff --git a/public/account-links.js b/public/account-links.js index b718af0ed..798f2b14d 100644 --- a/public/account-links.js +++ b/public/account-links.js @@ -289,6 +289,13 @@ li.appendChild(ul); } var actions = el('div', 'acct-actions'); + // #1018 M2d: the owner edits the station data on the node page, with + // no code and no advert. + var edit = el('a', 'btn btn-primary acct-edit-station', 'Edit station data'); + var key = encodeURIComponent(l.pubkey); // a hex key, encoded: no markup and no scheme can reach the hash link + edit.setAttribute('href', '#/nodes/' + key + '?section=node-antenna'); + edit.setAttribute('data-testid', 'account-edit-station'); + actions.appendChild(edit); if (l.tier === 'verified') { var lab = el('label', 'acct-check'); var box = el('input'); diff --git a/public/account-station.js b/public/account-station.js new file mode 100644 index 000000000..9387b0fcd --- /dev/null +++ b/public/account-station.js @@ -0,0 +1,199 @@ +/* === CoreScope — account-station.js (#1018 M2d) === */ +'use strict'; + +// Station data through owner links: an owner of a repeater or room server +// (linked to their account, verified or by admin login) edits its station +// data on the node page without a code or an advert, and sees the change +// log. The form itself is the node page's owner form (antenna-claims.js); +// this module decides whether the viewer is an owner, sends the edit, +// waits until the ingestor applied it, and renders the change log. +// +// Server contract (cmd/server/accounts_station.go): +// POST /api/account/nodes/{pubkey}/station {heightM|clear, details|clearDetails} +// → 202 {requestId, review?: probation|objection} +// 403 closed · 404 not your node / hidden / no position · 429 +// GET /api/account/requests/{id} → {status: queued|done|error, error} +// GET /api/account/nodes/{pubkey}/history → {pubkey, entries: [{at, by, mine?, via, tier?, +// heightOp?, heightM?, detailsOp?, details?, status, inForce}], review?, reviewUntil?} +// (owners only; never the administrator contact) +// +// Every server string reaches the page through textContent only. Nothing is +// stored in the browser. The pure helpers have no DOM or network access and +// are tested in Node (test-1018-m2d-station.js). + +(function (root) { + // ── Pure helpers ────────────────────────────────────────────────────── + + function fmtDate(ms) { + var d = new Date(ms); + return isFinite(d.getTime()) ? d.toLocaleString(undefined, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }) : ''; + } + + // ownerHint is the line above the owner's form. + function ownerHint(link) { + var how = link && link.tier === 'self_reported' ? 'linked by an admin login' : 'a verified owner'; + return 'You own this node (' + how + '). What you save here is used straight away: no code and no advert needed. ' + + 'A new public contact or hardware model text is checked by an administrator first.'; + } + + // reviewText says why every edit of this owner waits for the + // administrator now, or '' when they apply at once. + function reviewText(review, until) { + if (review === 'probation') { + return 'You joined a node that already had an owner, so your changes are checked by an administrator' + + (until ? ' until ' + fmtDate(until) : ' for a few days') + '. This protects the owners who were here first.'; + } + if (review === 'objection') return 'Another owner objected to your link, so your changes wait for the administrator’s decision.'; + return ''; + } + + // savedText is the line after a station edit was applied. review is the + // POST answer's; heldFreeText whether the edit carried a new public + // contact or model text (it waits for the administrator). + function savedText(review, heldFreeText) { + if (review) return { text: 'Sent to the administrator. ' + reviewText(review, null), kind: 'info' }; + if (heldFreeText) return { text: 'Saved. The public contact or model text is shown once an administrator has checked it.', kind: 'success' }; + return { text: 'Saved. The node page shows it now.', kind: 'success' }; + } + + // saveError maps a refused POST to the owner's words. + function saveError(err) { + var s = err && err.status; + if (s === 404) return 'You are not an owner of this node any more, or it has no position. Reload the page.'; + if (s === 403) return 'Station data cannot be changed on this site right now.'; + if (s === 429) return 'Too many changes right now. Please try again in a while.'; + if (s === 401) return 'You are signed out. Sign in on the Account page and try again.'; + return (err && err.message) || 'That did not work. Please try again.'; + } + + // heldFreeText: the body sets a public contact or model text other than + // the one in force (current: the /station details, or null). + function heldFreeText(body, current) { + var d = body && body.details; + if (!d) return false; + var cur = current || {}; + return (!!d.contactPublic && d.contactPublic !== (cur.contactPublic || '')) || + (!!d.hardwareModel && d.hardwareModel !== (cur.hardwareModel || '')); + } + + var STATUS = { + approved: 'In use', + superseded: 'Replaced', + proven: 'Waiting for the administrator', + rejected: 'Rejected by the administrator', + revoked: 'Withdrawn by the administrator' + }; + + // entryWhat is what one change did, in words; fmtDetails turns a details + // set into its "label value" text (AntennaClaims' wording). + function entryWhat(e, fmtDetails) { + var bits = []; + if (e.heightOp === 'set' && typeof e.heightM === 'number') bits.push('height ' + e.heightM.toFixed(1) + ' m'); + if (e.heightOp === 'clear') bits.push('height removed'); + if (e.detailsOp === 'set') { + var t = fmtDetails ? fmtDetails(e.details) : ''; + bits.push(t ? 'details: ' + t : 'details set'); + } + if (e.detailsOp === 'clear') bits.push('details removed'); + return bits.join('; '); + } + + // historyRows turns the change log into display rows. + function historyRows(entries, fmtDetails) { + return (Array.isArray(entries) ? entries : []).map(function (e) { + var status = STATUS[e.status] || e.status || ''; + if (e.status === 'approved' && !e.inForce) status = 'Replaced'; + return { + when: fmtDate(e.at), + who: String(e.by || '') + (e.tier === 'self_reported' ? ' (admin login)' : ''), + what: entryWhat(e, fmtDetails), + status: status, + inForce: !!e.inForce, + mine: !!e.mine + }; + }); + } + + // ── Network ─────────────────────────────────────────────────────────── + + function acct() { return root.Account || null; } + + // ownerLink resolves with the account's link to pubkey, or null: signed + // out, accounts off, or not an owner. No request beyond the account's + // own boot (one per page load). + function ownerLink(pubkey) { + var A = acct(); + if (!A || typeof A.boot !== 'function' || typeof A.linkFor !== 'function') return Promise.resolve(null); + return A.boot().then(function () { return A.enabled() ? A.linkFor(pubkey) : null; }, function () { return null; }); + } + + // save sends the edit and resolves once the ingestor applied it with + // {review}, or rejects with an Error whose message is for the owner. + function save(pubkey, body, isAlive) { + var A = acct(); + return A.call('POST', '/account/nodes/' + encodeURIComponent(pubkey) + '/station', body).then(function (res) { + return new Promise(function (resolve, reject) { + A.waitApplied(res && res.requestId, isAlive, function (st) { + var out = root.AccountLinks ? root.AccountLinks.writeOutcome(st) : { ok: st && st.status === 'done', error: st && st.error }; + if (out.ok) resolve({ review: res.review || '' }); + else reject(new Error(out.error || (out.unknown ? 'No answer yet. Reload the page in a moment to see whether it was saved.' : 'That did not work. Please try again.'))); + }); + }); + }, function (err) { throw new Error(saveError(err)); }); + } + + // ── Change log ──────────────────────────────────────────────────────── + + function el(tag, cls, text) { + var e = document.createElement(tag); + if (cls) e.className = cls; + if (text != null) e.textContent = text; + return e; + } + + // mountHistory fills host with the node's change log (owners only), and + // calls onReview with the review state. One request per call. + function mountHistory(host, pubkey, fmtDetails, onReview) { + if (!host) return; + var A = acct(); + A.call('GET', '/account/nodes/' + encodeURIComponent(pubkey) + '/history').then(function (h) { + if (!host.isConnected) return; + if (onReview) onReview(reviewText(h && h.review, h && h.reviewUntil)); + host.textContent = ''; + var rows = historyRows(h && h.entries, fmtDetails); + var box = el('details', 'acst-history'); + box.setAttribute('data-testid', 'acst-history'); + box.appendChild(el('summary', null, 'Change log (' + rows.length + ')')); + if (!rows.length) box.appendChild(el('p', 'text-muted', 'No changes yet.')); + var list = el('ol', 'acst-history-list'); + rows.forEach(function (r) { + var li = el('li', 'acst-entry' + (r.inForce ? ' acst-in-force' : '')); + li.setAttribute('data-testid', 'acst-entry'); + var head = el('div', 'acst-entry-head'); + head.appendChild(el('strong', null, r.who)); + head.appendChild(el('span', 'acst-when', r.when)); + head.appendChild(el('span', 'acst-status', r.status)); + li.appendChild(head); + if (r.what) li.appendChild(el('div', 'acst-what', r.what)); + list.appendChild(li); + }); + box.appendChild(list); + box.appendChild(el('p', 'ac-field-hint', 'Only the owners of this node see this. Other owners are not named; the administrator contact is never shown here.')); + host.appendChild(box); + host.hidden = false; + }, function () { /* no change log */ }); + } + + root.AccountStation = { + ownerHint: ownerHint, + reviewText: reviewText, + savedText: savedText, + saveError: saveError, + heldFreeText: heldFreeText, + entryWhat: entryWhat, + historyRows: historyRows, + ownerLink: ownerLink, + save: save, + mountHistory: mountHistory + }; +})(typeof window !== 'undefined' ? window : this); diff --git a/public/account.css b/public/account.css index e1d4492f7..73a8e375a 100644 --- a/public/account.css +++ b/public/account.css @@ -179,3 +179,4 @@ .acct-oneclick-step .acct-chip:empty { display: none; } .acct-oneclick-step[data-state="failed"] { color: var(--danger); } .acct-oneclick-guide { min-height: 44px; display: flex; align-items: center; } +.acct-edit-station { display: inline-flex; align-items: center; text-decoration: none; } diff --git a/public/account.js b/public/account.js index 5057cdda2..a4bcc8769 100644 --- a/public/account.js +++ b/public/account.js @@ -288,6 +288,32 @@ }); } + // waitApplied polls a queued write's status until the ingestor has + // applied or refused it, then calls onDone with the last status. One + // poller per write, ended when isAlive() turns false. + function waitApplied(id, isAlive, onDone) { + var AL = root.AccountLinks, AC = root.AntennaClaims; + if (!id || !AL || !AC) { onDone(null); return; } + AC.createStatusPoller({ + settings: AC.DEFAULT_SETTINGS, + isAlive: isAlive, + fetchStatus: function (rid) { return call('GET', '/account/requests/' + encodeURIComponent(rid)); }, + keepGoing: function (st) { return !AL.writeOutcome(st).done; }, + onUpdate: function (st) { if (AL.writeOutcome(st).done) onDone(st); }, + onGiveUp: function () { onDone({ status: 'timeout' }); } + }).start(id); + } + + // linkFor is the signed-in account's active link to pubkey, or null + // (#1018 M2d: the node page offers the owner's form). + function linkFor(pubkey) { + var links = state.account && state.account.links; + var pk = String(pubkey || '').toLowerCase(); + if (!Array.isArray(links)) return null; + for (var i = 0; i < links.length; i++) if (links[i] && links[i].pubkey === pk) return links[i]; + return null; + } + function linkSignature() { var AL = root.AccountLinks; if (!AL || !state.account) return ''; @@ -727,21 +753,7 @@ v.linkPoller.start(id); }, stopPoll: function () { if (v.linkPoller) v.linkPoller.cancel(); }, - // waitApplied polls a queued write's status until the ingestor has - // applied or refused it, then calls onDone with the last status. One - // poller per write, ended with the page (isAlive). - waitApplied: function (id, onDone) { - var AL = root.AccountLinks, AC = root.AntennaClaims; - if (!id) { onDone(null); return; } - AC.createStatusPoller({ - settings: AC.DEFAULT_SETTINGS, - isAlive: function () { return v.alive; }, - fetchStatus: function (rid) { return call('GET', '/account/requests/' + encodeURIComponent(rid)); }, - keepGoing: function (st) { return !AL.writeOutcome(st).done; }, - onUpdate: function (st) { if (AL.writeOutcome(st).done) onDone(st); }, - onGiveUp: function () { onDone({ status: 'timeout' }); } - }).start(id); - } + waitApplied: function (id, onDone) { waitApplied(id, function () { return v.alive; }, onDone); } }); root.AccountLinks.scrollToTab(el); } @@ -893,6 +905,9 @@ root.Account = { boot: boot, enabled: function () { return !!(state.config && state.config.enabled); }, + call: call, + waitApplied: waitApplied, + linkFor: linkFor, mountEntry: mountEntry, utf8Bytes: utf8Bytes, utf8Prefix: utf8Prefix, diff --git a/public/antenna-claims.css b/public/antenna-claims.css index 0ee341c0e..ac1ee398c 100644 --- a/public/antenna-claims.css +++ b/public/antenna-claims.css @@ -104,8 +104,9 @@ a.ac-item-name, .ac-item-proof { display: flex; align-items: center; align-self: flex-start; min-height: 44px; } .ac-item-status { flex-basis: 100%; margin-top: 0; } .ac-item-status:empty, .ac-admin-status:empty { display: none; } -/* A decision's result is scrolled into view clear of the fixed bars. */ -.ac-item-status, .ac-admin-status { +/* A decision's result, and an owner's "Saved." line, are scrolled into + view clear of the fixed bars. */ +.ac-item-status, .ac-admin-status, .ac-status { scroll-margin-top: 64px; scroll-margin-bottom: calc(12px + var(--bottom-nav-reserve, 0px)); } @@ -136,3 +137,17 @@ a.ac-item-name, .ac-item-proof { display: flex; align-items: center; align-self: form only; the admin Approve and Unlock buttons keep their look while a request is in flight, as before #898 (review PR#908 F7). */ .ac-form .ac-submit:disabled { opacity: 0.5; cursor: not-allowed; } +/* #1018 M2d — the radio and power inputs, and the owner's change log. */ +.ac-radio { border: 0; padding: 0; margin: 6px 0; min-width: 0; } +.ac-radio > .ac-label { padding: 0; } +.ac-num { width: 9em; max-width: 100%; } +.acst-review { margin: 0 0 8px; font-size: 13px; color: var(--status-amber-text); } +.acst-history-host { margin-top: 12px; } +.acst-history > summary { min-height: 44px; display: flex; align-items: center; cursor: pointer; font-weight: 600; font-size: 13px; } +.acst-history-list { list-style: none; margin: 0 0 8px; padding: 0; } +.acst-entry { border-top: 1px solid var(--border); padding: 6px 0; font-size: 13px; } +.acst-entry-head { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; } +.acst-when { color: var(--text-muted); font-size: 12px; } +.acst-status { margin-left: auto; font-size: 12px; color: var(--text-muted); } +.acst-in-force .acst-status { color: var(--status-green-text); font-weight: 600; } +.acst-what { overflow-wrap: anywhere; } diff --git a/public/antenna-claims.js b/public/antenna-claims.js index 468544364..5555d0ce1 100644 --- a/public/antenna-claims.js +++ b/public/antenna-claims.js @@ -184,7 +184,13 @@ var p = powerList(d.power); if (p) det.power = p; if (labelOf(INSTALLATIONS, d.installation)) det.installation = d.installation; - addKept(det, d.kept); + var kept = d.kept; + if (d.stationRaw) { + var sf = parseStationFields(d.stationRaw); + if (sf.error) return { error: sf.error, field: sf.field }; + kept = sf.values; + } + addKept(det, kept); if (d.hardware) { if (!validHardwareKey(d.hardware)) return { error: 'Choose the hardware from the list.', field: 'hardware' }; det.hardware = d.hardware; @@ -364,6 +370,55 @@ if (power.indexOf('solar') >= 0 && isNum(kept.solarW)) det.solarW = kept.solarW; } + // STATION_FIELDS are the form's inputs for the #1017 M3 values (#1018 + // M2d: an owner fills in everything in one sitting): [key, label, unit, + // min, max, step (0.1 or 1), example], with the bounds of + // antennaclaim.DetailsInput.Validate. A value off its grid is refused, + // never rounded, like a height; empty means "not given". + var STATION_FIELDS = [ + ['txPowerDbm', 'TX power at the antenna port', 'dBm', -9, 37, 0.1, '22'], + ['cableLossDb', 'Cable and connector loss', 'dB', 0, 20, 0.1, '1.5'], + ['azimuthDeg', 'Direction the antenna points', '\u00b0 from north', 0, 359, 1, '270'], + ['beamwidthDeg', 'Beamwidth', '\u00b0', 10, 180, 1, '60'], + ['batteryWh', 'Battery capacity', 'Wh', 0.1, 5000, 0.1, '100'], + ['solarW', 'Solar panel', 'W', 0.1, 500, 0.1, '20'] + ]; + + // parseStationFields reads the raw inputs ({txPowerDbm: '22', …}) into + // numbers: → { values } or { error, field }. A decimal comma and a minus + // sign (U+2212) are accepted. Which values are sent is addKept's rule. + function parseStationFields(raw) { + var values = {}; + raw = raw || {}; + for (var i = 0; i < STATION_FIELDS.length; i++) { + var f = STATION_FIELDS[i]; + var s = String(raw[f[0]] == null ? '' : raw[f[0]]).trim().replace(',', '.').replace(/^\u2212/, '-'); + if (!s) continue; + var whole = f[5] === 1; + var ok = whole ? /^-?[0-9]{1,4}$/.test(s) : /^-?[0-9]{1,4}(\.[0-9]+)?$/.test(s); + var unit = f[2].charAt(0) === '\u00b0' ? '\u00b0' : ' ' + f[2]; + var range = f[1] + ' must be ' + f[3] + ' to ' + f[4] + unit + (whole ? ', a whole number.' : ', in steps of 0.1.'); + if (!ok || (!whole && /\.[0-9]{2,}$/.test(s) && !/\.[0-9]0+$/.test(s))) return { error: range, field: f[0] }; + var n = whole ? Number(s) : Math.round(Number(s) * 10) / 10; + if (n === 0) n = 0; // no -0 on the wire + if (!(n >= f[3] && n <= f[4])) return { error: range, field: f[0] }; + values[f[0]] = n; + } + if (isNum(values.beamwidthDeg) && !isNum(values.azimuthDeg)) return { error: 'Give the direction too, or leave the beamwidth empty.', field: 'beamwidthDeg' }; + return { values: values }; + } + + // stationFieldsShown is which of the M3 inputs apply to the form's other + // choices: the direction and beamwidth for yagi or panel, the battery with + // power battery, the solar panel with power solar (the server's + // cross-field rules). A hidden input is not sent. + function stationFieldsShown(antennaType, power) { + var directional = antennaType === 'yagi' || antennaType === 'panel'; + power = power || {}; + return { txPowerDbm: true, cableLossDb: true, azimuthDeg: directional, beamwidthDeg: directional, + batteryWh: !!power.battery, solarW: !!power.solar }; + } + // keptValues is the admin row's text for the M3 values a claim sets. function keptValues(d) { var out = []; @@ -996,7 +1051,13 @@ // requests on a node page without it. var H = hw(); var ready = stationHardwareKey(r) && H ? H.load() : Promise.resolve(null); - return ready.then(function (entries) { if (view.alive) renderStation(station, r, entries); }); + return ready.then(function (entries) { + if (!view.alive) return; + renderStation(station, r, entries); + // The Station block above it has grown: show the "Saved." line + // again if it was pushed under the bottom nav (review PR#1095 F7). + if (view.flashLine) { reveal(view.flashLine); view.flashLine = null; } + }); }); } var body = el('div', 'ac-body'); @@ -1007,7 +1068,39 @@ body.appendChild(el('p', 'text-muted', NO_POSITION)); return; } - renderForm(body, n, view); + // An owner linked to this node through their account (#1018 M2d) + // saves without a code; everyone else gets the claim form. + var AS = root.AccountStation; + if (!AS) { renderForm(body, n, view); return; } + AS.ownerLink(n.public_key).then(function (link) { + if (!view.alive || !body.isConnected) return; + view.link = link; + renderForm(body, n, view); + if (!link) return; + var hist = el('div', 'acst-history-host'); + hist.hidden = true; + section.appendChild(hist); + var H = hw(); + (H ? H.load().then(null, function () { return null; }) : Promise.resolve(null)).then(function (entries) { + AS.mountHistory(hist, n.public_key, function (d) { return detailsText(d, entries); }, function (text) { + var line = body.querySelector('.acst-review'); + if (line) { line.textContent = text; line.hidden = !text; } + }); + }); + }); + } + + // detailsText is a details set in one line, for the owner's change log. + function detailsText(d, entries) { + if (!d) return ''; + var out = []; + var hwText = hardwareText(entries, typeof d.hardware === 'string' ? d.hardware : '', d.hardwareModel); + if (hwText) out.push(hwText); + else if (d.hardware) out.push(String(d.hardware) + (d.hardwareModel ? ' ' + String(d.hardwareModel) : '')); + detailValues(d).forEach(function (r) { out.push(r[0].toLowerCase() + ' ' + r[1]); }); + out = out.concat(keptValues(d)); + if (typeof d.contactPublic === 'string' && d.contactPublic) out.push('public contact ' + d.contactPublic); + return out.join(', '); } // radioGroup builds one fieldset of Keep/Set/Remove-style radios. It @@ -1222,6 +1315,30 @@ wrap.appendChild(powerSet); var inst = selectOf(INSTALLATIONS, 'ac-installation'); wrap.appendChild(field('Installation', inst, null, 'acInstallation')); + // The radio, direction and power values (#1017 M3), each shown only + // where the server's rules let it apply. + var radio = el('fieldset', 'ac-fieldset ac-radio'); + radio.appendChild(el('legend', 'ac-label', 'Radio and power (optional)')); + var sfInputs = {}, sfRows = {}; + STATION_FIELDS.forEach(function (f) { + var inp = textInput('ac-' + f[0], { inputmode: f[3] < 0 ? 'text' : (f[5] === 1 ? 'numeric' : 'decimal'), placeholder: f[6] }); + inp.className = 'input ac-num'; + var id = 'ac' + f[0].charAt(0).toUpperCase() + f[0].slice(1); + var row = field(f[1] + ' (' + f[2] + ')', inp, null, id); + sfInputs[f[0]] = inp; + sfRows[f[0]] = row; + radio.appendChild(row); + }); + wrap.appendChild(radio); + function syncShown() { + var ticked = {}; + POWER.forEach(function (p) { ticked[p[0]] = powerBoxes[p[0]].checked; }); + var shown = stationFieldsShown(type.value, ticked); + STATION_FIELDS.forEach(function (f) { sfRows[f[0]].hidden = !shown[f[0]]; }); + } + type.addEventListener('change', syncShown); + powerSet.addEventListener('change', syncShown); + syncShown(); var pub = textInput('ac-contact-public', { maxlength: '64' }); pub.className = 'input ac-contact'; var pubRow = field('Public contact (optional)', pub, 'Shown publicly to everyone on this node\u2019s page.', 'acContactPublic', 'Shown publicly'); @@ -1237,7 +1354,6 @@ wrap.appendChild(el('p', 'ac-field-hint ac-replace-note', 'Saving details replaces all of them: an administrator contact you leave empty is removed.')); var dirty = false; - var kept = {}; wrap.addEventListener('input', function () { dirty = true; }); wrap.addEventListener('change', function () { dirty = true; }); loadStation(n, view).then(function (r) { @@ -1249,25 +1365,42 @@ inst.value = pf.installation; pub.value = pf.contactPublic; hwp.set(pf.hardware, pf.hardwareModel); - kept = keptStationFields(r); + var kept = keptStationFields(r); + STATION_FIELDS.forEach(function (f) { + var v = kept[f[0]]; + sfInputs[f[0]].value = isNum(v) ? (f[5] === 1 ? String(v) : v.toFixed(1)) : ''; + }); + syncShown(); }); return { el: wrap, read: function () { var power = {}; POWER.forEach(function (p) { power[p[0]] = powerBoxes[p[0]].checked; }); + var shown = stationFieldsShown(type.value, power); + var stationRaw = {}; + STATION_FIELDS.forEach(function (f) { if (shown[f[0]]) stationRaw[f[0]] = sfInputs[f[0]].value; }); return Object.assign({ antennaType: type.value, gainRaw: gain.value, power: power, installation: inst.value, - contactPublic: pub.value, contactAdmin: adm.value, kept: kept }, hwp.read()); + contactPublic: pub.value, contactAdmin: adm.value, stationRaw: stationRaw }, hwp.read()); }, activate: hwp.activate, - focus: { gain: gain, contactPublic: pub, contactAdmin: adm, details: type, hardware: hwp.focus.hardware, hardwareModel: hwp.focus.hardwareModel } + focus: Object.assign({ gain: gain, contactPublic: pub, contactAdmin: adm, details: type, hardware: hwp.focus.hardware, hardwareModel: hwp.focus.hardwareModel }, sfInputs) }; } function renderForm(body, n, view) { body.textContent = ''; var details = !!view.detailsEnabled; - body.appendChild(el('p', 'ac-hint', details + var link = view.link || null; + if (link) { + var hint = el('p', 'ac-hint acst-owner-hint', root.AccountStation.ownerHint(link)); + hint.setAttribute('data-testid', 'acst-owner-hint'); + body.appendChild(hint); + var review = el('p', 'acst-review'); + review.setAttribute('data-testid', 'acst-review'); + review.hidden = true; + body.appendChild(review); + } else body.appendChild(el('p', 'ac-hint', details ? 'Own this node? Tell this site how high its antenna is and how the station is built. Terrain profiles use the height instead of an estimate; the station details are shown on this page. ' + 'You prove you control the node by putting a short code into its name and sending an advert. One code covers everything you change here.' : 'Own this node? Tell this site how high its antenna is. Terrain profiles use it instead of an estimate. ' + @@ -1305,7 +1438,7 @@ form.appendChild(detailModes.fieldset); } var actions = el('div', 'ac-row ac-submit-row'); - var submit = el('button', 'btn btn-primary ac-submit', 'Get code'); + var submit = el('button', 'btn btn-primary ac-submit', link ? 'Save' : 'Get code'); submit.type = 'submit'; submit.setAttribute('data-testid', 'ac-submit'); actions.appendChild(submit); @@ -1340,6 +1473,15 @@ heightModes.on(sync); if (detailModes) detailModes.on(sync); sync(); + if (view.flash) { + setStatus(status, view.flash); + status.setAttribute('data-testid', 'ac-form-status'); + view.flash = null; + // The section was drawn again: on a phone the line can end up under + // the bottom nav (review PR#1095 F7). + reveal(status); + view.flashLine = status; + } form.addEventListener('submit', function (e) { e.preventDefault(); var built = buildClaimBody(choice()); @@ -1350,6 +1492,7 @@ return; } var claim = built.body; + if (link) { saveAsOwner(claim); return; } submit.disabled = true; status.setAttribute('data-busy', ''); setStatus(status, { text: 'Asking for a code…', kind: 'info' }); @@ -1377,6 +1520,27 @@ setStatus(status, { text: msg, kind: 'error' }); }).then(function () { status.removeAttribute('data-busy'); if (submit.isConnected) sync(); }); }); + + // saveAsOwner sends the edit through the account link and, once the + // ingestor applied it, draws the section again: the height line, the + // Station block and the change log then show the new values. + function saveAsOwner(claim) { + var AS = root.AccountStation; + submit.disabled = true; + status.setAttribute('data-busy', ''); + setStatus(status, { text: 'Saving\u2026', kind: 'info' }); + loadStation(n, view).then(function (r) { + var held = AS.heldFreeText(claim, r && !r.stale ? r.details : null); + return AS.save(n.public_key, claim, function () { return view.alive; }).then(function (res) { + if (!view.alive) return; + view.station = null; + view.flash = AS.savedText(res.review, held); + renderOwnerSection(view.section, n, view); + }); + }).then(null, function (err) { + if (view.alive && status.isConnected) setStatus(status, { text: err.message, kind: 'error' }); + }).then(function () { status.removeAttribute('data-busy'); if (submit.isConnected) sync(); }); + } } function renderClaim(body, n, view, id, info) { @@ -1813,6 +1977,9 @@ compassPoint: compassPoint, stationPrefill: stationPrefill, keptStationFields: keptStationFields, + parseStationFields: parseStationFields, + stationFieldsShown: stationFieldsShown, + STATION_FIELDS: STATION_FIELDS, stationHardwareKey: stationHardwareKey, checkHardwareModel: checkHardwareModel, adminNeedsHardware: adminNeedsHardware, diff --git a/public/index.html b/public/index.html index 36efbb006..d0e0d607d 100644 --- a/public/index.html +++ b/public/index.html @@ -327,6 +327,7 @@ + diff --git a/scripts/e2e-shards.json b/scripts/e2e-shards.json index 6a736227e..f47105d8c 100644 --- a/scripts/e2e-shards.json +++ b/scripts/e2e-shards.json @@ -310,6 +310,7 @@ {"file":"test-issue-1599-replay-freeze-e2e.js","shard":3,"env":{"CHROMIUM_REQUIRE":"1","BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":4.097,"secondsByExecution":[3.76,4.546,4.364,4.461,3.678,3.773]}, {"file":"test-issue-1657-analytics-channels-group-sprites-e2e.js","shard":3,"env":{"CHROMIUM_REQUIRE":"1","BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":2.119,"secondsByExecution":[1.922,1.944,2.034,1.892,2.675,2.245]}, {"file":"test-issue-1367-channels-chat-app-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":2.771,"secondsByExecution":[2.454,2.498,2.66,2.484,3.46,3.067]}, + {"file":"test-1018-m2d-station-e2e.js","shard":3,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_INGESTOR_BIN":"./corescope-ingestor","FIXTURE_DB":"test-fixtures/e2e-fixture.db"},"output":"e2e","meanSeconds":45,"measurementNote":"New suite; #1018 M2d the owner's golden path with the real server and ingestor on a copy of the fixture (accounts, antenna claims and station details on, two seeded companions and repeaters, the shared tests/e2e-real-stack.js broker): sign in by signed challenge, link the repeater with the one-click admin login through tests/fake-companion.js, Edit station data from the owner card, fill in height and every station detail incl. TX power, cable loss, direction, beamwidth, battery and solar, Save: the Station block shows it at once, the change log lists the edit and the contact waiting for review, a signed-out visitor sees it; at 375x560 light with real taps and at 1280x900 dark. About 40s locally; no CI duration measured yet. Assigned to the shard of the other real-stack suite it follows (test-channel-proposals-e2e.js).","secondsByExecution":[]}, {"file":"test-channel-proposals-e2e.js","shard":3,"env":{"CHROMIUM_REQUIRE":"1","CORESCOPE_SERVER_BIN":"./corescope-server","CORESCOPE_INGESTOR_BIN":"./corescope-ingestor","FIXTURE_DB":"test-fixtures/e2e-fixture.db"},"output":"e2e","meanSeconds":23.543,"secondsByExecution":[23.588,23.816,23.942,22.142,23.934,23.837]}, {"file":"test-issue-1236-map-mobile-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":3.109,"secondsByExecution":[2.734,2.853,2.937,4.151,3.078,2.903]}, {"file":"test-issue-1273-qr-overlay-height-e2e.js","shard":3,"env":{"BASE_URL":"$BASE_URL"},"output":"e2e","meanSeconds":3.409,"secondsByExecution":[2.922,2.958,3.144,2.947,4.68,3.804]}, diff --git a/test-1018-m2d-station-e2e.js b/test-1018-m2d-station-e2e.js new file mode 100644 index 000000000..74ce930bf --- /dev/null +++ b/test-1018-m2d-station-e2e.js @@ -0,0 +1,314 @@ +#!/usr/bin/env node +/* E2E (#1018 M2d): the owner's golden path with the real binaries — link a + * repeater, fill in its station data, and the node page shows it. + * + * Starts its own ingestor and server (both built from this repo) against a + * temp copy of the E2E fixture database with accounts, antenna claims and + * station details on, plus a minimal MQTT broker (tests/e2e-real-stack.js). + * Two seeded companions (test keys) and two seeded repeaters with a + * position. For each viewport (375x560 light with real taps; 1280x900 dark + * with the mouse), one owner: + * + * 1. signs in with a signed challenge (#1018 M1b, done through the API in + * the page: the sign-in UI has its own suite) and has the repeater in + * My nodes; + * 2. links it on the Account page with the one-click admin login (#1018 + * M2b) through the fake companion of tests/fake-companion.js: the real + * server queues it and the real ingestor links it self-reported; + * 3. taps "Edit station data" on the owner card: the node page's owner + * section says "You own this node", asks for no code, and its button + * is Save; + * 4. sets the height and every station detail in one go (antenna, gain, + * power, installation, TX power, cable loss, direction, beamwidth, + * battery, solar panel and a public contact) and taps Save: the page + * waits for the ingestor, says the contact waits for an administrator, + * and draws the Station block with the new values at once (the claim + * snapshot is dropped on "done") without the unreviewed contact; the + * "Saved." line is in view, clear of the top bar and bottom nav; + * 5. the change log lists the edit (in use) and the contact (waiting), + * by "You (admin login)", and never the administrator contact; + * 6. a signed-out visitor sees the same Station block on the node page; + * 7. at 375x560 every control in the owner section is at least 44 px + * high and nothing scrolls sideways; no uncaught page error. + * + * Env: CORESCOPE_SERVER_BIN, CORESCOPE_INGESTOR_BIN, FIXTURE_DB, PUBLIC_DIR, + * CHROMIUM_PATH, CHROMIUM_REQUIRE=1, SCREENSHOT_DIR (optional PR shots). + */ +'use strict'; + +const assert = require('assert'); +const crypto = require('crypto'); +const { execFileSync } = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { chromium } = require('playwright'); +const { startFakeBroker, portFrom, createProcesses, waitFor } = require('./tests/e2e-real-stack'); +const { tapWhenSettled } = require('./tests/e2e-tap'); + +const ROOT = __dirname; +const SERVER_BIN = path.resolve(process.env.CORESCOPE_SERVER_BIN || path.join(ROOT, 'corescope-server')); +const INGESTOR_BIN = path.resolve(process.env.CORESCOPE_INGESTOR_BIN || path.join(ROOT, 'corescope-ingestor')); +const FIXTURE_DB = path.resolve(process.env.FIXTURE_DB || path.join(ROOT, 'test-fixtures', 'e2e-fixture.db')); +const PUBLIC_DIR = path.resolve(process.env.PUBLIC_DIR || path.join(ROOT, 'public')); +const SHOT_DIR = process.env.SCREENSHOT_DIR || ''; +const API_KEY = 'e2e-m2d-station-admin-key-0123456789'; +const PW = 'Hill-top-91'; +const ADMIN_CONTACT = 'ZZadmin-only-7'; +const FAKE_SRC = fs.readFileSync(path.join(ROOT, 'tests', 'fake-companion.js'), 'utf8'); +const NAME = 'test-1018-m2d-station-e2e.js'; + +let passed = 0, failed = 0; +async function step(name, fn) { + try { await fn(); passed++; console.log(' ✓ ' + name); } + catch (e) { failed++; console.error(' ✗ ' + name + '\n ' + ((e && e.stack) || e)); } +} + +// A test companion: an ed25519 key pair; the public key is its node key. +function companion() { + const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519'); + const raw = publicKey.export({ format: 'jwk' }).x; + return { pk: Buffer.from(raw, 'base64url').toString('hex'), privateKey }; +} + +const RUNS = [ + { label: '375x560 light', vp: { width: 375, height: 560 }, theme: 'light', phone: true, rep: '5d' + '1a'.repeat(31), name: 'M2d Hilltop' }, + { label: '1280x900 dark', vp: { width: 1280, height: 900 }, theme: 'dark', phone: false, rep: '5d' + '2b'.repeat(31), name: 'M2d Harbour' }, +]; + +async function main() { + for (const f of [SERVER_BIN, INGESTOR_BIN, FIXTURE_DB]) { + if (!fs.existsSync(f)) { console.error(NAME + ': FAIL — missing ' + f); process.exit(1); } + } + let browser; + try { + browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH || undefined, + args: ['--no-sandbox', '--disable-gpu', '--disable-dev-shm-usage'] }); + } catch (err) { + if (process.env.CHROMIUM_REQUIRE === '1') { console.error(NAME + ': FAIL — Chromium unavailable: ' + err.message); process.exit(1); } + console.log(NAME + ': SKIP (Chromium unavailable)'); + process.exit(0); + } + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'corescope-m2d-e2e-')); + const procs = createProcesses(dir); + const broker = await startFakeBroker(); + const port = await portFrom(13700); + const base = 'http://localhost:' + port; // a Secure session cookie needs a secure context + const db = path.join(dir, 'meshcore.db'); + fs.copyFileSync(FIXTURE_DB, db); + // The ingestor migrates the database first (it owns every write); the + // seed rows go in after, before the server reads its node cache. + const owners = RUNS.map(() => companion()); + const cfg = { apiKey: API_KEY, accounts: { enabled: true }, antennaClaims: { enabled: true, detailsEnabled: true } }; + const serverDir = path.join(dir, 'server'); + fs.mkdirSync(serverDir); + fs.writeFileSync(path.join(serverDir, 'config.json'), JSON.stringify(cfg)); + const ingestorConfig = path.join(dir, 'ingestor.json'); + fs.writeFileSync(ingestorConfig, JSON.stringify(Object.assign({ dbPath: db, + mqttSources: [{ name: 'e2e', broker: 'mqtt://127.0.0.1:' + broker.port, topics: ['meshcore/#'], connectTimeoutSec: 5 }] }, cfg))); + + const pageErrors = []; + try { + const ingestor = procs.start('ingestor', INGESTOR_BIN, ['-config', ingestorConfig]); + await waitFor('ingestor MQTT subscription', () => { + if (ingestor.exitCode !== null) throw new Error('ingestor exited: see ' + ingestor.logFile); + return procs.logHas(ingestor, /MQTT \[e2e\] subscribed/); + }, 60000); + const sql = (s) => execFileSync('sqlite3', ['-cmd', '.timeout 5000', db, s], { encoding: 'utf8' }).trim(); + const now = new Date().toISOString(); + owners.forEach((o, i) => { + sql(`INSERT INTO nodes (public_key, name, role, last_seen, first_seen, advert_count) VALUES ('${o.pk}', 'E2E Companion ${i}', 'companion', '${now}', '${now}', 1)`); + }); + RUNS.forEach((r, i) => { + sql(`INSERT INTO nodes (public_key, name, role, lat, lon, last_seen, first_seen, advert_count) VALUES ('${r.rep}', '${r.name}', 'repeater', ${55.70 + i / 100}, ${12.50 + i / 100}, '${now}', '${now}', 1)`); + }); + const server = procs.start('server', SERVER_BIN, ['-port', String(port), '-db', db, '-public', PUBLIC_DIR, '-config-dir', serverDir]); + await waitFor('server health', async () => { + if (server.exitCode !== null) throw new Error('server exited: see ' + server.logFile); + return (await fetch(base + '/api/healthz')).ok; + }, 60000); + await waitFor('accounts available (session key)', async () => (await (await fetch(base + '/api/account/config')).json()).available, 30000); + console.log(`\n=== ${NAME} against ${base} ===\n`); + + for (let i = 0; i < RUNS.length; i++) { + const run = RUNS[i], me = owners[i]; + const ctx = await browser.newContext({ viewport: run.vp, hasTouch: run.phone, isMobile: run.phone }); + await ctx.addInitScript((t) => { + try { + if (!sessionStorage.getItem('e2e-init')) { + sessionStorage.setItem('e2e-init', '1'); + localStorage.setItem('meshcore-theme', t); + localStorage.setItem('meshcore-user-level', 'experienced'); + for (const h of ['row-swipe', 'tab-swipe', 'edge-drawer', 'pull-refresh']) localStorage.setItem('meshcore-gesture-hints-' + h, 'seen'); + } + } catch (_) {} + }, run.theme); + await ctx.addInitScript({ content: FAKE_SRC }); + await ctx.addInitScript((c) => { + const clock = { now: () => Date.now(), setTimeout: (f, ms) => setTimeout(f, ms) }; + window.__fake = window.FakeCompanion.create({ clock, nodeKey: c.node, adminPassword: c.pw }); + const apis = window.FakeCompanion.browserApis(window.__fake, { errors: [], onPicker: () => {} }); + for (const k of ['bluetooth', 'serial']) { + try { delete navigator[k]; } catch (_) {} + Object.defineProperty(Navigator.prototype, k, { get: () => apis[k], configurable: true }); + } + }, { node: run.rep, pw: PW }); + const page = await ctx.newPage(); + page.setDefaultTimeout(20000); + page.on('pageerror', (e) => pageErrors.push(run.label + ': ' + e.message)); + const tap = (sel) => (run.phone ? tapWhenSettled(page, sel) : page.click(sel)); + const api = (method, p, body) => page.evaluate(async ([m, u, b]) => { + const r = await fetch('/api' + u, { method: m, credentials: 'same-origin', headers: b ? { 'Content-Type': 'application/json' } : {}, body: b ? JSON.stringify(b) : undefined }); + return { status: r.status, body: await r.json().catch(() => null) }; + }, [method, p, body]); + const shot = async (n) => { if (SHOT_DIR) { await page.waitForTimeout(300); await page.screenshot({ path: path.join(SHOT_DIR, n + '.png') }); } }; + + await step(`${run.label}: sign in with the companion and put the repeater in My nodes`, async () => { + await page.goto(base + '/#/home', { waitUntil: 'domcontentloaded' }); + const ch = await api('POST', '/account/login/challenge', { pubkey: me.pk }); + assert.strictEqual(ch.status, 200, JSON.stringify(ch)); + const sig = crypto.sign(null, Buffer.from(ch.body.challenge), me.privateKey).toString('hex'); + const signed = await api('POST', '/account/login/signed', { challengeId: ch.body.challengeId, signature: sig }); + assert.strictEqual(signed.status, 202, JSON.stringify(signed)); + await waitFor('the sign-in proven', async () => (await api('GET', '/account/login/' + signed.body.requestId)).body.status === 'proven'); + const sess = await api('POST', '/account/session', { requestId: signed.body.requestId, redeemSecret: signed.body.redeemSecret }); + assert.strictEqual(sess.status, 200, JSON.stringify(sess)); + const add = await api('POST', '/account/my-nodes', { op: 'add', nodes: [{ pubkey: run.rep, name: run.name }] }); + assert.strictEqual(add.status, 202, JSON.stringify(add)); + await waitFor('My nodes saved', async () => (await api('GET', '/account/requests/' + add.body.requestId)).body.status === 'done'); + }); + + await step(`${run.label}: link it with the one-click admin login; the real ingestor links it`, async () => { + await page.goto(base + '/#/account?tab=links', { waitUntil: 'domcontentloaded' }); + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.waitForSelector('[data-testid="account-oneclick"]'); + await page.selectOption('[data-testid="account-oneclick-node"]', run.rep); + const pw = '[data-testid="account-oneclick-password"]'; + if (run.phone) await tapWhenSettled(page, pw); else await page.click(pw); + await page.fill(pw, PW); + await tap('[data-testid="account-oneclick-start-serial"]'); + await page.waitForSelector('[data-testid="account-oneclick-done"]', { timeout: 60000 }); + const st = await page.locator('[data-testid="account-oneclick-status"]').textContent(); + assert.ok(/^Linked\./.test(st), 'status: ' + st); + await tap('[data-testid="account-oneclick-done"]'); + await page.waitForSelector(`[data-testid="account-owner-card"][data-pubkey="${run.rep}"] [data-testid="account-edit-station"]`); + }); + + const OWNER = '#node-antenna'; + await step(`${run.label}: "Edit station data" opens the node page's owner form: no code, a Save button`, async () => { + await tap(`[data-testid="account-owner-card"][data-pubkey="${run.rep}"] [data-testid="account-edit-station"]`); + await page.waitForSelector(OWNER + ' [data-testid="acst-owner-hint"]'); + assert.ok(new RegExp('#/nodes/' + run.rep + '\\?section=node-antenna$').test(page.url()), 'deep link: ' + page.url()); + const hint = await page.locator(OWNER + ' [data-testid="acst-owner-hint"]').textContent(); + assert.ok(/You own this node \(linked by an admin login\)/.test(hint) && /no code/.test(hint), 'hint: ' + hint); + assert.strictEqual((await page.locator(OWNER + ' [data-testid="ac-submit"]').textContent()).trim(), 'Save'); + }); + + await step(`${run.label}: everything in one go — Save applies it and the Station block shows it at once`, async () => { + const posts = []; + const onReq = (r) => { if (r.method() === 'POST') posts.push({ url: r.url(), body: r.postData() || '' }); }; + page.on('request', onReq); + await tap(OWNER + ' label:has([data-testid="ac-mode-set"])'); + await page.fill(OWNER + ' [data-testid="ac-height"]', '18.5'); + await tap(OWNER + ' label:has([data-testid="ac-details-set"])'); + await page.selectOption(OWNER + ' [data-testid="ac-antenna-type"]', 'yagi'); + await page.fill(OWNER + ' [data-testid="ac-gain"]', '9'); + await tap(OWNER + ' label:has([data-testid="ac-power-solar"])'); + await tap(OWNER + ' label:has([data-testid="ac-power-battery"])'); + await page.selectOption(OWNER + ' [data-testid="ac-installation"]', 'mast'); + for (const [k, v] of [['txPowerDbm', '22'], ['cableLossDb', '1,5'], ['azimuthDeg', '270'], ['beamwidthDeg', '60'], ['batteryWh', '100'], ['solarW', '20']]) { + await page.fill(OWNER + ` [data-testid="ac-${k}"]`, v); + } + await page.fill(OWNER + ' [data-testid="ac-contact-public"]', 'OZ1ABC'); + await page.fill(OWNER + ' [data-testid="ac-contact-admin"]', ADMIN_CONTACT); + if (run.phone) await shot('m2d-1-form-' + run.theme); + await tap(OWNER + ' [data-testid="ac-submit"]'); + await page.waitForFunction((sel) => { + const s = document.querySelector(sel + ' [data-testid="ac-form-status"]'); + return s && /^Saved\./.test(s.textContent); + }, OWNER, { timeout: 30000 }); + page.off('request', onReq); + const status = await page.locator(OWNER + ' [data-testid="ac-form-status"]').textContent(); + assert.ok(/public contact or model text is shown once an administrator has checked it/.test(status), 'status: ' + status); + const station = posts.filter((p) => p.url.endsWith('/station')); + assert.strictEqual(station.length, 1, 'one station POST: ' + JSON.stringify(posts.map((p) => p.url))); + const sent = JSON.parse(station[0].body); + assert.deepStrictEqual(sent, { heightM: 18.5, details: { antennaType: 'yagi', gainDbi: 9, power: ['solar', 'battery'], installation: 'mast', + txPowerDbm: 22, cableLossDb: 1.5, azimuthDeg: 270, beamwidthDeg: 60, batteryWh: 100, solarW: 20, contactPublic: 'OZ1ABC', contactAdmin: ADMIN_CONTACT } }); + assert.ok(!posts.some((p) => /antenna-claims/.test(p.url)), 'no code was asked for'); + await page.waitForSelector(OWNER + ' [data-testid="ac-station"]:not([hidden])'); + const block = await page.locator(OWNER + ' [data-testid="ac-station"]').textContent(); + for (const want of ['Yagi', '9.0 dBi', 'Solar + Battery', 'Mast']) assert.ok(block.includes(want), want + ' missing: ' + block); + assert.ok(!block.includes('OZ1ABC'), 'the unreviewed contact is shown: ' + block); + // The "Saved." line is in view, not under the bottom nav or the top + // bar, once the Station block above it has been drawn (review + // PR#1095 F7). + const seen = await page.waitForFunction((sel) => { + const r = document.querySelector(sel + ' [data-testid="ac-form-status"]').getBoundingClientRect(); + const nav = document.querySelector('.bottom-nav'); + const navTop = nav && nav.getBoundingClientRect().height ? nav.getBoundingClientRect().top : window.innerHeight; + return r.top >= 52 && r.bottom <= navTop; + }, OWNER, { timeout: 5000 }).then(() => true, () => false); + const where = await page.evaluate((sel) => { + const r = document.querySelector(sel + ' [data-testid="ac-form-status"]').getBoundingClientRect(); + const nav = document.querySelector('.bottom-nav'); + return { top: r.top, bottom: r.bottom, navTop: nav ? nav.getBoundingClientRect().top : null, vh: window.innerHeight }; + }, OWNER); + assert.ok(seen, 'the Saved line is out of view: ' + JSON.stringify(where)); + await shot('m2d-2-saved-' + (run.phone ? run.theme : 'desktop')); + }); + + await step(`${run.label}: the change log lists the edit in use and the contact waiting, by You (admin login)`, async () => { + await page.waitForSelector(OWNER + ' [data-testid="acst-history"]'); + const box = page.locator(OWNER + ' [data-testid="acst-history"]'); + await tap(OWNER + ' [data-testid="acst-history"] summary'); + const entries = await box.locator('[data-testid="acst-entry"]').allTextContents(); + assert.strictEqual(entries.length, 2, 'entries: ' + JSON.stringify(entries)); + assert.ok(entries.every((e) => /You \(admin login\)/.test(e)), JSON.stringify(entries)); + assert.ok(entries.some((e) => /In use/.test(e) && /height 18\.5 m/.test(e) && /TX 22\.0 dBm/.test(e) && /direction 270/.test(e)), JSON.stringify(entries)); + assert.ok(entries.some((e) => /Waiting for the administrator/.test(e) && /public contact OZ1ABC/.test(e)), JSON.stringify(entries)); + const html = await page.content(); + assert.ok(!html.includes(ADMIN_CONTACT), 'the administrator contact reached the page'); + if (run.phone) await shot('m2d-3-history-' + run.theme); + }); + + await step(`${run.label}: a signed-out visitor sees the same Station block`, async () => { + const anon = await browser.newContext({ viewport: run.vp }); + const p2 = await anon.newPage(); + await p2.goto(base + '/#/nodes/' + run.rep, { waitUntil: 'domcontentloaded' }); + await p2.waitForSelector('#node-antenna [data-testid="ac-station"]:not([hidden])', { timeout: 20000 }); + const block = await p2.locator('#node-antenna [data-testid="ac-station"]').textContent(); + assert.ok(block.includes('Yagi') && block.includes('9.0 dBi'), block); + assert.strictEqual(await p2.locator('[data-testid="acst-owner-hint"]').count(), 0, 'a visitor gets the owner form'); + assert.strictEqual(await p2.locator('[data-testid="acst-history"]').count(), 0, 'a visitor gets the change log'); + await anon.close(); + }); + + if (run.phone) { + await step(`${run.label}: 44 px controls in the owner section, no sideways scroll`, async () => { + await tap(OWNER + ' label:has([data-testid="ac-details-set"])'); + const small = await page.evaluate((sel) => [...document.querySelectorAll(sel + ' button, ' + sel + ' input[type=radio], ' + sel + ' input[type=checkbox], ' + sel + ' summary')] + .map((b) => b.closest('label') || b) + .filter((b) => b.offsetParent && b.getBoundingClientRect().height < 44) + .map((b) => (b.textContent || b.tagName).trim().slice(0, 40)), OWNER); + assert.deepStrictEqual(small, [], 'under 44 px: ' + small.join(', ')); + const w = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth); + assert.ok(w <= 1, 'scrolls sideways by ' + w + ' px'); + }); + } + await ctx.close(); + } + + await step('no uncaught page errors', async () => assert.deepStrictEqual(pageErrors, [])); + } finally { + await browser.close().catch(() => {}); + await procs.stopAll(); + broker.close(); + if (failed) console.error('logs kept in ' + dir); + else fs.rmSync(dir, { recursive: true, force: true }); + } + console.log(`${NAME}: ${passed} passed, ${failed} failed`); + process.exit(failed ? 1 : 0); +} + +main().catch((e) => { console.error(NAME + ': FAIL — ' + ((e && e.stack) || e)); process.exit(1); }); diff --git a/test-1018-m2d-station.js b/test-1018-m2d-station.js new file mode 100644 index 000000000..53512c20b --- /dev/null +++ b/test-1018-m2d-station.js @@ -0,0 +1,199 @@ +#!/usr/bin/env node +/* #1018 M2d — unit tests for station data through owner links: the pure + * helpers of public/account-station.js and the radio and power inputs of + * public/antenna-claims.js (#1017 M3 values in the shared form), the real + * production files loaded into a vm context. The owner's golden path in a + * browser is test-1018-m2d-station-e2e.js. */ +'use strict'; + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const pub = (f) => path.join(__dirname, 'public', f); + +function load() { + const ctx = { console, Promise, Math, JSON, Object, Array, String, Number, Date, encodeURIComponent, URLSearchParams }; + ctx.window = ctx; + ctx.setTimeout = setTimeout; + ctx.clearTimeout = clearTimeout; + vm.createContext(ctx); + for (const f of ['antenna-height.js', 'admin-key.js', 'hardware.js', 'antenna-claims.js', 'account-links.js', 'account-station.js']) { + vm.runInContext(fs.readFileSync(pub(f), 'utf8'), ctx, { filename: pub(f) }); + } + return ctx; +} + +const ctx = load(); +const AC = ctx.AntennaClaims, AS = ctx.AccountStation; +const tests = []; +function test(name, fn) { tests.push({ name, fn }); } +function eq(a, b, m) { assert.strictEqual(JSON.stringify(a), JSON.stringify(b), m); } + +// ── The radio and power inputs: the server's bounds and grids ─────────── +test('parseStationFields accepts every bound on the grid, empty is not given', () => { + eq(AC.parseStationFields({}).values, {}); + eq(AC.parseStationFields({ txPowerDbm: '', cableLossDb: ' ' }).values, {}); + const ok = [ + ['txPowerDbm', '-9', -9], ['txPowerDbm', '37', 37], ['txPowerDbm', '22,5', 22.5], ['txPowerDbm', '−2', -2], + ['cableLossDb', '0', 0], ['cableLossDb', '20', 20], ['cableLossDb', '1.50', 1.5], + ['azimuthDeg', '0', 0], ['azimuthDeg', '359', 359], + ['batteryWh', '0.1', 0.1], ['batteryWh', '5000', 5000], ['solarW', '0.1', 0.1], ['solarW', '500', 500] + ]; + for (const [k, raw, want] of ok) { + const r = AC.parseStationFields({ [k]: raw }); + assert.strictEqual(r.error, undefined, k + ' ' + raw + ': ' + r.error); + assert.strictEqual(r.values[k], want, k + ' ' + raw); + } + const both = AC.parseStationFields({ azimuthDeg: '90', beamwidthDeg: '10' }); + eq(both.values, { azimuthDeg: 90, beamwidthDeg: 10 }); + eq(AC.parseStationFields({ azimuthDeg: '90', beamwidthDeg: '180' }).values.beamwidthDeg, 180); +}); + +test('parseStationFields refuses past each bound and off the grid, naming the field', () => { + const bad = [ + ['txPowerDbm', '-9.1'], ['txPowerDbm', '37.1'], ['txPowerDbm', '22.55'], ['txPowerDbm', 'x'], + ['cableLossDb', '-0.1'], ['cableLossDb', '20.1'], + ['azimuthDeg', '-1'], ['azimuthDeg', '360'], ['azimuthDeg', '90.5'], + ['batteryWh', '0'], ['batteryWh', '5000.1'], ['solarW', '0'], ['solarW', '500.1'] + ]; + for (const [k, raw] of bad) { + const r = AC.parseStationFields({ [k]: raw }); + assert.ok(r.error, k + ' ' + raw + ' accepted'); + assert.strictEqual(r.field, k, k + ' ' + raw); + } + for (const bw of ['9', '181']) { + const r = AC.parseStationFields({ azimuthDeg: '90', beamwidthDeg: bw }); + assert.strictEqual(r.field, 'beamwidthDeg', 'beamwidth ' + bw); + } + const lone = AC.parseStationFields({ beamwidthDeg: '60' }); + assert.strictEqual(lone.field, 'beamwidthDeg', 'a beamwidth without a direction'); +}); + +test('stationFieldsShown follows the server cross-field rules', () => { + eq(AC.stationFieldsShown('omni', {}), { txPowerDbm: true, cableLossDb: true, azimuthDeg: false, beamwidthDeg: false, batteryWh: false, solarW: false }); + const y = AC.stationFieldsShown('yagi', { solar: true, battery: true }); + assert.ok(y.azimuthDeg && y.beamwidthDeg && y.batteryWh && y.solarW); + assert.ok(AC.stationFieldsShown('panel', {}).azimuthDeg); + assert.ok(!AC.stationFieldsShown('', { mains: true }).batteryWh); +}); + +test('buildClaimBody sends the typed radio and power values the rules allow', () => { + const choice = (det) => ({ height: { op: 'keep' }, details: Object.assign({ op: 'set', power: {} }, det) }); + let r = AC.buildClaimBody(choice({ antennaType: 'yagi', power: { solar: true }, stationRaw: { txPowerDbm: '22', cableLossDb: '1.5', azimuthDeg: '270', beamwidthDeg: '60', solarW: '20' } })); + eq(r.body.details, { antennaType: 'yagi', power: ['solar'], txPowerDbm: 22, cableLossDb: 1.5, azimuthDeg: 270, beamwidthDeg: 60, solarW: 20 }); + // A value whose condition does not hold is not sent (the input is hidden). + r = AC.buildClaimBody(choice({ antennaType: 'omni', stationRaw: { azimuthDeg: '270', batteryWh: '50', txPowerDbm: '20' } })); + eq(r.body.details, { antennaType: 'omni', txPowerDbm: 20 }); + r = AC.buildClaimBody(choice({ antennaType: 'omni', stationRaw: { txPowerDbm: '99' } })); + assert.strictEqual(r.field, 'txPowerDbm'); + assert.ok(/-9 to 37/.test(r.error), r.error); + // Without the inputs (an older caller), the kept values still go through. + r = AC.buildClaimBody(choice({ antennaType: 'omni', kept: { txPowerDbm: 14 } })); + eq(r.body.details, { antennaType: 'omni', txPowerDbm: 14 }); +}); + +// ── Owner mode ────────────────────────────────────────────────────────── +test('ownerHint names the tier; reviewText explains probation and objections', () => { + assert.ok(/verified owner/.test(AS.ownerHint({ tier: 'verified' }))); + assert.ok(/admin login/.test(AS.ownerHint({ tier: 'self_reported' }))); + assert.ok(/no code/.test(AS.ownerHint({ tier: 'verified' }))); + assert.strictEqual(AS.reviewText('', null), ''); + assert.ok(/already had an owner/.test(AS.reviewText('probation', Date.UTC(2026, 11, 5)))); + assert.ok(/objected/.test(AS.reviewText('objection'))); +}); + +test('savedText: applied, applied with free text waiting, or sent for review', () => { + eq(AS.savedText('', false).kind, 'success'); + assert.ok(/shows it now/.test(AS.savedText('', false).text)); + assert.ok(/administrator has checked/.test(AS.savedText('', true).text)); + const r = AS.savedText('probation', false); + assert.strictEqual(r.kind, 'info'); + assert.ok(/Sent to the administrator/.test(r.text)); +}); + +test('heldFreeText: only a new public contact or model text waits', () => { + assert.strictEqual(AS.heldFreeText({ heightM: 10 }, null), false); + assert.strictEqual(AS.heldFreeText({ details: { antennaType: 'omni' } }, null), false); + assert.strictEqual(AS.heldFreeText({ details: { contactPublic: 'OZ1ABC' } }, null), true); + assert.strictEqual(AS.heldFreeText({ details: { contactPublic: 'OZ1ABC' } }, { contactPublic: 'OZ1ABC' }), false); + assert.strictEqual(AS.heldFreeText({ details: { hardware: 'other', hardwareModel: 'Homebrew' } }, { hardwareModel: 'Old' }), true); + assert.strictEqual(AS.heldFreeText({ details: {} }, { contactPublic: 'OZ1ABC' }), false, 'removing a contact is no risk'); +}); + +test('saveError maps every refusal to the owner’s words', () => { + for (const [status, re] of [[404, /not an owner/], [403, /cannot be changed/], [429, /Too many/], [401, /signed out/]]) { + assert.ok(re.test(AS.saveError({ status })), String(status)); + } + assert.strictEqual(AS.saveError({ status: 400, message: 'heightM must be 0-100 m' }), 'heightM must be 0-100 m'); +}); + +test('historyRows: who, when, what and status; an approved row out of force reads Replaced', () => { + const rows = AS.historyRows([ + { at: Date.UTC(2026, 11, 2, 12), by: 'You', mine: true, via: 'link', tier: 'self_reported', heightOp: 'set', heightM: 12, status: 'approved', inForce: true }, + { at: Date.UTC(2026, 11, 2, 11), by: 'Co-owner A', via: 'link', tier: 'verified', detailsOp: 'set', details: { antennaType: 'yagi' }, status: 'proven', inForce: false }, + { at: Date.UTC(2026, 11, 2, 10), by: 'Advert claim', via: 'advert', heightOp: 'clear', detailsOp: 'clear', status: 'approved', inForce: false }, + { at: Date.UTC(2026, 11, 2, 9), by: 'A former owner', via: 'link', heightOp: 'set', heightM: 9, status: 'superseded', inForce: false } + ], (d) => 'antenna ' + d.antennaType); + eq(rows.map((r) => r.who), ['You (admin login)', 'Co-owner A', 'Advert claim', 'A former owner']); + eq(rows.map((r) => r.status), ['In use', 'Waiting for the administrator', 'Replaced', 'Replaced']); + eq(rows.map((r) => r.what), ['height 12.0 m', 'details: antenna yagi', 'height removed; details removed', 'height 9.0 m']); + assert.ok(rows[0].inForce && rows[0].mine && !rows[1].inForce); + eq(AS.historyRows(null), []); +}); + +// ownerLink: signed out, accounts off, an owner, not an owner. +test('ownerLink resolves with the account link or null', async () => { + const pk = 'cd'.repeat(32); + ctx.Account = undefined; + assert.strictEqual(await AS.ownerLink(pk), null); + const link = { pubkey: pk, tier: 'verified' }; + let enabled = false; + ctx.Account = { boot: () => Promise.resolve(), enabled: () => enabled, linkFor: (k) => (k === pk ? link : null) }; + assert.strictEqual(await AS.ownerLink(pk), null, 'accounts off'); + enabled = true; + assert.strictEqual(await AS.ownerLink(pk), link); + assert.strictEqual(await AS.ownerLink('ef'.repeat(32)), null); + ctx.Account = { boot: () => Promise.reject(new Error('x')), enabled: () => true, linkFor: () => link }; + assert.strictEqual(await AS.ownerLink(pk), null, 'boot failed'); +}); + +// save: the POST, then the applied status; a refusal and an ingestor error. +test('save waits for the ingestor and reports its outcome', async () => { + const pk = 'cd'.repeat(32); + const calls = []; + let outcome = { status: 'done' }; + ctx.Account = { + call: (m, p, b) => { calls.push([m, p, b]); return p.indexOf('/station') > 0 && b && b.heightM === 99 ? Promise.reject(Object.assign(new Error('x'), { status: 404 })) : Promise.resolve({ requestId: 'f'.repeat(32), review: '' }); }, + waitApplied: (id, alive, done) => { assert.strictEqual(id, 'f'.repeat(32)); assert.ok(alive()); done(outcome); } + }; + const r = await AS.save(pk, { heightM: 12 }, () => true); + eq(r, { review: '' }); + eq(calls[0], ['POST', '/account/nodes/' + pk + '/station', { heightM: 12 }]); + outcome = { status: 'error', error: 'you are not an owner of this node' }; + await assert.rejects(AS.save(pk, { heightM: 12 }, () => true), /not an owner of this node/); + await assert.rejects(AS.save(pk, { heightM: 99 }, () => true), /not an owner of this node any more/); + outcome = { status: 'timeout' }; + await assert.rejects(AS.save(pk, { heightM: 12 }, () => true), /No answer yet/); +}); + +// No HTML sink: every server string reaches the page through textContent. +test('account-station.js has no HTML sinks', () => { + const src = fs.readFileSync(pub('account-station.js'), 'utf8'); + assert.ok(!/innerHTML|outerHTML|insertAdjacentHTML|document\.write/.test(src)); +}); + +(async () => { + let passed = 0; + for (const t of tests) { + try { + await t.fn(); + passed++; + } catch (e) { + console.error('FAIL ' + t.name + '\n ' + (e && e.stack || e)); + process.exitCode = 1; + } + } + console.log(`test-1018-m2d-station.js: ${passed}/${tests.length} passed`); +})(); diff --git a/test-all.sh b/test-all.sh index c610c8ab2..ddcf766e6 100755 --- a/test-all.sh +++ b/test-all.sh @@ -152,6 +152,7 @@ run test-1018-account.js run test-1018-companion-link.js run test-1018-m2a-links.js run test-1018-m2b-oneclick.js +run test-1018-m2d-station.js run test-packet-detail-channel-xss.js run test-channels-name-escaping.js diff --git a/tests/e2e-real-stack.js b/tests/e2e-real-stack.js new file mode 100644 index 000000000..85341e3cf --- /dev/null +++ b/tests/e2e-real-stack.js @@ -0,0 +1,113 @@ +'use strict'; +/* Real-stack E2E harness: the real server and ingestor binaries against a + * temp copy of the fixture database, with a minimal in-process MQTT 3.1.1 + * broker so the ingestor can start (CONNECT, SUBSCRIBE and PING only; no + * packet is published). Every spawned process is registered, so stopAll() + * stops it even when a start fails half-way, and each start gets its own + * log file, so a wait never matches a line an earlier process wrote. + * + * The same broker and process handling as test-channel-proposals-e2e.js, + * shared from here for new suites (#1018 M2d). */ + +const { spawn } = require('child_process'); +const fs = require('fs'); +const net = require('net'); +const path = require('path'); + +function startFakeBroker() { + return new Promise((resolve) => { + const sockets = new Set(); + const server = net.createServer((sock) => { + sockets.add(sock); + sock.on('close', () => sockets.delete(sock)); + sock.on('error', () => {}); + let buf = Buffer.alloc(0); + sock.on('data', (d) => { + buf = Buffer.concat([buf, d]); + for (;;) { + if (buf.length < 2) return; + let len = 0, mult = 1, i = 1, complete = false; + for (; i < buf.length && i <= 4; i++) { + len += (buf[i] & 0x7f) * mult; + mult *= 128; + if ((buf[i] & 0x80) === 0) { complete = true; i++; break; } + } + if (!complete || buf.length < i + len) return; + const type = buf[0] >> 4; + const body = buf.slice(i, i + len); + buf = buf.slice(i + len); + if (type === 1) sock.write(Buffer.from([0x20, 0x02, 0x00, 0x00])); // CONNACK accepted + else if (type === 8) { // SUBSCRIBE → SUBACK granting QoS 0 per topic + let n = 0; + for (let p = 2; p + 2 <= body.length;) { p += 2 + body.readUInt16BE(p) + 1; n++; } + sock.write(Buffer.from([0x90, 2 + n, body[0], body[1]].concat(new Array(n).fill(0)))); + } else if (type === 12) sock.write(Buffer.from([0xd0, 0x00])); // PINGRESP + else if (type === 14) sock.end(); + } + }); + }); + server.listen(0, '127.0.0.1', () => resolve({ + port: server.address().port, + close: () => { sockets.forEach((s) => s.destroy()); server.close(); }, + })); + }); +} + +// portFrom resolves with the first free port from `from` up (13700 by +// default: other suites and agents use the lower ones). +function portFrom(from) { + const tryPort = (p) => new Promise((resolve) => { + const s = net.createServer(); + s.once('error', () => resolve(false)); + s.listen(p, '127.0.0.1', () => s.close(() => resolve(true))); + }); + return (async () => { + for (let p = from || 13700; p < (from || 13700) + 200; p++) if (await tryPort(p)) return p; + throw new Error('no free port from ' + (from || 13700)); + })(); +} + +function createProcesses(dir) { + const children = new Set(); + let count = 0; + function start(label, bin, args) { + const logFile = path.join(dir, label + '-' + (++count) + '.log'); + const out = fs.openSync(logFile, 'w'); + const child = spawn(bin, args, { stdio: ['ignore', out, out] }); + fs.closeSync(out); + child.label = label; + child.logFile = logFile; + children.add(child); + child.once('exit', () => children.delete(child)); + return child; + } + async function stop(child) { + if (!child || child.exitCode !== null) return; + const exited = new Promise((r) => child.once('exit', r)); + child.kill('SIGTERM'); + const t = setTimeout(() => child.kill('SIGKILL'), 5000); + await exited; + clearTimeout(t); + } + return { + start, + stop, + async stopAll() { for (const c of Array.from(children)) await stop(c); }, + logHas(child, re) { try { return re.test(fs.readFileSync(child.logFile, 'utf8')); } catch (e) { return false; } }, + }; +} + +async function waitFor(what, fn, timeoutMs) { + const deadline = Date.now() + (timeoutMs || 20000); + let last; + while (Date.now() < deadline) { + try { + const v = await fn(); + if (v) return v; + } catch (e) { last = e; } + await new Promise((r) => setTimeout(r, 200)); + } + throw new Error('timed out waiting for ' + what + (last ? ': ' + last.message : '')); +} + +module.exports = { startFakeBroker, portFrom, createProcesses, waitFor };