diff --git a/README.md b/README.md index 547cb5c..effd339 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,7 @@ VotingPlugin Control is designed to manage and troubleshoot a VotingPlugin netwo - Run guided setup for standalone and proxy/backend networks. - Configure common settings through searchable presets. - Use Codex CLI or a compatible local stdio MCP client to read and preview a named backend vote site or automatic site-creation policy for up to ten explicit backends through opt-in local MCP, then review and apply it in Control. Separately grant agents scoped topology, Network Doctor checks, proxy routing previews, non-vote transport checks, and typed General Settings, Vote Sites, and Rewards editor previews. Network grants can include coordinated proxy-method previews and guided common settings, VoteLog, and Vote Party v2. See [agent setup](docs/agent-setup.md). +- Edit allowlisted nested settings and bounded lists in the Full YAML workbench, or prepare scoped MCP previews for agent-visible fields. Command lists and database pool settings remain available to browser administrators. See [configuration coverage](docs/configuration-coverage.md). - Set up or synchronize Vote Sites while preserving existing rewards and sensitive values. - Configure automatic Vote Site creation. - Configure VoteLogging and retention. diff --git a/docs/agent-setup.md b/docs/agent-setup.md index b85bbe6..389bc41 100644 --- a/docs/agent-setup.md +++ b/docs/agent-setup.md @@ -167,3 +167,17 @@ cannot return the complete expected diff. Each node applies its own revision and - **Vote Party** requires both quick-setup versions and a typed v2 READ with an explicit enabled value. It edits enablement, threshold, recipient flags and a nonblank broadcast. Legacy v1-only connectors and inconsistent READ replies are unavailable for this agent workflow. Reward commands remain browser-managed. + + +## Typed managed-file fields + +Grant **Read and preview typed managed-file fields** and **Track operations**. Use +`list_configuration_fields` to obtain the exact field catalog for a managed file, +`read_configuration_fields` on one authorized node, and `preview_configuration_fields` with +that read operation ID and up to eight explicit typed overrides. The status result returns only +present agent-visible values. List values are rendered as quoted lists and edits take JSON arrays. + +The connector must confirm the same source revision, masked document and exact leaf paths before +browser approval. The proposal preserves all bytes outside selected values. Missing keys, ambiguous +mappings and lists with internal comments require the existing browser workflow. Commands, free-text +lists and database fields are absent from the MCP catalog. See [configuration coverage](configuration-coverage.md). diff --git a/docs/configuration-coverage.md b/docs/configuration-coverage.md new file mode 100644 index 0000000..f755bde --- /dev/null +++ b/docs/configuration-coverage.md @@ -0,0 +1,34 @@ +# VotingPlugin configuration editing coverage + +Use **Configuration → Full YAML → Edit typed fields** after reading the selected file. It shows the present fields +supported by the typed editor and their current values. Edit one value using JSON, review its old and new values, +then approve. MCP can list its own field catalog and preview up to eight typed changes from one scoped read. Every +typed preview checks the same node session, file revision, masked source and exact connector change paths. + +| Domain | Typed browser and scoped MCP coverage | Other supported browser editing | +| --- | --- | --- | +| `Config.yml` | General Settings and guided presets, plus reminder flags, time changes, vote limits, broadcast limits, reward-world lists and other catalog fields | Full YAML and database pool size | +| `VoteSites.yml` | Named sites, editable site fields, and scalar inline reward fields through existing tools | Full YAML, split site files where supported, and existing typed reward command list editing | +| `SpecialRewards.yml` | Existing Vote Party v2 presets plus reset, eligibility and cumulative flags and values | Full YAML and typed Vote Party global, reminder and reward command lists | +| `Rewards/*.yml` | Existing named reward scalar tools on capable backends | Existing named reward and command list editors and Full YAML | +| `BungeeSettings.yml` | Existing coordinated method tooling plus per-server points and rewards, event forwarding, extra rewards and Redis TLS flags | Full YAML, global data pool size and global party command list | +| `bungeeconfig.yml` | Routing and coordinated method tooling plus broadcast scope and forwarding, wait and cache settings, scheduling and party target lists | Full YAML, pool sizes and party command lists. File changes can require a separate proxy restart | +| `GUI.yml` and `Shop.yml` | Known GUI item/URL and vote-shop appearance or behavior fields | Full YAML and selected lore lists. Named shop entries and custom layouts use Full YAML | + +The catalog specifies exact fields and bounds. The typed editor works on present supported values. It rejects ambiguous +mappings and skips unsupported representations. It retains unknown fields and comments outside the replaced YAML span. +A list with comments inside its edited span stays in Full YAML. Connector comment preservation still depends on the +negotiated file contract. + +The editor saves command strings as configuration for VotingPlugin's normal reward events. It has no command or reward +execution action. Review the complete command list in the browser before saving. Avoid placing credentials in command +arguments, messages or other free-text fields. + +Use the existing masked browser workflow for connection settings. Typed connection tuning is limited to pool sizes. +Passwords, tokens, connection codes and keys are absent from both typed catalogs. Leave existing redaction markers +untouched to preserve secrets in the Full YAML workflow. The MCP read returns typed fields without the YAML document, +command values, approval material or connection settings. + +This covers VotingPlugin configuration files already supported by the enrolled connector. It does not edit player data, +balances, vote totals, SQL tables, generated runtime files, other plugins, or host settings. Existing capability, reload, +rollback and restart reporting applies. Neither editor can trigger a process restart or deployment. diff --git a/docs/mcp-network-coverage.md b/docs/mcp-network-coverage.md index 273dec7..2d1572f 100644 --- a/docs/mcp-network-coverage.md +++ b/docs/mcp-network-coverage.md @@ -6,7 +6,7 @@ A proxy-network grant limits where an agent may use MCP. The negotiated node cap | --- | --- | --- | | Enrolled identity, liveness, accepted capabilities, proxy/backend presence and topology | Bounded discovery and topology, with proxy snapshot freshness and truncation indicators | Extend large-network link pagination | | Network Doctor, overview, diagnostics, vote-site health, vote-log summary/search/trace, exact player lookup, site resolution, reward simulation | Network Doctor status and read-only observation refresh with a separate health action | Further diagnostic projections. Player and log data need separate projections and access decisions | -| Bukkit managed YAML, split VoteSites, named reward files, supported file comments, General Settings, typed Vote Sites and Rewards | Typed backend and proxy General Settings, plus a named-site guided preview and typed Vote Sites and scalar Rewards editors | Add typed editor tools using their existing validators, per-target revisions, and bounded results | +| Bukkit managed YAML, split VoteSites, named reward files, supported file comments, General Settings, typed Vote Sites and Rewards | Typed backend and proxy General Settings, plus typed managed-file fields, a named-site guided preview, and typed Vote Sites and scalar Rewards editors | Add typed editor tools using their existing validators, per-target revisions, and bounded results | | Quick setup v1/v2, standalone/proxy setup, common settings, auto-create, vote logging, Vote Party, rewards and VoteSites sync | Named-site, automatic site creation, common settings, VoteLog and Vote Party v2 | Standalone and proxy-backend setup remain in the browser | | Proxy routing, fixed proxy YAML, coordinated proxy-method v1/v2 and transport tests | Typed routing and coordinated method proposals with browser approval, plus a non-vote transport check | Add further curated proxy projections | | Configuration review, apply, status, retries, durable operation history, snapshots and drift | Token-free, per-target status for operations from the same grant. Browser-only Apply. Automatic site policy supports 1–10 explicit backends with immutable revisions | Extend bounded multi-node review and partial-failure reporting to other safe typed operations | @@ -28,6 +28,7 @@ MCP uses an opt-in server boundary, proxy-network grants, bounded discovery and | Typed General Settings | Implemented and tested | Both node roles use the curated editor, scoped reads, exact revision and diff, and browser approval. Proxy applies report restart required | | Typed Vote Sites editor | Implemented and tested | Exact-site read, typed add/edit, and removal for reviewable sites without inline Rewards. Revision, masked source and leaf changes checked before browser approval | | Typed Rewards editor | Implemented and tested for supported scalar fields | Inline and named-file reward reads, exact same-scope scalar previews and browser approval. Command payloads and whole-scope edits stay in administrator workflows | +| Typed managed-file fields | Implemented and tested | Catalog-backed booleans, bounded integers, enum values and identifier lists across six files. One target and up to eight changes. Exact source/diff checks and browser approval. Command lists and database pool tuning are browser-only | | Coordinated proxy method | Implemented and tested | Full fresh topology, exact method capability, per-peer revision, backend-first apply and explicit partial persistence. Runtime readiness and other proxy transport settings are outside the revision contract | | VoteSites sync | Browser only pending complete diff proof | The connector can replace a destination scalar or list with a mapping while omitting the removed value from its change paths. Agent approval needs revision-matched source and destination shape evidence and a typed source projection | | Guided common settings, VoteLog and Vote Party v2 | Implemented and tested | Both same-session READs agree on revision, key presence is reviewed, and approval checks every target's exact diff. Up to four explicit targets. Vote Party v1 and database selection stay in the browser | diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java b/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java index 3f82774..2cbe8ad 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/AgentOperations.java @@ -20,7 +20,7 @@ import java.util.function.Supplier; public final class AgentOperations { - private static final Set ACTIONS = Set.of("discover", "read", "preview", "status", "health", "routing", "transport", "site-policy", "site-policy-batch", "general-settings", "vote-sites-editor", "rewards-editor", "proxy-method", "common-settings", "vote-logging", "vote-party"); + private static final Set ACTIONS = Set.of("discover", "read", "preview", "status", "health", "routing", "transport", "site-policy", "site-policy-batch", "general-settings", "vote-sites-editor", "rewards-editor", "proxy-method", "common-settings", "vote-logging", "vote-party", "managed-fields"); private final Map grants = new HashMap<>(); private final Map healthRefreshes = new HashMap<>(); private final NodeRegistry registry; @@ -164,6 +164,28 @@ public synchronized Map refreshHealth(String token, RefreshHealt } } + public synchronized Object managedFieldsCatalog(String token, FieldsCatalog request) { + authorize(token, "managed-fields"); + return Map.of("fields", ManagedFields.catalog(request.file(), true)); + } + + public synchronized Object readManagedFields(String token, FieldsRead request) { + Grant grant = authorize(token, "managed-fields"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.readAgentManagedFields(grant.id(), request.nodeId(), request.file())); + }); + } + + public synchronized Object previewManagedFields(String token, FieldsPreview request) { + Grant grant = authorize(token, "managed-fields"); + return withStableTopology(() -> { + requireNode(grant, request.nodeId()); + return project(operations.previewAgentManagedFields(grant.id(), request.nodeId(), + parseId(request.readOperationId()), request.overrides())); + }); + } + public synchronized void requireGuidedAccess(String token) { if (authorize(token, null).actions().stream().noneMatch(Set.of("common-settings", "vote-logging", "vote-party")::contains)) { denied(); @@ -563,6 +585,9 @@ public record Issue(List nodeIds, List actions, Integer minutes, public record Discovery(Integer offset) { } public record HealthRequest(List nodeIds) { } public record RefreshHealth(String nodeId) { } + public record FieldsCatalog(String file) { } + public record FieldsRead(String nodeId, String file) { } + public record FieldsPreview(String nodeId, String readOperationId, Map overrides) { } public record GuidedRead(String nodeId, String preset, String evidence) { } public record GuidedTarget(String nodeId, String presetReadId, String presenceReadId) { } public record GuidedPreview(String preset, List targets, Map overrides) { } diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java b/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java index fe08df6..7b35441 100644 --- a/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java +++ b/src/main/java/com/bencodez/votingplugin/control/domain/ConfigurationOperations.java @@ -256,6 +256,67 @@ private boolean agentTransportPeerCurrent(StoredOperation operation, NodeStatus return transportPeerAvailable(proxy, backend) && operation.agentPeerSession.equals(backend.sessionId()); } + synchronized OperationView readAgentManagedFields(UUID agent, String nodeId, String file) { + prune(); + requireAgentCapacity(agent); + ManagedFields.catalog(file, true); + var selector = ManagedConfiguration.file(file, null); + var targets = validateTargets(List.of(nodeId), selector.capability()); + validateConfigurationTargets(targets, selector); + var read = create("READ", targets, selector, null, Map.of(), agent); + operations.get(read.operationId()).agentManagedFieldRead = true; + return read; + } + + synchronized OperationView previewAgentManagedFields(UUID agent, String nodeId, UUID readId, + Map overrides) { + prune(); + requireAgentCapacity(agent); + var read = agentOperation(agent, readId); + if (!read.agentManagedFieldRead) throw invalid("A scoped typed configuration READ is required"); + return createManagedFieldPreview(readId, nodeId, read.configuration.fileName(), overrides, agent).operation(); + } + + public synchronized List managedFieldState(UUID readId, String nodeId, String file) { + requireBrowserManagedFieldRead(readId, file); + return ManagedFields.read(file, fileSnapshot(readId, nodeId, file).configuration().content(), false); + } + + public synchronized ManagedFieldPreview previewManagedFields(UUID readId, String nodeId, String file, + Map overrides) { + requireBrowserManagedFieldRead(readId, file); + return createManagedFieldPreview(readId, nodeId, file, overrides, null); + } + + private void requireBrowserManagedFieldRead(UUID readId, String file) { + ManagedFields.catalog(file, false); + var read = operations.get(readId); + if (read != null && read.agent != null) throw invalid("An administrator managed-file READ is required"); + } + + private ManagedFieldPreview createManagedFieldPreview(UUID readId, String nodeId, String file, + Map overrides, UUID agent) { + var snapshot = fileSnapshot(readId, nodeId, file); + var content = snapshot.configuration().content(); + var patch = ManagedFields.patch(file, content, overrides, agent != null); + var selector = ManagedConfiguration.file(file, patch.content()); + var targets = validateTargets(List.of(nodeId), selector.capability()); + validateConfigurationTargets(targets, selector); + byte[] approval = new byte[32]; + random.nextBytes(approval); + var preview = create("PREVIEW", targets, selector, Base64.getUrlEncoder().withoutPadding().encodeToString(approval), + Map.of(nodeId, snapshot.revision()), agent); + var stored = operations.get(preview.operationId()); + stored.managedFieldPreview = true; + stored.agentDocumentDigest = AgentSetup.documentDigest(content); + stored.agentExpectedChanges = patch.changes(); + stored.agentBefore = patch.before(); + stored.agentAfter = patch.after(); + return new ManagedFieldPreview(preview, patch.before(), patch.after()); + } + + public record ManagedFieldPreview(OperationView operation, Map before, Map after) { } + synchronized OperationView readAgentGeneralSettings(UUID agent, String nodeId) { prune(); requireAgentCapacity(agent); @@ -538,7 +599,7 @@ public synchronized OperationView approveAgentPreview(UUID id) { } throw invalid("Preview is unavailable for browser approval"); } - return createApply(id, preview.approvalToken, true); + return createApply(id, preview.approvalToken, ApprovalRoute.AGENT_BROWSER); } private boolean agentReviewReady(StoredOperation operation) { @@ -550,10 +611,35 @@ && currentAgentCoordination(operation) } public synchronized OperationView createApply(UUID previewId, String approvalToken) { - return createApply(previewId, approvalToken, false); + return createApply(previewId, approvalToken, ApprovalRoute.LEGACY); } - private OperationView createApply(UUID previewId, String approvalToken, boolean browserAgentReview) { + public synchronized OperationView approveManagedFields(UUID id) { + prune(); + var preview = operations.get(id); + if (preview == null || !managedFieldReviewReady(preview)) throw invalid("Typed preview is unavailable for approval"); + return createApply(id, preview.approvalToken, ApprovalRoute.FIELDS_BROWSER); + } + + public synchronized void discardManagedFields(UUID id) { + prune(); + var preview = operations.get(id); + if (preview == null || preview.agent != null || !preview.managedFieldPreview + || !"PREVIEW".equals(preview.type) || preview.approvalUsed) return; + audit.append("PREVIEW_DISCARDED", id, null, "MANAGED_FIELDS"); + preview.approvalUsed = true; + } + + private boolean managedFieldReviewReady(StoredOperation operation) { + return operation.agent == null && operation.managedFieldPreview && "PREVIEW".equals(operation.type) + && !operation.approvalUsed && operation.complete() + && operation.results.values().stream().allMatch(ConfigurationTaskResult::success) + && clock.instant().isBefore(operation.createdAt.plus(ACTIVE_RETENTION)); + } + + private enum ApprovalRoute { LEGACY, AGENT_BROWSER, FIELDS_BROWSER } + + private OperationView createApply(UUID previewId, String approvalToken, ApprovalRoute route) { prune(); LinkedHashMap priorOperations = new LinkedHashMap<>(operations); long priorChanges = retainedChangeBytes; @@ -561,7 +647,9 @@ private OperationView createApply(UUID previewId, String approvalToken, boolean long priorFiles = retainedFileBytes; StoredOperation preview = operations.get(previewId); if (preview == null || !"PREVIEW".equals(preview.type)) throw invalid("preview operation was not found"); - if ((preview.agent != null) != browserAgentReview) throw invalid("Preview requires its original approval route"); + ApprovalRoute expected = preview.agent != null ? ApprovalRoute.AGENT_BROWSER + : preview.managedFieldPreview ? ApprovalRoute.FIELDS_BROWSER : ApprovalRoute.LEGACY; + if (route != expected) throw invalid("Preview requires its original approval route"); if (!preview.complete() || preview.results.values().stream().anyMatch(result -> !result.success())) { throw new ValidationException("PREVIEW_INCOMPLETE", "Every node must pass preview before apply", List.of()); } @@ -592,7 +680,7 @@ private OperationView createApply(UUID previewId, String approvalToken, boolean } preview.approvalUsed = true; try { - if (browserAgentReview) { + if (route == ApprovalRoute.AGENT_BROWSER) { audit.append("AGENT_APPLY_APPROVED", apply.id, targets.nodeIds().size() == 1 ? targets.nodeIds().get(0) : null, preview.id.toString()); } else { @@ -1407,7 +1495,7 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co "Configuration changed since READ; read and preview again", null, (ManagedConfiguration) null, List.of(), false, false, result.attemptId()); } - if (operation.agent != null && "PREVIEW".equals(operation.type) && result.success() + if ((operation.agent != null || operation.managedFieldPreview) && "PREVIEW".equals(operation.type) && result.success() && (result.changes().size() >= 20 || result.changes().contains("additional changes omitted") || retainedChangeBytes + result.changes().stream().mapToLong( change -> change.getBytes(StandardCharsets.UTF_8).length).sum() > MAX_RETAINED_CHANGE_BYTES @@ -1420,7 +1508,14 @@ private OperationView completeCurrentSession(UUID operationId, String nodeId, Co if (operation.agent != null && operation.agentPeerSession == null && "READ".equals(operation.type) && result.success()) { try { - if (operation.agentGuidedRead != null) { + if (operation.agentManagedFieldRead) { + if (result.configuration() == null) throw new IllegalArgumentException("Missing typed source"); + var values = new LinkedHashMap(); + for (var row : ManagedFields.read(operation.configuration.fileName(), result.configuration().content(), true)) { + values.put(row.field().path(), ManagedFields.display(row.value())); + } + agentRead = Map.copyOf(values); + } else if (operation.agentGuidedRead != null) { if (ManagedConfiguration.FILE.equals(operation.configuration.domain())) { if (result.configuration() == null || result.configuration().content() == null) { throw new IllegalArgumentException("Missing masked presence evidence"); @@ -1758,7 +1853,8 @@ private OperationView view(StoredOperation operation, boolean includeRetainedCon ? "SUCCEEDED" : "COMPLETED_WITH_ERRORS") : "RUNNING"; String approval = "PREVIEW".equals(operation.type) && operation.complete() && operation.results.values().stream().allMatch(ConfigurationTaskResult::success) - && !operation.approvalUsed && operation.agent == null ? operation.approvalToken : null; + && !operation.approvalUsed && operation.agent == null && !operation.managedFieldPreview + ? operation.approvalToken : null; Map results = operation.results; if (!includeRetainedContent) { LinkedHashMap summaries = new LinkedHashMap<>(); @@ -1772,7 +1868,8 @@ private OperationView view(StoredOperation operation, boolean includeRetainedCon return new OperationView(operation.id, operation.type, state, operation.createdAt, operation.configuration == null ? null : operation.configuration.publicView(), Map.copyOf(operation.states), Map.copyOf(results), approval, operation.sourceOperationId, - operation.recovered, retryable(operation), operation.agent, agentReviewReady(operation)); + operation.recovered, retryable(operation), operation.agent, + agentReviewReady(operation) || managedFieldReviewReady(operation)); } private static boolean retryable(StoredOperation operation) { @@ -1958,6 +2055,8 @@ private static final class StoredOperation { private String agentEditorSite; private AgentSetup.RewardField agentRewardField; private boolean agentGeneralSettings; + private boolean agentManagedFieldRead; + private boolean managedFieldPreview; private GuidedSettings agentGuidedRead; private GuidedSettings agentGuidedPreview; private Set agentVoteLogRestartTargets = Set.of(); diff --git a/src/main/java/com/bencodez/votingplugin/control/domain/ManagedFields.java b/src/main/java/com/bencodez/votingplugin/control/domain/ManagedFields.java new file mode 100644 index 0000000..5e2df03 --- /dev/null +++ b/src/main/java/com/bencodez/votingplugin/control/domain/ManagedFields.java @@ -0,0 +1,294 @@ +package com.bencodez.votingplugin.control.domain; + +import com.bencodez.votingplugin.control.protocol.ManagedConfiguration; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import org.yaml.snakeyaml.LoaderOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.SafeConstructor; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.SequenceNode; +import org.yaml.snakeyaml.nodes.Tag; + +/** Explicit VotingPlugin field catalog and source-span edits over existing managed files. */ +public final class ManagedFields { + public static final int MAX_EDITS = 8; + private static final int MAX_LIST = 24; + private static final int MAX_LINE = 240; + private static final Map> CATALOG = Map.of( + "Config.yml", List.of( + flag("CreateBackups"), flag("VoteCommandEnabled"), flag("TreatVanishAsOffline"), + flag("QueueVotesDuringTimeChange"), flag("VoteReminderOptions.Enabled"), + flag("VoteReminderOptions.StopAfterMatch"), flag("AutomaticTimeChanges.Day"), + flag("AutomaticTimeChanges.Week"), flag("AutomaticTimeChanges.Month"), + flag("OfflineVotesLimit.Enabled"), integer("OfflineVotesLimit.Amount", 0, 10000), + integer("VoteBroadcast.MaxSitesListed", 0, 200), + integer("PointsOnVote", 0, 100000), integer("LimitVotePoints", -1, 100000000), + identifiers("DefaultRewardWorlds"), identifiers("DefaultRewardBlackListedWorlds"), + browserInteger("Database.MaxConnections", 1, 100)), + "BungeeSettings.yml", List.of( + flag("PerServerRewards"), flag("PerServerPoints"), flag("TriggerVotifierEvent"), + flag("GiveExtraAllSitesRewards"), flag("Redis.SSL"), + browserInteger("GlobalData.MaxConnections", 1, 100), + browserList("BungeeVotePartyGlobalCommands")), + "SpecialRewards.yml", List.of( + flag("VoteParty.ResetEachDay"), flag("VoteParty.ResetWeekly"), flag("VoteParty.ResetMonthly"), + flag("VoteParty.OnlyOncePerDay"), flag("VoteParty.OnlyOncePerWeek"), + flag("VoteParty.ResetExtraVotesWeekly"), flag("VoteParty.ResetExtraVotesMonthly"), + flag("VoteParty.CountFakeVotes"), flag("VoteParty.CountOfflineVotes"), + integer("VoteParty.UserVotesRequired", 0, 100000), flag("OnlyOneCumulative"), + browserList("VoteParty.GlobalCommands"), browserList("VoteParty.Rewards.Commands"), + browserList("VoteParty.VoteReminder.Commands")), + "bungeeconfig.yml", List.of( + flag("ProxyBroadcast.Enabled"), identifiers("ProxyBroadcast.Scope.Servers"), + choices("ProxyBroadcast.Scope.Mode", "PLAYER_SERVER", "ALL_SERVERS", "SERVERS", "ALL_EXCEPT"), + choices("ProxyBroadcast.OfflineMode", "NONE", "QUEUE", "FORWARD"), + identifiers("ProxyBroadcast.OfflineForward.Servers"), identifiers("WhiteListedServers"), + flag("WaitForUserOnline"), integer("VoteCacheTime", -1, 3650), + integer("MaxAmountOfVotesPerDay", -1, 100000), + flag("AutomaticTimeChanges.Day"), flag("AutomaticTimeChanges.Week"), + flag("AutomaticTimeChanges.Month"), flag("VoteParty.SendToAllServers"), + identifiers("VoteParty.ServersToSend"), + integer("VoteParty.IncreaseVotesRequired", 0, 100000), + browserInteger("Database.MaxConnections", 1, 100), + browserInteger("GlobalData.MaxConnections", 1, 100), browserList("VoteParty.BungeeCommands")), + "GUI.yml", List.of(flag("CHEST.VoteURL.BackButton"), flag("CHEST.VoteURL.ViewAllUrlsButtonEnabled"), + flag("CHEST.VoteURL.AllUrlsButton.RequireAllSitesVoted"), + integer("CHEST.VoteGUI.URL.Item.Amount", 1, 64), integer("CHEST.VoteGUI.Shop.Item.Amount", 1, 64), + browserList("CHEST.VoteGUI.URL.Item.Lore"), browserList("CHEST.VoteGUI.Shop.Item.Lore")), + "Shop.yml", List.of(flag("VoteShop.Enabled"), flag("VoteShop.BackButton"), + flag("VoteShop.HideLimitedReached"), flag("VoteShop.RequireConfirmation"), + flag("VoteShop.ReopenGUIOnPurchase"), + integer("VoteShop.BackButtonItem.Amount", 1, 64), + integer("VoteShop.BackButtonItem.Slot", 0, 53))); + + private ManagedFields() { } + + public enum Kind { BOOLEAN, INTEGER, CHOICE, IDENTIFIER_LIST, TEXT_LIST } + + public record Field(String path, Kind kind, Integer minimum, Integer maximum, List choices, boolean browserOnly) { } + + public record Entry(Field field, Object value) { } + + record Patch(String content, Map before, Map after, Set changes) { } + + private record Located(Field field, Object value, int start, int end, String prefix) { } + + public static List files() { return CATALOG.keySet().stream().sorted().toList(); } + + public static Set agentPaths() { + var paths = new HashSet(); + CATALOG.values().forEach(fields -> fields.stream().filter(field -> !field.browserOnly()).forEach(field -> paths.add(field.path()))); + return Set.copyOf(paths); + } + + public static List catalog(String file, boolean agent) { + var fields = file == null ? null : CATALOG.get(file); + if (fields == null) throw invalid("Choose an allowlisted configuration file"); + return fields.stream().filter(field -> !agent || !field.browserOnly()).toList(); + } + + static List read(String file, String document, boolean agent) { + return locate(file, document, agent).values().stream().map(value -> new Entry(value.field(), value.value())).toList(); + } + + static Patch patch(String file, String document, Map overrides, boolean agent) { + if (overrides == null || overrides.isEmpty() || overrides.size() > MAX_EDITS) throw invalid("Choose one to eight typed fields"); + var locations = locate(file, document, agent); + var before = new LinkedHashMap(); + var after = new LinkedHashMap(); + var edits = new ArrayList(); + for (var request : overrides.entrySet()) { + var location = locations.get(request.getKey()); + if (location == null) throw invalid("Selected field is absent, unsupported, or outside this editor"); + Object proposed = normalize(location.field(), request.getValue()); + if (proposed.equals(location.value())) continue; + before.put(request.getKey(), display(location.value())); + after.put(request.getKey(), display(proposed)); + edits.add(new Splice(location.start(), location.end(), location.prefix() + encode(proposed))); + } + if (edits.isEmpty()) throw invalid("No typed field changed"); + edits.sort(Comparator.comparingInt(Splice::start).reversed()); + var patched = new StringBuilder(document); + int previous = document.length(); + for (var edit : edits) { + if (edit.end() > previous) throw invalid("Overlapping YAML values"); + patched.replace(edit.start(), edit.end(), edit.value()); + previous = edit.start(); + } + String result = patched.toString(); + var confirmed = locate(file, result, agent); + for (var entry : after.entrySet()) { + var location = confirmed.get(entry.getKey()); + if (location == null || !entry.getValue().equals(display(location.value()))) throw invalid("Typed YAML edit could not be verified"); + } + Set diff = after.keySet().stream().map(path -> "changed " + path).collect(java.util.stream.Collectors.toUnmodifiableSet()); + return new Patch(result, Map.copyOf(before), Map.copyOf(after), diff); + } + + static String display(Object value) { + // Use the same escaped representation for browser review and MCP projection. + return value instanceof List ? encode(value) : value.toString(); + } + + private static Map locate(String file, String content, boolean agent) { + var fields = catalog(file, agent); + if (content == null || content.length() > ManagedConfiguration.MAX_CONTENT || content.indexOf('\0') >= 0) { + throw invalid("Managed document exceeds the typed editor limit"); + } + var options = new LoaderOptions(); + options.setAllowDuplicateKeys(false); + options.setAllowRecursiveKeys(false); + options.setMaxAliasesForCollections(0); + options.setNestingDepthLimit(32); + options.setCodePointLimit(ManagedConfiguration.MAX_CONTENT); + options.setMergeOnCompose(false); + Node root; + try { + root = new Yaml(new SafeConstructor(options)).compose(new StringReader(content)); + } catch (RuntimeException malformed) { + throw invalid("Managed document does not contain safe, unambiguous YAML"); + } + if (!(root instanceof MappingNode)) throw invalid("Managed document must be a YAML mapping"); + var result = new LinkedHashMap(); + for (var field : fields) { + Node current = root; + ScalarNode key = null; + for (String part : field.path().split("[.]")) { + if (!(current instanceof MappingNode mapping)) { + current = null; + break; + } + Keyed entry = child(mapping, part); + if (entry == null) { + current = null; + break; + } + key = entry.key(); + current = entry.value(); + } + if (current == null || current.getAnchor() != null) continue; + Object value = decode(field, current); + if (value == null) continue; + int start = offset(content, current.getStartMark().getIndex()); + Node last = current; + String prefix = ""; + if (current instanceof SequenceNode sequence && !sequence.getValue().isEmpty() + && sequence.getFlowStyle() == org.yaml.snakeyaml.DumperOptions.FlowStyle.BLOCK) { + last = sequence.getValue().get(sequence.getValue().size() - 1); + if (current.getStartMark().getColumn() == key.getStartMark().getColumn()) prefix = " "; + } + int end = offset(content, last.getEndMark().getIndex()); + if (start >= end || content.substring(start, end).contains("#")) continue; + result.put(field.path(), new Located(field, value, start, end, prefix)); + } + return result; + } + + private static Keyed child(MappingNode mapping, String part) { + if (mapping.getAnchor() != null || !Tag.MAP.equals(mapping.getTag())) throw invalid("Unsupported YAML mapping"); + var keys = new HashSet(); + Keyed match = null; + for (var tuple : mapping.getValue()) { + if (!(tuple.getKeyNode() instanceof ScalarNode key) || !Tag.STR.equals(key.getTag()) + || !keys.add(key.getValue().toLowerCase(Locale.ROOT)) || key.getValue().contains(".")) { + throw invalid("Duplicate, compound, or unsupported YAML key"); + } + if (part.equalsIgnoreCase(key.getValue())) { + if (!part.equals(key.getValue())) throw invalid("Noncanonical YAML key for a managed field"); + match = new Keyed(key, tuple.getValueNode()); + } + } + return match; + } + + private static Object decode(Field field, Node node) { + if (node instanceof SequenceNode sequence && Tag.SEQ.equals(sequence.getTag()) + && (field.kind() == Kind.IDENTIFIER_LIST || field.kind() == Kind.TEXT_LIST)) { + if (sequence.getValue().size() > MAX_LIST) return null; + var items = new ArrayList(); + for (Node item : sequence.getValue()) { + if (!(item instanceof ScalarNode scalar) || !Tag.STR.equals(scalar.getTag()) || scalar.getAnchor() != null + || scalar.getStartMark().getLine() != scalar.getEndMark().getLine()) return null; + items.add(scalar.getValue()); + } + return tryNormalize(field, items); + } + if (!(node instanceof ScalarNode scalar) || scalar.getStartMark().getLine() != scalar.getEndMark().getLine()) return null; + String text = scalar.getValue(); + return switch (field.kind()) { + case BOOLEAN -> Tag.BOOL.equals(scalar.getTag()) && Set.of("true", "false").contains(text) + ? Boolean.valueOf(text) : null; + case INTEGER -> Tag.INT.equals(scalar.getTag()) && text.matches("-?(0|[1-9][0-9]{0,8})") + ? tryNormalize(field, Integer.parseInt(text)) : null; + case CHOICE -> Tag.STR.equals(scalar.getTag()) ? tryNormalize(field, text) : null; + default -> null; + }; + } + + private static Object tryNormalize(Field field, Object value) { + try { + return normalize(field, value); + } catch (IllegalArgumentException unsupported) { + return null; + } + } + + private static Object normalize(Field field, Object value) { + switch (field.kind()) { + case BOOLEAN: + if (value instanceof Boolean) return value; + break; + case INTEGER: + if (value instanceof Integer number && number >= field.minimum() && number <= field.maximum()) return value; + break; + case CHOICE: + if (value instanceof String text && field.choices().contains(text)) return text; + break; + case IDENTIFIER_LIST, TEXT_LIST: + if (value instanceof List items && items.size() <= MAX_LIST && items.stream().allMatch(item -> + item instanceof String text && validLine(field.kind(), text))) return List.copyOf(items); + break; + } + throw invalid("Typed field value is outside the supported schema"); + } + + private static boolean validLine(Kind kind, String text) { + return !text.isBlank() && text.length() <= MAX_LINE && text.codePoints().noneMatch(Character::isISOControl) + && !text.contains("__VOTINGPLUGIN_CONTROL_REDACTED__") + && (kind == Kind.TEXT_LIST || text.matches("[A-Za-z0-9][A-Za-z0-9_-]{0,63}")); + } + + private static String encode(Object value) { + if (value instanceof List list) return list.stream().map(item -> quote((String) item)) + .collect(java.util.stream.Collectors.joining(", ", "[", "]")); + if (value instanceof String text) return quote(text); + return value.toString(); + } + + private static String quote(String value) { + return "'" + value.replace("'", "''") + "'"; + } + + private static int offset(String source, int codePoints) { return source.offsetByCodePoints(0, codePoints); } + private static IllegalArgumentException invalid(String message) { return new IllegalArgumentException(message); } + + private static Field flag(String path) { return new Field(path, Kind.BOOLEAN, null, null, List.of(), false); } + private static Field integer(String path, int min, int max) { return new Field(path, Kind.INTEGER, min, max, List.of(), false); } + private static Field browserInteger(String path, int min, int max) { return new Field(path, Kind.INTEGER, min, max, List.of(), true); } + private static Field identifiers(String path) { return new Field(path, Kind.IDENTIFIER_LIST, null, null, List.of(), false); } + private static Field browserList(String path) { return new Field(path, Kind.TEXT_LIST, null, null, List.of(), true); } + private static Field choices(String path, String... values) { return new Field(path, Kind.CHOICE, null, null, List.of(values), false); } + + private record Keyed(ScalarNode key, Node value) { } + private record Splice(int start, int end, String value) { } +} diff --git a/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java b/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java index 4d79866..8a0cbe6 100644 --- a/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java +++ b/src/main/java/com/bencodez/votingplugin/control/http/ControlHttpServer.java @@ -698,6 +698,35 @@ private void route(HttpExchange exchange) throws IOException { send(exchange, 202, configurationOperations.createRead(request.nodeIds(), request.configuration())); return; } + if ((CONFIGURATION + "/managed-fields/state").equals(path)) { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + ManagedFieldsState request = read(exchange, ManagedFieldsState.class, true); + send(exchange, 200, configurationOperations.managedFieldState(request.readOperationId(), request.nodeId(), request.file())); + return; + } + if ((CONFIGURATION + "/managed-fields/apply").equals(path)) { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + ManagedFieldsApproval request = read(exchange, ManagedFieldsApproval.class, true); + send(exchange, 202, configurationOperations.approveManagedFields(request.previewOperationId())); + return; + } + if ((CONFIGURATION + "/managed-fields/discard-preview").equals(path)) { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + ManagedFieldsApproval request = read(exchange, ManagedFieldsApproval.class, true); + configurationOperations.discardManagedFields(request.previewOperationId()); + send(exchange, 200, Map.of("discarded", true)); + return; + } + if ((CONFIGURATION + "/managed-fields/preview").equals(path)) { + requireMethod(exchange, "POST"); + authenticateWebSession(exchange, true); + ManagedFieldsPreview request = read(exchange, ManagedFieldsPreview.class, true); + send(exchange, 202, configurationOperations.previewManagedFields(request.readOperationId(), request.nodeId(), request.file(), request.overrides())); + return; + } if ((CONFIGURATION + "/general-settings/state").equals(path)) { requireMethod(exchange, "POST"); authenticateAdmin(exchange, true); @@ -1137,6 +1166,7 @@ private void routeAgent(HttpExchange exchange, String path) throws IOException { case "transport" -> "transport"; case "site-policy-read", "site-policy-preview" -> "site-policy"; case "site-policy-batch" -> "site-policy-batch"; + case "fields-catalog", "fields-read", "fields-preview" -> "managed-fields"; case "guided-read", "guided-preview" -> "guided"; case "proxy-method-read", "proxy-method-preview" -> "proxy-method"; case "reward-read", "reward-preview" -> "rewards-editor"; @@ -1159,6 +1189,9 @@ private void routeAgent(HttpExchange exchange, String path) throws IOException { case "topology" -> agentOperations.topology(token, read(exchange, AgentOperations.Discovery.class, true)); case "health" -> agentOperations.health(token, read(exchange, AgentOperations.HealthRequest.class, true)); case "health-refresh" -> agentOperations.refreshHealth(token, read(exchange, AgentOperations.RefreshHealth.class, true)); + case "fields-catalog" -> agentOperations.managedFieldsCatalog(token, read(exchange, AgentOperations.FieldsCatalog.class, true)); + case "fields-read" -> agentOperations.readManagedFields(token, read(exchange, AgentOperations.FieldsRead.class, true)); + case "fields-preview" -> agentOperations.previewManagedFields(token, read(exchange, AgentOperations.FieldsPreview.class, true)); case "guided-read" -> agentOperations.readGuided(token, read(exchange, AgentOperations.GuidedRead.class, true)); case "guided-preview" -> agentOperations.previewGuided(token, read(exchange, AgentOperations.GuidedPreview.class, true)); case "proxy-method-read" -> agentOperations.readProxyMethod(token, read(exchange, AgentOperations.ProxyMethodRead.class, true)); @@ -1190,6 +1223,10 @@ private void routeAgent(HttpExchange exchange, String path) throws IOException { } } + private record ManagedFieldsApproval(UUID previewOperationId) { } + private record ManagedFieldsState(UUID readOperationId, String nodeId, String file) { } + private record ManagedFieldsPreview(UUID readOperationId, String nodeId, String file, Map overrides) { } + private UUID readAgentId(HttpExchange exchange) throws IOException { AgentId request = read(exchange, AgentId.class, true); return AgentOperations.parseId(request.operationId()); diff --git a/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java b/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java index fd6ece3..fe2c4b5 100644 --- a/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java +++ b/src/main/java/com/bencodez/votingplugin/control/mcp/StdioAdapter.java @@ -2,6 +2,7 @@ import com.bencodez.votingplugin.control.domain.GeneralSettingsDocument; import com.bencodez.votingplugin.control.domain.GuidedSettings; +import com.bencodez.votingplugin.control.domain.ManagedFields; import com.bencodez.votingplugin.control.domain.VoteSitesDocument; import com.fasterxml.jackson.core.StreamReadConstraints; @@ -149,6 +150,11 @@ private Object call(JsonNode id, JsonNode params) throws InterruptedException { } private static boolean validResult(String route, JsonNode result) { + if ("fields-catalog".equals(route)) { + if (!fields(result, Set.of("fields"))) return false; + return ManagedFields.files().stream().anyMatch(file -> result.path("fields") + .equals(JSON.valueToTree(ManagedFields.catalog(file, true)))); + } if ("topology".equals(route)) return validTopology(result); if ("health".equals(route)) return validHealth(result); if ("health-refresh".equals(route)) { @@ -268,6 +274,7 @@ private static boolean validValues(JsonNode result) { Set keys = new java.util.HashSet<>(GeneralSettingsDocument.editableKeys()); keys.addAll(VoteSitesDocument.editableKeys()); keys.addAll(GuidedSettings.resultKeys()); + keys.addAll(ManagedFields.agentPaths()); keys.addAll(Set.of("siteKey", "rewardsConfigured", "rewardField", "rewardValue", "method", "useBungeecord")); keys.addAll(Set.of("name", "exists", "serviceSite", "voteUrl", "enabled", "displayName", "priority", "hidden", "voteDelay", "material", "displayItem.amount", "sendVotesToAllServers", "blockedServers")); @@ -342,6 +349,34 @@ private static Map tools() { tools.put("refresh_node_health", new Tool("refresh_node_health", "health-refresh", "Queue the read-only Network Doctor observation for an authorized node.", object(Map.of("nodeId", node), List.of("nodeId")))); + var managedFile = Map.of("type", "string", "enum", ManagedFields.files()); + var fieldProperties = new LinkedHashMap(); + for (String file : ManagedFields.files()) { + for (var field : ManagedFields.catalog(file, true)) { + var schema = switch (field.kind()) { + case BOOLEAN -> flag; + case INTEGER -> Map.of("type", "integer", "minimum", field.minimum(), "maximum", field.maximum()); + case CHOICE -> Map.of("type", "string", "enum", field.choices()); + case IDENTIFIER_LIST -> Map.of("type", "array", "maxItems", 24, + "items", Map.of("type", "string", "pattern", "^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$")); + case TEXT_LIST -> throw new IllegalStateException("Free-text lists are browser-only"); + }; + fieldProperties.put(field.path(), schema); + } + } + var managedOverrides = new LinkedHashMap<>(object(fieldProperties, List.of())); + managedOverrides.put("minProperties", 1); + managedOverrides.put("maxProperties", ManagedFields.MAX_EDITS); + tools.put("list_configuration_fields", new Tool("list_configuration_fields", "fields-catalog", + "List agent-editable field names and value types for one managed configuration file.", + object(Map.of("file", managedFile), List.of("file")))); + tools.put("read_configuration_fields", new Tool("read_configuration_fields", "fields-read", + "Read present typed configuration fields on one authorized node. The source file stays in Control.", + object(Map.of("nodeId", node, "file", managedFile), List.of("nodeId", "file")))); + tools.put("preview_configuration_fields", new Tool("preview_configuration_fields", "fields-preview", + "Preview one to eight typed edits to the file bound to a current read. Browser approval is required.", + object(Map.of("nodeId", node, "readOperationId", id, "overrides", managedOverrides), + List.of("nodeId", "readOperationId", "overrides")))); var guidedPreset = Map.of("type", "string", "enum", List.of("common-settings", "vote-logging", "vote-party")); var guidedTarget = object(Map.of("nodeId", node, "presetReadId", id, "presenceReadId", id), List.of("nodeId", "presetReadId", "presenceReadId")); diff --git a/src/main/resources/web/app.js b/src/main/resources/web/app.js index 3fcbb6c..6d37f29 100644 --- a/src/main/resources/web/app.js +++ b/src/main/resources/web/app.js @@ -3903,6 +3903,8 @@ async function waitForDeployment(operation, generation) { } function discardAuthenticationState(reason) { + if (typedFieldsDialog.open) typedFieldsDialog.close(); + clearTypedFields(); clearAgentCredential(); agentGrantForm.reset(); agentGrants.replaceChildren(); @@ -4234,9 +4236,11 @@ async function waitForOperation(operation, statusElement = operationStatus, cont rememberVoteLoggingRestart(operation); const applied = operation.type === 'APPLY' && Object.values(operation.results || {}).some(result => result?.success); + const previousGeneration = inputGeneration; if (applied) { invalidateConfigurationReads(); invalidateGuidedSetupReads(); + options.onApplyInvalidation?.(previousGeneration); if (tabFromHash() === 'quick-setup') window.setTimeout(() => void autoLoadTab('quick-setup'), 0); if (tabFromHash() === 'overview') { text(dataOverview, 'Configuration changed; refreshing server overview…'); @@ -4885,6 +4889,165 @@ async function loadFileConfiguration(automatic = false) { } } +const typedFieldsDialog = document.querySelector('#managed-fields-dialog'); +const typedFieldsKey = document.querySelector('#managed-fields-key'); +const typedFieldsValue = document.querySelector('#managed-fields-value'); +const typedFieldsStatus = document.querySelector('#managed-fields-status'); +const typedFieldsPreview = document.querySelector('#managed-fields-preview'); +const typedFieldsApply = document.querySelector('#managed-fields-apply'); +let typedFields = null; + +function typedFieldsCurrent(editor, generation = inputGeneration) { + return typedFieldsDialog.open && editor === typedFields && authenticated + && editor.authGeneration === authenticationGeneration && editor.generation === generation + && editor.file === configurationFile.value && editor.nodeId === selectedConfigurationNodeId() + && editor.sessionId === nodeIndex.get(editor.nodeId)?.sessionId; +} + +function discardTypedFieldApproval(editor) { + const approval = editor?.approval; + if (!editor) return; + editor.previewRequest = null; + editor.approval = null; + discardTypedFieldOperation(editor, approval); +} + +function discardTypedFieldOperation(editor, approval) { + if (approval && authenticated && editor.authGeneration === authenticationGeneration && !logoutInFlight) { + void authorized('/api/v1/configuration/managed-fields/discard-preview', { + method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(approval) + }).catch(() => {}); + } +} + +function clearTypedFields() { + discardTypedFieldApproval(typedFields); + typedFields = null; + typedFieldsKey.replaceChildren(); + typedFieldsValue.value = ''; + text(typedFieldsStatus, ''); + typedFieldsPreview.disabled = true; + typedFieldsApply.disabled = true; +} + +function selectTypedField() { + if (!typedFields) return; + discardTypedFieldApproval(typedFields); + typedFieldsApply.disabled = true; + const row = typedFields.fields.get(typedFieldsKey.value); + typedFieldsValue.value = row ? JSON.stringify(row.value, null, 2) : ''; + typedFieldsPreview.disabled = !row; + text(typedFieldsStatus, row ? row.field.kind.toLowerCase().replaceAll('_', ' ') : 'This file has no present typed fields.'); +} + +document.querySelector('#open-managed-fields').addEventListener('click', async () => { + if (!authenticated || configurationDirty || configurationSourceKind !== 'READ' || !lastFileReadOperation) { + text(fileOperationStatus, 'Load the current file and clear unsaved YAML changes before editing typed fields.'); + return; + } + clearTypedFields(); + const nodeId = selectedConfigurationNodeId(); + const editor = {nodeId, sessionId: nodeIndex.get(nodeId)?.sessionId, file: configurationFile.value, + readOperationId: lastFileReadOperation.operationId, authGeneration: authenticationGeneration, + generation: inputGeneration, fields: new Map()}; + typedFields = editor; + typedFieldsDialog.showModal(); + text(typedFieldsStatus, 'Loading typed fields…'); + try { + const rows = await authorized('/api/v1/configuration/managed-fields/state', { + method: 'POST', headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({readOperationId: editor.readOperationId, nodeId, file: editor.file}) + }); + if (!typedFieldsCurrent(editor)) return; + for (const row of rows) { + editor.fields.set(row.field.path, row); + const option = text(document.createElement('option'), row.field.path); + option.value = row.field.path; + typedFieldsKey.append(option); + } + selectTypedField(); + } catch (error) { + if (typedFieldsCurrent(editor)) text(typedFieldsStatus, error.message); + } +}); + +typedFieldsKey.addEventListener('change', selectTypedField); +typedFieldsValue.addEventListener('input', () => { + const previewPending = Boolean(typedFields?.previewRequest); + discardTypedFieldApproval(typedFields); + typedFieldsApply.disabled = true; + if (previewPending) typedFieldsPreview.disabled = !typedFields.fields.has(typedFieldsKey.value); +}); +typedFieldsDialog.addEventListener('close', clearTypedFields); + +typedFieldsPreview.addEventListener('click', async () => { + const editor = typedFields; + if (!editor || !typedFieldsCurrent(editor)) return; + const key = typedFieldsKey.value; + const input = typedFieldsValue.value; + discardTypedFieldApproval(editor); + const request = {}; + editor.previewRequest = request; + const requestCurrent = () => editor.previewRequest === request && typedFieldsCurrent(editor) + && key === typedFieldsKey.value && input === typedFieldsValue.value; + let approval; + typedFieldsApply.disabled = true; + typedFieldsPreview.disabled = true; + try { + const proposal = await authorized('/api/v1/configuration/managed-fields/preview', { + method: 'POST', headers: {'Content-Type': 'application/json'}, + body: JSON.stringify({readOperationId: editor.readOperationId, nodeId: editor.nodeId, file: editor.file, + overrides: {[key]: JSON.parse(input)}}) + }); + approval = {previewOperationId: proposal.operation.operationId}; + if (!requestCurrent()) return; + const operation = await waitForOperation(proposal.operation, typedFieldsStatus, operationContext(), + {contextCurrent: requestCurrent}); + if (!requestCurrent()) return; + if (operation.browserReviewReady) { + editor.approval = approval; + approval = null; + const restart = editor.file === 'bungeeconfig.yml' + ? '\nRestart the node separately before assuming the running transport changed.' : ''; + text(typedFieldsStatus, `${editor.nodeId} · ${editor.file} · ${key}\n${proposal.before[key]} → ${proposal.after[key]}${restart}`); + typedFieldsApply.disabled = false; + } + } catch (error) { + if (requestCurrent()) text(typedFieldsStatus, error.message); + } finally { + discardTypedFieldOperation(editor, approval); + if (requestCurrent()) { + editor.previewRequest = null; + typedFieldsPreview.disabled = false; + } + } +}); + +typedFieldsApply.addEventListener('click', async () => { + const editor = typedFields; + if (!editor?.approval || !typedFieldsCurrent(editor)) return; + const approval = editor.approval; + editor.approval = null; + typedFieldsApply.disabled = true; + typedFieldsPreview.disabled = true; + try { + // The shared Apply helper advances the generation before queueing work. + editor.generation = inputGeneration + 1; + const result = await startConfigurationOperation('/api/v1/configuration/managed-fields/apply', approval, typedFieldsStatus, { + onApplyInvalidation: previousGeneration => { + if (typedFieldsCurrent(editor, previousGeneration)) editor.generation = inputGeneration; + } + }); + if (!typedFieldsCurrent(editor)) return; + // Shared Apply invalidation schedules the file reload for the active context. + if (result.state === 'SUCCEEDED') typedFieldsDialog.close(); + } catch (error) { + if (typedFieldsCurrent(editor)) text(typedFieldsStatus, error.message); + } finally { + if (typedFieldsCurrent(editor)) typedFieldsPreview.disabled = false; + } +}); + readFileConfiguration.addEventListener('click', () => { void loadFileConfiguration(false); }); previewFileConfiguration.addEventListener('click', async () => { diff --git a/src/main/resources/web/index.html b/src/main/resources/web/index.html index c68b8db..0713c10 100644 --- a/src/main/resources/web/index.html +++ b/src/main/resources/web/index.html @@ -378,11 +378,25 @@

Full VotingPlugin configuration

Line 1, Column 1 · 1 line · 0 characters
Tab inserts two spaces · Ctrl/⌘+S previews only; use Approve and apply to save
+
+ +

Typed configuration fields

+ + + + +

+              
+ + +
+
+
Choose an online Bukkit node with file control.
@@ -744,6 +758,7 @@

Agent access

+ diff --git a/src/test/java/com/bencodez/votingplugin/control/domain/AgentOperationsTest.java b/src/test/java/com/bencodez/votingplugin/control/domain/AgentOperationsTest.java index 640e566..b83f767 100644 --- a/src/test/java/com/bencodez/votingplugin/control/domain/AgentOperationsTest.java +++ b/src/test/java/com/bencodez/votingplugin/control/domain/AgentOperationsTest.java @@ -863,6 +863,60 @@ private static UUID guidedRead(AgentOperations agents, ConfigurationOperations o return id; } + @Test void managedFieldsRequireExactScopedReadAndNodePreviewBeforeBrowserApply() throws Exception { + var clock = new MutableClock(); + var registry = new InMemoryNodeRegistry(clock, Duration.ofMinutes(2)); + UUID session = UUID.randomUUID(); + String node = "proxy"; + registry.register(new NodeRegistration(node, session, node, "VELOCITY", "fixture", 1, + Set.of(ConfigurationOperations.PROXY_FILE_CAPABILITY), Set.of())); + try (var operations = new ConfigurationOperations(registry, new ConfigurationAuditLog(directory, clock), clock)) { + var agents = new AgentOperations(registry, operations, clock); + var grant = agents.issue(new AgentOperations.Issue(List.of(node), List.of("managed-fields", "status"), 10, null)); + var other = agents.issue(new AgentOperations.Issue(List.of(node), List.of("managed-fields"), 10, null)); + var ordinary = agents.issue(new AgentOperations.Issue(List.of(node), List.of("read", "preview"), 10, null)); + var request = new AgentOperations.FieldsRead(node, "bungeeconfig.yml"); + assertThrows(SecurityException.class, () -> agents.readManagedFields(ordinary.token(), request)); + assertThrows(ValidationException.class, () -> agents.readManagedFields(grant.token(), + new AgentOperations.FieldsRead(node, "Config.yml"))); + UUID id = (UUID) ((Map) agents.readManagedFields(grant.token(), request)).get("operationId"); + var source = ManagedConfiguration.file("bungeeconfig.yml", "ProxyBroadcast:\n Scope:\n" + + " Servers: [lobby]\nDatabase:\n MaxConnections: 3\n Password: %s%n" + .formatted("__VOTINGPLUGIN_CONTROL_REDACTED__")); + var read = operations.claim(node, session); + String revision = "a".repeat(64); + operations.complete(id, node, new ConfigurationTaskResult(session, true, "OK", "fixture", + revision, source, List.of(), false, false, read.attemptId())); + assertEquals(Map.of("ProxyBroadcast.Scope.Servers", "['lobby']"), + ((Map) agents.status(grant.token(), id)).get("values")); + assertThrows(ValidationException.class, () -> operations.managedFieldState(id, node, "bungeeconfig.yml")); + var edits = new AgentOperations.FieldsPreview(node, id.toString(), Map.of("ProxyBroadcast.Scope.Servers", List.of("survival"))); + assertThrows(ValidationException.class, () -> agents.previewManagedFields(other.token(), edits)); + assertThrows(IllegalArgumentException.class, () -> agents.previewManagedFields(grant.token(), + new AgentOperations.FieldsPreview(node, id.toString(), Map.of("Database.MaxConnections", 8)))); + for (boolean exact : List.of(false, true)) { + UUID preview = (UUID) ((Map) agents.previewManagedFields(grant.token(), edits)).get("operationId"); + var task = operations.claim(node, session); + assertEquals(source.content().replace("[lobby]", "['survival']"), task.configuration().content()); + var current = exact ? source : ManagedConfiguration.file("bungeeconfig.yml", + source.content().replace("MaxConnections: 3", "MaxConnections: 4")); + operations.complete(preview, node, new ConfigurationTaskResult(session, true, "OK", "fixture", + revision, current, List.of("changed ProxyBroadcast.Scope.Servers"), false, false, task.attemptId())); + assertEquals(exact, operations.get(preview).browserReviewReady()); + assertNull(operations.get(preview).approvalToken()); + if (exact) { + assertThrows(ValidationException.class, () -> operations.createApply(preview, "invalid")); + UUID apply = agents.approve(preview).operationId(); + var applyTask = operations.claim(node, session); + assertEquals(revision, applyTask.expectedRevision()); + operations.complete(apply, node, new ConfigurationTaskResult(session, true, "OK", "fixture", + "b".repeat(64), applyTask.configuration(), List.of(), false, false, applyTask.attemptId())); + assertTrue(agents.status(grant.token(), apply).toString().contains("restartRequired=true")); + } + } + } + } + private static final class MutableClock extends Clock { private Instant now = Instant.EPOCH; diff --git a/src/test/java/com/bencodez/votingplugin/control/domain/ManagedFieldsTest.java b/src/test/java/com/bencodez/votingplugin/control/domain/ManagedFieldsTest.java new file mode 100644 index 0000000..65c5db2 --- /dev/null +++ b/src/test/java/com/bencodez/votingplugin/control/domain/ManagedFieldsTest.java @@ -0,0 +1,62 @@ +package com.bencodez.votingplugin.control.domain; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; + +class ManagedFieldsTest { + @Test void editsOnlySelectedNestedScalarsAndListsAndPreservesAdjacentComments() { + String source = """ + # preserve this note + ProxyBroadcast: + Enabled: true # preserve this note too + OfflineForward: + Servers: + - first + - second + Unrelated: unchanged + """; + var patch = ManagedFields.patch("bungeeconfig.yml", source, Map.of( + "ProxyBroadcast.Enabled", false, "ProxyBroadcast.OfflineForward.Servers", List.of("third")), true); + assertEquals(source.replace("Enabled: true", "Enabled: false") + .replace(" - first\n - second", " ['third']"), patch.content()); + assertEquals(Set.of("changed ProxyBroadcast.Enabled", "changed ProxyBroadcast.OfflineForward.Servers"), patch.changes()); + assertEquals("['first', 'second']", patch.before().get("ProxyBroadcast.OfflineForward.Servers")); + assertEquals("['third']", patch.after().get("ProxyBroadcast.OfflineForward.Servers")); + } + + @Test void browserOnlyCommandAndPoolFieldsNeverEnterAgentCatalogOrRead() { + String commands = "VoteParty:\n Rewards:\n Commands: ['sample-action']\n"; + assertTrue(ManagedFields.read("SpecialRewards.yml", commands, true).isEmpty()); + assertEquals(List.of("sample-action"), ManagedFields.read("SpecialRewards.yml", commands, false).get(0).value()); + assertFalse(ManagedFields.agentPaths().contains("Database.MaxConnections")); + assertThrows(IllegalArgumentException.class, () -> ManagedFields.patch("SpecialRewards.yml", commands, + Map.of("VoteParty.Rewards.Commands", List.of("sample-next")), true)); + assertEquals(commands.replace("sample-action", "sample-next"), ManagedFields.patch("SpecialRewards.yml", + commands, Map.of("VoteParty.Rewards.Commands", List.of("sample-next")), false).content()); + String database = "Database:\n MaxConnections: 4\n Password: %s%n" + .formatted("__VOTINGPLUGIN_CONTROL_REDACTED__"); + assertEquals(database.replace("MaxConnections: 4", "MaxConnections: 8"), ManagedFields.patch( + "Config.yml", database, Map.of("Database.MaxConnections", 8), false).content()); + assertThrows(IllegalArgumentException.class, () -> ManagedFields.patch("Config.yml", + database, Map.of("Database.Password", "fixture"), false)); + } + + @Test void rejectsUnknownFilesPathsAmbiguousKeysAndNonreviewableLists() { + assertThrows(IllegalArgumentException.class, () -> ManagedFields.catalog("ServerData.yml", false)); + assertThrows(IllegalArgumentException.class, () -> ManagedFields.patch("Config.yml", "PointsOnVote: 1\n", + Map.of("PointsOnVote", -1), true)); + assertThrows(IllegalArgumentException.class, () -> ManagedFields.patch("Config.yml", + "OfflineVotesLimit: {Amount: 2, amount: 3}\n", Map.of("OfflineVotesLimit.Amount", 5), true)); + assertThrows(IllegalArgumentException.class, () -> ManagedFields.patch("Config.yml", + "DefaultRewardWorlds:\n- world\n# Keep this note\n- world2\n", Map.of("DefaultRewardWorlds", List.of()), true)); + assertThrows(IllegalArgumentException.class, () -> ManagedFields.patch("Config.yml", + "DefaultRewardWorlds: [world]\n", Map.of("DefaultRewardWorlds", List.of("has spaces")), true)); + } +} diff --git a/src/test/java/com/bencodez/votingplugin/control/http/AgentMcpHttpTest.java b/src/test/java/com/bencodez/votingplugin/control/http/AgentMcpHttpTest.java index 7fe597b..527d5fa 100644 --- a/src/test/java/com/bencodez/votingplugin/control/http/AgentMcpHttpTest.java +++ b/src/test/java/com/bencodez/votingplugin/control/http/AgentMcpHttpTest.java @@ -148,7 +148,7 @@ private void start(boolean agentEnabled) throws Exception { new StdioAdapter(base.toString(), token).run(new ByteArrayInputStream(input.getBytes(StandardCharsets.UTF_8)), frames); var replies = frames.toString(StandardCharsets.UTF_8).lines().toList(); assertEquals(4, replies.size()); - assertEquals(23, json.readTree(replies.get(1)).path("result").path("tools").size()); + assertEquals(26, json.readTree(replies.get(1)).path("result").path("tools").size()); assertEquals("proxy-a", json.readTree(replies.get(2)).path("result").path("structuredContent") .path("items").get(0).path("nodeId").asText()); assertEquals(applyId, json.readTree(replies.get(3)).path("result").path("structuredContent") @@ -197,6 +197,60 @@ private void completeAgentTask(String operationId, String type, String revision, assertEquals(200, response.statusCode(), response.body()); } + @Test void typedBrowserFieldEditorRequiresSessionAndCsrf() throws Exception { + String fixturePassphrase = UUID.randomUUID().toString(); + credentials.setWebPassword(fixturePassphrase.toCharArray()); + var login = send("POST", "/api/v1/auth/login", json.writeValueAsString(Map.of("password", fixturePassphrase)), null); + String cookie = login.headers().firstValue("Set-Cookie").orElseThrow().split(";", 2)[0]; + var browser = Map.of("Cookie", cookie, "X-CSRF-Token", json.readTree(login.body()).path("csrfToken").asText()); + String browserState = "/api/v1/configuration/managed-fields/state"; + assertAuthFailure(send("POST", browserState, "{}", adminToken)); + assertError(sendWithHeaders("POST", browserState, "{}", Map.of("Cookie", cookie)), 403, "CSRF_REQUIRED"); + assertEquals(201, send("POST", "/api/v1/nodes/register", registration() + .replace("VELOCITY", "BUKKIT").replace("presence.snapshot", "config.files.v1"), nodeToken).statusCode()); + String read = json.writeValueAsString(Map.of("nodeIds", java.util.List.of("proxy-a"), + "configuration", Map.of("domain", "file", "fileName", "SpecialRewards.yml"))); + var start = sendWithHeaders("POST", "/api/v1/configuration/read", read, browser); + assertEquals(202, start.statusCode(), start.body()); + String id = json.readTree(start.body()).path("operationId").asText(); + var poll = send("POST", "/api/v1/nodes/proxy-a/operations", "{\"sessionId\":\"" + SESSION + "\"}", nodeToken); + String attempt = json.readTree(poll.body()).path("attemptId").asText(); + String yaml = "VoteParty:\n GlobalCommands: [sample-action]\n"; + String result = json.writeValueAsString(Map.of("success", true, "code", "OK", "message", "fixture", + "sessionId", SESSION, "attemptId", attempt, "revision", "a".repeat(64), "changes", java.util.List.of(), + "configuration", Map.of("domain", "file", "fileName", "SpecialRewards.yml", "content", yaml))); + assertEquals(200, send("POST", "/api/v1/nodes/proxy-a/operations/" + id + "/result", result, nodeToken).statusCode()); + String payload = json.writeValueAsString(Map.of("readOperationId", id, "nodeId", "proxy-a", "file", "SpecialRewards.yml")); + var fields = sendWithHeaders("POST", browserState, payload, browser); + assertEquals(200, fields.statusCode(), fields.body()); + assertEquals("sample-action", json.readTree(fields.body()).get(0).path("value").get(0).asText()); + var edit = json.readTree(payload).deepCopy(); + ((com.fasterxml.jackson.databind.node.ObjectNode) edit).putObject("overrides") + .putArray("VoteParty.GlobalCommands").add("sample-next"); + var queued = sendWithHeaders("POST", "/api/v1/configuration/managed-fields/preview", edit.toString(), browser); + assertEquals(202, queued.statusCode(), queued.body()); + String preview = json.readTree(queued.body()).path("operation").path("operationId").asText(); + var task = json.readTree(send("POST", "/api/v1/nodes/proxy-a/operations", + "{\"sessionId\":\"" + SESSION + "\"}", nodeToken).body()); + assertTrue(task.path("configuration").path("content").asText().contains("sample-next")); + var previewResult = (com.fasterxml.jackson.databind.node.ObjectNode) json.readTree(result); + previewResult.put("attemptId", task.path("attemptId").asText()); + previewResult.putArray("changes").add("changed VoteParty.GlobalCommands"); + assertEquals(200, send("POST", "/api/v1/nodes/proxy-a/operations/" + preview + "/result", + previewResult.toString(), nodeToken).statusCode()); + var retained = json.readTree(get("/api/v1/operations/" + preview, adminToken).body()); + assertTrue(retained.path("browserReviewReady").asBoolean()); + assertTrue(retained.path("approvalToken").isNull() || retained.path("approvalToken").isMissingNode()); + String approval = json.writeValueAsString(Map.of("previewOperationId", preview)); + String browserApply = "/api/v1/configuration/managed-fields/apply"; + assertAuthFailure(send("POST", browserApply, approval, adminToken)); + assertError(sendWithHeaders("POST", browserApply, approval, Map.of("Cookie", cookie)), 403, "CSRF_REQUIRED"); + var genericApply = json.writeValueAsString(Map.of("previewOperationId", preview, "approvalToken", "invalid")); + assertEquals(400, send("POST", "/api/v1/configuration/apply", genericApply, adminToken).statusCode()); + assertEquals(202, sendWithHeaders("POST", browserApply, approval, browser).statusCode()); + assertEquals(400, sendWithHeaders("POST", browserApply, approval, browser).statusCode()); + } + private String registration() { return "{\"nodeId\":\"proxy-a\",\"sessionId\":\"" + SESSION + "\",\"displayName\":\"Proxy A\"," + "\"platform\":\"VELOCITY\",\"pluginVersion\":\"7.1.2\",\"protocolVersion\":1," diff --git a/src/test/web/app-managed-fields.test.cjs b/src/test/web/app-managed-fields.test.cjs new file mode 100644 index 0000000..06f992f --- /dev/null +++ b/src/test/web/app-managed-fields.test.cjs @@ -0,0 +1,177 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const test = require('node:test'); +const vm = require('node:vm'); + +const source = fs.readFileSync(path.join(__dirname, '../../main/resources/web/app.js'), 'utf8'); +function section(start, end) { + const offset = source.indexOf(start); + const limit = source.indexOf(end, offset); + assert.ok(offset >= 0 && limit > offset); + return source.slice(offset, limit); +} + +function harness() { + let click; + let finish; + let rereads = 0; + let finishRead; + const read = new Promise(resolve => { finishRead = resolve; }); + const scheduled = []; + const terminal = new Promise(resolve => { finish = resolve; }); + const noop = () => {}; + const editor = {authGeneration: 1, generation: 1, file: 'Config.yml', nodeId: 'backend', + sessionId: 'session', approval: {previewOperationId: 'preview'}}; + const ctx = { + typedFields: editor, typedFieldsDialog: {open: true, close() { this.open = false; }}, + typedFieldsApply: {addEventListener(_name, handler) { click = handler; }}, typedFieldsPreview: {}, + typedFieldsStatus: {}, fileOperationStatus: {}, operationStatus: {}, configurationContent: {}, + configurationDirty: false, configurationFile: {value: 'Config.yml'}, authenticated: true, + authenticationGeneration: 1, inputGeneration: 1, configurationOperationsInFlight: 0, + selectedConfigurationNodeId: () => 'backend', nodeIndex: new Map([['backend', {sessionId: 'session'}]]), + dedicatedSetupApprovals: new Map(), fileReadCache: new Map(), settingsHealthGeneration: 0, + dashboardConfigurationGeneration: 0, settingsEditor: null, settingsHealthReader: null, + voteSitesEditor: null, rewardsEditor: null, autoLoadPending: new Set(), + tabFromHash: () => 'configurations', window: {setTimeout: callback => scheduled.push(callback)}, + operationContext: () => ({}), operationContextCurrent: () => true, + operationSummary: operation => operation.state, text: (target, value) => { target.textContent = value; }, + authorized: async (url, request) => { + assert.equal(url, '/api/v1/configuration/managed-fields/apply'); + assert.deepEqual(JSON.parse(request.body), {previewOperationId: 'preview'}); + return terminal; + }, + loadFileConfiguration: async () => { rereads++; await read; }, + autoLoadTab: tab => { + assert.equal(tab, 'configurations'); + return ctx.loadFileConfiguration(true); + }, + updateConfigurationButtons: noop, updateExtendedButtons: noop, syncYamlEditorView: noop, + rememberOperation: noop, rememberVoteLoggingRestart: noop, invalidateGuidedSetupReads: noop, + invalidateDashboardInspection: noop + }; + vm.createContext(ctx); + vm.runInContext(section('function clearApprovals(', 'function updateEditorPosition(') + + section('function invalidateConfigurationReads(', 'async function loadEnrollments(') + + section('function typedFieldsCurrent(', 'function discardTypedFieldApproval(') + + section("typedFieldsApply.addEventListener('click'", 'readFileConfiguration.addEventListener('), ctx); + return {ctx, click, finish, finishRead, scheduled, rereads: () => rereads}; +} + +test('successful typed Apply closes the dialog and relies on the one scheduled reread', async () => { + const {ctx, click, finish, finishRead, scheduled, rereads} = harness(); + const pending = click(); + finish({type: 'APPLY', state: 'SUCCEEDED', results: {backend: {success: true}}}); + await new Promise(resolve => setImmediate(resolve)); + assert.equal(ctx.inputGeneration, 3); + assert.equal(scheduled.length, 1); + const refresh = scheduled.shift()(); + ctx.configurationFile.value = 'GUI.yml'; + ctx.fileOperationStatus.textContent = 'Loading GUI.yml'; + finishRead(); + await Promise.all([pending, refresh]); + assert.equal(ctx.typedFieldsDialog.open, false); + assert.equal(rereads(), 1); + assert.equal(ctx.fileOperationStatus.textContent, 'Loading GUI.yml'); +}); + +for (const [name, change] of Object.entries({ + 'input generation': ctx => ctx.clearApprovals(), + 'selected file': ctx => { ctx.configurationFile.value = 'GUI.yml'; }, + 'node session': ctx => { ctx.nodeIndex.set('backend', {sessionId: 'new-session'}); }, + 'authentication': ctx => { ctx.authenticationGeneration++; } +})) { + test(`completed typed Apply leaves a changed ${name} context alone`, async () => { + const {ctx, click, finish, rereads} = harness(); + const pending = click(); + change(ctx); + finish({type: 'APPLY', state: 'SUCCEEDED', results: {backend: {success: true}}}); + await pending; + assert.equal(ctx.typedFieldsDialog.open, true); + assert.equal(rereads(), 0); + }); +} + +function previewHarness() { + let click; + const requests = []; + const discarded = []; + const ctx = { + typedFields: {readOperationId: 'read', nodeId: 'backend', file: 'Config.yml', authGeneration: 1}, + typedFieldsCurrent: editor => ctx.current && editor === ctx.typedFields, + current: true, authenticated: true, authenticationGeneration: 1, logoutInFlight: false, + typedFieldsKey: {value: 'Enabled'}, typedFieldsValue: {value: 'true'}, typedFieldsStatus: {}, + typedFieldsPreview: {addEventListener(_name, handler) { click = handler; }}, + typedFieldsApply: {}, text: (target, value) => { target.textContent = value; }, + operationContext: () => ({}), + waitForOperation: async operation => operation, + authorized: (url, request) => { + const data = JSON.parse(request.body); + if (url.endsWith('/discard-preview')) { + discarded.push(data.previewOperationId); + return Promise.resolve(); + } + assert.ok(url.endsWith('/preview')); + return new Promise(resolve => requests.push(resolve)); + } + }; + vm.createContext(ctx); + vm.runInContext(section('function discardTypedFieldApproval(', 'function clearTypedFields(') + + section("typedFieldsPreview.addEventListener('click'", "typedFieldsApply.addEventListener('click'"), ctx); + const complete = (index, operationId, key) => requests[index]({ + operation: {operationId, browserReviewReady: true}, before: {[key]: 'before'}, after: {[key]: 'after'} + }); + return {ctx, click, complete, discarded}; +} + +test('out-of-order preview responses discard only the stale operation and preserve the newer approval', async () => { + const {ctx, click, complete, discarded} = previewHarness(); + const older = click(); + ctx.typedFieldsKey.value = 'Other'; + const newer = click(); + complete(1, 'newer', 'Other'); + await newer; + const status = ctx.typedFieldsStatus.textContent; + complete(0, 'older', 'Enabled'); + await older; + assert.deepEqual(discarded, ['older']); + assert.equal(ctx.typedFields.approval?.previewOperationId, 'newer'); + assert.equal(ctx.typedFieldsApply.disabled, false); + assert.equal(ctx.typedFieldsStatus.textContent, status); +}); + +test('preview completion in a changed editor context discards only its own operation', async () => { + const {ctx, click, complete, discarded} = previewHarness(); + const pending = click(); + ctx.current = false; + complete(0, 'stale', 'Enabled'); + await pending; + assert.deepEqual(discarded, ['stale']); + assert.equal(ctx.typedFields.approval, null); + assert.equal(ctx.typedFieldsApply.disabled, true); +}); + +test('a superseded poll cannot publish an approval even for identical field values', async () => { + const {ctx, click, complete, discarded} = previewHarness(); + let finishPoll; + let polling; + const started = new Promise(resolve => { polling = resolve; }); + ctx.waitForOperation = operation => { + if (operation.operationId !== 'older') return Promise.resolve(operation); + return new Promise(resolve => { + finishPoll = () => resolve(operation); + polling(); + }); + }; + const older = click(); + complete(0, 'older', 'Enabled'); + await started; + const newer = click(); + complete(1, 'newer', 'Enabled'); + await newer; + finishPoll(); + await older; + assert.deepEqual(discarded, ['older']); + assert.equal(ctx.typedFields.approval?.previewOperationId, 'newer'); + assert.equal(ctx.typedFieldsApply.disabled, false); +}); diff --git a/src/test/web/authentication-state.test.cjs b/src/test/web/authentication-state.test.cjs index f74d018..b5abe0c 100644 --- a/src/test/web/authentication-state.test.cjs +++ b/src/test/web/authentication-state.test.cjs @@ -43,6 +43,12 @@ function harness() { return elements.get(selector); }; const context = { + typedFields: {approval: null}, typedFieldsDialog: element('#managed-fields-dialog'), + typedFieldsKey: element('#managed-fields-key'), typedFieldsValue: element('#managed-fields-value'), + typedFieldsStatus: element('#managed-fields-status'), typedFieldsPreview: element('#managed-fields-preview'), + typedFieldsApply: element('#managed-fields-apply'), + agentCredentialOutput: Object.assign(new Element(), {querySelector: element}), + agentGrantForm: new Element(), agentGrants: new Element(), agentGrantStatus: new Element(), agentReview: new Element(), settingsHealthReader: null, settingsEditor: {clear() {}}, voteSitesEditor: {clear() {}}, rewardsEditor: {clear() {}}, workspace: {logout() {}}, registryAvailable: true, authenticationGeneration: 3, authenticated: true, csrfToken: 'csrf', approvedPreview: {}, approvedFilePreview: {}, approvedQuickPreview: {}, loadedQuickSetup: {}, quickSetupDirty: true, @@ -82,7 +88,8 @@ function harness() { updateConfigurationButtons() {}, updateExtendedButtons() {}, text(target, value) { target.textContent = value; } }; vm.createContext(context); - vm.runInContext([declaration('clearSessionRewardFileOptions'), declaration('discardAuthenticationState')].join('\n'), + vm.runInContext(['clearSessionRewardFileOptions', 'discardTypedFieldApproval', 'discardTypedFieldOperation', 'clearTypedFields', 'clearAgentCredential', + 'discardAuthenticationState'].map(declaration).join('\n'), context, {filename: 'authentication-state.js'}); return {context, element}; } @@ -92,6 +99,9 @@ test('sign-out and session expiry share teardown that clears Vote Sites and Rewa assert.match(appSource, /authorized\('\/api\/v1\/auth\/logout', \{method: 'POST'\}\)[\s\S]*discardAuthenticationState\('Signed out\.'/); for (const reason of ['Signed out.', 'Session expired. Sign in again.']) { const {context, element} = harness(); + const typedDialog = element('#managed-fields-dialog'); typedDialog.open = true; + element('#managed-fields-key').replaceChildren(new Element()); + element('#managed-fields-value').value = 'draft configuration'; const dialog = element('#vote-site-add-dialog'); dialog.open = true; element('#vote-site-search').value = 'draft site'; element('#vote-site-filter').value = 'partial'; element('#vote-site-ack').checked = true; element('#rewards-search').value = 'draft reward'; element('#rewards-operation').value = 'REPLACE_LIST'; @@ -103,6 +113,12 @@ test('sign-out and session expiry share teardown that clears Vote Sites and Rewa context.configurationFile.value = dynamicOption.value; context.yamlEditorSearch.value = 'database-password'; vm.runInContext(`discardAuthenticationState(${JSON.stringify(reason)})`, context); + assert.equal(typedDialog.closeCalled, true); + assert.equal(context.typedFields, null); + assert.equal(element('#managed-fields-key').children.length, 0); + assert.equal(element('#managed-fields-value').value, ''); + assert.equal(element('#managed-fields-preview').disabled, true); + assert.equal(element('#managed-fields-apply').disabled, true); assert.equal(element('#vote-site-form').resetCalled, true); assert.equal(element('#vote-site-add-form').resetCalled, true); assert.equal(dialog.closeCalled, true);