Skip to content

feat(config): add Zod-based simulator configuration syntax validation - #1874

Merged
jerome-benoit merged 11 commits into
mainfrom
feat/simulator-config-validation
May 27, 2026
Merged

jerome-benoit merged 11 commits into
mainfrom
feat/simulator-config-validation

Conversation

@jerome-benoit

Copy link
Copy Markdown
Contributor

PR Checklist

  • Please add a description of your changes.
  • Please ensure title follows conventional commits.
  • We need your changes to come with unit tests in order to keep this project in quality and easy to maintain.
  • If your changes contain any new feature please be sure to document it.
  • Please add a link to the open issue or task that this pull request will resolve.

Does this PR introduce a breaking change?

  • Yes
  • No

Boot-time behaviour change is treated as an internal feature evolution: the simulator now exits with a structured error when the configuration is invalid, instead of silently falling back to defaults. Configurations that were valid before remain valid; configurations that were invalid (and previously caused undefined behaviour) now fail fast at boot. No semver-major bump.


Summary

Add syntactic validation for the simulator configuration file (src/assets/config.json), mirroring the existing charging-station template validation pattern. Replaces the hand-maintained ConfigurationData interface with z.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 via z.custom<T>().
  • ConfigurationMigrations.ts — CURRENT_CONFIGURATION_SCHEMA_VERSION = 1, coerceConfigurationVersion(), applyConfigurationMigration(), migrateV0ToV1 (pure remap of all deprecated keys to canonical destinations, including dotted paths like logEnabled → log.enabled).
  • ConfigurationValidation.ts — validateConfiguration() pipeline (guard → structuredClone → coerceVersion → applyMigration → safeParse → transform), transformConfiguration() emits logger.warn for each deprecated key still present, ConfigurationValidationError extends BaseError with structured fieldErrors: { message, path }[], filePath, migratedFrom?.

Integration (src/utils/Configuration.ts)

  • getConfigurationData() calls validateConfiguration() after JSON.parse. On failure at boot, the configuration validation error is printed via console.error(chalk.red(...)) and the process exits with code 1.
  • Hot-reload fs.watch callback now does snapshot-then-restore: captures configurationData and configurationSectionCache before clearing, restores on validation failure (the simulator continues with the previous valid configuration). configurationFileReloading is reset in a finally block on both paths.
  • Removed checkWorkerProcessType and checkWorkerElementsPerWorker call sites — the schema now enforces these constraints.

Atomic type migration

  • src/types/ConfigurationData.ts: replaced contents with export type ConfigurationData = z.infer<typeof ConfigurationSchema> (plus sub-section type aliases derived from the schema). The hand-maintained interface no longer exists.
  • All consumers updated (Bootstrap.ts, SimulatorState.ts, types/index.ts, tests/utils/Configuration.test.ts).

Removals

  • src/utils/ConfigurationMigration.ts deleted (deprecated-key remap is now owned by ConfigurationMigrations.ts v0→v1 step).
  • checkWorkerProcessType removed from src/worker/WorkerUtils.ts and src/worker/index.ts.
  • checkWorkerElementsPerWorker removed from src/utils/ConfigurationUtils.ts.
  • Their corresponding direct test cases in tests/worker/WorkerUtils.test.ts and tests/utils/ConfigurationUtils.test.ts.

Configuration template

  • src/assets/config-template.json: "$schemaVersion": 1 added as first key.

Tests

File Tests
tests/charging-station/ConfigurationSchema.test.ts 63
tests/charging-station/ConfigurationMigrations.test.ts 44
tests/charging-station/ConfigurationValidation.test.ts 39 + 1 inline error-message snapshot
tests/charging-station/ConfigurationValidation-perf.test.ts 1 (asserts p99 < 50 ms over 100 iterations)
tests/utils/Configuration-hot-reload.test.ts 3 (valid reload, invalid reload + rollback, flag reset on both paths)

Round-trip tests verify that:

  • src/assets/config-template.json parses successfully through the schema.
  • The hardcoded fallback object in Configuration.ts (used when dist/assets/config.json is absent) is also schema-valid.
  • All 25 deprecated top-level keys are accepted (.optional()) and emit one logger.warn each.

Full suite: 2569 pass / 0 fail / 6 skipped.

Quality gates

  • pnpm typecheck ✅
  • pnpm lint ✅ (0 errors)
  • pnpm test ✅
  • pnpm build ✅

Documentation

README.md configuration table updated with $schemaVersion row.

Backward compatibility

  • Existing configurations without $schemaVersion are 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.
  • All ~25 known deprecated top-level keys remain accepted (with a deprecation warning); user configurations in the wild keep working.
  • docker/config.json and similar deployment configs are auto-migrated through the same path.

Design notes

  • Zod over Ajv: the charging-station template validator already uses Zod v4 (zod ^4.4.3); Ajv is reserved for OCPP wire-protocol message validation. This PR follows that separation.
  • Strict at every level: simulator configuration is internal — typos must fail loudly. Unlike the template schema (which uses z.looseObject() for vendor extensions), ConfigurationSchema uses z.object().strict() everywhere.
  • Single source of truth for the type: z.infer<typeof ConfigurationSchema> eliminates the drift risk between a hand-maintained interface and the runtime schema.
  • Migration chain is extensible: future schema breaking changes add one migrateV{N}ToV{N+1} function and bump CURRENT_CONFIGURATION_SCHEMA_VERSION.

🤖 Implemented with assistance from AI coding agents per SAP guideline for AI-generated code contributions.

…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
Copilot AI review requested due to automatic review settings May 26, 2026 23:47
@hyperspace-pr-bot

Copy link
Copy Markdown
Contributor

Summary

The following content is AI-generated and provides a summary of the pull request:


feat(config): Add Zod-Based Simulator Configuration Schema Validation

New Feature

✨ Introduces boot-time validation for the simulator configuration file (src/assets/config.json) using Zod v4. Invalid configurations now cause a structured error and process exit at boot instead of silently falling back to defaults. Hot-reloads of an invalid config gracefully roll back to the last valid state. This mirrors the existing charging-station template validation pattern and replaces the hand-maintained ConfigurationData interface with a single-source-of-truth Zod schema.

Changes

  • src/charging-station/ConfigurationSchema.ts (new): Zod v4 strict schema for the simulator configuration, including sub-schemas for log, worker, storage, UI server, authentication, and station template URLs. All ~25 deprecated top-level keys are declared as .optional() with @deprecated markers.
  • src/charging-station/ConfigurationMigrations.ts (new): Migration chain (CURRENT_CONFIGURATION_SCHEMA_VERSION = 1), coerceConfigurationVersion(), applyConfigurationMigration(), and a migrateV0ToV1 step that remaps all deprecated keys (e.g. logEnabled → log.enabled) to canonical destinations.
  • src/charging-station/ConfigurationValidation.ts (new): validateConfiguration() pipeline (guard → clone → coerce version → migrate → safeParse → transform), transformConfiguration() that emits logger.warn per deprecated key, and ConfigurationValidationError extends BaseError with structured fieldErrors.
  • src/utils/Configuration.ts: Integrates validateConfiguration() after JSON.parse. Boot failure prints a red error and exits with code 1. Hot-reload now uses snapshot-then-restore semantics, resetting the configurationFileReloading flag in finally. Removed calls to checkWorkerProcessType and checkWorkerElementsPerWorker (now enforced by the schema).
  • src/types/ConfigurationData.ts: Replaced the hand-maintained interface with export type ConfigurationData = z.infer<typeof ConfigurationSchema> and derived sub-type aliases. Eliminates drift risk between the interface and the runtime schema.
  • src/utils/ConfigurationMigration.ts (deleted): Deprecated-key remap logic moved to ConfigurationMigrations.ts.
  • src/utils/ConfigurationUtils.ts: Removed checkWorkerElementsPerWorker (superseded by schema validation).
  • src/worker/WorkerUtils.ts / src/worker/index.ts: Removed checkWorkerProcessType (superseded by schema z.enum).
  • src/assets/config-template.json: Added "$schemaVersion": 1 as the first key.
  • README.md: Added $schemaVersion row to the configuration table.
  • tests/charging-station/ConfigurationSchema.test.ts (new): 63 tests covering required fields, deprecated key acceptance, sub-section schemas, enum constraints, and round-trip validation of config-template.json.
  • tests/charging-station/ConfigurationMigrations.test.ts (new): 44 tests for version coercion and v0→v1 migration, including immutability and conflict-resolution checks.
  • tests/charging-station/ConfigurationValidation.test.ts (new): 39 tests + 1 error-message snapshot for the full validation pipeline, error shape, and deprecation warnings.
  • tests/charging-station/ConfigurationValidation-perf.test.ts (new): 1 performance test asserting p99 < 50 ms over 100 iterations on config-template.json.
  • tests/utils/Configuration-hot-reload.test.ts (new): 3 tests covering valid reload, invalid reload with rollback, and configurationFileReloading flag reset on both paths.
  • tests/utils/ConfigurationUtils.test.ts / tests/worker/WorkerUtils.test.ts: Removed test cases for the deleted checkWorkerElementsPerWorker and checkWorkerProcessType helpers.

  • 🔄 Regenerate and Update Summary
  • ✏️ Insert as PR Description (deletes this comment)
  • 🗑️ Delete comment
PR Bot Information

Version: 1.21.0

  • Output Template: Default Template
  • Summary Prompt: Default Prompt
  • LLM: anthropic--claude-4.6-sonnet
  • Event Trigger: pull_request.opened
  • File Content Strategy: Full file content
  • Correlation ID: 7263b2ab-6d9b-4e3d-8284-9804fb64185e

@hyperspace-pr-bot hyperspace-pr-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Double $schemaVersion stamping (ConfigurationMigrations.ts line 94): Both migrateV0ToV1 and the applyConfigurationMigration loop write $schemaVersion, creating a redundant and potentially misleading dual-write when more migration steps are added.

  2. Silent data loss for autoReconnectMaxRetries (ConfigurationMigrations.ts line 13): The self-mapping autoReconnectMaxRetries → autoReconnectMaxRetries causes the key to be deleted during v0→v1 migration (the legacy !== canonical guard skips the copy, but the delete still runs), while the schema continues to accept it and buildWorkerSection still reads it. This is contradictory.

  3. moduleName needlessly exported (ConfigurationValidation.ts line 15): moduleName is only used as an internal error-prefix within this module; exporting it leaks an implementation detail.

  4. Stale supervisionURLs remapping in getSupervisionUrls: Configuration.getSupervisionUrls() still manually copies supervisionURLs → supervisionUrls on 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.

  5. Off-by-one p99 index (ConfigurationValidation-perf.test.ts line 43): timings[98] over 100 sorted samples is the 98th percentile, not p99. The true p99 over 100 samples is timings[99] (the maximum).

PR Bot Information

Version: 1.21.0

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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), and ConfigurationValidation (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.

Comment thread src/types/ConfigurationData.ts Resolved
Comment thread src/utils/Configuration.ts Resolved
- 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.
Copilot AI review requested due to automatic review settings May 27, 2026 19:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated 3 comments.

…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.
Copilot AI review requested due to automatic review settings May 27, 2026 20:24

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated 2 comments.

Comment on lines +165 to 170
process.exit(1)
}
throw validationError
}
Configuration.configurationFileWatcher ??= Configuration.getConfigurationFileWatcher()
} catch (error) {
@jerome-benoit
jerome-benoit force-pushed the feat/simulator-config-validation branch from b287f4a to ea16afa Compare May 27, 2026 20:33
…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.
Copilot AI review requested due to automatic review settings May 27, 2026 20:44

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated 1 comment.

- 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.
Copilot AI review requested due to automatic review settings May 27, 2026 21:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 21 out of 21 changed files in this pull request and generated no new comments.

@jerome-benoit
jerome-benoit merged commit c1c8233 into main May 27, 2026
43 checks passed
This was referenced May 27, 2026
jerome-benoit added a commit that referenced this pull request Jun 15, 2026
…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.
jerome-benoit added a commit that referenced this pull request Jun 15, 2026
…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.
@jerome-benoit
jerome-benoit deleted the feat/simulator-config-validation branch June 15, 2026 19:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants