Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions apps/web/public/i18n/locales/en/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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 }) => (
<a href={href}>{children}</a>
),
}));

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(<UnsafeRolesDialog open onOpenChange={onOpenChange} />);
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
expect(eventBus.emit).toHaveBeenCalledWith("dialog:unsafeRoles", {
action: "dismiss",
});
expect(setDialogOpen).toHaveBeenCalledWith("unsafeRoles", false);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,15 @@ export const UnsafeRolesDialog = ({
};

return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog
open={open}
onOpenChange={(next) => {
// Esc and outside clicks dismiss too, so the pending role choice
// is answered rather than left waiting.
if (next) onOpenChange(next);
else handleCloseDialog("dismiss");
}}
>
<DialogContent className="max-w-8 flex flex-col">
<DialogClose onClick={() => handleCloseDialog("dismiss")} />
<DialogHeader>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ export const useUnsafeRolesDialog = () => {
}, [setDialogOpen]);

const validateRoleSelection = useCallback(
(newRoleKey: string): Promise<boolean> => {
if (!UNSAFE_ROLES.includes(newRoleKey as UnsafeRole)) {
return Promise.resolve(true);
}
(newRoleKey: string): boolean | Promise<boolean> => {
// Answered synchronously so the select saves a safe role at once.
if (!UNSAFE_ROLES.includes(newRoleKey as UnsafeRole)) return true;

setDialogOpen("unsafeRoles", true);

Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/components/Form/DynamicForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ export interface GenericFormElementProps<T extends FieldValues, Y> {
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<T extends FieldValues> {
Expand Down Expand Up @@ -191,6 +197,11 @@ export function DynamicForm<T extends FieldValues>({
disabled={isDisabled(field.disabledBy, field.disabled)}
isDirty={fieldState.isDirty}
invalid={fieldState.invalid}
submit={
submitType === "onChange"
? () => void handleSubmit(onSubmit)()
: undefined
}
/>
);
return (
Expand Down
3 changes: 3 additions & 0 deletions apps/web/src/components/Form/DynamicFormField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export interface DynamicFormFieldProps<T extends FieldValues> {
disabled?: boolean;
isDirty?: boolean;
invalid?: boolean;
submit?: () => void;
}

export function DynamicFormField<T extends FieldValues>({
Expand All @@ -41,6 +42,7 @@ export function DynamicFormField<T extends FieldValues>({
disabled,
isDirty,
invalid,
submit,
}: DynamicFormFieldProps<T>) {
switch (field.type) {
case "text":
Expand Down Expand Up @@ -73,6 +75,7 @@ export function DynamicFormField<T extends FieldValues>({
disabled={disabled}
isDirty={isDirty}
invalid={invalid}
submit={submit}
/>
);
case "passwordGenerator":
Expand Down
85 changes: 85 additions & 0 deletions apps/web/src/components/Form/FormSelect.test.tsx
Original file line number Diff line number Diff line change
@@ -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<string, number> = { A: 0, B: 1 };

const renderSelect = (
validate?: (key: string) => boolean | Promise<boolean>,
) => {
const onSubmit = vi.fn();
render(
<DynamicForm<{ choice: number }>
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<typeof vi.fn>) =>
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<boolean>((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");
});
});
17 changes: 15 additions & 2 deletions apps/web/src/components/Form/FormSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ import { type FieldValues, useController } from "react-hook-form";
export interface SelectFieldProps<T> extends BaseFormBuilderProps<T> {
type: "select";
selectChange?: (e: string, name: string) => void;
validate?: (newValue: string) => Promise<boolean>;
/** False keeps the current value. Answer synchronously when you can. */
validate?: (newValue: string) => boolean | Promise<boolean>;
defaultValue?: string;
properties: BaseFormBuilderProps<T>["properties"] & {
defaultValue?: T;
Expand Down Expand Up @@ -44,6 +45,7 @@ export function SelectInput<T extends FieldValues>({
field,
isDirty,
invalid,
submit,
}: GenericFormElementProps<T, SelectFieldProps<T>>) {
const {
field: { value, onChange, ref, onBlur, ...rest },
Expand Down Expand Up @@ -79,10 +81,21 @@ export function SelectInput<T extends FieldValues>({
}

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) {
Expand Down
Loading
Loading