diff --git a/apps/web/public/i18n/locales/en/config.json b/apps/web/public/i18n/locales/en/config.json index 6e6c5ca07..abeb58fcd 100644 --- a/apps/web/public/i18n/locales/en/config.json +++ b/apps/web/public/i18n/locales/en/config.json @@ -568,11 +568,18 @@ }, "packetSignaturePolicy": { "label": "Protection level", - "description": "Compatible accepts unsigned packets but drops any with a wrong signature. Balanced also rejects unsigned broadcasts from nodes that have signed before. Strict accepts only packets with a verified signature or successful PKI decryption, so packets from older nodes may be ignored.", - "compatible": "Compatible - Accept Unsigned", - "balanced": "Balanced - Prefer Authenticated", - "strict": "Strict - Require Authentication", - "unsupported": "This device does not support packet signature verification." + "compatible": "Compatible — Accept unsigned", + "compatibleDescription": "Accept unsigned traffic for maximum compatibility. A signature that can be checked and is wrong still drops the packet.", + "balanced": "Balanced — Prefer authenticated", + "balancedDescription": "Reject unsigned downgrade attempts from nodes known to sign.", + "strict": "Strict — Require authentication", + "strictDescription": "Only show and process cryptographically authenticated mesh packets. Older nodes and oversized packets may disappear.", + "unsupported": "This connected device does not support packet signature verification.", + "strictConfirm": { + "title": "Enable Strict authentication?", + "description": "Strict ignores every remote mesh packet that is not cryptographically authenticated. Older firmware, licensed or ham nodes without PKI keys, and oversized packets may disappear. PKI-authenticated direct messages remain available.", + "confirm": "Enable Strict" + } }, "lockdown": { "label": "Lockdown mode", diff --git a/apps/web/src/components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.test.tsx b/apps/web/src/components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.test.tsx new file mode 100644 index 000000000..57e8c26c9 --- /dev/null +++ b/apps/web/src/components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.test.tsx @@ -0,0 +1,31 @@ +import { eventBus } from "@core/utils/eventBus.ts"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { UnsafeRolesDialog } from "./UnsafeRolesDialog.tsx"; + +vi.mock("@core/utils/eventBus.ts", () => ({ + eventBus: { on: vi.fn(), off: vi.fn(), emit: vi.fn() }, +})); + +vi.mock("@components/UI/Typography/Link.tsx", () => ({ + Link: ({ href, children }: { href: string; children: React.ReactNode }) => ( + {children} + ), +})); + +const setDialogOpen = vi.fn(); +vi.mock("@core/stores", () => ({ + useDevice: () => ({ setDialogOpen }), +})); + +describe("UnsafeRolesDialog", () => { + it("answers the pending role choice as dismissed when closed with Esc", () => { + const onOpenChange = vi.fn(); + render(); + fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" }); + expect(eventBus.emit).toHaveBeenCalledWith("dialog:unsafeRoles", { + action: "dismiss", + }); + expect(setDialogOpen).toHaveBeenCalledWith("unsafeRoles", false); + }); +}); diff --git a/apps/web/src/components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.tsx b/apps/web/src/components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.tsx index e3f83e6b4..2f53a9a09 100644 --- a/apps/web/src/components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.tsx +++ b/apps/web/src/components/Dialog/UnsafeRolesDialog/UnsafeRolesDialog.tsx @@ -40,7 +40,15 @@ export const UnsafeRolesDialog = ({ }; return ( - + { + // Esc and outside clicks dismiss too, so the pending role choice + // is answered rather than left waiting. + if (next) onOpenChange(next); + else handleCloseDialog("dismiss"); + }} + > handleCloseDialog("dismiss")} /> diff --git a/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.test.tsx b/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.test.tsx index 4adcd091d..359f26c6f 100644 --- a/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.test.tsx +++ b/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.test.tsx @@ -77,8 +77,8 @@ describe("useUnsafeRolesDialog", () => { const { result } = renderUnsafeRolesHook(); const safeRole = "SAFE_ROLE"; - const validationResult = - await result.current.validateRoleSelection(safeRole); + // Synchronous, so the select saves the role within its change event. + const validationResult = result.current.validateRoleSelection(safeRole); expect(validationResult).toBe(true); expect(mockDevice.setDialogOpen).not.toHaveBeenCalled(); diff --git a/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.ts b/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.ts index 39623e086..81df31962 100644 --- a/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.ts +++ b/apps/web/src/components/Dialog/UnsafeRolesDialog/useUnsafeRolesDialog.ts @@ -13,10 +13,9 @@ export const useUnsafeRolesDialog = () => { }, [setDialogOpen]); const validateRoleSelection = useCallback( - (newRoleKey: string): Promise => { - if (!UNSAFE_ROLES.includes(newRoleKey as UnsafeRole)) { - return Promise.resolve(true); - } + (newRoleKey: string): boolean | Promise => { + // Answered synchronously so the select saves a safe role at once. + if (!UNSAFE_ROLES.includes(newRoleKey as UnsafeRole)) return true; setDialogOpen("unsafeRoles", true); diff --git a/apps/web/src/components/Form/DynamicForm.tsx b/apps/web/src/components/Form/DynamicForm.tsx index 3be70c744..4a6b6e51d 100644 --- a/apps/web/src/components/Form/DynamicForm.tsx +++ b/apps/web/src/components/Form/DynamicForm.tsx @@ -50,6 +50,12 @@ export interface GenericFormElementProps { field: Y; isDirty?: boolean; invalid?: boolean; + /** + * Saves the form as a change would, for a field whose value lands after + * the change event (e.g. once a confirmation dialog resolves). Unset when + * the form saves on submit. + */ + submit?: () => void; } export interface DynamicFormProps { @@ -191,6 +197,11 @@ export function DynamicForm({ disabled={isDisabled(field.disabledBy, field.disabled)} isDirty={fieldState.isDirty} invalid={fieldState.invalid} + submit={ + submitType === "onChange" + ? () => void handleSubmit(onSubmit)() + : undefined + } /> ); return ( diff --git a/apps/web/src/components/Form/DynamicFormField.tsx b/apps/web/src/components/Form/DynamicFormField.tsx index 9452d30c4..bbbf401b5 100644 --- a/apps/web/src/components/Form/DynamicFormField.tsx +++ b/apps/web/src/components/Form/DynamicFormField.tsx @@ -33,6 +33,7 @@ export interface DynamicFormFieldProps { disabled?: boolean; isDirty?: boolean; invalid?: boolean; + submit?: () => void; } export function DynamicFormField({ @@ -41,6 +42,7 @@ export function DynamicFormField({ disabled, isDirty, invalid, + submit, }: DynamicFormFieldProps) { switch (field.type) { case "text": @@ -73,6 +75,7 @@ export function DynamicFormField({ disabled={disabled} isDirty={isDirty} invalid={invalid} + submit={submit} /> ); case "passwordGenerator": diff --git a/apps/web/src/components/Form/FormSelect.test.tsx b/apps/web/src/components/Form/FormSelect.test.tsx new file mode 100644 index 000000000..b31ea6277 --- /dev/null +++ b/apps/web/src/components/Form/FormSelect.test.tsx @@ -0,0 +1,85 @@ +import { DynamicForm } from "@components/Form/DynamicForm.tsx"; +import { render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { beforeAll, describe, expect, it, vi } from "vitest"; + +beforeAll(() => { + Element.prototype.hasPointerCapture ??= () => false; + Element.prototype.releasePointerCapture ??= () => {}; + Element.prototype.scrollIntoView ??= () => {}; +}); + +const OPTIONS: Record = { A: 0, B: 1 }; + +const renderSelect = ( + validate?: (key: string) => boolean | Promise, +) => { + const onSubmit = vi.fn(); + render( + + onSubmit={onSubmit} + defaultValues={{ choice: 0 }} + fieldGroups={[ + { + label: "Group", + description: "", + fields: [ + { + type: "select", + name: "choice", + label: "Choice", + description: "", + validate, + properties: { enumValue: OPTIONS }, + }, + ], + }, + ]} + />, + ); + return onSubmit; +}; + +const pick = async (name: string) => { + const user = userEvent.setup(); + await user.click(screen.getByRole("combobox")); + await user.click(screen.getByRole("option", { name })); +}; + +const saved = (onSubmit: ReturnType) => + onSubmit.mock.calls.map(([values]) => values.choice); + +describe("SelectInput", () => { + it("saves the chosen option", async () => { + const onSubmit = renderSelect(); + await pick("B"); + await waitFor(() => expect(saved(onSubmit).at(-1)).toBe(1)); + }); + + it("saves an option a synchronous validate accepts", async () => { + const onSubmit = renderSelect(() => true); + await pick("B"); + await waitFor(() => expect(saved(onSubmit).at(-1)).toBe(1)); + }); + + it("saves an option once an asynchronous validate accepts it", async () => { + let accept: (accepted: boolean) => void = () => {}; + const onSubmit = renderSelect( + () => new Promise((resolve) => (accept = resolve)), + ); + await pick("B"); + expect(saved(onSubmit)).not.toContain(1); + accept(true); + await waitFor(() => expect(saved(onSubmit).at(-1)).toBe(1)); + expect(saved(onSubmit).filter((choice) => choice === 1)).toHaveLength(1); + expect(screen.getByRole("combobox")).toHaveTextContent("B"); + }); + + it("keeps the current option when validate refuses", async () => { + const onSubmit = renderSelect(() => Promise.resolve(false)); + await pick("B"); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(saved(onSubmit)).not.toContain(1); + expect(screen.getByRole("combobox")).toHaveTextContent("A"); + }); +}); diff --git a/apps/web/src/components/Form/FormSelect.tsx b/apps/web/src/components/Form/FormSelect.tsx index a5fc1ca67..32feaedcf 100644 --- a/apps/web/src/components/Form/FormSelect.tsx +++ b/apps/web/src/components/Form/FormSelect.tsx @@ -16,7 +16,8 @@ import { type FieldValues, useController } from "react-hook-form"; export interface SelectFieldProps extends BaseFormBuilderProps { type: "select"; selectChange?: (e: string, name: string) => void; - validate?: (newValue: string) => Promise; + /** False keeps the current value. Answer synchronously when you can. */ + validate?: (newValue: string) => boolean | Promise; defaultValue?: string; properties: BaseFormBuilderProps["properties"] & { defaultValue?: T; @@ -44,6 +45,7 @@ export function SelectInput({ field, isDirty, invalid, + submit, }: GenericFormElementProps>) { const { field: { value, onChange, ref, onBlur, ...rest }, @@ -79,10 +81,21 @@ export function SelectInput({ } if (field.validate) { - const isValid = await field.validate(selectedKey); + // A synchronous answer applies the value within this event, so the + // form's change handler submits the new value rather than the old one. + const result = field.validate(selectedKey); + const answeredLater = typeof result !== "boolean"; + const isValid = answeredLater ? await result : result; if (!isValid) { return; } + if (answeredLater) { + // The change event has already saved the old value; save the new one. + field.selectChange?.(newValue, selectedKey); + onChange(Number.parseInt(newValue, 10)); + submit?.(); + return; + } } if (field.selectChange) { diff --git a/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx b/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx index dc757bd99..338722bea 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/Security.test.tsx @@ -9,7 +9,8 @@ import { waitFor, within, } from "@testing-library/react"; -import { beforeEach, describe, expect, it, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest"; import { RemoteSettingsContext, type RemoteSettingsScope, @@ -67,6 +68,29 @@ vi.mock("@core/kmp/hooks", () => ({ useSignal: (signal: { value: unknown }) => signal.value, })); +// Radix Select calls these, which jsdom lacks. +beforeAll(() => { + Element.prototype.hasPointerCapture ??= () => false; + Element.prototype.releasePointerCapture ??= () => {}; + Element.prototype.scrollIntoView ??= () => {}; +}); + +const Policy = Protobuf.Config.Config_SecurityConfig_PacketSignaturePolicy; +const LABELS = { + compatible: "Compatible — Accept unsigned", + balanced: "Balanced — Prefer authenticated", + strict: "Strict — Require authentication", +}; +const policySelect = () => + screen.getByRole("combobox", { name: "Protection level" }); +const choosePolicy = async (label: string) => { + const user = userEvent.setup(); + await user.click(policySelect()); + await user.click(screen.getByRole("option", { name: label })); +}; +const stagedPolicies = () => + setRadioSection.mock.calls.map(([, staged]) => staged.packetSignaturePolicy); + describe("Security", () => { beforeEach(() => { metadata = { hasXeddsa: true }; @@ -104,7 +128,7 @@ describe("Security", () => { ).toBeDisabled(); expect( screen.getByText( - "This device does not support packet signature verification.", + "This connected device does not support packet signature verification.", ), ).toBeInTheDocument(); }); @@ -117,6 +141,100 @@ describe("Security", () => { ).toBeDisabled(); }); + describe("packet authenticity", () => { + it("offers the three policies in Android's order", async () => { + render(); + await userEvent.setup().click(policySelect()); + expect( + screen.getAllByRole("option").map((option) => option.textContent), + ).toEqual([LABELS.compatible, LABELS.balanced, LABELS.strict]); + }); + + it("shows Compatible, the protobuf default, when the radio sends no policy", () => { + render(); + expect(policySelect()).toHaveTextContent(LABELS.compatible); + expect( + screen.getByText(/Accept unsigned traffic for maximum compatibility/), + ).toBeInTheDocument(); + }); + + it("describes the chosen policy", () => { + security = create(Protobuf.Config.Config_SecurityConfigSchema, { + ...baseSecurity, + packetSignaturePolicy: Policy.STRICT, + }); + render(); + expect(policySelect()).toHaveTextContent(LABELS.strict); + expect( + screen.getByText( + "Only show and process cryptographically authenticated mesh packets. Older nodes and oversized packets may disappear.", + ), + ).toBeInTheDocument(); + }); + + it("stages Balanced without asking", async () => { + render(); + await choosePolicy(LABELS.balanced); + expect(screen.queryByRole("dialog")).toBeNull(); + await waitFor(() => expect(stagedPolicies()).toContain(Policy.BALANCED)); + }); + + it("keeps the previous policy when Strict is cancelled", async () => { + render(); + await choosePolicy(LABELS.strict); + const dialog = screen.getByRole("dialog", { + name: "Enable Strict authentication?", + }); + expect(dialog).toHaveTextContent( + "Strict ignores every remote mesh packet that is not cryptographically authenticated.", + ); + expect(dialog).toHaveTextContent("oversized packets may disappear"); + fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + expect(policySelect()).toHaveTextContent(LABELS.compatible); + expect(stagedPolicies()).not.toContain(Policy.STRICT); + }); + + it("stages Strict once confirmed", async () => { + render(); + await choosePolicy(LABELS.strict); + const dialog = screen.getByRole("dialog", { + name: "Enable Strict authentication?", + }); + fireEvent.click( + within(dialog).getByRole("button", { name: "Enable Strict" }), + ); + await waitFor(() => expect(stagedPolicies()).toContain(Policy.STRICT)); + expect(policySelect()).toHaveTextContent(LABELS.strict); + }); + + it("drops a pending Strict confirmation when support goes away", async () => { + const { rerender } = render(); + await choosePolicy(LABELS.strict); + expect(screen.getByRole("dialog")).toBeVisible(); + metadata = { hasXeddsa: false }; + rerender(); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + metadata = { hasXeddsa: true }; + rerender(); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(stagedPolicies()).not.toContain(Policy.STRICT); + }); + + it("leaves Strict for a weaker policy without asking", async () => { + security = create(Protobuf.Config.Config_SecurityConfigSchema, { + ...baseSecurity, + packetSignaturePolicy: Policy.STRICT, + }); + render(); + await choosePolicy(LABELS.compatible); + expect(screen.queryByRole("dialog")).toBeNull(); + await waitFor(() => + expect(stagedPolicies()).toContain(Policy.COMPATIBLE), + ); + }); + }); + it("shows the public key and masks the private key until asked", () => { render(); const zeroKey = "A".repeat(43) + "="; @@ -328,6 +446,15 @@ describe("Security on a remote node", () => { expect(staged.serialEnabled).toBe(true); expect(staged.privateKey).toEqual(nodeKey); }); + + it("stages Strict with the node's own key once confirmed", async () => { + renderRemote(); + await choosePolicy(LABELS.strict); + fireEvent.click(screen.getByRole("button", { name: "Enable Strict" })); + await waitFor(() => expect(stagedPolicies()).toContain(Policy.STRICT)); + const [, staged] = setRadioSection.mock.calls.at(-1) ?? []; + expect(staged.privateKey).toEqual(nodeKey); + }); }); describe("that withheld its private key (firmware 2.8.1+)", () => { @@ -353,6 +480,7 @@ describe("Security on a remote node", () => { screen.queryByRole("button", { name: "Add admin key" }), ).toBeNull(); expect(screen.getByRole("button", { name: "+ Add key" })).toBeDisabled(); + expect(policySelect()).toBeDisabled(); }); }); }); @@ -374,6 +502,7 @@ describe("Security while settings are read-only", () => { expect(screen.getByRole("button", { name })).toBeDisabled(); } expect(screen.getByRole("switch", { name: "Managed Mode" })).toBeDisabled(); + expect(policySelect()).toBeDisabled(); // Reading a key is not a change: the public key can still be copied. const publicKey = screen.getByRole("group", { name: "Public Key" }); expect( diff --git a/apps/web/src/components/PageComponents/Settings/Security/Security.tsx b/apps/web/src/components/PageComponents/Settings/Security/Security.tsx index 6795364f3..ffdd4e37d 100644 --- a/apps/web/src/components/PageComponents/Settings/Security/Security.tsx +++ b/apps/web/src/components/PageComponents/Settings/Security/Security.tsx @@ -17,6 +17,7 @@ import { READ_ONLY_ROWS_CLASS, ReadOnlyFieldset, SettingsReadOnlyContext, + useSettingsReadOnly, } from "@components/Settings/SettingsReadOnly.tsx"; import { Button } from "@components/UI/Button.tsx"; import { Callout } from "@components/UI/Callout.tsx"; @@ -121,6 +122,7 @@ export const Security = ({ onFormInit }: SecurityConfigProps) => { const [removingSlot, setRemovingSlot] = useState(); const [pickingRadio, setPickingRadio] = useState(false); const [generatingKey, setGeneratingKey] = useState(false); + const [confirmingStrict, setConfirmingStrict] = useState(false); useEffect(() => { onFormInit?.(formMethods); @@ -174,13 +176,61 @@ export const Security = ({ onFormInit }: SecurityConfigProps) => { // labels rather than the raw enum names. const PacketSignaturePolicy = Protobuf.Config.Config_SecurityConfig_PacketSignaturePolicy; - const packetSignaturePolicyOptions = { + const packetSignaturePolicyOptions: Record = { [t("security.packetSignaturePolicy.compatible")]: PacketSignaturePolicy.COMPATIBLE, [t("security.packetSignaturePolicy.balanced")]: PacketSignaturePolicy.BALANCED, [t("security.packetSignaturePolicy.strict")]: PacketSignaturePolicy.STRICT, }; + const packetSignaturePolicyHelp: Record = { + [PacketSignaturePolicy.COMPATIBLE]: t( + "security.packetSignaturePolicy.compatibleDescription", + ), + [PacketSignaturePolicy.BALANCED]: t( + "security.packetSignaturePolicy.balancedDescription", + ), + [PacketSignaturePolicy.STRICT]: t( + "security.packetSignaturePolicy.strictDescription", + ), + }; + const packetSignaturePolicy = useWatch({ + control, + name: "packetSignaturePolicy", + }); + const readOnly = useSettingsReadOnly() || locked; + // Only a radio that reports XEdDSA signing can apply the policy. + const canSetPolicy = metadata?.hasXeddsa === true && !readOnly; + // Losing support or write access cancels a pending Strict confirmation, + // as on Android, so it can't reappear by itself when access returns. + const [couldSetPolicy, setCouldSetPolicy] = useState(canSetPolicy); + if (couldSetPolicy !== canSetPolicy) { + setCouldSetPolicy(canSetPolicy); + if (!canSetPolicy) setConfirmingStrict(false); + } + + /** Strict hides unauthenticated traffic, so it is confirmed first. */ + const confirmPolicyChange = (label: string): boolean => { + const next = packetSignaturePolicyOptions[label]; + if ( + next !== PacketSignaturePolicy.STRICT || + packetSignaturePolicy === PacketSignaturePolicy.STRICT + ) { + return true; + } + setConfirmingStrict(true); + return false; + }; + + const enableStrict = () => { + setConfirmingStrict(false); + if (!canSetPolicy) return; + setValue("packetSignaturePolicy", PacketSignaturePolicy.STRICT, { + shouldDirty: true, + shouldValidate: true, + }); + void handleSubmit(onSubmit)(); + }; /** The translated validation message for a field, as DynamicForm shows it. */ const errorText = (name: Path): string | undefined => { @@ -467,9 +517,9 @@ export const Security = ({ onFormInit }: SecurityConfigProps) => { description: metadata?.hasXeddsa === false ? t("security.packetSignaturePolicy.unsupported") - : t("security.packetSignaturePolicy.description"), - // Only a radio that reports XEdDSA signing can apply the policy. + : packetSignaturePolicyHelp[packetSignaturePolicy], disabled: metadata?.hasXeddsa !== true, + validate: confirmPolicyChange, properties: { enumValue: packetSignaturePolicyOptions, }, @@ -542,6 +592,17 @@ export const Security = ({ onFormInit }: SecurityConfigProps) => { ) : ( form )} + +