Repository navigation
feat(config): add Zod-based simulator configuration syntax validation - #1874
Conversation
…keleton - Add ConfigurationMigrations.ts: CURRENT_CONFIGURATION_SCHEMA_VERSION=1, coerceConfigurationVersion, applyConfigurationMigration, migrateV0ToV1 with DEPRECATED_KEY_REMAPPINGS (~25 legacy keys) - Add ConfigurationSchema.ts: strict Zod v4 schema for all config sections (log, worker, performanceStorage, uiServer, stationTemplateUrls) with deprecated keys as .optional() - Add ConfigurationValidation.ts: validateConfiguration pipeline (guard→clone→coerce→migrate→safeParse→transform) + ConfigurationValidationError extends BaseError with structured fieldErrors - Add $schemaVersion: 1 to config-template.json - Add ConfigurationFixtures.ts test helpers - Add ConfigurationSchema.test.ts (63 tests), ConfigurationMigrations.test.ts (44 tests) - Wire validateConfiguration into Configuration.getConfigurationData() with hard-throw at boot (console.error+chalk+process.exit(1)) - Hot-reload snapshot rollback: pre-clear snapshot, restore on failure - Replace ConfigurationData interface with z.infer<typeof ConfigurationSchema> - Migrate all consumers atomically (SimulatorState, Configuration, types barrel) - Delete checkWorkerProcessType and checkWorkerElementsPerWorker (subsumed by schema) - Delete ConfigurationMigration.ts (logic moved to ConfigurationMigrations.ts) - Add ConfigurationValidation.test.ts (39 tests), Configuration-hot-reload.test.ts - Add ConfigurationValidation-perf.test.ts (p99 < 50ms budget) - Add error message snapshot test - Update README.md with $schemaVersion documentation
…sites - Delete src/utils/ConfigurationMigration.ts (deprecated-key logic now owned by ConfigurationMigrations.ts v0→v1 migration step) - Remove checkDeprecatedConfigurationKeys import and call site from Configuration.getStationTemplateUrls() — validation pipeline in getConfigurationData() already handles deprecated key remapping
SummaryThe following content is AI-generated and provides a summary of the pull request: feat(config): Add Zod-Based Simulator Configuration Schema ValidationNew Feature✨ Introduces boot-time validation for the simulator configuration file ( Changes
PR Bot InformationVersion:
|
There was a problem hiding this comment.
The pull request is well-structured and introduces a solid Zod-based validation pipeline that mirrors the existing template-validation pattern. The test coverage is thorough. However, there are several substantive issues identified in the review:
-
Double
$schemaVersionstamping (ConfigurationMigrations.tsline 94): BothmigrateV0ToV1and theapplyConfigurationMigrationloop write$schemaVersion, creating a redundant and potentially misleading dual-write when more migration steps are added. -
Silent data loss for
autoReconnectMaxRetries(ConfigurationMigrations.tsline 13): The self-mappingautoReconnectMaxRetries → autoReconnectMaxRetriescauses the key to be deleted during v0→v1 migration (thelegacy !== canonicalguard skips the copy, but the delete still runs), while the schema continues to accept it andbuildWorkerSectionstill reads it. This is contradictory. -
moduleNameneedlessly exported (ConfigurationValidation.tsline 15):moduleNameis only used as an internal error-prefix within this module; exporting it leaks an implementation detail. -
Stale
supervisionURLsremapping ingetSupervisionUrls:Configuration.getSupervisionUrls()still manually copiessupervisionURLs→supervisionUrlson the live cached object (mutable in-place), but the migration pipeline already performs this remap before storage. This is dead code that also mutates shared state in violation of the immutability principle. -
Off-by-one p99 index (
ConfigurationValidation-perf.test.tsline 43):timings[98]over 100 sorted samples is the 98th percentile, not p99. The true p99 over 100 samples istimings[99](the maximum).
PR Bot Information
Version: 1.21.0
- Correlation ID:
7263b2ab-6d9b-4e3d-8284-9804fb64185e - Event Trigger:
pull_request.opened - File Content Strategy: Full file content
- Agent Instructions:
- LLM:
anthropic--claude-4.6-sonnet
There was a problem hiding this comment.
Pull request overview
This PR introduces a Zod-based, versioned validation + migration pipeline for the simulator configuration, aligning it with the existing charging-station template validation approach and making invalid configurations fail fast (boot) or roll back (hot-reload).
Changes:
- Added
ConfigurationSchema(Zod),ConfigurationMigrations(v0→v1 remap), andConfigurationValidation(guard → migrate → validate → warn) for simulator config parsing. - Integrated validation into
src/utils/Configuration.ts, including snapshot/rollback semantics for hot-reload and removal of ad-hoc worker config validators. - Updated configuration types to be derived from the schema and added/updated extensive unit tests + documentation ($schemaVersion).
Reviewed changes
Copilot reviewed 20 out of 20 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
| tests/worker/WorkerUtils.test.ts | Removes tests for deleted checkWorkerProcessType helper. |
| tests/utils/ConfigurationUtils.test.ts | Removes tests for deleted checkWorkerElementsPerWorker helper. |
| tests/utils/Configuration.test.ts | Updates tests to include $schemaVersion in config data. |
| tests/utils/Configuration-hot-reload.test.ts | Adds tests for hot-reload rollback and flag-reset behavior. |
| tests/charging-station/helpers/ConfigurationFixtures.ts | Adds shared fixtures for schema/migration/validation tests. |
| tests/charging-station/ConfigurationValidation.test.ts | Adds unit tests for validation pipeline, errors, warnings, and assets. |
| tests/charging-station/ConfigurationValidation-perf.test.ts | Adds performance budget test for validation pipeline. |
| tests/charging-station/ConfigurationSchema.test.ts | Adds unit tests for schema behavior (strictness, enums, deprecated keys). |
| tests/charging-station/ConfigurationMigrations.test.ts | Adds unit tests for version coercion and v0→v1 migration behavior. |
| src/worker/WorkerUtils.ts | Removes checkWorkerProcessType. |
| src/worker/index.ts | Stops exporting checkWorkerProcessType. |
| src/utils/ConfigurationUtils.ts | Removes checkWorkerElementsPerWorker and unused type import. |
| src/utils/ConfigurationMigration.ts | Deletes legacy deprecated-key warning/migration logic. |
| src/utils/Configuration.ts | Integrates config validation, boot-time failure, and hot-reload rollback. |
| src/types/ConfigurationData.ts | Switches ConfigurationData typing to z.infer of Zod schemas. |
| src/charging-station/ConfigurationValidation.ts | Adds validation pipeline + structured validation error and deprecation warnings. |
| src/charging-station/ConfigurationSchema.ts | Adds strict Zod schema for simulator configuration (with deprecated keys). |
| src/charging-station/ConfigurationMigrations.ts | Adds schema versioning, coercion, and v0→v1 migration/remap. |
| src/assets/config-template.json | Adds $schemaVersion: 1 to the template. |
| README.md | Documents $schemaVersion in the configuration table. |
- Add JSDoc descriptions for setAtPath() params - Add JSDoc descriptions and @returns for migrateV0ToV1 - Whitelist 'emerg' (syslog level) and 'REMAPPINGS' in cspell dictionary
Address audit findings on PR #1874: - Extract deprecated-key sweep into pure remapDeprecatedKeys() that reports warnings and field errors via return value instead of side effects. Runs unconditionally regardless of $schemaVersion so v1 configs still containing deprecated keys never silently drop user values (B3). - Replace silent-drop setAtPath with collision- and intermediate-aware variant: equal-value writes are idempotent no-ops, unequal values produce a typed field error (B4), non-object intermediates are reported and stop traversal instead of overwriting user data (N7). - Type DEPRECATED_KEY_REMAPPINGS as Record<string, string | null>; null marks deprecated keys with no canonical destination, replacing the autoReconnectMaxRetries self-mapping that silently dropped the user value (B2). Add 'worker.elementStartDelay' as a dotted source key so nested deprecations live in the same single source of truth. - Refactor ConfigurationValidationError: primary constructor takes FieldError[] + a context with explicit phase ('migration' | 'schema'); static fromZodError() factory wraps Zod failures. Error messages now carry the phase in their tag for clearer diagnostics. - Switch deprecation-warning channel from logger.warn to console.warn to break a re-entrant boot path where the Logger proxy lazily resolved Configuration.getConfigurationSection('log'), recursing into the validation pipeline (B1). transformConfiguration is now a pure deep clone — its previous warning loop moved upstream to the sweep. - Delete dead post-migration remapping in Configuration.ts: deprecatedLogKeyMap, deprecatedWorkerKeyMap, the delete configurationData.workerPoolStrategy mutation, the cast hiding the legacy 'supervisionURLs' read, and the worker.elementStartDelay fallback (B6). All deprecation handling now flows through the migration's single source of truth. - Make hot-reload reload loop async end-to-end. Awaits the change callback inside the same lock so subsequent reloads cannot interleave with an in-flight callback. Adds configurationFileReloadPending so events arriving during a reload coalesce into exactly one drain reload after the current one completes (N8). - Polish schema: use z.enum(NativeEnum) directly for ApplicationProtocol and ApplicationProtocolVersion to preserve literal-type narrowing on UIServerConfiguration (N4); drop the BaseConfigurationSchema alias (N5).
Tests aligned with the rebuilt validation pipeline: - Split migration tests into a remapDeprecatedKeys block (per-key sweep, null-destination removal for autoReconnectMaxRetries, equal-value collision idempotency, unequal-value collision field error, non-object intermediate field error, nested worker.elementStartDelay) and a lean applyConfigurationMigration block (version-bump only, immutability). - Replace the empty self-mapping branch with explicit hasOwnProperty removal assertions to defeat the previously vacuous test. - ConfigurationValidation tests: switch deprecation-warning channel spies from logger.warn to console.warn (B1 regression also asserts logger.warn is never called from the pipeline), tolerate schema-incompatible remap targets so the warning fires before the downstream throw, add B3 sweep / B6 SSOT / future-version pipeline / ConfigurationValidationError shape (FieldError[] + phase, fromZodError factory, schema-phase aggregation) tests, and update the error-message snapshot to include the new [phase] tag. - transformConfiguration immutability test verifies a fresh validation is unaffected by mutating a prior return value. - ConfigurationSchema tests: strict parity for performanceStorage and uiServer.authentication; StationTemplateUrl entry constraints (empty file, negative numberOfStations, deprecated numberOfStation, unknown key); worker.elementsPerWorker and poolMaxSize/MinSize positive-integer constraints; log.statisticsInterval non-negative integer constraints; bidirectional schema/DEPRECATED_KEY_REMAPPINGS sync meta-test that walks both top-level and nested @deprecated describe markers. - Hot-reload tests rebuilt around the async runReloadLoop: validation failure asserts the logged error is a ConfigurationValidationError; JSON parse error path asserts configurationData and section cache are fully restored (Gap 7); a sentinel watcher survives a failed reload; N8 rapid double-save coalesces into exactly one drain reload reflecting the latest content; flag reset is exercised on both paths. - Configuration validation perf test: relative p99 budget (20× median with a 1ms floor) plus an absolute 500ms catastrophic ceiling, replacing the flaky absolute 50ms threshold (N1). - Fixtures: new buildInvalidJsonString, buildV1WithDeprecatedKey (handles top-level and dotted source keys), and buildV0WithDeprecatedKeyCollision builders for the new test cases.
…tions Polish pass after PR audit: bring comments and docstrings in line with the existing TemplateMigrations / TemplateValidation / TemplateSchema patterns, drop ceremonial AI-generated narration, and fix two precision defects. - ConfigurationMigrations.ts: trim getAtPath / setAtPath / remapDeprecatedKeys / migrateV0ToV1 / applyConfigurationMigration JSDocs to match Template* density; drop the historical "now handled unconditionally upstream" paragraph (AGENTS.md "exclude historical evolution"). - ConfigurationValidation.ts: collapse the duplicated pipeline narration (the function-level JSDoc already enumerates stages, the inline // Stage N — markers were removing them); shorten the ConfigurationValidationError class docstring; tighten transformConfiguration JSDoc and drop the aspirational "future cross-field invariants" sentence; collapse the 5-line re-entrancy comment to a 2-line rationale. - ConfigurationSchema.ts: fix two precision defects in JSDoc — stale module name (ConfigurationMigration → ConfigurationMigrations) and wrong subject (numberOfStation is not in the remap table; nothing auto-migrates it). Disambiguate WorkerConfigurationSchema description (resourceLimits is bridged, not deprecated; elementStartDelay is the deprecated alias). - Configuration.ts: shrink runReloadLoop and performReload JSDocs to two- line summaries matching the surrounding private-method conventions in the same file; collapse the 4-line ESLint-disable rationale to a single -- suffix on the disable directive. - Test fixtures and headers: drop internal review codes (B1/B3/B4/B6/N7/N8/ Gap-7/RG-4) from JSDocs and test names — they had no lookup table and would be opaque to future maintainers; trim test-file headers to the one-line Template* shape.
| process.exit(1) | ||
| } | ||
| throw validationError | ||
| } | ||
| Configuration.configurationFileWatcher ??= Configuration.getConfigurationFileWatcher() | ||
| } catch (error) { |
b287f4a to
ea16afa
Compare
…iants Addresses 4 PR review findings cross-validated by 2 oracles. - ConfigurationMigrations: drop `useWorkerPool` (boolean→enum), `distributeStationToTenantEqually` and `distributeStationsToTenantsEqually` (boolean→enum), and `uiWebSocketServer` (legacy shape→strict object) to `null` (warn-and-delete) — same pattern as `workerPoolStrategy` and `autoReconnectMaxRetries`. v0 configurations carrying any of these legacy keys would otherwise auto-write a value the strict schema rejects, killing the simulator at boot. Migration now warns and asks the user to set the canonical key explicitly. Fixes the BLOCKING finding from the PR review (regression on 'v0 configs remain valid'). - ConfigurationMigrations: remove redundant `out.$schemaVersion = 1` from `migrateV0ToV1`. The `applyConfigurationMigration` loop is the single owner of version stamping; per-step writes are silently overwritten and become misleading once a second migration is added. - ConfigurationSchema: tighten `StationTemplateUrlSchema.numberOfStations` from `.nonnegative()` to `.positive()` — `0` was schema-valid but semantically meaningless (a template entry that spawns no station) and conflicts with `isValidNumberOfStations()` which rejects `<= 0`. Deprecated `numberOfStation` and `provisionedNumberOfStations` keep `.nonnegative()` (back-compat / 'none provisioned' is meaningful). - ConfigurationValidation: import `isEmpty` directly from `utils/Utils.js` instead of the `utils/index.js` barrel, which re-exports `Configuration` and creates the cycle `ConfigurationValidation → utils/index → Configuration → ConfigurationValidation`. Mirrors the existing direct-path `BaseError` import in `ConfigurationMigrations.ts` for the same TDZ-cycle-avoidance reason.
- ConfigurationSchema.ts: correct StorageConfigurationSchema JSDoc — 'URI' is accepted but not auto-migrated (not in DEPRECATED_KEY_REMAPPINGS); narrow ConfigurationSchema JSDoc meta-test scope claim to 'top-level and worker.* keys' to match actual test coverage. - README.md: clarify that deprecated-key remapping is unconditional (runs on every load, not only on v0 migration).
…bled-entry convention Revert the .positive() tightening from 95cd26d: docker/config.json ships 5 stationTemplateUrls entries with `numberOfStations: 0` (used as a 'keep on disk but disabled' convention), and this file is copied to src/assets/config.json by docker/Dockerfile at image build time. With .positive(), Docker images built from this branch would fail to start on validateConfiguration's strict parse → process.exit(1). Bootstrap loops already tolerate 0 (no-op, no crash). The original .nonnegative() correctly models the on-disk convention; isValidNumberOfStations() in UIServerSecurity.ts is for runtime UI add-station requests, a separate concern from config-file parsing.
…1901) * fix(config): tighten Zod validation on uiServer.options.port (#1874) Replace the permissive z.custom<ListenOptions> bridge under uiServer.options with a typed object schema validating known primitive fields, so bad transport-level values (e.g. port: "not-a-number") fail at boot time in ConfigurationSchema.safeParse instead of later inside node:net.Server.listen with ERR_SOCKET_BAD_PORT. The existing accessPolicy refinement is preserved via .pipe(); unknown keys are still passed through (.loose()) to keep the ListenOptions extension surface (e.g. signal: AbortSignal) usable. Validates: - port: integer in [0, 65535] - host: non-empty string - backlog: non-negative integer - path: non-empty string - exclusive / ipv6Only / readableAll / writableAll: boolean Tests: 10 new cases in tests/utils/ConfigurationSchema.test.ts and 1 integration assertion in tests/utils/ConfigurationValidation.test.ts covering the structured Zod error path uiServer.options.port routed through ConfigurationValidationError. * docs(config): align JSDoc with composite uiServer.options schema Address review comment on #1901: the JSDoc above UIServerListenOptionsObjectSchema was named after the composite UIServerListenOptionsSchema, leaving the helper described under the wrong name and the composite undocumented. UIServerConfigurationSchema also still referenced the now-removed permissive z.custom<ListenOptions> bridge. - UIServerListenOptionsObjectSchema gets its own JSDoc describing the typed object layer (.loose() + primitive constraints). - UIServerListenOptionsSchema gets a JSDoc describing the full chain: object guard → accessPolicy refinement → pipe to typed object. - UIServerConfigurationSchema JSDoc updated to reference the new composite schema instead of the obsolete custom bridge. No behavior change, no test change.
…1903) * fix(config): enforce Zod simulator-config validation at boot (#1874) Audit pass over uiServer.* primitives that PR #1901 left under-constrained. Each constraint closes a concrete fail-fast gap surfaced by a 3-angle design review (schema completeness, fail-fast wiring, adversarial risk). UIServerAuthenticationSchema: - username: z.string().min(1).optional() — empty username currently passes; AbstractUIServer falls back to '' and authenticates against the empty configured value, silently bypassing Basic-Auth. - password: z.string().min(1).optional() — same hole on password. - username .refine(no ':') (RFC 7617) — lifts the runtime check at UIServerFactory.ts:48-54 into the schema layer. - object-level .refine: enabled === true requires both username and password. Closes the silent-bypass when authentication is enabled with no creds. UIServerAccessPolicySchema: - object-level .refine: allowLoopbackProxy === true requires trustedProxies.length >= 1. With allowLoopbackProxy: true and an empty trustedProxies list, the proxy-trust check at runtime always evaluates against the empty allowlist, contradicting the operator's intent. No wiring change: Configuration.ts:160 (boot, process.exit(1)) and Configuration.ts:386-431 (hot-reload, rollback) already route ConfigurationValidationError correctly. Schema tightening lands at parse time without rewiring. Test fixture update: tests/utils/ConfigurationSchema.test.ts unknown-key test for uiServer.authentication now includes valid username/password alongside bogusAuthKey so the unknown-key intent stays unambiguous after the new object-level superRefine. 9 new test cases (5 reject + 3 accept regression-anchors + 1 cross-field reject) covering rejection paths and the docker/config.json-shape acceptance. Designs that did NOT survive cross-validation are documented as out-of-scope follow-ups: type×version coupling (coupled to in-place mutation bug at UIServerFactory.ts:69), type×auth coupling (defense in depth at runtime is intentional), options.{path,readableAll,writableAll, ipv6Only} refinements (no shipped config exercises these), and the TLS-non-loopback wildcard refine (would break docker/config.json:18). * fix(config): refine auth schema error path and tighten test path checks Address review feedback on #1903: src/utils/ConfigurationSchema.ts - UIServerAuthenticationSchema object-level .refine now carries path: ['username'], producing an error path of 'uiServer.authentication.username' rather than 'uiServer.authentication'. Mirrors the path: ['allowLoopbackProxy'] convention already used on UIServerAccessPolicySchema and yields a more actionable message. - JSDoc clarifies that the field-level constraints (min(1), no ':') apply unconditionally even when authentication.enabled is false: the schema is intentionally stricter than the runtime guard in UIServerFactory so a credentials value cannot ship under enabled: false and become a bypass the moment enabled flips on (e.g. via hot-reload). tests/utils/ConfigurationSchema.test.ts - Three .includes('uiServer.authentication') substring checks tightened to .startsWith('uiServer.authentication') so they cannot match a hypothetical sibling key like 'uiServer.authenticationFoo'. Affects the two object-level coupling tests and the unknown-key fixture assertion. Exact-element checks at lines 630/651 (specific leaf paths) and the leaf-specific .includes at line 671 are left as-is. No behavior change. 114/114 schema tests pass, typecheck + lint clean. * docs(config): tighten UIServerAuthenticationSchema JSDoc Rewrite the JSDoc as a single factual paragraph matching the file convention (LogConfigurationSchema, WorkerConfigurationSchema, UIServerListenOptionsObjectSchema, ...) — 12 lines collapsed to 7, no redundant phrasing, structured as: constraint definitions → required-when-enabled coupling → unconditional-field-level rationale. Per AGENTS.md 'Documentation conventions' (concision, structure). * fix(config): emit per-field error paths on auth-required refine Address sub-agent review feedback on #1903. src/utils/ConfigurationSchema.ts - Replace the .refine() with a fixed path: ['username'] by a .superRefine() that emits one issue per actually-missing field with the correct path. Configurations supplying only 'username' now surface the issue at 'uiServer.authentication.password' rather than 'uiServer.authentication.username', and vice versa. Configurations missing both produce two issues, one per field. tests/utils/ConfigurationSchema.test.ts - 'should reject authentication enabled without username and password' now asserts both 'uiServer.authentication.username' and 'uiServer.authentication.password' paths are present, locking the per-field issue contract. - 'should reject authentication enabled with username but no password' now asserts 'uiServer.authentication.password' specifically — would catch the prior path-misanchoring regression. - The 'should reject unknown key in uiServer.authentication section' regression-anchor now asserts i.code === 'unrecognized_keys' at the 'uiServer.authentication' path, locking the unknown-key intent so a hypothetical future refine cannot satisfy the assertion by accident. 114/114 schema tests pass, typecheck + lint clean. No production- runtime behavior change beyond per-field error paths. * fix(ui-common): align authenticationConfigSchema with simulator auth schema Apply the same defense-in-depth + per-field-error-path pattern shipped on the simulator-side UIServerAuthenticationSchema in this PR. The Web UI client schema (consumed by ui/web/src/main.ts and transitively by ui/cli/src/config/loader.ts) carried the same set of defects: - password lacked min(1) at the field level - username regex /^[^:]*$/ accepted the empty string - a single .refine combined type-check + presence + length, producing a generic error at the auth object root with no path - empty creds shipped under enabled: false would become a Basic-Auth bypass the moment enabled is flipped on ui/common/src/config/schema.ts - password: z.string().min(1).optional() - username: z.string().min(1).refine(no ':' RFC 7617).optional() (replaces the regex which silently accepted '') - .refine(...) replaced by .superRefine(...) emitting one issue per actually-missing field with the correct path, only when enabled === true && type === PROTOCOL_BASIC_AUTH (existing type-check short-circuit preserved as future-proofing). - JSDoc mirrors the simulator-side sibling, documenting the intentional stricter-than-runtime semantics. ui/common/tests/config.test.ts - 4 new tests: empty password rejected (path 'authentication.password'), username with ':' rejected (RFC 7617 message at 'authentication.username'), password-only and username-only enabled configs each rejected at the missing field's path. - 2 existing tests tightened: 'missing credentials' now asserts both username and password paths; 'empty username' now asserts the 'authentication.username' path. - 6 redundant 'if (result.success) return' narrowing guards removed — assert.strictEqual already narrows the result type. 118/118 ui-common tests pass, typecheck + lint clean. No production behavior change for the only valid-config consumer ('admin'/'admin' shape regression-anchored). * fix(config): point accessPolicy refine error path at the actionable field Address review feedback on #1903. The .refine() rejecting 'allowLoopbackProxy: true' with empty 'trustedProxies' attached its issue at path ['allowLoopbackProxy'] — the trigger of the rejection, but not the field the operator must edit. Move the path to ['trustedProxies'] so structured log scrapers and IDE jump-to-field tooling steer the operator to the field that needs populating. The message wording (which already names both fields) is unchanged. Test 'should reject allowLoopbackProxy=true with empty trustedProxies' tightened from a permissive substring check ('allowLoopbackProxy or trustedProxies') to an exact-path check on 'uiServer.accessPolicy.trustedProxies' so the path contract is locked. A second review suggestion (gate the auth credentials-required superRefine on type === PROTOCOL_BASIC_AUTH) was investigated and declined: the server-side AuthenticationType enum has BASIC_AUTH AND PROTOCOL_BASIC_AUTH (unlike the Web UI client's single-member enum), both runtime paths require username/password (AbstractUIServer.ts:358-381), and adding the type-gate would re-open the silent Basic-Auth bypass on the legacy 'basic-auth' path that this PR is closing on the modern path. 114/114 schema tests pass, typecheck + lint clean. * docs(config): refine auth-schema JSDoc rationale and tighten RFC 7617 path check Address sub-agent review feedback on #1903. src/utils/ConfigurationSchema.ts + ui/common/src/config/schema.ts - Drop the 'across hot-reload toggles of enabled' phrasing in the UIServerAuthenticationSchema and authenticationConfigSchema JSDoc. Hot-reload of uiServer.* is documented as a no-op in the PR body (R4: Bootstrap.ts:103,161 instantiates the UI server once), so the unconditional field-level constraints are an early-detection signal rather than a hot-reload mitigation. The accurate rationale is that empty placeholders cannot ship under enabled: false and become a Basic-Auth bypass on the next boot with enabled: true. - The asymmetry between the two superRefines (server gates only on enabled; Web UI also gates on type === PROTOCOL_BASIC_AUTH) is preserved and intentional — server-side AuthenticationType has legacy BASIC_AUTH which is also credential-required at runtime (AbstractUIServer.ts isBasicAuthEnabled / isValidBasicAuth). The rationale is captured in this commit body and the prior 86a6d4a commit body for git blame discoverability. tests/utils/ConfigurationSchema.test.ts - RFC 7617 username-rejection test now matches the issue path with i.path.join('.') === 'uiServer.authentication.username' (exact) instead of String.prototype.includes (substring), aligning with every other test in the file and with the ui-common sibling. 114/114 schema tests + 118/118 ui-common tests pass, typecheck + lint clean. No behavior change.
PR Checklist
Does this PR introduce a breaking change?
Summary
Add syntactic validation for the simulator configuration file (
src/assets/config.json), mirroring the existing charging-station template validation pattern. Replaces the hand-maintainedConfigurationDatainterface withz.infer<typeof ConfigurationSchema>(single source of truth = the Zod schema).Motivation
The simulator configuration loader had zero schema validation: ~25 deprecated top-level keys silently accepted, no enum constraints, no cross-field rules, no informative errors when the file was malformed. Invalid configurations caused undefined behaviour downstream rather than a clear boot-time error.
The charging-station template validator (
TemplateValidation.ts/TemplateSchema.ts/TemplateMigrations.ts) is the canonical pattern in this repo. This PR mirrors it for the simulator configuration.What changed
New modules (
src/charging-station/)ConfigurationSchema.ts— Zod v4 schema,z.object().strict()at every level,$schemaVersion: z.literal(1)literal, all ~25 deprecated keys declared as.optional().describe('@deprecated: ...'). Sub-schemas:LogConfigurationSchema,WorkerConfigurationSchema,StorageConfigurationSchema,UIServerConfigurationSchema,UIServerAuthenticationSchema,StationTemplateUrlSchema. External types (ResourceLimits,ListenOptions) bridged viaz.custom<T>().ConfigurationMigrations.ts—CURRENT_CONFIGURATION_SCHEMA_VERSION = 1,coerceConfigurationVersion(),applyConfigurationMigration(),migrateV0ToV1(pure remap of all deprecated keys to canonical destinations, including dotted paths likelogEnabled→log.enabled).ConfigurationValidation.ts—validateConfiguration()pipeline (guard → structuredClone → coerceVersion → applyMigration → safeParse → transform),transformConfiguration()emitslogger.warnfor each deprecated key still present,ConfigurationValidationError extends BaseErrorwith structuredfieldErrors: { message, path }[],filePath,migratedFrom?.Integration (
src/utils/Configuration.ts)getConfigurationData()callsvalidateConfiguration()afterJSON.parse. On failure at boot, the configuration validation error is printed viaconsole.error(chalk.red(...))and the process exits with code1.fs.watchcallback now does snapshot-then-restore: capturesconfigurationDataandconfigurationSectionCachebefore clearing, restores on validation failure (the simulator continues with the previous valid configuration).configurationFileReloadingis reset in afinallyblock on both paths.checkWorkerProcessTypeandcheckWorkerElementsPerWorkercall sites — the schema now enforces these constraints.Atomic type migration
src/types/ConfigurationData.ts: replaced contents withexport type ConfigurationData = z.infer<typeof ConfigurationSchema>(plus sub-section type aliases derived from the schema). The hand-maintained interface no longer exists.Bootstrap.ts,SimulatorState.ts,types/index.ts,tests/utils/Configuration.test.ts).Removals
src/utils/ConfigurationMigration.tsdeleted (deprecated-key remap is now owned byConfigurationMigrations.tsv0→v1 step).checkWorkerProcessTyperemoved fromsrc/worker/WorkerUtils.tsandsrc/worker/index.ts.checkWorkerElementsPerWorkerremoved fromsrc/utils/ConfigurationUtils.ts.tests/worker/WorkerUtils.test.tsandtests/utils/ConfigurationUtils.test.ts.Configuration template
src/assets/config-template.json:"$schemaVersion": 1added as first key.Tests
tests/charging-station/ConfigurationSchema.test.tstests/charging-station/ConfigurationMigrations.test.tstests/charging-station/ConfigurationValidation.test.tstests/charging-station/ConfigurationValidation-perf.test.tstests/utils/Configuration-hot-reload.test.tsRound-trip tests verify that:
src/assets/config-template.jsonparses successfully through the schema.Configuration.ts(used whendist/assets/config.jsonis absent) is also schema-valid..optional()) and emit onelogger.warneach.Full suite: 2569 pass / 0 fail / 6 skipped.
Quality gates
pnpm typecheck✅pnpm lint✅ (0 errors)pnpm test✅pnpm build✅Documentation
README.mdconfiguration table updated with$schemaVersionrow.Backward compatibility
$schemaVersionare auto-migrated from v0: deprecated keys are remapped (logEnabled→log.enabled,supervisionURLs→supervisionUrls, etc.), then validated against the v1 schema. Conflict resolution favours the canonical key.docker/config.jsonand similar deployment configs are auto-migrated through the same path.Design notes
zod ^4.4.3); Ajv is reserved for OCPP wire-protocol message validation. This PR follows that separation.z.looseObject()for vendor extensions),ConfigurationSchemausesz.object().strict()everywhere.z.infer<typeof ConfigurationSchema>eliminates the drift risk between a hand-maintained interface and the runtime schema.migrateV{N}ToV{N+1}function and bumpCURRENT_CONFIGURATION_SCHEMA_VERSION.🤖 Implemented with assistance from AI coding agents per SAP guideline for AI-generated code contributions.