On desktop, tauri-plugin-dialog 2.6.0 replaces window.confirm with an async function: confirm(...) returned a Promise, always truthy, so every guard `if (!confirm(...)) return;` let the action run before the user answered. Deleting a secondary profile removed its database even on "Cancel". - confirmAction() (src/services/confirmService.ts) calls the plugin's ask() with a warning icon and buttons labelled in the app language (common.confirm / common.cancel); a failed call resolves false and is logged (fail closed). @tauri-apps/plugin-dialog 2.6.0 added, the crate's version. - The six sites await it: profile, category, adjustment, budget template and Balance category deletions, and both confirmations of the license key removal (performRemoveLicense takes an async confirm). - native-dialog-guard.test.ts fails on any native confirm/alert in src/ and on any confirmation not awaited (TypeScript does not flag `!promise`). - Tests: confirmService, the deletion of a profile in ProfileFormModal, and the license removal tests with an async confirm (test: reproduces #421: six of them were red on the old code). Refs #421 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
467 lines
19 KiB
TypeScript
467 lines
19 KiB
TypeScript
import { useCallback, useEffect, useMemo, useReducer } from "react";
|
|
import {
|
|
ACTIVATION_TOKEN_LOG,
|
|
activateMachine,
|
|
deactivateMachine,
|
|
listActivatedMachines,
|
|
getActivationStatus,
|
|
removeLicense,
|
|
type ActivationStatus,
|
|
type LicenseError,
|
|
type LicenseErrorCode,
|
|
type LicenseResult,
|
|
type MachineInfo,
|
|
type MachineList,
|
|
} from "../services/licenseService";
|
|
import { logInfo, logWarn } from "../services/logService";
|
|
import { useLicenseContext } from "../contexts/LicenseContext";
|
|
|
|
// Machine activation state of the License card (issue #270), and the removal of the
|
|
// stored key (#370), which frees this machine's slot first when it is activated.
|
|
//
|
|
// The license server allows 5 requests per minute and per IP, shared by
|
|
// activate, verify and deactivate. The machine-limit path (activate → 409 →
|
|
// list via verify → deactivate → activate) therefore has to fit in 4 calls:
|
|
// a successful deactivation removes the machine locally instead of re-running
|
|
// verify, and nothing loads the list from an effect (StrictMode would double
|
|
// it). List loads come only from explicit handlers.
|
|
//
|
|
// A `license_revoked` answer, from any of the three calls, is persisted by the Rust
|
|
// command that received it (#365): this hook only reloads the LicenseContext, so the
|
|
// edition (Free) and the card follow. The revocation check, made at app start and after
|
|
// a key is entered (#373), shares that budget: one check brings the machine-limit path to
|
|
// the 5 requests of the first minute, and two checks in that minute (one at start for a
|
|
// previous key, one when a new key is entered) bring it to 6, so its last call can get a
|
|
// 429, which the card names as a rate-limit error. Removing the key of an activated
|
|
// machine spends one deactivate call (#370).
|
|
//
|
|
// Loading the list may remove this machine's activation token, when the list names no
|
|
// activation of this machine (#367): the activation status is read again after every list
|
|
// load, a local read, so "Activate" comes back without a reload. No request is added.
|
|
|
|
export interface LicenseMachinesState {
|
|
activation: ActivationStatus | null;
|
|
machines: MachineInfo[];
|
|
listOpen: boolean;
|
|
listLoading: boolean;
|
|
listLoaded: boolean;
|
|
/** Error of the list itself (verify) or of a deactivation. */
|
|
listError: LicenseError | null;
|
|
activating: boolean;
|
|
/** Error of the last activation. Survives the list load it may trigger. */
|
|
activationError: LicenseError | null;
|
|
/** Machine being deactivated; every Deactivate button is disabled meanwhile. */
|
|
deactivatingId: string | null;
|
|
/**
|
|
* The stored key is being removed (#370), its slot freed first when asked: the card's
|
|
* other actions wait, since each reads or writes the key or the token it removes.
|
|
*/
|
|
removing: boolean;
|
|
/** Error of the last removal of the key, named on the card. */
|
|
removeError: LicenseError | null;
|
|
}
|
|
|
|
export type LicenseMachinesAction =
|
|
| { type: "ACTIVATION_STATUS"; activation: ActivationStatus }
|
|
| { type: "TOGGLE_LIST" }
|
|
| { type: "LIST_LOAD_START" }
|
|
| { type: "LIST_LOAD_DONE"; machines: MachineInfo[] }
|
|
| { type: "LIST_LOAD_ERROR"; error: LicenseError }
|
|
| { type: "ACTIVATE_START" }
|
|
| { type: "ACTIVATE_DONE" }
|
|
| { type: "ACTIVATE_ERROR"; error: LicenseError }
|
|
| { type: "DEACTIVATE_START"; machineId: string }
|
|
| { type: "DEACTIVATE_DONE"; machineId: string }
|
|
| { type: "DEACTIVATE_ERROR"; error: LicenseError }
|
|
| { type: "REMOVE_START" }
|
|
| { type: "REMOVE_ERROR"; error: LicenseError }
|
|
| { type: "REMOVE_END" };
|
|
|
|
export const initialLicenseMachinesState: LicenseMachinesState = {
|
|
activation: null,
|
|
machines: [],
|
|
listOpen: false,
|
|
listLoading: false,
|
|
listLoaded: false,
|
|
listError: null,
|
|
activating: false,
|
|
activationError: null,
|
|
deactivatingId: null,
|
|
removing: false,
|
|
removeError: null,
|
|
};
|
|
|
|
export function licenseMachinesReducer(
|
|
state: LicenseMachinesState,
|
|
action: LicenseMachinesAction,
|
|
): LicenseMachinesState {
|
|
switch (action.type) {
|
|
case "ACTIVATION_STATUS":
|
|
return { ...state, activation: action.activation };
|
|
case "TOGGLE_LIST":
|
|
return { ...state, listOpen: !state.listOpen };
|
|
// The list actions never touch activationError: the machine-limit message
|
|
// must stay visible while the list it opened loads (D2).
|
|
case "LIST_LOAD_START":
|
|
return { ...state, listLoading: true, listError: null };
|
|
case "LIST_LOAD_DONE":
|
|
return {
|
|
...state,
|
|
listLoading: false,
|
|
listLoaded: true,
|
|
listError: null,
|
|
machines: action.machines,
|
|
};
|
|
case "LIST_LOAD_ERROR":
|
|
// listLoaded stays false so that reopening the list retries.
|
|
return {
|
|
...state,
|
|
listLoading: false,
|
|
listLoaded: false,
|
|
listError: action.error,
|
|
machines: [],
|
|
};
|
|
case "ACTIVATE_START":
|
|
return { ...state, activating: true, activationError: null };
|
|
case "ACTIVATE_DONE":
|
|
// The loaded list no longer reflects the server: close it and mark it
|
|
// stale rather than spending another verify call.
|
|
return { ...state, activating: false, listOpen: false, listLoaded: false, machines: [] };
|
|
case "ACTIVATE_ERROR":
|
|
return {
|
|
...state,
|
|
activating: false,
|
|
activationError: action.error,
|
|
listOpen: action.error.code === "machine_limit_reached" ? true : state.listOpen,
|
|
};
|
|
case "DEACTIVATE_START":
|
|
return { ...state, deactivatingId: action.machineId, listError: null };
|
|
case "DEACTIVATE_DONE":
|
|
return {
|
|
...state,
|
|
deactivatingId: null,
|
|
machines: state.machines.filter((m) => m.machine_id !== action.machineId),
|
|
// A slot is now free: the machine-limit message no longer holds.
|
|
activationError:
|
|
state.activationError?.code === "machine_limit_reached" ? null : state.activationError,
|
|
};
|
|
case "DEACTIVATE_ERROR":
|
|
return { ...state, deactivatingId: null, listError: action.error };
|
|
case "REMOVE_START":
|
|
return { ...state, removing: true, removeError: null };
|
|
case "REMOVE_ERROR":
|
|
return { ...state, removing: false, removeError: action.error };
|
|
case "REMOVE_END":
|
|
return { ...state, removing: false };
|
|
}
|
|
}
|
|
|
|
/** The "no machine activated" line: only for a loaded, empty, error-free list. */
|
|
export function selectShowEmptyState(state: LicenseMachinesState): boolean {
|
|
return (
|
|
state.listLoaded && !state.listLoading && state.machines.length === 0 && state.listError === null
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Deactivate buttons are live only when no deactivation, no list reload and no removal of
|
|
* the key is running. A reload (e.g. the one a 409 triggers over an already loaded list)
|
|
* returns the server's list as of its request: a machine deactivated meanwhile would
|
|
* reappear in it. A removal may be freeing this machine's slot itself (#370).
|
|
*/
|
|
export function selectCanDeactivate(state: LicenseMachinesState): boolean {
|
|
return state.deactivatingId === null && !state.listLoading && !state.removing;
|
|
}
|
|
|
|
/**
|
|
* The Activate button is live only when the key is not revoked and no activation, no
|
|
* list reload, no deactivation and no removal of the key is running. A revoked key gets a
|
|
* 403 on every attempt, each one spending the shared rate budget. A verify answer landing
|
|
* after a successful activation would mark as fresh a list that no longer includes this
|
|
* machine; an activation racing a deactivation could clear the machine-limit message and
|
|
* spend the rate budget; one racing a removal would write a token next to no key (#370).
|
|
*/
|
|
export function selectCanActivate(state: LicenseMachinesState, revoked: boolean): boolean {
|
|
return (
|
|
!revoked &&
|
|
!state.activating &&
|
|
!state.listLoading &&
|
|
state.deactivatingId === null &&
|
|
!state.removing
|
|
);
|
|
}
|
|
|
|
/**
|
|
* "Remove the key" is live only when no removal, no activation and no deactivation is
|
|
* running (#370): an activation writes the token of the key it read, and a deactivation
|
|
* drops the token of the slot it freed. The card also waits for a key being stored.
|
|
*/
|
|
export function selectCanRemoveKey(state: LicenseMachinesState): boolean {
|
|
return !state.removing && !state.activating && state.deactivatingId === null;
|
|
}
|
|
|
|
/** Whether opening the list (from `state`, before the toggle) should load it. */
|
|
export function shouldLoadOnOpen(state: LicenseMachinesState): boolean {
|
|
return !state.listOpen && !state.listLoading && (!state.listLoaded || state.listError !== null);
|
|
}
|
|
|
|
export interface LicenseMachinesDeps {
|
|
activateMachine: () => Promise<LicenseResult<void>>;
|
|
deactivateMachine: (machineId: string) => Promise<LicenseResult<void>>;
|
|
listActivatedMachines: () => Promise<LicenseResult<MachineList>>;
|
|
getActivationStatus: () => Promise<ActivationStatus>;
|
|
refresh: () => Promise<void>;
|
|
/** Writes to the in-app log: a token the list load removed (#367). */
|
|
logInfo: (...args: unknown[]) => void;
|
|
dispatch: (action: LicenseMachinesAction) => void;
|
|
}
|
|
|
|
/**
|
|
* Rust has just persisted the revocation, whichever call learned it: reload the license
|
|
* so the edition and the revoked state follow.
|
|
*/
|
|
async function noteRevocation(deps: LicenseMachinesDeps, error: LicenseError): Promise<void> {
|
|
if (error.code === "license_revoked") await deps.refresh();
|
|
}
|
|
|
|
/** Local read (no network). Best effort: a failure keeps the last known status. */
|
|
export async function loadActivationStatus(deps: LicenseMachinesDeps): Promise<void> {
|
|
try {
|
|
const activation = await deps.getActivationStatus();
|
|
deps.dispatch({ type: "ACTIVATION_STATUS", activation });
|
|
} catch {
|
|
// The card keeps showing the previous activation status.
|
|
}
|
|
}
|
|
|
|
export async function loadMachines(deps: LicenseMachinesDeps): Promise<void> {
|
|
deps.dispatch({ type: "LIST_LOAD_START" });
|
|
const result = await deps.listActivatedMachines();
|
|
if (!result.ok) {
|
|
deps.dispatch({ type: "LIST_LOAD_ERROR", error: result.error });
|
|
await noteRevocation(deps, result.error);
|
|
return;
|
|
}
|
|
deps.dispatch({ type: "LIST_LOAD_DONE", machines: result.value.machines });
|
|
if (result.value.token_dropped === "not_listed") {
|
|
deps.logInfo(ACTIVATION_TOKEN_LOG.not_listed_for_this_machine);
|
|
}
|
|
// Rust may have just removed a token that stood for no activation of this machine (#367):
|
|
// read the status again, so the card offers "Activate" without a reload.
|
|
await loadActivationStatus(deps);
|
|
}
|
|
|
|
export async function performActivate(deps: LicenseMachinesDeps): Promise<void> {
|
|
deps.dispatch({ type: "ACTIVATE_START" });
|
|
const result = await deps.activateMachine();
|
|
if (!result.ok) {
|
|
deps.dispatch({ type: "ACTIVATE_ERROR", error: result.error });
|
|
await noteRevocation(deps, result.error);
|
|
if (result.error.code === "machine_limit_reached") {
|
|
await loadMachines(deps);
|
|
}
|
|
return;
|
|
}
|
|
deps.dispatch({ type: "ACTIVATE_DONE" });
|
|
await loadActivationStatus(deps);
|
|
// Reloads the license context after the server call. Since #347 (D12) activation no
|
|
// longer changes the edition: the key alone decides it.
|
|
await deps.refresh();
|
|
}
|
|
|
|
export async function performDeactivate(deps: LicenseMachinesDeps, machineId: string): Promise<void> {
|
|
deps.dispatch({ type: "DEACTIVATE_START", machineId });
|
|
const result = await deps.deactivateMachine(machineId);
|
|
if (!result.ok) {
|
|
deps.dispatch({ type: "DEACTIVATE_ERROR", error: result.error });
|
|
await noteRevocation(deps, result.error);
|
|
return;
|
|
}
|
|
// Removed locally, no verify call: see the rate budget note at the top.
|
|
deps.dispatch({ type: "DEACTIVATE_DONE", machineId });
|
|
await loadActivationStatus(deps);
|
|
// Same reload as after an activation; the edition does not change either (#347, D12).
|
|
await deps.refresh();
|
|
}
|
|
|
|
// -----------------------------------------------------------------------------
|
|
// Removal of the stored key (#370)
|
|
// -----------------------------------------------------------------------------
|
|
|
|
/** What a removal needs to know about the stored key. */
|
|
export interface RemoveLicenseState {
|
|
/** This machine is activated for the stored key, as `get_activation_status` last said. */
|
|
isActivated: boolean;
|
|
/** The license server revoked the stored key (#365). */
|
|
revoked: boolean;
|
|
}
|
|
|
|
/**
|
|
* What a removal started now knows: the activation status loaded last, none (not activated)
|
|
* before it is loaded, and the revocation the license context holds.
|
|
*/
|
|
export function selectRemoveLicenseState(
|
|
state: LicenseMachinesState,
|
|
revoked: boolean,
|
|
): RemoveLicenseState {
|
|
return { isActivated: state.activation?.is_activated === true, revoked };
|
|
}
|
|
|
|
/**
|
|
* Whether the removal asks Rust to free this machine's slot first (D2): an activated machine
|
|
* whose key is not revoked. The server freed every slot of a revoked key when it revoked it.
|
|
* Rust checks the token and the revocation again before it sends anything.
|
|
*/
|
|
export function releasesSlot(state: RemoveLicenseState): boolean {
|
|
return state.isActivated && !state.revoked;
|
|
}
|
|
|
|
/**
|
|
* The first confirmation says what the removal does in this state (D3): a revoked key stops
|
|
* being sent to the license server; a valid key locks the modules of its edition, the data
|
|
* staying; an activated machine frees its slot first.
|
|
*/
|
|
export function removeLicenseConfirmKey(state: RemoveLicenseState): string {
|
|
if (state.revoked) return "license.removeKey.confirmRevoked";
|
|
return state.isActivated ? "license.removeKey.confirmActivated" : "license.removeKey.confirmValid";
|
|
}
|
|
|
|
/**
|
|
* Failures of the slot release after which the key may still be removed, the slot staying
|
|
* occupied: the license server could not be reached, refused for now, or answered badly
|
|
* (error table of #370). Rust returns them with nothing removed. Any other failure is named
|
|
* on the card, without "remove anyway".
|
|
*/
|
|
export const RELEASE_RETRY_CODES: readonly LicenseErrorCode[] = [
|
|
"network",
|
|
"server",
|
|
"rate_limit",
|
|
"invalid_response",
|
|
];
|
|
|
|
/** The in-app log lines of a removal: one per removal, one per release or removal that failed. */
|
|
export const REMOVE_LOG = {
|
|
removed: "License: the stored key was removed",
|
|
released: "License: the stored key was removed, after this machine's slot was freed on the license server",
|
|
slotKept: "License: the stored key was removed; this machine's slot stays occupied on the license server",
|
|
releaseFailed: "License: this machine's slot could not be freed on the license server",
|
|
failed: "License: the stored key could not be removed",
|
|
} as const;
|
|
|
|
/** The card's side of a removal: its confirmation dialog and its translations. */
|
|
export interface RemoveLicenseUi {
|
|
/** `confirmAction` in the card: resolves true to go on, false on a refusal (#421). */
|
|
confirm: (message: string) => Promise<boolean>;
|
|
/** `t` of react-i18next. */
|
|
t: (key: string, options?: Record<string, unknown>) => string;
|
|
}
|
|
|
|
export interface RemoveLicenseDeps extends RemoveLicenseUi {
|
|
removeLicense: (releaseSlot: boolean) => Promise<LicenseResult<void>>;
|
|
refresh: () => Promise<void>;
|
|
logInfo: (...args: unknown[]) => void;
|
|
logWarn: (...args: unknown[]) => void;
|
|
dispatch: (action: LicenseMachinesAction) => void;
|
|
}
|
|
|
|
/**
|
|
* Remove the stored key, after a confirmation that says what that does in this state (#370).
|
|
* A refused confirmation calls nothing. With this machine activated, Rust frees its slot
|
|
* first; when the license server cannot be reached or answers badly, nothing is removed and a
|
|
* second confirmation names the reason and asks whether to remove the key anyway, the slot
|
|
* staying occupied. Any other failure is named on the card. Each removal, and each release or
|
|
* removal that failed, is written to the in-app log. After a removal the license context is
|
|
* reloaded: the card remounts without a key, and the revocation check has nothing to send.
|
|
* It is reloaded after a failure too (local reads only): Rust deletes the key first, so a
|
|
* token that could not be deleted leaves the key gone, and the card must not keep showing it
|
|
* under "the key was not removed".
|
|
*/
|
|
export async function performRemoveLicense(
|
|
deps: RemoveLicenseDeps,
|
|
state: RemoveLicenseState,
|
|
): Promise<void> {
|
|
if (!(await deps.confirm(deps.t(removeLicenseConfirmKey(state))))) return;
|
|
deps.dispatch({ type: "REMOVE_START" });
|
|
const releaseSlot = releasesSlot(state);
|
|
let result = await deps.removeLicense(releaseSlot);
|
|
let removedLog: string = releaseSlot ? REMOVE_LOG.released : REMOVE_LOG.removed;
|
|
if (!result.ok && releaseSlot && RELEASE_RETRY_CODES.includes(result.error.code)) {
|
|
deps.logWarn(REMOVE_LOG.releaseFailed, result.error.code);
|
|
const reason = deps.t(result.error.i18nKey, result.error.params);
|
|
if (!(await deps.confirm(deps.t("license.removeKey.confirmWithoutRelease", { reason })))) {
|
|
deps.dispatch({ type: "REMOVE_END" });
|
|
return;
|
|
}
|
|
result = await deps.removeLicense(false);
|
|
removedLog = REMOVE_LOG.slotKept;
|
|
}
|
|
if (!result.ok) {
|
|
deps.logWarn(REMOVE_LOG.failed, result.error.code);
|
|
await deps.refresh();
|
|
deps.dispatch({ type: "REMOVE_ERROR", error: result.error });
|
|
return;
|
|
}
|
|
deps.logInfo(removedLog);
|
|
await deps.refresh();
|
|
deps.dispatch({ type: "REMOVE_END" });
|
|
}
|
|
|
|
/**
|
|
* Machine list, activation and removal of the key of the License card. `enabled` is false
|
|
* in the free edition, where the card shows no machine section and the activation status is
|
|
* not loaded; the removal stays available (a revoked key resolves to Free).
|
|
*/
|
|
export function useLicenseMachines(enabled: boolean) {
|
|
const { refresh, revoked } = useLicenseContext();
|
|
const [state, dispatch] = useReducer(licenseMachinesReducer, initialLicenseMachinesState);
|
|
|
|
const deps = useMemo<LicenseMachinesDeps>(
|
|
() => ({
|
|
activateMachine,
|
|
deactivateMachine,
|
|
listActivatedMachines,
|
|
getActivationStatus,
|
|
refresh,
|
|
logInfo,
|
|
dispatch,
|
|
}),
|
|
[refresh],
|
|
);
|
|
|
|
// Local activation status only (get_activation_status reads the token on
|
|
// disk): safe to run twice under StrictMode.
|
|
useEffect(() => {
|
|
if (enabled) void loadActivationStatus(deps);
|
|
}, [enabled, deps]);
|
|
|
|
const activate = useCallback(() => performActivate(deps), [deps]);
|
|
const deactivate = useCallback((machineId: string) => performDeactivate(deps, machineId), [deps]);
|
|
const toggleList = useCallback(() => {
|
|
const load = shouldLoadOnOpen(state);
|
|
dispatch({ type: "TOGGLE_LIST" });
|
|
if (load) void loadMachines(deps);
|
|
}, [state, deps]);
|
|
// The card passes its confirmation dialog and its translations (#370).
|
|
const removeKey = useCallback(
|
|
(ui: RemoveLicenseUi) =>
|
|
performRemoveLicense(
|
|
{ ...ui, removeLicense, refresh: deps.refresh, logInfo, logWarn, dispatch: deps.dispatch },
|
|
selectRemoveLicenseState(state, revoked),
|
|
),
|
|
[state, revoked, deps],
|
|
);
|
|
|
|
return {
|
|
state,
|
|
/** The license server revoked the stored key (LicenseContext, #365). */
|
|
revoked,
|
|
activate,
|
|
deactivate,
|
|
toggleList,
|
|
removeKey,
|
|
showEmptyState: selectShowEmptyState(state),
|
|
canDeactivate: selectCanDeactivate(state),
|
|
canActivate: selectCanActivate(state, revoked),
|
|
canRemoveKey: selectCanRemoveKey(state),
|
|
};
|
|
}
|