From 7d83bbeecb92d64e985b09a3cb385dcdb5fafdc7 Mon Sep 17 00:00:00 2001 From: MrAlders0n Date: Sun, 15 Nov 2026 01:29:13 -0500 Subject: [PATCH] Match the server's request reasons and error codes --- src/features/account/errors.ts | 3 +- src/features/account/requestReason.ts | 21 +++++ .../account/sections/RequestsSection.tsx | 3 +- src/i18n/locales/en.json | 17 +++- src/i18n/locales/fr.json | 18 +++- src/i18n/locales/sv.json | 17 +++- tests/api/auth.test.ts | 25 +++++ .../features/account/requestsSection.test.tsx | 4 +- tests/features/account/serverContract.test.ts | 92 +++++++++++++++++++ tests/hooks/useSession.test.tsx | 10 ++ 10 files changed, 200 insertions(+), 10 deletions(-) create mode 100644 src/features/account/requestReason.ts create mode 100644 tests/features/account/serverContract.test.ts diff --git a/src/features/account/errors.ts b/src/features/account/errors.ts index a4028bf..fd47843 100644 --- a/src/features/account/errors.ts +++ b/src/features/account/errors.ts @@ -3,6 +3,7 @@ import type { TFunction } from "i18next"; const KNOWN = new Set([ "invalid_credentials", "email_unverified", "token_invalid", "username_taken", "weak_password", "invalid_input", "registration_closed", "not_signed_in", "csrf_rejected", "accounts_disabled", + "service_unavailable", "read_only", ]); function when(t: TFunction, ms?: number): string { @@ -29,7 +30,7 @@ export function authErrorText(t: TFunction, err: unknown): string { export const errorCode = (err: unknown): string | undefined => (err as { code?: string } | null)?.code; const REQUEST_CODES = new Set([ - "request_limit", "already_requested", "not_a_repeater", "password_invalid", "no_password_blocked", "requests_disabled", + "request_limit", "already_requested", "not_a_repeater", "password_invalid", "no_password_blocked", "requests_disabled", "not_found", ]); // Telemetry request errors; any other code falls back to the shared mapping. Never echoes the request. diff --git a/src/features/account/requestReason.ts b/src/features/account/requestReason.ts new file mode 100644 index 0000000..b323d7f --- /dev/null +++ b/src/features/account/requestReason.ts @@ -0,0 +1,21 @@ +import type { TFunction } from "i18next"; + +// The sentences beacon-server's polling package puts in statusReason, by the catalog key that carries each. +const REASONS: Record = { + "No observer can reach this repeater yet.": "noObserver", + "Every observer that can reach this repeater is already polling its maximum.": "noSeat", + "The repeater did not accept this guest password. Enter a new one.": "loginFailed", + "The repeater did not accept a blank or hello login. Enter a guest password.": "blankFailed", + "The repeater gave admin access to this password, so Beacon deleted it. Enter a guest password, never an admin one.": "adminStopped", + "This repeater gives admin access to a blank login, so Beacon will not poll it without a guest password.": "blankBlocked", +}; +const OFFLINE = /^Not heard by any observer for (\d+) days?\.$/; + +// A server reason in the user's language; one this build does not know shows as the server sent it. +export function requestReasonText(t: TFunction, reason: string): string { + const key = REASONS[reason]; + if (key) return t(`account.requests.reason.${key}`); + const offline = OFFLINE.exec(reason); + if (offline) return t("account.requests.reason.offline", { count: Number(offline[1]) }); + return reason; +} diff --git a/src/features/account/sections/RequestsSection.tsx b/src/features/account/sections/RequestsSection.tsx index 6826b17..96e4d52 100644 --- a/src/features/account/sections/RequestsSection.tsx +++ b/src/features/account/sections/RequestsSection.tsx @@ -9,6 +9,7 @@ import { FormStatus } from "../../../components/form/FormStatus"; import { PasswordField } from "../../../components/form/PasswordField"; import { GUEST_PASSWORD_MAX, TELEMETRY_REQUESTS_KEY, useTelemetryRequests } from "../../../hooks/useTelemetryRequests"; import { requestErrorText } from "../errors"; +import { requestReasonText } from "../requestReason"; import type { TelemetryRequest } from "../types"; import { ProfileSection } from "./ProfileSection"; import { useSessionEnded } from "./useSessionEnded"; @@ -48,7 +49,7 @@ function RequestRow({ request }: { request: TelemetryRequest }) { )} {t(`account.requests.status.${request.status}`)} - {request.statusReason &&
{request.statusReason}
} + {request.statusReason &&
{requestReasonText(t, request.statusReason)}
}
{t("account.requests.polledBy")} {request.poller ? request.poller.name : t("account.requests.noObserver")} diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index c827eef..82d7c42 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -1161,7 +1161,9 @@ "token_invalid": "This link is no longer valid.", "not_signed_in": "You are not signed in. Sign in and try again.", "csrf_rejected": "The request was rejected. Reload the page and try again.", - "accounts_disabled": "Accounts are not enabled on this server." + "accounts_disabled": "Accounts are not enabled on this server.", + "service_unavailable": "The server is busy. Try again in a moment.", + "read_only": "This server is read-only right now. Try again later." }, "profile": { "title": "Profile", @@ -1288,6 +1290,16 @@ "admin_stopped": "Stopped: that password gave admin access and was deleted", "disabled": "Paused: the repeater has not been heard recently" }, + "reason": { + "noObserver": "No observer can reach this repeater yet.", + "noSeat": "Every observer that can reach this repeater is already polling its maximum.", + "loginFailed": "The repeater did not accept this guest password. Enter a new one.", + "blankFailed": "The repeater did not accept a blank or hello login. Enter a guest password.", + "adminStopped": "The repeater gave admin access to this password, so Beacon deleted it. Enter a guest password, never an admin one.", + "blankBlocked": "This repeater gives admin access to a blank login, so Beacon will not poll it without a guest password.", + "offline_one": "Not heard by any observer for {{count}} day.", + "offline_other": "Not heard by any observer for {{count}} days." + }, "polledBy": "Polled by", "noObserver": "no observer yet", "lastReading": "Last reading", @@ -1316,7 +1328,8 @@ "not_a_repeater": "Only repeaters and room servers can be polled.", "password_invalid": "The password must be 1 to 15 characters.", "no_password_blocked": "This repeater gives admin access without a password, so it cannot be polled this way", - "requests_disabled": "Telemetry requests are not enabled on this server." + "requests_disabled": "Telemetry requests are not enabled on this server.", + "not_found": "That request no longer exists." } }, "portal": { diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index e8e290f..17388bd 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1170,7 +1170,9 @@ "token_invalid": "Ce lien n’est plus valide.", "not_signed_in": "Vous n’êtes pas connecté. Connectez-vous et réessayez.", "csrf_rejected": "La requête a été refusée. Rechargez la page et réessayez.", - "accounts_disabled": "Les comptes ne sont pas activés sur ce serveur." + "accounts_disabled": "Les comptes ne sont pas activés sur ce serveur.", + "service_unavailable": "Le serveur est occupé. Réessayez dans un instant.", + "read_only": "Ce serveur est en lecture seule pour le moment. Réessayez plus tard." }, "profile": { "title": "Profil", @@ -1300,6 +1302,17 @@ "admin_stopped": "Arrêté : ce mot de passe donnait un accès administrateur et a été supprimé", "disabled": "En pause : le répéteur n’a pas été entendu récemment" }, + "reason": { + "noObserver": "Aucun observateur ne peut encore atteindre ce répéteur.", + "noSeat": "Tous les observateurs qui peuvent atteindre ce répéteur interrogent déjà leur maximum.", + "loginFailed": "Le répéteur n’a pas accepté ce mot de passe invité. Saisissez-en un nouveau.", + "blankFailed": "Le répéteur n’a pas accepté une connexion vide ou « hello ». Saisissez un mot de passe invité.", + "adminStopped": "Le répéteur a donné un accès administrateur avec ce mot de passe, donc Beacon l’a supprimé. Saisissez un mot de passe invité, jamais celui d’un administrateur.", + "blankBlocked": "Ce répéteur donne un accès administrateur avec une connexion vide, donc Beacon ne l’interrogera pas sans mot de passe invité.", + "offline_one": "Aucun observateur ne l’a entendu depuis {{count}} jour.", + "offline_many": "Aucun observateur ne l’a entendu depuis {{count}} jours.", + "offline_other": "Aucun observateur ne l’a entendu depuis {{count}} jours." + }, "polledBy": "Interrogé par", "noObserver": "aucun observateur pour l’instant", "lastReading": "Dernière mesure", @@ -1328,7 +1341,8 @@ "not_a_repeater": "Seuls les répéteurs et les serveurs de salon peuvent être interrogés.", "password_invalid": "Le mot de passe doit comporter de 1 à 15 caractères.", "no_password_blocked": "Ce répéteur donne un accès administrateur sans mot de passe, il ne peut donc pas être interrogé de cette façon", - "requests_disabled": "Les demandes de télémétrie ne sont pas activées sur ce serveur." + "requests_disabled": "Les demandes de télémétrie ne sont pas activées sur ce serveur.", + "not_found": "Cette demande n’existe plus." } }, "portal": { diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index e3b2fc7..d72a378 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -1048,7 +1048,9 @@ "token_invalid": "Länken är inte längre giltig.", "not_signed_in": "Du är inte inloggad. Logga in och försök igen.", "csrf_rejected": "Begäran avvisades. Ladda om sidan och försök igen.", - "accounts_disabled": "Konton är inte aktiverade på den här servern." + "accounts_disabled": "Konton är inte aktiverade på den här servern.", + "service_unavailable": "Servern är upptagen. Försök igen om en stund.", + "read_only": "Servern är skrivskyddad just nu. Försök igen senare." }, "profile": { "title": "Profil", @@ -1175,6 +1177,16 @@ "admin_stopped": "Stoppad: lösenordet gav administratörsåtkomst och raderades", "disabled": "Pausad: repeatern har inte hörts på sistone" }, + "reason": { + "noObserver": "Ingen observatör kan nå den här repeatern ännu.", + "noSeat": "Alla observatörer som kan nå den här repeatern avläser redan sitt max.", + "loginFailed": "Repeatern godtog inte det här gästlösenordet. Ange ett nytt.", + "blankFailed": "Repeatern godtog inte en tom eller hello-inloggning. Ange ett gästlösenord.", + "adminStopped": "Repeatern gav administratörsåtkomst med det här lösenordet, så Beacon raderade det. Ange ett gästlösenord, aldrig ett administratörslösenord.", + "blankBlocked": "Den här repeatern ger administratörsåtkomst med en tom inloggning, så Beacon avläser den inte utan gästlösenord.", + "offline_one": "Ingen observatör har hört den på {{count}} dag.", + "offline_other": "Ingen observatör har hört den på {{count}} dagar." + }, "polledBy": "Avläses av", "noObserver": "ingen observatör ännu", "lastReading": "Senaste värde", @@ -1203,7 +1215,8 @@ "not_a_repeater": "Bara repeatrar och rumsservrar kan avläsas.", "password_invalid": "Lösenordet måste vara 1 till 15 tecken.", "no_password_blocked": "Den här repeatern ger administratörsåtkomst utan lösenord, så den kan inte avläsas på det här sättet", - "requests_disabled": "Telemetribegäran är inte aktiverade på den här servern." + "requests_disabled": "Telemetribegäran är inte aktiverade på den här servern.", + "not_found": "Den begäran finns inte längre." } }, "portal": { diff --git a/tests/api/auth.test.ts b/tests/api/auth.test.ts index 9d59c12..03e1fc0 100644 --- a/tests/api/auth.test.ts +++ b/tests/api/auth.test.ts @@ -118,3 +118,28 @@ describe("requests", () => { expect(init.body).toBe(body === undefined ? undefined : JSON.stringify(body)); }); }); + +describe("answers beacon-server really sends", () => { + it("keeps the stored Atlas under current on a 409", async () => { + const current = { revision: 9, range: "24h", limit: 12, pins: [] }; + stub(409, { error: { code: "atlas_conflict", message: "The Atlas was changed elsewhere." }, current }); + const err = await me.putAtlas({ baseRevision: 7, range: "24h", pins: [] }).catch((e) => e as AuthError); + expect(err).toBeInstanceOf(AuthError); + expect(err).toMatchObject({ status: 409, code: "atlas_conflict" }); + expect((err as AuthError).body).toMatchObject({ current }); + }); + + it("carries Retry-After and the code of a 503 service_unavailable", async () => { + stub(503, { error: { code: "service_unavailable", message: "Try again in a moment." } }, { "Retry-After": "5" }); + const err = await me.get().catch((e) => e as AuthError); + expect(err).toMatchObject({ status: 503, code: "service_unavailable", retryAfterMs: 5000 }); + }); + + it("sends enabled true and null passwords the way the server reads them", async () => { + const fn = stub(200, {}); + await requests.update("r1", { enabled: true }); + await requests.update("r1", { password: null }); + const bodies = fn.mock.calls.map((c) => (c as unknown as [string, RequestInit])[1].body); + expect(bodies).toEqual(['{"enabled":true}', '{"password":null}']); + }); +}); diff --git a/tests/features/account/requestsSection.test.tsx b/tests/features/account/requestsSection.test.tsx index 2d1d8c0..68c3908 100644 --- a/tests/features/account/requestsSection.test.tsx +++ b/tests/features/account/requestsSection.test.tsx @@ -31,7 +31,7 @@ beforeEach(() => { limit: 3, requests: [ req(), - req({ id: "r2", node: { id: null, publicKey: "ee", name: "Ridge" }, status: "disabled", statusReason: "not heard for 7 days", hasPassword: true, poller: null, latestReadingAt: null }), + req({ id: "r2", node: { id: null, publicKey: "ee", name: "Ridge" }, status: "disabled", statusReason: "Not heard by any observer for 7 days.", hasPassword: true, poller: null, latestReadingAt: null }), ], }); }); @@ -66,7 +66,7 @@ describe("telemetry requests section", () => { const b = row("Ridge"); expect(b.queryByRole("link")).not.toBeInTheDocument(); expect(b.getByText("Paused: the repeater has not been heard recently")).toBeInTheDocument(); - expect(b.getByText("not heard for 7 days")).toBeInTheDocument(); + expect(b.getByText("Not heard by any observer for 7 days.")).toBeInTheDocument(); expect(b.getByText("Password set")).toBeInTheDocument(); }); diff --git a/tests/features/account/serverContract.test.ts b/tests/features/account/serverContract.test.ts new file mode 100644 index 0000000..249c9d0 --- /dev/null +++ b/tests/features/account/serverContract.test.ts @@ -0,0 +1,92 @@ +import { afterEach, describe, expect, it } from "vitest"; +import i18n from "../../../src/i18n"; +import { authErrorText, requestErrorText } from "../../../src/features/account/errors"; +import { fromServer, toPut, type ServerAtlas } from "../../../src/features/atlas/atlasSync"; +import { requestReasonText } from "../../../src/features/account/requestReason"; + +// Every reason string beacon-server's polling package can put in statusReason. +const SERVER_REASONS = [ + "No observer can reach this repeater yet.", + "Every observer that can reach this repeater is already polling its maximum.", + "The repeater did not accept this guest password. Enter a new one.", + "The repeater did not accept a blank or hello login. Enter a guest password.", + "The repeater gave admin access to this password, so Beacon deleted it. Enter a guest password, never an admin one.", + "This repeater gives admin access to a blank login, so Beacon will not poll it without a guest password.", + "Not heard by any observer for 7 days.", +]; + +afterEach(() => i18n.changeLanguage("en")); + +describe("telemetry request reasons", () => { + it.each(["en", "fr", "sv"])("has %s text for every server reason", async (lang) => { + await i18n.changeLanguage(lang); + const english = i18n.getFixedT("en"); + for (const reason of SERVER_REASONS) { + const text = requestReasonText(i18n.t, reason); + expect(text).not.toMatch(/^account\./); + if (lang === "en") expect(text).toBe(reason); + else expect(text, reason).not.toBe(requestReasonText(english, reason)); + } + }); + + it("fills in the offline days", async () => { + expect(requestReasonText(i18n.t, "Not heard by any observer for 7 days.")).toContain("7"); + expect(requestReasonText(i18n.t, "Not heard by any observer for 1 days.")).toContain("1"); + }); + + it("shows a reason it does not know as sent, and nothing for none", () => { + expect(requestReasonText(i18n.t, "Something new.")).toBe("Something new."); + expect(requestReasonText(i18n.t, "")).toBe(""); + }); +}); + +describe("error codes the server can send", () => { + it.each(["en", "fr", "sv"])("maps service_unavailable, read_only and not_found in %s", async (lang) => { + await i18n.changeLanguage(lang); + for (const code of ["service_unavailable", "read_only", "not_found"]) { + const text = requestErrorText(i18n.t, { code }); + expect(text, code).not.toBe(authErrorText(i18n.t, {})); + expect(text).not.toMatch(/^account\./); + } + }); +}); + +// What GET /me/atlas marshals: a node pin without tiles or view, a node the server lost, an observer pin whose +// observer row is gone (observerId null), and an observer pin with a chosen tile layout. +const KEY_A = "0f".repeat(32); +const KEY_B = "1e".repeat(32); +const KEY_C = "2d".repeat(32); +const SERVER_ATLAS = JSON.parse(`{ + "revision": 7, "range": "3d", "limit": 12, + "pins": [ + {"kind":"node","name":"Hilltop","publicKey":"${KEY_A}","id":"3f2b8c1e-6a52-4d0e-9b57-0d3d2b6a1c11","observerId":null,"view":"heard"}, + {"kind":"node","name":"Gone","publicKey":"${KEY_B}","id":null,"observerId":null}, + {"kind":"observer","name":"North Ridge","observerPublicKey":"${KEY_C}","observerId":null,"tiles":["snr","rssi","noise","queue"]} + ] +}`) as ServerAtlas; + +describe("Atlas document as the server marshals it", () => { + it("reads null ids and omitted fields", () => { + const { atlas } = fromServer(SERVER_ATLAS, null, {}); + expect(atlas.range).toBe("3d"); + expect(atlas.pins).toHaveLength(3); + expect(atlas.pins[0]).toMatchObject({ kind: "node", publicKey: KEY_A, view: "heard" }); + expect(atlas.pins[1]).toMatchObject({ kind: "node", publicKey: KEY_B }); + expect(atlas.pins[2]).toMatchObject({ kind: "observer", tiles: ["snr", "rssi", "noise", "queue"] }); + }); + + it("sends a body the server's validator accepts", () => { + const { atlas, keys } = fromServer(SERVER_ATLAS, null, {}); + const body = toPut(atlas, keys, SERVER_ATLAS.revision); + expect(Object.keys(body).sort()).toEqual(["baseRevision", "pins", "range"]); + expect(body.pins.length).toBeLessThanOrEqual(12); + for (const pin of body.pins) { + expect(["node", "observer"]).toContain(pin.kind); + if (pin.kind === "node") expect(pin.publicKey).toMatch(/^[0-9a-f]{64}$/); + else expect("observerId" in pin || "observerPublicKey" in pin).toBe(true); + if ("view" in pin) expect(["heard", "observer"]).toContain(pin.view); + if (pin.tiles) expect(new Set(pin.tiles).size).toBe(4); + expect([...pin.name].length).toBeLessThanOrEqual(160); + } + }); +}); diff --git a/tests/hooks/useSession.test.tsx b/tests/hooks/useSession.test.tsx index 08dfa2b..b92108a 100644 --- a/tests/hooks/useSession.test.tsx +++ b/tests/hooks/useSession.test.tsx @@ -52,6 +52,16 @@ describe("useSession", () => { expect(meCalls()).toHaveLength(1); }); + it("keeps the user when a later /me answers 503 service_unavailable", async () => { + stub("local", 200, { user }); + const { result } = renderHook(() => useSession(), { wrapper }); + await waitFor(() => expect(result.current.user).toEqual(user)); + stub("local", 503, { error: { code: "service_unavailable", message: "Try again in a moment." } }); + await act(async () => { await client.refetchQueries({ queryKey: ["me"], exact: true }); }); + expect(client.getQueryState(["me"])?.status).toBe("error"); + expect(result.current.user).toEqual(user); + }); + it("makes no /me request when accounts are off", async () => { stub("off", 200, { user }); const { result } = renderHook(() => useSession(), { wrapper });