Modular logistics and supply chain operating system (LSOS)
JavaScript driver-appfleet-managementfreight-managementinfrastructureinventory-managementlast-mile-deliverylogisticsondemandopen-sourceorder-managementroute-optimizationsupply-chain-managementtracking-and-monitoringtransport-management-systemtransportationwarehouse-management
release/v0.7.70 (#721)
Ronffb34b02a5a2
diff --git a/RELEASE.md b/RELEASE.mdindex 5cd726a5..c74f2af5 100644--- a/RELEASE.md+++ b/RELEASE.md@@ -1,24 +1,20 @@-> v0.7.69 ~ "SMS guard, authenticated realtime channels, database backups, private media buckets, tracking page settings and verified storefront reviews"+> v0.7.70 ~ "Manage realtime socket authentication from the console"---## Highlights-Fleetbase `0.7.69` ships Core API `1.6.70`, FleetOps `0.6.72`, Storefront `0.4.25`, Ledger `0.0.13`, Customer Portal `0.0.16`, Dev Engine `0.2.18`, Ember UI `0.4.6`, Ember Core `0.3.26` and FleetOps Data `0.2.3`.-- **SMS send guard.** Every text the platform sends passes a guard before a provider is called: destination validation, per-organization and per-number budgets, a circuit breaker, blocked countries and prefixes, and a send ledger. A new Admin → API Traffic → **SMS Guard** page configures it at runtime. The guard is **on in `enforce` mode by default**; switch to `monitor` for the first days after upgrading.-- **Fleetbase socket server and authenticated realtime channels.** The stock SocketCluster image is replaced by `fleetbase/fleetbase-socket`, which can authenticate channels with short-lived tokens, and the API publishes through a signed internal endpoint. The console, FleetOps and Storefront fetch tokens when the server offers them. **Socket auth is off by default** and stays off until `SOCKETCLUSTER_AUTH_ENABLED=true`, so every existing socket client keeps working.-- **Database backups that fail loudly.** Admin → Database Backups with status, schedule, retention and recent runs. Failed backups email the configured addresses, and the image now includes `mysqldump`.-- **Private media buckets.** Stored file links are signed on read, so the S3 media bucket can be fully private. FleetOps signatures and Storefront review photos upload without a public ACL.-- **FleetOps:** tracking page settings per organization, a safer public order lookup, structured label codes, status-guarded order edits with `order.changed` events, and a long list of order, geofence and orchestrator fixes.-- **Storefront:** verified-purchase reviews, order chat with the driver, richer public promotions, a console UX overhaul and hardened customer verification.-- **API cache invalidation.** Writes invalidate every cached list, record and relationship that embeds the written table, across Core, FleetOps, Storefront and Ledger.-- **Security fixes** in Core (requested relations, notifiables, company-scoped deletes), Storefront (network console actions) and Customer Portal (organization settings).+- **Socket settings in the admin console.** Configure → Socket now shows the socket server's status and recent authorization denials. It lets system administrators turn socket authentication on and choose the mode (`off`, `log`, `enforce`) without restarting anything. The shared auth key stays in the environment and is never shown.++- **The socket server applies settings at runtime.** With `SOCKETCLUSTER_AUTH_KEY` set, `fleetbase/fleetbase-socket` polls the API's signed `GET int/v1/socket/config` (every `SOCKETCLUSTER_CONFIG_POLL_SECONDS`, default 30) and applies the switch, mode and origins without a restart. Entering `enforce` disconnects every client once so their subscriptions are re-authorized. `/stats` reports the effective config and the top channel-authorization denials, which the console shows. Helm gains `socketcluster.configUrl` and `configPollSeconds`; docker-compose needs nothing new. (#722, core-api #314)+- **Fix: the socket test console escapes event content** instead of rendering it as HTML. (#722)---## Component Versions-- `console`: `0.7.69`-- `core-api`: `1.6.70`-- `fleetops`: `0.6.72`-- `storefront`: `0.4.25`+- `console`: `0.7.70`+- `core-api`: `1.6.71`+- `fleetops`: `0.6.73`+- `storefront`: `0.4.27`+- `registry-bridge`: `0.1.11`- `ledger`: `0.0.13`- `customer-portal`: `0.0.16`- `dev-engine`: `0.2.18`@@ -26,131 +22,37 @@ Fleetbase `0.7.69` ships Core API `1.6.70`, FleetOps `0.6.72`, Storefront `0.4.2- `ember-core`: `0.3.26`- `fleetops-data`: `0.2.3`- `iam-engine`: `0.1.13`-- `registry-bridge`: `0.1.10`------## Fleetbase (console, images, installer)-### SMS Guard admin page (#714, #715, #716)-- **Admin → API Traffic → SMS Guard**: enable the guard and switch between `enforce` and `monitor` at runtime; budgets per organization, per destination number, new-organization probation and the platform as a whole; circuit-breaker thresholds, blocked countries and prefixes, alert emails; per-organization exceptions; pauses (what the breaker or an administrator paused, pause now, lift); and 24-hour usage per organization from the send ledger. Everything applies within a minute, no deployment.--### Socket server and channel authentication (#704, #710)-- **`fleetbase/fleetbase-socket`** replaces `socketcluster/socketcluster` in compose, the installer, Helm and the image build (amd64 and arm64).-- **Channel authentication** with `off`, `log` and `enforce` modes. With it on, clients present a token, the socket server asks the API whether that token may follow a channel, and the API publishes through a signed internal endpoint on port 8001.-- **Off until switched on:** auth needs `SOCKETCLUSTER_AUTH_ENABLED=true` on the API and the socket server. The installer generates a key but leaves the switch off and the mode at `log`. Compose, the override example, the installer and the Helm chart carry the new variables (#710).-- **Console socket test** listens on the admin's own `test.{user}` channel and reports refused subscriptions.--### Database backups (#703)-- **Admin → Database Backups:** last success and last run, with a warning when the last run failed or nothing succeeded in 26 hours. Frequency, time and day; disk, bucket and path; databases; retention by days or count; minimum dump size; failure emails; and recent runs with "Run backup now".-- **`mysqldump` in the image.** Before, the backup bucket only ever received empty gzip files.--### Public pages (#711, #712)-- **Public `/~/` pages take a nested path.** `/~/{slug}/{anything}` resolves to the page registered for `{slug}`, which reads the rest of the path itself. FleetOps' tracking page uses `/~/t/{company}/{number}` and `/~/track/{number}`.-- **Fix: public pages scroll again** after the nested route change.--### Build and CI (#701, #702, #717, #718, #719)-- **Build Fleetbase Binaries** passes again on Linux, and the macOS job runs on GitHub-hosted runners (#701). **The static binaries include the `geos` PHP extension** (#702), which FleetOps uses for geometry such as service-area centroids.-- The **API contract** job that FleetOps, Storefront and Ledger run against the published image is deterministic: tracking deletes run before the order delete, the order activity cycle ends itself, Storefront's order and review requests run after a captured order, and socket auth stays off to match production (#717, #718, #719).------## Core API `1.6.70` (`1.6.69` + `1.6.70`)-### Added-- **SMS send guard** (#305, #307): destination validation with libphonenumber (mobile numbers only), per-organization and per-number budgets, new-organization probation, a circuit breaker with learned signals, blocked countries and prefixes, alert emails, and a **send ledger** (`sms_sends`) with every allowed send settled against the provider outcome and every refusal with its reason. Admin API under `int/v1/sms-guard`. `SmsServiceChannel` delivers notification texts through the guard too.-- **Verification code tracing and single-use hashed codes** (#289, #307): `verification_codes` gains tracing columns; `generateSmsVerificationFor(..., ['hashed' => true])` stores an HMAC and returns the plain code once; `check()` counts attempts and reports `valid`, `invalid`, `expired` or `locked`; `consume()` uses a code up.-- **`generateSmsVerificationFor()` takes a `phone` option** (1.6.70): the code is texted to that number instead of the subject's own, which a customer changing their phone number needs.-- **Authenticated realtime channels** (#290): socket tokens, a channel authorizer with per-resource resolvers, and signed HTTP publish. `POST int/v1/socket/token` mints a user token, `POST v1/socket/system-token` serves platform API callers, and `POST int/v1/socket/authorize` is called only by the socket server.-- **Comment visibility and `comment.created`** (#306): comments carry `meta.visibility` (`internal` or `customer`). Public `GET v1/comments` no longer returns internal comments. **Chat participant roles and system messages**: participants expose `role`, messages expose `system` and `meta`.-- **API cache dependencies** (#299, #300, #301): cache keys carry the versions of every table they embed, so a write to a related table invalidates the lists, records and relationships that embed it.-- **Database backups** (#288, #295, #296): settings-driven `db:backup` on a configurable schedule, `DB_BACKUP_*` defaults, admin API under `int/v1/database-backups`.-- **API request logs** (#302): any route that attaches `LogApiRequests` is logged, and an extension can relate the log row to its own ids.--### Changed-- **Private media buckets** (#287): stored file URLs into the configured `s3` bucket are signed on read.-- **Faster lookups** (#291): the country lookup is cached and `files.subject_uuid` is indexed.-- `without[]` uses `makeHidden()`; requested relation names come back as declared; `withCounts()` accepts an array (#303).--### Security-- **Requested relations must be relations** (#303): `with`, `expand`, `with_count` and `count` reached Eloquent unchecked, so a request could run any public method on a model.-- **Only registered notifiables are resolved** from saved notification settings (#304).-- **Deletes are scoped to the company** (#304): the company constraint on `deleteRecord` never matched. Reports are filtered by company.-- **A failed comment publish no longer leaves every model unguarded** in a long-lived Octane worker (#298).-- Order lifecycle events reach `driverAssigned.{driver uuid}` again (#306).--### Removed-- `MysqlS3Backup`, `S3BackupTrimmer` and `config/laravel-mysql-s3-backup.php` (#288). The unrouted legacy Twilio-direct SMS login methods on `AuthController` (#307).------## FleetOps `0.6.72`-### New-- **Tracking Page settings** (#355, #357): Fleet-Ops → Settings → Tracking Page lets each organization configure the customer tracking page: its own page at `/t/{slug}`, whether its numbers can be tracked on the shared page, branding, how customers verify, and what verified customers see. Administrators set the shared page's defaults under Fleet-Ops Config → Tracking Page.-- **Structured label codes** (#356): QR codes carry a tracking URL with the tracking number and the owner's public id; barcodes use Code 128; every scan endpoint still accepts the old codes.-- **Status-guarded order edits and `order.changed` events** (#394, #398): an order's route, items, contact, schedule, notes and amounts can be edited after it is placed, and every edit is broadcast as `order.changed`; `order.driver_unassigned` when a driver is taken off. Only ad hoc orders are offered to drivers.-- **Socket auth** (#358): FleetOps channel resolvers, driver socket tokens and a per-customer tracking channel.-- **Hashed single-use verification codes, no stub users before verification** (#395); **SMS-sending routes throttled per address** (#393); an SMS guard refusal answers with its status (#396).-- **Customer photos on live order and board cards** (#387), a **latest proof-of-delivery photos** dashboard widget (#388), and organisations choose **where the live map opens** (#389).-- **Shared resource descriptors and identity stubs** come from fleetops-data (#379, #380).--### Fixed-- **Safer public order lookup** (#352): `GET int/v1/fleet-ops/lookup` is rate limited per address and returns a minimal resource without notes, meta or internal ids.-- **Signatures on private S3 buckets** (#353): written without an ACL and served through signed URLs; legacy avatar URLs are re-signed.-- Customer credentials email links to `/customer-access/{slug}` (#354). Parcel box images in production builds (#370). The shipped map-marker as the live-map fallback icon (#371).-- Places answer 404 when missing (#373). Radius circles at the requested size (#374). Public ids in facilitator and customer filters (#375). The new order draft survives editing a place (#376).-- **Deleting an order soft-deletes its payload, entities and tracking data with it** (#377). Managed users for test keys go to the sandbox database (#378).-- Telematics retention no longer scans the whole `device_events` table (#381). Zones return geofence trigger and dwell settings (#382).-- Distance is not measured from a driver's placeholder position (#383). A queued dispatch cannot reset a started order (#384). Geofence arrival is marked against the order's current destination (#385). The orchestrator runs the engine selected in settings and reports honest results (#386).-- Cached lists are invalidated when the tables they embed are written (#390). Driver and vehicle observer cleanup, latest-status index, contact address filter (#391). Relation return types declared for the console; resource expansions filtered through core (#392).-- Russian street-field translations align with the customer portal (#397, thanks @spanchenko).----## Storefront `0.4.25`-### New-- **Verified-purchase reviews** (#115): reviews tied to a completed order, an eligibility endpoint, deleting your own review. Public reviews no longer show the reviewer's email or phone.-- **Order chat** with the driver delivering the order (#117): get the chat, page messages, send text and photos, mark read; new messages on `chat.{id}`.-- **Public promotions** include the store, the shareable code and availability (#116). **Product add-on limits** on public payloads (#118).-- **Console UX overhaul** (#137): context switcher, network screens, cards, panels, promotions hub and create order. Drivers, customers, vehicles and places render through the shared identity components (#120).-- **Hardened customer verification** (#144, #145): creation codes are refused for identities that already have an account, numbers are validated, SMS routes are throttled, code guessing locks out, codes are hashed and single-use, and order alerts are guarded.-- Logged storefront requests relate to the store or network whose key made them (#143).-- Order chat needs socket authentication switched on (see Upgrade Steps); until then the chat endpoints answer but no realtime messages are delivered.--### Fixed-- Review photos upload without a public ACL (#112). Network and console store listings are faster (#114).-- A network order's other stores are added as pickup waypoints (#138). Removing a store through `addStores` keeps its other networks (#139).-- Storefront list caches are invalidated when the tables they embed change (#140).-- **Security:** network console actions only act on the session company's networks (#141). Relation return types declared for the console (#142).------## Ledger `0.0.13`-- **Transaction lists stay current** (#33): the cached list declares the tables it embeds, so edits to line items, journal entries, accounts and the transaction's parties invalidate it.-- **Public API requests are logged** (#34, #35): writes to the public wallet API and the customer invoice routes land in the API request logs.--## Customer Portal `0.0.16`-- **Security: portal customers could read and overwrite organization settings** (#22). The admin settings routes now require the permission, and the portal account is scoped to the company.-- Creating the default access slug no longer crashes when the company-name slug is taken (#22).--## Dev Engine `0.2.18`-- The sockets viewer shows `subscribeFail` and `kickOut` with the server's reason, and socket payloads render as escaped text (#51).+## Core API `1.6.71`+- **Socket settings from the console** (#314): `GET`/`POST int/v1/settings/socket` and the signed `GET int/v1/socket/config` the socket server polls. The key stays in the environment.+- **A controller's filter is used for every query it serves** (#315): under Octane the first controller to list a model decided the filter for every other, so a Storefront network's Orders page listed every order in the company.+- **Live and test-mode data no longer share API cache entries** (#312): cache keys carry the database connection.+- **Driver-assigned lifecycle events reach `driver.{public_id}` and `driver.{uuid}`** (#311); `driverAssigned.*` is still published and deprecated.+- Internal Category responses include `parent_uuid` (#316), which Storefront's nested categories build their tree from.-## Ember UI `0.4.6`-- **Skeleton loading components** and loading substates for engines (#189). **Dark resource card tier.** The dashboard **report widget runs the report** instead of showing stored results (#188).-- Fixes: notes on contacts save, the date picker shows its date format, `CoordinatesInput` accepts null, badge and button tones.+## FleetOps `0.6.73`+- **Fix: creating a driver or contact with a test API key returned 500** (#404): only the columns the sandbox tables have are copied.+- **Fix: manifest lookups are scoped to the caller's organization** (#403).+- **Fix: the proof-of-delivery dashboard widget loads** (#407): it requested a path that did not exist.-## Ember Core `0.3.26`-- **The console socket authenticates with short-lived socket tokens** (#97): fetched from `POST int/v1/socket/token`, refreshed before expiry, re-authenticated on sign-in and organization switch. With socket auth off on the server it connects anonymously as before.+## Storefront `0.4.27` (`0.4.26` + `0.4.27`)+- **QPay orders keep the customer's note** (#159): the app saves the note on the checkout before paying (`PUT storefront/v1/checkouts/notes`), and every way an order is created takes it from there when none comes with the capture. Notes are trimmed and capped at 2,000 characters. **The customer's note leads the order panel** in a highlighted box, with line breaks kept and callable phone numbers; staff notes stay in the Notes section. **Opening a network order no longer swaps the list for its loading skeleton.** (#159)+- **Nested categories** up to three levels for products and catalogs, with parent and depth on the public API and product rollup into parent categories (#156). **Catalog categories have icons** (#155). Category icon uploads no longer write the file record into `icon` (#157).+- **QPay orders complete in the published app again** (#158): a status request without `verify` checks with QPay and creates the order straight away.+- **New stores and networks show straight away** in the switcher (#148). **Network orders open at their own URL** and the in-place order panel scrolls (#149). **Settings save after a toggle** (#152). A network's saved gateways and notification channels show after a refresh (#154).+- **A truck's status decides whether it takes orders**; new trucks start inactive (#153). **Truck orders are marked** with `meta.food_truck` (#150).-## FleetOps Data `0.2.3`-- **Shared resource identity descriptors** for driver, vehicle, customer, contact, place, order, vendor and fleet, usable from any extension (#86, #88). The **identity stub builder** moves here (#87). An order's customer loads with its saved places (#85).+## Registry Bridge `0.1.11`+- **Fix: registry endpoints returned 500 in console test mode** (#41): registry data always reads the live connection.+- **Fix: the Purchased extensions page showed blank cards** (#40).---## Upgrade Steps-- **Run migrations.** Core: `database_backups`, the `files.subject_uuid` index, `meta` on chat participants and messages, `sms_sends` and the `verification_codes` tracing columns. Storefront: the `reviews` index and `order_uuid` column.-- **SMS guard is on in `enforce` mode** (`SMS_GUARD_ENABLED`, `SMS_GUARD_MODE`). To watch before refusing, deploy with `SMS_GUARD_MODE=monitor` or switch it in Admin → API Traffic → SMS Guard, review the `sms.would_block` log entries, then switch to `enforce`.-- **Socket auth:** nothing changes until you set `SOCKETCLUSTER_AUTH_ENABLED=true`. Roll it out in this order:- 1. Ship clients that request a socket token and fall back to connecting without one when the token route answers 404 (this console, FleetOps and Storefront already do).- 2. Switch it on for the API (application, queue, scheduler) and the socket server, with `SOCKETCLUSTER_AUTH_MODE=log`.- 3. Check the deny log, then switch to `enforce`.-- **Database backups** replace the old S3 backup settings. Configure them in Admin → Database Backups or with `DB_BACKUP_*`.-- **Private media bucket:** remove any public `s3:GetObject` statement from the bucket policy and turn on Block Public Access.-- **Extensions:** a relation that clients request through `with`, `expand` or counts must declare an Eloquent `Relation` return type or be listed in `$withable`, or it stops loading. Every `dynamic:` notifiable must be registered through `NotificationRegistry::registerNotifiable()`.-- **Public API clients:** `GET v1/comments` no longer returns internal comments, `POST v1/comments` accepts `visibility`, and comment, chat participant and chat message responses gain fields. The public order lookup returns a minimal resource.+- Run `composer update` / pull the images as usual. No migrations in this release.+- Storefront `0.4.27` requires Core API `1.6.71`. The Storefront app sends the checkout note from v0.1.0 on; older apps keep sending it with the capture (Stripe) as before.+- Socket settings: nothing changes until an administrator saves one under Configure → Socket; environment values stay the defaults. Older socket server images keep reading their environment.+- Storefront trucks: a truck is on sale only while its Storefront status is **Active**; check your trucks' status after upgrading.---## Need help?diff --git a/api/composer.json b/api/composer.jsonindex e1327e71..871d8b81 100644--- a/api/composer.json+++ b/api/composer.json@@ -20,12 +20,12 @@"require": {"php": ">=8.0 <8.3","appstract/laravel-opcache": "^4.0",- "fleetbase/core-api": "^1.6.70",+ "fleetbase/core-api": "^1.6.71","fleetbase/ai": "^0.0.5",- "fleetbase/fleetops-api": "^0.6.72",- "fleetbase/registry-bridge": "^0.1.10",+ "fleetbase/fleetops-api": "^0.6.73",+ "fleetbase/registry-bridge": "^0.1.11","fleetbase/customer-portal-api": "^0.0.16",- "fleetbase/storefront-api": "^0.4.25",+ "fleetbase/storefront-api": "^0.4.27","fleetbase/ledger-api": "^0.0.13","fleetbase/valhalla-api": "^0.0.4","fleetbase/vroom-api": "^0.0.4",diff --git a/api/composer.lock b/api/composer.lockindex 7b1fd751..82a1b344 100644--- a/api/composer.lock+++ b/api/composer.lock@@ -4,7 +4,7 @@"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies","This file is @generated automatically"],- "content-hash": "1a7feb03ab908457ae3eea2b68fc5a5e",+ "content-hash": "6aeaca96c954a0e62f378e88711e99fb","packages": [{"name": "appstract/laravel-opcache",@@ -2310,16 +2310,16 @@},{"name": "fleetbase/core-api",- "version": "1.6.70",+ "version": "1.6.71","source": {"type": "git","url": "https://github.com/fleetbase/core-api.git",- "reference": "7ccac1413beb71041133a4ef4f1bb6e54076c964"+ "reference": "5e488132d7f84038f9b6d9944603349dee8a65bb"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/fleetbase/core-api/zipball/7ccac1413beb71041133a4ef4f1bb6e54076c964",- "reference": "7ccac1413beb71041133a4ef4f1bb6e54076c964",+ "url": "https://api.github.com/repos/fleetbase/core-api/zipball/5e488132d7f84038f9b6d9944603349dee8a65bb",+ "reference": "5e488132d7f84038f9b6d9944603349dee8a65bb","shasum": ""},"require": {@@ -2415,9 +2415,9 @@],"support": {"issues": "https://github.com/fleetbase/core-api/issues",- "source": "https://github.com/fleetbase/core-api/tree/v1.6.70"+ "source": "https://github.com/fleetbase/core-api/tree/v1.6.71"},- "time": "2026-10-14T08:47:48+00:00"+ "time": "2026-10-16T08:11:24+00:00"},{"name": "fleetbase/countries",@@ -2555,16 +2555,16 @@},{"name": "fleetbase/fleetops-api",- "version": "0.6.72",+ "version": "0.6.73","source": {"type": "git","url": "https://github.com/fleetbase/fleetops.git",- "reference": "4a4ce41a85cb272e8c431fd8a68422c301ddbb7c"+ "reference": "7887aa5effe54704d75544c6ce72be894e38a52a"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/fleetbase/fleetops/zipball/4a4ce41a85cb272e8c431fd8a68422c301ddbb7c",- "reference": "4a4ce41a85cb272e8c431fd8a68422c301ddbb7c",+ "url": "https://api.github.com/repos/fleetbase/fleetops/zipball/7887aa5effe54704d75544c6ce72be894e38a52a",+ "reference": "7887aa5effe54704d75544c6ce72be894e38a52a","shasum": ""},"require": {@@ -2642,9 +2642,9 @@],"support": {"issues": "https://github.com/fleetbase/fleetops/issues",- "source": "https://github.com/fleetbase/fleetops/tree/v0.6.72"+ "source": "https://github.com/fleetbase/fleetops/tree/v0.6.73"},- "time": "2026-10-14T09:20:39+00:00"+ "time": "2026-10-16T08:12:01+00:00"},{"name": "fleetbase/laravel-mysql-spatial",@@ -2792,16 +2792,16 @@},{"name": "fleetbase/registry-bridge",- "version": "0.1.10",+ "version": "0.1.11","source": {"type": "git","url": "https://github.com/fleetbase/registry-bridge.git",- "reference": "4691c426daf9a7bf8c212140264ceb0edd9c92f4"+ "reference": "7eecac11e0b9a3ab0ece8728b8a2a9706d89dffd"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/fleetbase/registry-bridge/zipball/4691c426daf9a7bf8c212140264ceb0edd9c92f4",- "reference": "4691c426daf9a7bf8c212140264ceb0edd9c92f4",+ "url": "https://api.github.com/repos/fleetbase/registry-bridge/zipball/7eecac11e0b9a3ab0ece8728b8a2a9706d89dffd",+ "reference": "7eecac11e0b9a3ab0ece8728b8a2a9706d89dffd","shasum": ""},"require": {@@ -2814,10 +2814,11 @@},"require-dev": {"friendsofphp/php-cs-fixer": "^3.34.1",+ "laravel/framework": "^10.0","nunomaduro/collision": "^7.0","pestphp/pest": "^2.33.2","phpstan/phpstan": "^1.10.38",- "symfony/var-dumper": "^5.4.29"+ "symfony/var-dumper": "^5.4.29|^6.2"},"type": "library","extra": {@@ -2868,26 +2869,26 @@],"support": {"issues": "https://github.com/fleetbase/registry-bridge/issues",- "source": "https://github.com/fleetbase/registry-bridge/tree/v0.1.10"+ "source": "https://github.com/fleetbase/registry-bridge/tree/v0.1.11"},- "time": "2026-09-28T10:52:37+00:00"+ "time": "2026-10-16T08:11:31+00:00"},{"name": "fleetbase/storefront-api",- "version": "0.4.25",+ "version": "0.4.27","source": {"type": "git","url": "https://github.com/fleetbase/storefront.git",- "reference": "90c89ab5c576d130e2a5c7e7c63bd9b8edfdd740"+ "reference": "dc22cf37f7a31a1574326aa1c9d5d4edc2bea4fc"},"dist": {"type": "zip",- "url": "https://api.github.com/repos/fleetbase/storefront/zipball/90c89ab5c576d130e2a5c7e7c63bd9b8edfdd740",- "reference": "90c89ab5c576d130e2a5c7e7c63bd9b8edfdd740",+ "url": "https://api.github.com/repos/fleetbase/storefront/zipball/dc22cf37f7a31a1574326aa1c9d5d4edc2bea4fc",+ "reference": "dc22cf37f7a31a1574326aa1c9d5d4edc2bea4fc","shasum": ""},"require": {- "fleetbase/core-api": "^1.6.70",+ "fleetbase/core-api": "^1.6.71","fleetbase/fleetops-api": "*","geocoder-php/google-maps-places-provider": "^1.4","laravel-notification-channels/apn": "^5.0",@@ -2952,9 +2953,9 @@],"support": {"issues": "https://github.com/fleetbase/storefront/issues",- "source": "https://github.com/fleetbase/storefront/tree/v0.4.25"+ "source": "https://github.com/fleetbase/storefront/tree/v0.4.27"},- "time": "2026-10-14T09:31:37+00:00"+ "time": "2026-10-16T09:24:16+00:00"},{"name": "fleetbase/twilio",diff --git a/console/app/components/configure/socket.hbs b/console/app/components/configure/socket.hbsindex d7c3dfe8..e1bd1821 100644--- a/console/app/components/configure/socket.hbs+++ b/console/app/components/configure/socket.hbs@@ -1,46 +1,290 @@-<ContentPanel @title="SocketCluster Connection" @open={{true}} @wrapperClass="bordered-classic">- <p class="mb-4">The SocketCluster configuration cannot be changed at this time.</p>- <div id="output" class="font-mono rounded-lg max-h-full px-6 py-4 overflow-y-scroll bg-black shadow-inner dark:shadow-none">- <div class="flex items-center justify-between mb-4">- <div class="block w-1/2 font-mono text-sm font-semibold text-green-300">- Output+<div class="space-y-6" ...attributes>+ {{#if this.settings}}+ <ContentPanel @title="Socket Server Status" @open={{true}} @wrapperClass="bordered-classic">+ <div class="flex items-center justify-between mb-4">+ <div class="flex items-center text-sm font-semibold" data-test-socket-reachable={{if this.status "yes" "no"}}>+ {{#if this.status}}+ <FaIcon @icon="circle-check" class="mr-2 text-green-500" />+ <span class="text-gray-900 dark:text-gray-100">The socket server is reachable from the API</span>+ {{else}}+ <FaIcon @icon="triangle-exclamation" class="mr-2 text-red-500" />+ <span class="text-gray-900 dark:text-gray-100">The socket server is not reachable from the API</span>+ {{/if}}+ </div>+ <Button @size="sm" @icon="arrows-rotate" @text="Refresh" @onClick={{this.refresh}} @isLoading={{this.load.isRunning}} data-test-socket-refresh /></div>- {{#if this.events.length}}- <div class="flex items-center justify-end w-1/2 text-sm text-green-300">- <Spinner @iconClass="green-loader" />- <span class="ml-2 text-sm font-mono">- Awaiting events...- </span>- </div>- {{/if}}- </div>+ {{#unless this.status}}+ <p class="mb-4 text-xs text-gray-600 dark:text-gray-400" data-test-socket-status-error>+ {{or this.statusError "No status was returned."}}+ The internal stats endpoint needs SOCKETCLUSTER_AUTH_KEY on the API and the socket server, and the API must reach the socket server's internal port.+ </p>+ {{/unless}}- <div>- {{#each this.events as |event|}}- <div class="mb-3 text-sm font-mono rounded-lg shadow-sm flex flex-row">- <div class="text-{{event.color}}-300 uppercase text-sm font-mono pr-2 flex-shrink-0">- [{{event.time}}]:+ <div class="grid grid-cols-1 gap-4 text-sm md:grid-cols-2">+ <div data-test-socket-effective-enabled>+ <div class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Socket authentication</div>+ <div class="mt-1 flex items-center space-x-2">+ <span class="font-semibold text-gray-900 dark:text-gray-100">{{if this.settings.enabled "On" "Off"}}</span>+ <Badge @status={{if (eq this.settings.sources.enabled "setting") "info" "default"}} @text={{if (eq this.settings.sources.enabled "setting") "Console setting" "Environment"}} @hideStatusDot={{true}} @disableHumanize={{true}} />+ </div>+ </div>+ <div data-test-socket-effective-mode>+ <div class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Mode</div>+ <div class="mt-1 flex items-center space-x-2">+ <span class="font-semibold text-gray-900 dark:text-gray-100">{{or this.settings.mode "Socket server default (env)"}}</span>+ <Badge @status={{if (eq this.settings.sources.mode "setting") "info" "default"}} @text={{if (eq this.settings.sources.mode "setting") "Console setting" "Environment"}} @hideStatusDot={{true}} @disableHumanize={{true}} />+ </div>+ </div>+ <div data-test-socket-key>+ <div class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Auth key</div>+ <div class="mt-1 font-semibold {{if this.keyConfigured 'text-green-600 dark:text-green-300' 'text-yellow-600 dark:text-yellow-300'}}">+ {{if this.keyConfigured "Configured" "Not configured"}}+ </div>+ </div>+ <div data-test-socket-connections>+ <div class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Connections</div>+ <div class="mt-1 font-semibold text-gray-900 dark:text-gray-100">+ {{#if this.status}}+ {{or this.status.clients 0}}+ {{#if this.status.pending_clients}}<span class="text-xs font-normal text-gray-500">(+{{this.status.pending_clients}} connecting)</span>{{/if}}+ {{else}}+ —+ {{/if}}+ </div>+ </div>+ <div data-test-socket-running>+ <div class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Socket server is running</div>+ <div class="mt-1 font-semibold text-gray-900 dark:text-gray-100">+ {{#if this.serverConfig}}+ {{if this.serverConfig.enabled "On" "Off"}}, {{this.serverConfig.mode}}+ <span class="text-xs font-normal text-gray-500">(from {{if (eq this.serverConfig.source "api") "the API" "its environment"}})</span>+ {{else}}+ —+ {{/if}}</div>- <div class="text-{{event.color}}-300 text-sm font-mono">- {{html-safe event.content}}+ </div>+ <div data-test-socket-last-sync>+ <div class="text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">Last config sync</div>+ <div class="mt-1 font-semibold text-gray-900 dark:text-gray-100">+ {{#if this.serverConfig}}+ {{or this.lastSyncLabel "Never"}}+ {{else if this.status}}+ Not reported by this socket server version+ {{else}}+ —+ {{/if}}</div></div>+ </div>++ {{#if this.serverConfig.last_sync_error}}+ <div+ class="mt-4 flex items-start rounded-md border border-red-400 bg-red-50 px-3 py-2 text-xs text-red-800 dark:border-red-700 dark:bg-red-900 dark:text-red-100"+ data-test-socket-sync-error+ >+ <FaIcon @icon="triangle-exclamation" class="mr-2 mt-0.5" />+ <span>The socket server's last config poll failed ({{this.serverConfig.last_sync_error}}). It keeps running its last good config.</span>+ </div>+ {{/if}}++ {{#if this.isOutOfSync}}+ <div+ class="mt-4 flex items-start rounded-md border border-yellow-400 bg-yellow-50 px-3 py-2 text-xs text-yellow-800 dark:border-yellow-700 dark:bg-yellow-900 dark:text-yellow-100"+ data-test-socket-out-of-sync+ >+ <FaIcon @icon="clock" class="mr-2 mt-0.5" />+ <span>The socket server is not running these settings yet. It polls the API every 30 seconds; refresh to check again.</span>+ </div>+ {{/if}}+ </ContentPanel>++ <ContentPanel @title="Recent Denials" @open={{true}} @wrapperClass="bordered-classic" @panelBodyClass="p-0i" @panelBodyWrapperClass="p-0i">+ <p class="px-4 py-3 text-sm text-gray-600 dark:text-gray-400">+ Subscriptions and client publishes the socket server refused (in enforce mode) or would have refused (in log mode) since it started, grouped by client, channel+ prefix and reason. The 50 most frequent are shown. Tokens and ids are never included.+ </p>+ {{#if this.denials.length}}+ <div class="overflow-x-auto border-t border-gray-200 dark:border-gray-700" data-test-socket-denials>+ <table class="min-w-full text-sm">+ <thead>+ <tr class="text-left text-xs uppercase tracking-wide text-gray-500 dark:text-gray-400">+ <th class="px-4 py-2">Client</th>+ <th class="px-4 py-2">Channel prefix</th>+ <th class="px-4 py-2">Reason</th>+ <th class="px-4 py-2 text-right">Count</th>+ <th class="px-4 py-2">Last</th>+ </tr>+ </thead>+ <tbody>+ {{#each this.denials as |row|}}+ <tr class="border-t border-gray-100 text-gray-800 dark:border-gray-800 dark:text-gray-200" data-test-socket-denial>+ <td class="px-4 py-2 font-mono text-xs">{{or row.client "unknown"}}</td>+ <td class="px-4 py-2 font-mono text-xs">{{or row.prefix "(token)"}}</td>+ <td class="px-4 py-2 font-mono text-xs">{{row.reason}}</td>+ <td class="px-4 py-2 text-right">{{row.count}}</td>+ <td class="px-4 py-2 text-xs">{{row.lastAtLabel}}</td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ </div>{{else}}- <div class="flex items-center mt-6 text-green-300">- <Spinner @iconClass="green-loader" />- <span class="ml-2 text-sm font-mono">- Awaiting events...- </span>+ <p class="border-t border-gray-200 px-4 py-3 text-sm text-gray-500 dark:border-gray-700 dark:text-gray-400" data-test-socket-no-denials>No denials reported.</p>+ {{/if}}+ </ContentPanel>++ <ContentPanel @title="Socket Settings" @open={{true}} @wrapperClass="bordered-classic">+ <div class="mb-4 rounded-md border border-blue-200 bg-blue-50 px-4 py-3 text-sm text-blue-900 dark:border-blue-900 dark:bg-blue-900 dark:text-blue-100" data-test-socket-key-help>+ <p>+ Settings saved here override the environment on the API and the socket server. The socket server picks up a change within about 30 seconds, without a restart.+ Tick "Use environment" to clear a setting and go back to the environment value.+ </p>+ <p class="mt-2">+ The auth key is never stored or shown here: it lives only in SOCKETCLUSTER_AUTH_KEY. To rotate it, set the new key on the API (application, queue and scheduler) and the+ socket server, then restart both.+ </p>+ </div>++ <InputGroup @name="Socket authentication" @helpText="Verify socket tokens and authorize channel subscriptions. Needs SOCKETCLUSTER_AUTH_KEY.">+ <div class="space-y-2">+ <Checkbox @label="Use environment" @value={{this.inherits.enabled}} @onToggle={{fn this.toggleInherit "enabled"}} data-test-socket-inherit="enabled" />+ {{#unless this.inherits.enabled}}+ <Toggle+ @isToggled={{this.enabled}}+ @onToggle={{this.toggleEnabled}}+ @label={{if this.enabled "On" "Off"}}+ @disabled={{or this.isBusy (not this.keyConfigured)}}+ data-test-socket-enabled+ />+ {{#unless this.keyConfigured}}+ <p class="text-xs text-yellow-700 dark:text-yellow-300" data-test-socket-key-missing>+ Set SOCKETCLUSTER_AUTH_KEY on the API and the socket server before switching socket authentication on.+ </p>+ {{/unless}}+ {{/unless}}</div>- {{/each}}- </div>- </div>- {{#if this.testResponse}}- <div class="flex flex-row items-center rounded-lg border {{if (eq this.testResponse.status 'error') 'border-red-900 bg-red-800 text-red-100' 'border-green-900 bg-green-800 text-green-100'}} shadow-sm my-2 px-4 py-2">- <FaIcon @icon={{if (eq this.testResponse.status 'error') 'triangle-exclamation' 'circle-check'}} class="mr-1.5 {{if (eq this.testResponse.status 'error') 'text-red-200' 'text-green-200'}}" />- <span class="text-xs">{{this.this.testResponse.message}}</span>+ </InputGroup>++ <InputGroup @name="Mode" @helpText="What happens to subscriptions the API does not authorize while socket authentication is on.">+ <div class="space-y-2">+ <Checkbox @label="Use environment" @value={{this.inherits.mode}} @onToggle={{fn this.toggleInherit "mode"}} data-test-socket-inherit="mode" />+ {{#unless this.inherits.mode}}+ <Select+ @options={{this.modeOptions}}+ @optionValue="value"+ @optionLabel="label"+ @value={{this.mode}}+ @onSelect={{this.setMode}}+ class="w-full"+ data-test-socket-mode+ />+ {{/unless}}+ </div>+ </InputGroup>++ <InputGroup @name="Token lifetime (seconds)" @helpText="How long a socket token is valid, from 60 to 3600 seconds. Clients refresh tokens before they expire.">+ <div class="space-y-2">+ <Checkbox @label="Use environment" @value={{this.inherits.token_ttl}} @onToggle={{fn this.toggleInherit "token_ttl"}} data-test-socket-inherit="token_ttl" />+ {{#unless this.inherits.token_ttl}}+ <Input @type="number" @value={{this.tokenTtl}} min="60" max="3600" placeholder="900" class="w-full form-input" disabled={{this.isBusy}} data-test-socket-token-ttl />+ {{/unless}}+ </div>+ </InputGroup>++ <InputGroup+ @name="Allowed origins"+ @helpText="SocketCluster origins: host:port patterns separated by spaces, e.g. console.example.com:*. *:* allows every origin. Applies to new connections."+ >+ <div class="space-y-2">+ <Checkbox @label="Use environment" @value={{this.inherits.origins}} @onToggle={{fn this.toggleInherit "origins"}} data-test-socket-inherit="origins" />+ {{#unless this.inherits.origins}}+ <Input @value={{this.origins}} placeholder="console.example.com:*" class="w-full form-input" disabled={{this.isBusy}} data-test-socket-origins />+ {{/unless}}+ </div>+ </InputGroup>++ <InputGroup+ @name="Publisher origin"+ @helpText="The Origin header the API sends when it publishes over the websocket (while socket authentication is off). Must be an allowed origin, e.g. https://console.example.com."+ >+ <div class="space-y-2">+ <Checkbox+ @label="Use environment"+ @value={{this.inherits.publisher_origin}}+ @onToggle={{fn this.toggleInherit "publisher_origin"}}+ data-test-socket-inherit="publisher_origin"+ />+ {{#unless this.inherits.publisher_origin}}+ <Input @value={{this.publisherOrigin}} placeholder="https://console.example.com" class="w-full form-input" disabled={{this.isBusy}} data-test-socket-publisher-origin />+ {{/unless}}+ </div>+ </InputGroup>++ <div class="flex justify-end">+ <Button+ @type="primary"+ @icon="save"+ @text="Save Socket Settings"+ @onClick={{this.save}}+ @disabled={{this.isBusy}}+ @isLoading={{this.saveSettings.isRunning}}+ data-test-socket-save+ />+ </div>+ </ContentPanel>+ {{else}}+ <div class="flex items-center justify-center p-4" data-test-socket-loading>+ <Spinner @loadingMessage="Loading socket settings..." @wrapperClass="flex flex-row" @iconClass="mr-2" /></div>{{/if}}- <Button @wrapperClass="mt-3" @icon="plug" @text="Test Socket Connection" @onClick={{this.testSocketConnection}} @isLoading={{this.isLoading}} />-</ContentPanel>\ No newline at end of file++ <ContentPanel @title="SocketCluster Connection" @open={{true}} @wrapperClass="bordered-classic">+ <div id="output" class="font-mono rounded-lg max-h-full px-6 py-4 overflow-y-scroll bg-black shadow-inner dark:shadow-none">+ <div class="flex items-center justify-between mb-4">+ <div class="block w-1/2 font-mono text-sm font-semibold text-green-300">+ Output+ </div>+ {{#if this.events.length}}+ <div class="flex items-center justify-end w-1/2 text-sm text-green-300">+ <Spinner @iconClass="green-loader" />++ <span class="ml-2 text-sm font-mono">+ Awaiting events...+ </span>+ </div>+ {{/if}}+ </div>++ <div>+ {{#each this.events as |event|}}+ <div class="mb-3 text-sm font-mono rounded-lg shadow-sm flex flex-row" data-test-socket-event>+ <div class="text-{{event.color}}-300 uppercase text-sm font-mono pr-2 flex-shrink-0">+ [{{event.time}}]:+ </div>+ {{! Escaped on purpose: channel data and refusal reasons come from the network. }}+ <div class="text-{{event.color}}-300 text-sm font-mono whitespace-pre-wrap break-all" data-test-socket-event-content>{{event.content}}</div>+ </div>+ {{else}}+ <div class="flex items-center mt-6 text-green-300">+ <Spinner @iconClass="green-loader" />+ <span class="ml-2 text-sm font-mono">+ Awaiting events...+ </span>+ </div>+ {{/each}}+ </div>+ </div>+ {{#if this.testResponse}}+ <div+ class="flex flex-row items-center rounded-lg border+ {{if (eq this.testResponse.status 'error') 'border-red-900 bg-red-800 text-red-100' 'border-green-900 bg-green-800 text-green-100'}}+ shadow-sm my-2 px-4 py-2"+ >+ <FaIcon @icon={{if (eq this.testResponse.status "error") "triangle-exclamation" "circle-check"}} class="mr-1.5 {{if (eq this.testResponse.status 'error') 'text-red-200' 'text-green-200'}}" />+ <span class="text-xs" data-test-socket-test-message>{{this.testResponse.message}}</span>+ </div>+ {{/if}}+ <Button @wrapperClass="mt-3" @icon="plug" @text="Test Socket Connection" @onClick={{this.testSocketConnection}} @isLoading={{this.isLoading}} />+ </ContentPanel>+</div>diff --git a/console/app/components/configure/socket.js b/console/app/components/configure/socket.jsindex f5666b28..9bcd64c1 100644--- a/console/app/components/configure/socket.js+++ b/console/app/components/configure/socket.js@@ -2,8 +2,48 @@ import Component from '@glimmer/component';import { inject as service } from '@ember/service';import { tracked } from '@glimmer/tracking';import { action } from '@ember/object';+import { task } from 'ember-concurrency';import { format } from 'date-fns';+import { formatDateTime } from '../admin/database-backups';+/** The socket auth modes, as the select offers them. */+export const MODES = [+ { value: 'off', label: 'Off: tokens are verified, nothing is denied' },+ { value: 'log', label: 'Log: would-be denials are logged, nothing is denied' },+ { value: 'enforce', label: 'Enforce: unauthorized subscriptions and client publishing are refused' },+];++/** The settings an administrator can override; each falls back to the environment when null. */+export const FIELDS = ['enabled', 'mode', 'token_ttl', 'origins', 'publisher_origin'];++export const ENFORCE_WARNING =+ 'In enforce mode the socket server refuses every subscription the API does not authorize and blocks client publishing. ' ++ 'Clients that do not fetch socket tokens yet stop receiving realtime updates, and every connected socket reconnects once. ' ++ 'Run in log mode first and check the denials below.';++export const KEY_MISSING_MESSAGE = 'Socket authentication cannot be switched on until SOCKETCLUSTER_AUTH_KEY is set on the API and the socket server.';++/** A blank input means "use the environment" (null). */+function blankToNull(value) {+ const text = String(value ?? '').trim();++ return text === '' ? null : text;+}++function nullableInteger(value) {+ const text = blankToNull(value);++ return text === null ? null : Number(text);+}++/**+ * Admin > Configure > Socket.+ *+ * Shows the socket server's live status and recent denials, lets an administrator override the+ * environment's socket settings (null = use the environment), and keeps the test console that+ * publishes to the current user's own test channel. The auth key itself is environment-only and+ * never reaches the console.+ */export default class ConfigureSocketComponent extends Component {/*** Inject the `router` service@@ -29,6 +69,14 @@ export default class ConfigureSocketComponent extends Component {*/@service notifications;+ /**+ * Inject the `modalsManager` service+ *+ * @var {Service}+ * @memberof ConfigureSocketComponent+ */+ @service modalsManager;+/*** Inject the `socket` service*@@ -45,6 +93,29 @@ export default class ConfigureSocketComponent extends Component {*/@service currentUser;+ /**+ * The effective settings, the socket server's /stats (null when it cannot be reached) and+ * why it could not be reached. Assigned by apply().+ *+ * @memberof ConfigureSocketComponent+ */+ @tracked settings;+ @tracked status;+ @tracked statusError;++ /**+ * The form: one value per field, plus whether each field uses the environment instead.+ * Assigned by apply().+ *+ * @memberof ConfigureSocketComponent+ */+ @tracked inherits;+ @tracked enabled;+ @tracked mode;+ @tracked tokenTtl;+ @tracked origins;+ @tracked publisherOrigin;+/*** State of the test request.*@@ -82,6 +153,8 @@ export default class ConfigureSocketComponent extends Component {socketClient = null;channel = null;+ modeOptions = MODES;+/*** Date format to use for socket console events.*@@ -95,9 +168,160 @@ export default class ConfigureSocketComponent extends Component {*/constructor() {super(...arguments);+ this.load.perform();this.listenToTestSocket();}+ get isBusy() {+ return this.load.isRunning || this.saveSettings.isRunning;+ }++ get keyConfigured() {+ return this.settings?.key_configured === true;+ }++ /** The config the socket server reports running, or null (unreachable, or an older server). */+ get serverConfig() {+ return this.status?.config ?? null;+ }++ get lastSyncLabel() {+ return formatDateTime(this.serverConfig?.last_sync_at);+ }++ /**+ * Whether the socket server runs something other than the saved settings, e.g. right+ * after a save (it polls every 30 seconds) or when it cannot reach the API.+ */+ get isOutOfSync() {+ const server = this.serverConfig;+ if (!server || !this.settings) {+ return false;+ }+ if (server.enabled !== this.settings.enabled) {+ return true;+ }++ return Boolean(this.settings.enabled && this.settings.mode && server.mode !== this.settings.mode);+ }++ get denials() {+ return (this.status?.denials ?? []).map((row) => ({ ...row, lastAtLabel: formatDateTime(row.last_at) }));+ }++ @task *load() {+ try {+ const response = yield this.fetch.get('settings/socket');+ this.apply(response);+ } catch (error) {+ this.notifications.serverError(error);+ }+ }++ @task *saveSettings(payload) {+ try {+ // rawError keeps the API's `code` (e.g. key_missing) on the rejection.+ const response = yield this.fetch.post('settings/socket', payload, { rawError: true });+ this.apply(response);+ this.notifications.success('Socket settings saved. The socket server applies them within about 30 seconds.');+ } catch (error) {+ this.saveFailed(error);+ }+ }++ /**+ * Reports a failed save: the API refuses to switch auth on without a key (422 `key_missing`),+ * and Laravel's validation errors carry a message with per-field `errors`.+ */+ saveFailed(error) {+ if (error?.code === 'key_missing') {+ return this.notifications.error(KEY_MISSING_MESSAGE);+ }+ if (error && !Array.isArray(error.errors) && typeof error.message === 'string') {+ return this.notifications.error(error.message);+ }++ return this.notifications.serverError(error);+ }++ apply(response) {+ const settings = response?.settings ?? {};+ const sources = settings.sources ?? {};++ this.settings = settings;+ this.status = response?.status ?? null;+ this.statusError = response?.status_error ?? null;+ this.inherits = Object.fromEntries(FIELDS.map((field) => [field, sources[field] !== 'setting']));+ this.enabled = settings.enabled === true;+ this.mode = settings.mode ?? 'log';+ this.tokenTtl = settings.token_ttl ?? '';+ this.origins = settings.origins ?? '';+ this.publisherOrigin = settings.publisher_origin ?? '';+ }++ /** The POST body: every field, null where it uses the environment. */+ payload() {+ const pick = (field, value) => (this.inherits[field] ? null : value);++ return {+ enabled: pick('enabled', this.enabled),+ mode: pick('mode', this.mode),+ token_ttl: pick('token_ttl', nullableInteger(this.tokenTtl)),+ origins: pick('origins', blankToNull(this.origins)),+ publisher_origin: pick('publisher_origin', blankToNull(this.publisherOrigin)),+ };+ }++ /**+ * Whether saving this payload may start enforcing: enforce chosen while not enforcing yet,+ * or auth switched on with the mode left to the socket server, whose default is enforce.+ */+ entersEnforce(payload) {+ if (payload.enabled === false) {+ return false;+ }+ if (payload.mode === 'enforce') {+ return !(this.settings.enabled && this.settings.mode === 'enforce');+ }++ return payload.mode === null && payload.enabled === true && !this.settings.enabled;+ }++ @action save() {+ const payload = this.payload();+ if (!this.entersEnforce(payload)) {+ return this.saveSettings.perform(payload);+ }++ this.modalsManager.confirm({+ title: 'Enforce socket authentication?',+ body: ENFORCE_WARNING,+ acceptButtonText: 'Save and enforce',+ acceptButtonScheme: 'danger',+ confirm: async (modal) => {+ modal.startLoading();+ await this.saveSettings.perform(payload);+ return modal.done();+ },+ });+ }++ @action refresh() {+ return this.load.perform();+ }++ @action toggleInherit(field, inherit) {+ this.inherits = { ...this.inherits, [field]: inherit };+ }++ @action toggleEnabled(enabled) {+ this.enabled = enabled;+ }++ @action setMode(mode) {+ this.mode = mode;+ }+/*** Send a request to test the socket connection.*@@ -180,7 +404,9 @@ export default class ConfigureSocketComponent extends Component {}/**- * Subscribes to a test channel (closing any previous one) and logs its events.+ * Subscribes to a test channel (closing any previous one) and logs its events. Event+ * content is plain text: the template renders it escaped, since channel data and refusal+ * reasons come from the network.** @param {String} channelName* @memberof ConfigureSocketComponentdiff --git a/console/package.json b/console/package.jsonindex 44c22ae8..5073b54f 100644--- a/console/package.json+++ b/console/package.json@@ -1,6 +1,6 @@{"name": "@fleetbase/console",- "version": "0.7.69",+ "version": "0.7.70","private": true,"description": "Modular logistics and supply chain operating system (LSOS)","repository": "https://github.com/fleetbase/fleetbase",@@ -41,12 +41,12 @@"@fleetbase/ember-core": "^0.3.26","@fleetbase/ember-ui": "^0.4.6","@fleetbase/fleetops-data": "^0.2.3",- "@fleetbase/fleetops-engine": "^0.6.72",+ "@fleetbase/fleetops-engine": "^0.6.73","@fleetbase/iam-engine": "^0.1.13","@fleetbase/leaflet-routing-machine": "^3.2.17","@fleetbase/ledger-engine": "^0.0.13",- "@fleetbase/registry-bridge-engine": "^0.1.10",- "@fleetbase/storefront-engine": "^0.4.25",+ "@fleetbase/registry-bridge-engine": "^0.1.11",+ "@fleetbase/storefront-engine": "^0.4.27","@fleetbase/valhalla-engine": "^0.0.4","@fleetbase/vroom-engine": "^0.0.4","@formatjs/intl-datetimeformat": "^6.18.2",diff --git a/console/pnpm-lock.yaml b/console/pnpm-lock.yamlindex df024e57..adddd83e 100644--- a/console/pnpm-lock.yaml+++ b/console/pnpm-lock.yaml@@ -35,8 +35,8 @@ importers:specifier: ^0.2.3version: 0.2.3(@ember/[email protected])(@ember/[email protected](@babel/[email protected])([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected]))))([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))'@fleetbase/fleetops-engine':- specifier: ^0.6.72- version: 0.6.72(bffd95f1ee8fa5c6dc085f568b2e0221)+ specifier: ^0.6.73+ version: 0.6.73(bffd95f1ee8fa5c6dc085f568b2e0221)'@fleetbase/iam-engine':specifier: ^0.1.13version: 0.1.13(bffd95f1ee8fa5c6dc085f568b2e0221)@@ -47,11 +47,11 @@ importers:specifier: ^0.0.13version: 0.0.13(bffd95f1ee8fa5c6dc085f568b2e0221)'@fleetbase/registry-bridge-engine':- specifier: ^0.1.10- version: 0.1.10(bffd95f1ee8fa5c6dc085f568b2e0221)+ specifier: ^0.1.11+ version: 0.1.11(bffd95f1ee8fa5c6dc085f568b2e0221)'@fleetbase/storefront-engine':- specifier: ^0.4.25- version: 0.4.25(bffd95f1ee8fa5c6dc085f568b2e0221)+ specifier: ^0.4.27+ version: 0.4.27(bffd95f1ee8fa5c6dc085f568b2e0221)'@fleetbase/valhalla-engine':specifier: ^0.0.4version: 0.0.4(bffd95f1ee8fa5c6dc085f568b2e0221)@@ -1586,8 +1586,8 @@ packages:resolution: {integrity: sha512-brLYiGHZCKMDaZcyy2bJHY7SHsOTgNk8+XSpdqgmuoTT466xOg4qTPP56LxZbcp2uHyPiUvgNRb5K843gNtJww==}engines: {node: '>= 18'}- '@fleetbase/[email protected]':- resolution: {integrity: sha512-MOssPvfJf+Yzi5goOnj42OCXRdjOC/ea/aoSydTSrW+BnOmU6Cjxu6iPwZWAbgDVX5xX2gpdfWw9GEWrO+Wtwg==}+ '@fleetbase/[email protected]':+ resolution: {integrity: sha512-OQXahsprDxxfPZZ/feIqzK6ioCh9W5dKM8McYf3bRZMd6spd2YU3b/DsZ97VaoU8OZ8DnrYjNJGbnvUenexBrA==}engines: {node: '>= 18'}peerDependencies:ember-engines: ^0.9.0@@ -1611,14 +1611,14 @@ packages:peerDependencies:ember-engines: ^0.9.0- '@fleetbase/[email protected]':- resolution: {integrity: sha512-um/FqXDoU8XPwyzqPqCl2fY/9PCYtp57Gs+eGgGZdXYUNFblJks3k8sx8irjeqaiL6gHZTxVaRIbEmMRTN+WFA==}+ '@fleetbase/[email protected]':+ resolution: {integrity: sha512-6KgDO4t/ok7wF+AFpBdnOKKY9cjqmdrReUv3+l5+/LQWDE/hjxF5CMcQlXSPCnp2JnsE4Zb+nFR6f7cC9vBGfA==}engines: {node: '>= 18'}peerDependencies:ember-engines: ^0.9.0- '@fleetbase/[email protected]':- resolution: {integrity: sha512-3ucJKS1ZYhq3EijBOiHeI0PUUPCr+4eA3dGMxmNNlrn2FfB8HUxP5S4l/inxzUMecpZmbEunhR81xymmZV846Q==}+ '@fleetbase/[email protected]':+ resolution: {integrity: sha512-HwmHaqAcw50vTkhnow1FJqDG9voP87ACF9wyTBbSlJHmmInCiUEtqpNWrAPIimzkl16DxJ8oDOOHHYOlfEFgcw==}engines: {node: '>= 18'}peerDependencies:ember-engines: ^0.9.0@@ -11256,7 +11256,7 @@ snapshots:- utf-8-validate- webpack- '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':+ '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':dependencies:'@babel/core': 7.29.7'@fleetbase/ember-core': 0.3.26(@ember/[email protected])(@ember/[email protected](@babel/[email protected])([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected]))))([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))@@ -11451,7 +11451,7 @@ snapshots:- webpack-command- yaml- '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':+ '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':dependencies:'@babel/core': 7.29.7'@fleetbase/ember-core': 0.3.26(@ember/[email protected])(@ember/[email protected](@babel/[email protected])([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected]))))([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))@@ -11507,7 +11507,7 @@ snapshots:- webpack-command- yaml- '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':+ '@fleetbase/[email protected](bffd95f1ee8fa5c6dc085f568b2e0221)':dependencies:'@babel/core': 7.29.7'@fleetbase/ember-core': 0.3.26(@ember/[email protected])(@ember/[email protected](@babel/[email protected])([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected]([email protected])))([email protected]([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected]))))([email protected](@babel/[email protected])(@glimmer/[email protected](@babel/[email protected]))([email protected])([email protected]([email protected])))([email protected])([email protected]([email protected]))diff --git a/console/pnpm-workspace.yaml b/console/pnpm-workspace.yamlindex ccec3a55..dde9bf3e 100644--- a/console/pnpm-workspace.yaml+++ b/console/pnpm-workspace.yaml@@ -19,8 +19,9 @@ minimumReleaseAgeExclude:- '@fleetbase/[email protected]'- '@fleetbase/[email protected]'- '@fleetbase/[email protected]'- - '@fleetbase/[email protected]'- - '@fleetbase/[email protected]'+ - '@fleetbase/[email protected]'+ - '@fleetbase/[email protected]'- '@fleetbase/[email protected]'- '@fleetbase/[email protected]'- '@fleetbase/[email protected]'+ - '@fleetbase/[email protected]'diff --git a/console/tests/integration/components/configure/socket-test.js b/console/tests/integration/components/configure/socket-test.jsindex da902b23..6e6fed35 100644--- a/console/tests/integration/components/configure/socket-test.js+++ b/console/tests/integration/components/configure/socket-test.js@@ -1,9 +1,10 @@import { module, test } from 'qunit';import { setupRenderingTest } from '@fleetbase/console/tests/helpers';-import { render } from '@ember/test-helpers';+import { render, click, fillIn, settled } from '@ember/test-helpers';import { hbs } from 'ember-cli-htmlbars';import Service from '@ember/service';-import ConfigureSocketComponent from '@fleetbase/console/components/configure/socket';+import ConfigureSocketComponent, { ENFORCE_WARNING, KEY_MISSING_MESSAGE, MODES, FIELDS } from '@fleetbase/console/components/configure/socket';+import { formatDateTime } from '@fleetbase/console/components/admin/database-backups';import { captureComponent } from '@fleetbase/console/tests/helpers/capture-component';/**@@ -239,6 +240,17 @@ module('Integration | Component | configure/socket', function (hooks) {);});+ test('event content is rendered as text, never as HTML', async function (assert) {+ await this.buildWithEvents({+ subscribeFails: [{ error: { reason: '<b data-test-injected>no_token</b>' } }],+ messages: [{ html: '<img src="x" data-test-injected>' }],+ });++ assert.dom('[data-test-injected]').doesNotExist('markup from the network is not rendered');+ assert.dom('#output').containsText('<b data-test-injected>no_token</b>');+ assert.dom('#output').containsText('<img src=\\"x\\" data-test-injected>', 'channel data shows as JSON text');+ });+test('leaving the route closes the channel and clears the console', async function (assert) {const { component, closed, triggerRouteChange } = await this.buildWithEvents({ connects: [{}] });@@ -250,3 +262,369 @@ module('Integration | Component | configure/socket', function (hooks) {assert.deepEqual(component.events, [], 'and the console is cleared');});});++const STATUS = {+ started_at: '2026-10-15T08:00:00.000Z',+ uptime_seconds: 5400,+ mode: 'log',+ auth_enabled: true,+ clients: 3,+ pending_clients: 1,+ config: { enabled: true, mode: 'log', origins: 'console.example.com:*', source: 'api', last_sync_at: '2026-10-15T09:30:00.000Z', last_sync_error: null },+ denials: [+ { client: 'navigator/2.1.0', prefix: 'order', reason: 'no_token', count: 7, last_at: '2026-10-15T09:31:00.000Z' },+ { client: null, prefix: null, reason: 'bad_iss', count: 1, last_at: '2026-10-15T09:20:00.000Z' },+ ],+ counters: {},+};++function socketResponse({ settings = {}, sources = {}, status = STATUS, statusError = null } = {}) {+ return {+ settings: {+ enabled: true,+ mode: 'log',+ token_ttl: 900,+ origins: 'console.example.com:*',+ publisher_origin: null,+ key_configured: true,+ ...settings,+ sources: { enabled: 'setting', mode: 'setting', token_ttl: 'env', origins: 'setting', publisher_origin: 'env', ...sources },+ },+ status,+ status_error: statusError,+ };+}++function fakeModal() {+ return {+ loading: false,+ finished: false,+ startLoading() {+ this.loading = true;+ },+ done() {+ this.finished = true;+ },+ };+}++/** Lets the tasks' fetches (native promises, which settled() does not track) resolve. */+async function settle() {+ await new Promise((resolve) => setTimeout(resolve, 0));+ await settled();+}++module('Integration | Component | configure/socket settings', function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ const context = this;+ this.requests = [];+ this.getResponse = socketResponse();+ this.saveResponse = socketResponse({ settings: { origins: 'a.example.com:*' } });+ this.getError = null;+ this.saveError = null;++ const exhausted = () => ({+ [Symbol.asyncIterator]() {+ return { next: () => Promise.resolve({ done: true, value: undefined }) };+ },+ });+ class SocketStub extends Service {+ instance() {+ return { listener: exhausted, subscribe: () => Object.assign(exhausted(), { listener: exhausted, close() {} }) };+ }+ }+ class FetchStub extends Service {+ get(path) {+ context.requests.push({ method: 'get', path });+ return context.getError ? Promise.reject(context.getError) : Promise.resolve(context.getResponse);+ }+ post(path, payload, options) {+ context.requests.push({ method: 'post', path, payload, options });+ if (path !== 'settings/socket') {+ return Promise.resolve({ status: 'ok' });+ }+ return context.saveError ? Promise.reject(context.saveError) : Promise.resolve(context.saveResponse);+ }+ }+ class NotificationsStub extends Service {+ successes = [];+ errors = [];+ serverErrors = [];+ success(message) {+ this.successes.push(message);+ }+ error(message) {+ this.errors.push(message);+ }+ serverError(error) {+ this.serverErrors.push(error);+ }+ }+ class ModalsManagerStub extends Service {+ lastOptions = null;+ confirm(options) {+ this.lastOptions = options;+ }+ }+ class CurrentUserStub extends Service {+ id = 'user-uuid-1';+ }++ this.owner.lookup('service:intl').setLocale('en-us');+ this.owner.register('service:socket', SocketStub);+ this.owner.register('service:fetch', FetchStub);+ this.owner.register('service:notifications', NotificationsStub);+ this.owner.register('service:modals-manager', ModalsManagerStub);+ this.owner.register('service:current-user', CurrentUserStub);+ this.notifications = () => this.owner.lookup('service:notifications');+ this.modals = () => this.owner.lookup('service:modals-manager');+ this.saves = () => this.requests.filter((request) => request.method === 'post' && request.path === 'settings/socket');++ const captured = captureComponent(this.owner, 'configure/socket', ConfigureSocketComponent);+ this.build = async () => {+ await render(hbs`<Configure::Socket />`);+ await settle();+ return captured.instance;+ };+ });++ test('it exports the modes and fields the API accepts', function (assert) {+ assert.deepEqual(+ MODES.map((mode) => mode.value),+ ['off', 'log', 'enforce']+ );+ assert.deepEqual(FIELDS, ['enabled', 'mode', 'token_ttl', 'origins', 'publisher_origin']);+ });++ test('it loads the settings and the socket server status', async function (assert) {+ const component = await this.build();++ assert.deepEqual(this.requests[0], { method: 'get', path: 'settings/socket' });+ assert.dom('[data-test-socket-reachable="yes"]').exists();+ assert.dom('[data-test-socket-status-error]').doesNotExist();+ assert.dom('[data-test-socket-effective-enabled]').containsText('On');+ assert.dom('[data-test-socket-effective-enabled]').containsText('Console setting');+ assert.dom('[data-test-socket-effective-mode]').containsText('log');+ assert.dom('[data-test-socket-key]').containsText('Configured');+ assert.dom('[data-test-socket-connections]').containsText('3');+ assert.dom('[data-test-socket-connections]').containsText('(+1 connecting)');+ assert.dom('[data-test-socket-running]').containsText('On, log');+ assert.dom('[data-test-socket-running]').containsText('from the API');+ assert.dom('[data-test-socket-last-sync]').containsText(formatDateTime(STATUS.config.last_sync_at));+ assert.dom('[data-test-socket-sync-error]').doesNotExist();+ assert.dom('[data-test-socket-out-of-sync]').doesNotExist();+ assert.dom('[data-test-socket-key-help]').containsText('SOCKETCLUSTER_AUTH_KEY');+ assert.dom('[data-test-socket-key-help]').containsText('restart both');++ assert.dom('[data-test-socket-denial]').exists({ count: 2 });+ assert.dom('[data-test-socket-denials]').containsText('navigator/2.1.0');+ assert.dom('[data-test-socket-denials]').containsText('no_token');+ assert.dom('[data-test-socket-denials]').containsText('(token)');+ assert.dom('[data-test-socket-denials]').containsText('unknown');+ assert.strictEqual(component.denials[0].lastAtLabel, formatDateTime(STATUS.denials[0].last_at));++ assert.dom('[data-test-socket-inherit="enabled"]').isNotChecked();+ assert.dom('[data-test-socket-inherit="token_ttl"]').isChecked('an env-sourced field starts on "use environment"');+ assert.dom('[data-test-socket-token-ttl]').doesNotExist();+ assert.dom('[data-test-socket-origins]').hasValue('console.example.com:*');+ assert.dom('[data-test-socket-publisher-origin]').doesNotExist();+ assert.dom('[data-test-socket-mode]').hasValue('log');+ assert.dom('[data-test-socket-key-missing]').doesNotExist();++ assert.deepEqual(component.payload(), { enabled: true, mode: 'log', token_ttl: null, origins: 'console.example.com:*', publisher_origin: null });+ });++ test('it explains an unreachable socket server and a missing key', async function (assert) {+ this.getResponse = socketResponse({+ settings: { enabled: false, mode: null, key_configured: false },+ sources: { mode: 'env' },+ status: null,+ statusError: 'Connection refused',+ });+ const component = await this.build();++ assert.dom('[data-test-socket-reachable="no"]').exists();+ assert.dom('[data-test-socket-status-error]').containsText('Connection refused');+ assert.dom('[data-test-socket-effective-enabled]').containsText('Off');+ assert.dom('[data-test-socket-effective-mode]').containsText('Socket server default (env)');+ assert.dom('[data-test-socket-effective-mode]').containsText('Environment');+ assert.dom('[data-test-socket-key]').containsText('Not configured');+ assert.dom('[data-test-socket-connections]').containsText('—');+ assert.dom('[data-test-socket-last-sync]').containsText('—');+ assert.dom('[data-test-socket-no-denials]').exists();+ assert.dom('[data-test-socket-key-missing]').exists();+ assert.dom('[data-test-socket-enabled]').hasAttribute('data-disabled', '', 'cannot switch on without a key');+ assert.strictEqual(component.mode, 'log', 'a null mode starts the select on log');+ assert.deepEqual(component.denials, []);+ assert.false(component.isOutOfSync);+ });++ test('an older socket server reports no config, and a missing status error has a fallback', async function (assert) {+ this.getResponse = socketResponse({ status: { clients: 0 } });+ await this.build();++ assert.dom('[data-test-socket-last-sync]').containsText('Not reported by this socket server version');+ assert.dom('[data-test-socket-running]').containsText('—');+ assert.dom('[data-test-socket-connections]').containsText('0');++ this.getResponse = socketResponse({ status: null });+ await click('[data-test-socket-refresh]');+ await settle();+ assert.dom('[data-test-socket-status-error]').containsText('No status was returned.');+ assert.strictEqual(this.requests.filter((request) => request.method === 'get').length, 2, 'refresh reloads');+ });++ test('a sparse response falls back to safe values', async function (assert) {+ this.getResponse = {};+ const component = await this.build();++ assert.deepEqual(component.settings, {});+ assert.strictEqual(component.status, null);+ assert.strictEqual(component.statusError, null);+ assert.false(component.enabled);+ assert.strictEqual(component.mode, 'log');+ assert.strictEqual(component.tokenTtl, '');+ assert.strictEqual(component.origins, '');+ assert.strictEqual(component.publisherOrigin, '');+ assert.deepEqual(component.inherits, { enabled: true, mode: true, token_ttl: true, origins: true, publisher_origin: true });+ assert.false(component.keyConfigured);+ assert.deepEqual(component.payload(), { enabled: null, mode: null, token_ttl: null, origins: null, publisher_origin: null });++ component.apply(undefined);+ assert.deepEqual(component.settings, {});+ });++ test('it flags a socket server that runs other settings or failed to sync', async function (assert) {+ this.getResponse = socketResponse({+ status: { ...STATUS, config: { ...STATUS.config, enabled: false, mode: 'off', source: 'env', last_sync_at: null, last_sync_error: 'http_401' } },+ });+ const component = await this.build();++ assert.dom('[data-test-socket-out-of-sync]').exists();+ assert.dom('[data-test-socket-sync-error]').containsText('http_401');+ assert.dom('[data-test-socket-last-sync]').containsText('Never');+ assert.dom('[data-test-socket-running]').containsText('its environment');++ const server = (config) => ({ ...STATUS, config: { ...STATUS.config, ...config } });+ component.settings = { enabled: true, mode: 'enforce' };+ component.status = server({ enabled: true, mode: 'log' });+ assert.true(component.isOutOfSync, 'mode differs');+ component.status = server({ enabled: true, mode: 'enforce' });+ assert.false(component.isOutOfSync, 'in sync');+ component.settings = { enabled: true, mode: null };+ assert.false(component.isOutOfSync, 'a null mode is the server default');+ component.settings = { enabled: false, mode: 'enforce' };+ component.status = server({ enabled: false, mode: 'off' });+ assert.false(component.isOutOfSync, 'both off');+ component.status = null;+ assert.false(component.isOutOfSync, 'nothing to compare');+ });++ test('it saves the form in the shape the API expects', async function (assert) {+ const component = await this.build();++ await click('[data-test-socket-inherit="token_ttl"]');+ await fillIn('[data-test-socket-token-ttl]', '600');+ await fillIn('[data-test-socket-origins]', ' a.example.com:* ');+ await click('[data-test-socket-inherit="publisher_origin"]');+ await fillIn('[data-test-socket-publisher-origin]', 'https://console.example.com');+ await click('[data-test-socket-enabled]');+ assert.false(component.enabled, 'the toggle switches auth off');+ await click('[data-test-socket-enabled]');+ await fillIn('[data-test-socket-mode]', 'off');+ assert.strictEqual(component.mode, 'off');++ await click('[data-test-socket-save]');+ await settle();++ assert.deepEqual(this.saves(), [+ {+ method: 'post',+ path: 'settings/socket',+ payload: { enabled: true, mode: 'off', token_ttl: 600, origins: 'a.example.com:*', publisher_origin: 'https://console.example.com' },+ options: { rawError: true },+ },+ ]);+ assert.strictEqual(this.modals().lastOptions, null, 'no confirmation outside enforce');+ assert.strictEqual(this.notifications().successes.length, 1);+ assert.strictEqual(component.origins, 'a.example.com:*', 'the response is applied');+ });++ test('"use environment" sends null, and blank inputs mean the environment too', async function (assert) {+ const component = await this.build();++ await click('[data-test-socket-inherit="origins"]');+ assert.dom('[data-test-socket-origins]').doesNotExist();+ assert.strictEqual(component.payload().origins, null);++ component.toggleInherit('origins', false);+ component.toggleInherit('token_ttl', false);+ component.origins = null;+ component.tokenTtl = ' ';+ assert.strictEqual(component.payload().origins, null);+ assert.strictEqual(component.payload().token_ttl, null);+ });++ test('switching to enforce asks for confirmation first', async function (assert) {+ const component = await this.build();++ await fillIn('[data-test-socket-mode]', 'enforce');+ await click('[data-test-socket-save]');++ const options = this.modals().lastOptions;+ assert.strictEqual(options.body, ENFORCE_WARNING);+ assert.strictEqual(options.acceptButtonScheme, 'danger');+ assert.strictEqual(this.saves().length, 0, 'nothing is saved before the confirmation');++ const modal = fakeModal();+ await options.confirm(modal);+ assert.true(modal.loading);+ assert.true(modal.finished);+ assert.strictEqual(this.saves()[0].payload.mode, 'enforce');+ assert.strictEqual(component.mode, 'log', 'the saved response is applied');+ });++ test('entersEnforce covers every way a save can start enforcing', async function (assert) {+ const component = await this.build();+ const enters = (settings, payload) => {+ component.settings = settings;+ return component.entersEnforce(payload);+ };++ assert.false(enters({ enabled: false }, { enabled: false, mode: 'enforce' }), 'switched off');+ assert.true(enters({ enabled: true, mode: 'log' }, { enabled: true, mode: 'enforce' }), 'log to enforce');+ assert.true(enters({ enabled: false, mode: 'enforce' }, { enabled: null, mode: 'enforce' }), 'enforce while off');+ assert.false(enters({ enabled: true, mode: 'enforce' }, { enabled: true, mode: 'enforce' }), 'already enforcing');+ assert.true(enters({ enabled: false, mode: null }, { enabled: true, mode: null }), 'switched on with the server default mode');+ assert.false(enters({ enabled: true, mode: null }, { enabled: true, mode: null }), 'already on');+ assert.false(enters({ enabled: false, mode: null }, { enabled: null, mode: null }), 'switch left to the environment');+ assert.false(enters({ enabled: false, mode: null }, { enabled: true, mode: 'log' }), 'switched on in log mode');+ });++ test('it reports failed loads and saves', async function (assert) {+ this.getError = new Error('load failed');+ const component = await this.build();+ assert.deepEqual(+ this.notifications().serverErrors.map((error) => error.message),+ ['load failed']+ );++ this.saveError = { errors: ['Socket authentication cannot be switched on.'], code: 'key_missing' };+ await component.saveSettings.perform({ enabled: true });+ assert.deepEqual(this.notifications().errors, [KEY_MISSING_MESSAGE], 'key_missing gets its own message');++ this.saveError = { message: 'The origins field format is invalid.', errors: { origins: ['The origins field format is invalid.'] } };+ await component.saveSettings.perform({ origins: 'bad value\n' });+ assert.strictEqual(this.notifications().errors.at(-1), 'The origins field format is invalid.', 'a validation error shows its message');++ this.saveError = { errors: ['Server error'] };+ await component.saveSettings.perform({});+ assert.deepEqual(this.notifications().serverErrors.at(-1), { errors: ['Server error'] });++ component.saveFailed(undefined);+ assert.strictEqual(this.notifications().serverErrors.at(-1), undefined);+ assert.strictEqual(this.notifications().successes.length, 0);+ });+});diff --git a/docker/Dockerfile b/docker/Dockerfileindex 76945759..132a0a19 100644--- a/docker/Dockerfile+++ b/docker/Dockerfile@@ -82,7 +82,7 @@ ENV OCTANE_SERVER=frankenphp# its "develop" default it roughly doubled every request's time and disabled the OPcache# JIT in every image built from here, production included.ENV XDEBUG_MODE=off-ENV FLEETBASE_VERSION=0.7.69+ENV FLEETBASE_VERSION=0.7.70# Set environmentARG ENVIRONMENT=productiondiff --git a/infra/helm/templates/socketcluster.yaml b/infra/helm/templates/socketcluster.yamlindex 3ad693be..4f16b93d 100644--- a/infra/helm/templates/socketcluster.yaml+++ b/infra/helm/templates/socketcluster.yaml@@ -45,6 +45,14 @@ spec:value: "8001"- name: SOCKETCLUSTER_AUTHORIZE_URLvalue: {{ include "helm.socketAuthorizeUrl" . | quote }}+ {{- if $sc.configUrl }}+ - name: SOCKETCLUSTER_CONFIG_URL+ value: {{ $sc.configUrl | quote }}+ {{- end }}+ {{- if and (not (kindIs "invalid" $sc.configPollSeconds)) (ne (toString $sc.configPollSeconds) "") }}+ - name: SOCKETCLUSTER_CONFIG_POLL_SECONDS+ value: {{ $sc.configPollSeconds | toString | quote }}+ {{- end }}{{- if $sc.authMode }}- name: SOCKETCLUSTER_AUTH_MODEvalue: {{ $sc.authMode | quote }}diff --git a/infra/helm/values.yaml b/infra/helm/values.yamlindex 92479f95..e2616dd0 100644--- a/infra/helm/values.yaml+++ b/infra/helm/values.yaml@@ -109,6 +109,12 @@ socketcluster:existingSecretKey: SOCKETCLUSTER_AUTH_KEY# Override the API authorize endpoint. Default: the API Service's /int/v1/socket/authorize.authorizeUrl: ""+ # With a key set, the socket server polls the API for the settings saved under+ # Admin > Configure > Socket (on/off, mode, origins) and applies them without a restart.+ # configUrl overrides the polled endpoint (default: authorizeUrl with /authorize replaced+ # by /config); configPollSeconds sets the interval (socket server default 30, "0" = off).+ configUrl: ""+ configPollSeconds: ""# SOCKETCLUSTER_OPTIONS JSON, e.g. '{"origins":"https://console.example.com:*"}'options: ""# SOCKETCLUSTER_ORIGIN for the API: the Origin header its websocket publisher sends (useddiff --git a/packages/core-api b/packages/core-apiindex 7ccac141..5e488132 160000--- a/packages/core-api+++ b/packages/core-api@@ -1 +1 @@-Subproject commit 7ccac1413beb71041133a4ef4f1bb6e54076c964+Subproject commit 5e488132d7f84038f9b6d9944603349dee8a65bbdiff --git a/packages/fleetops b/packages/fleetopsindex 4a4ce41a..7887aa5e 160000--- a/packages/fleetops+++ b/packages/fleetops@@ -1 +1 @@-Subproject commit 4a4ce41a85cb272e8c431fd8a68422c301ddbb7c+Subproject commit 7887aa5effe54704d75544c6ce72be894e38a52adiff --git a/packages/registry-bridge b/packages/registry-bridgeindex 4691c426..7eecac11 160000--- a/packages/registry-bridge+++ b/packages/registry-bridge@@ -1 +1 @@-Subproject commit 4691c426daf9a7bf8c212140264ceb0edd9c92f4+Subproject commit 7eecac11e0b9a3ab0ece8728b8a2a9706d89dffddiff --git a/packages/storefront b/packages/storefrontindex 90c89ab5..dc22cf37 160000--- a/packages/storefront+++ b/packages/storefront@@ -1 +1 @@-Subproject commit 90c89ab5c576d130e2a5c7e7c63bd9b8edfdd740+Subproject commit dc22cf37f7a31a1574326aa1c9d5d4edc2bea4fcdiff --git a/socket/README.md b/socket/README.mdindex e3d1e364..2f9e7c50 100644--- a/socket/README.md+++ b/socket/README.md@@ -10,6 +10,9 @@ The realtime server behind the Fleetbase console, Navigator and Storefront apps.Only the API publishes.- **Signed internal publish.** The API publishes with a signed `POST /publish` to a second,internal-only listener instead of opening a websocket for every event.+- **Runtime config from the console.** With a key configured, the server polls the API for+ the settings an admin makes under Admin → Configure → Socket (on/off, mode, origins) and+ applies them without a restart. See [Runtime config](#runtime-config).Image: `fleetbase/fleetbase-socket` (linux/amd64 and linux/arm64).@@ -24,13 +27,15 @@ Image: `fleetbase/fleetbase-socket` (linux/amd64 and linux/arm64).| Variable | Default | Meaning ||---|---|---|-| `SOCKETCLUSTER_AUTH_ENABLED` | `false` | Switches socket auth on (`true`, `1`, `yes` or `on`). Must match the API's value. While it is off the mode is forced to `off`, the key is not used, and the internal publish and stats endpoints answer `503`, so clients that connect without socket tokens keep working even when a key is provisioned. |-| `SOCKETCLUSTER_AUTH_KEY` | unset | Shared secret, at least 32 characters. Must be identical on the API (application, queue and scheduler) and the socket server. Unset disables the feature: the mode is forced to `off` and a warning is logged at startup. A key shorter than 32 characters stops the server from starting. |-| `SOCKETCLUSTER_AUTH_MODE` | `enforce` when switched on with a key, else `off` | `off`, `log` or `enforce` (see below). |+| `SOCKETCLUSTER_AUTH_ENABLED` | `false` | Switches socket auth on (`true`, `1`, `yes` or `on`). Must match the API's value. While it is off the mode is forced to `off`, so clients that connect without socket tokens keep working even when a key is provisioned. This is the starting value: the console setting, when one is saved, overrides it at runtime. |+| `SOCKETCLUSTER_AUTH_KEY` | unset | Shared secret, at least 32 characters. Must be identical on the API (application, queue and scheduler) and the socket server. Unset disables the feature: the mode is forced to `off`, the internal endpoints answer `503`, there is no config polling, and a warning is logged at startup. A key shorter than 32 characters stops the server from starting. The key is only ever read from the environment; the console cannot see or change it. |+| `SOCKETCLUSTER_AUTH_MODE` | `enforce` when switched on with a key, else `off` | `off`, `log` or `enforce` (see below). Also the mode used when the console switches auth on without choosing one. || `SOCKETCLUSTER_AUTHORIZE_URL` | `http://application:8000/int/v1/socket/authorize` | The API's authorize endpoint, reached over the private network. |+| `SOCKETCLUSTER_CONFIG_URL` | the authorize URL with `/authorize` replaced by `/config` | The API's socket config endpoint, polled when a key is set. Only needed when the authorize URL does not end in `/authorize`. |+| `SOCKETCLUSTER_CONFIG_POLL_SECONDS` | `30` | How often to poll the config endpoint. `0` disables polling (environment config only). || `SOCKETCLUSTER_PORT` | `8000` | Public listener port. || `SOCKETCLUSTER_INTERNAL_PORT` | `8001` | Internal listener port. |-| `SOCKETCLUSTER_OPTIONS` | `{}` | JSON merged into the SocketCluster server options, e.g. `{"origins":"https://console.example.com:*"}`. The auth settings (`authKey`, `authVerifyAlgorithms`, `allowClientPublish`, ...) are owned by the server and are ignored here, with a warning. |+| `SOCKETCLUSTER_OPTIONS` | `{}` | JSON merged into the SocketCluster server options, e.g. `{"origins":"console.example.com:*"}`. Its `origins` is the starting value; an origins setting saved in the console overrides it at runtime. The auth settings (`authKey`, `authVerifyAlgorithms`, `allowClientPublish`, ...) are owned by the server and are ignored here, with a warning. || `SOCKETCLUSTER_SOCKET_CHANNEL_LIMIT` | `1000` | Maximum channels per socket. || `SOCKETCLUSTER_LOG_LEVEL` | `2` | `0` silent, `1` errors, `2` errors, info and warnings, `3` debug. || `SCC_STATE_SERVER_HOST`, `SCC_STATE_SERVER_PORT`, `SCC_AUTH_KEY`, `SCC_INSTANCE_IP`, `SCC_INSTANCE_IP_FAMILY`, `SCC_MAPPING_ENGINE`, `SCC_CLIENT_POOL_SIZE`, `SCC_STATE_SERVER_CONNECT_TIMEOUT`, `SCC_STATE_SERVER_ACK_TIMEOUT`, `SCC_STATE_SERVER_RECONNECT_RANDOMNESS`, `SCC_PUB_SUB_BATCH_DURATION`, `SCC_BROKER_RETRY_DELAY` | unset | SocketCluster Cluster (SCC) for running several instances, the same as the stock image: SCC is enabled when `SCC_STATE_SERVER_HOST` is set. |@@ -42,6 +47,47 @@ such as `https://console.example.com`, which it sends as the `Origin` header wheGenerate a key with, for example, `openssl rand -hex 32`.+To rotate the key, set the new value on the API (application, queue and scheduler) and the+socket server and restart both. Tokens signed with the old key stop verifying, and clients+fetch new ones on reconnect.++## Runtime config++When `SOCKETCLUSTER_AUTH_KEY` is set, the server polls `GET SOCKETCLUSTER_CONFIG_URL` every+`SOCKETCLUSTER_CONFIG_POLL_SECONDS` (first poll at startup). The request is signed with the+authorize key (see [Internal endpoints](#internal-endpoints), `msg = "fleetbase-socket:authorize"`,+empty body) and times out after 2 seconds. The API answers with the effective values, saved+console settings first, then the API's environment:++```json+{"enabled": true, "mode": "log", "origins": "console.example.com:*", "updated_at": "2026-10-15T09:30:00Z"}+```++- `enabled`, `mode` and `origins` replace the environment values. `mode: null` falls back+ to `SOCKETCLUSTER_AUTH_MODE`, then `enforce`; `origins: null` falls back to+ `SOCKETCLUSTER_OPTIONS.origins`, then `*:*`.+- Until the first good answer the environment config is in force. When the API cannot be+ reached, times out, or answers with something malformed, the last good config stays in+ force and the reason is reported on `/stats` (`config.last_sync_error`) and logged once.+- Changes apply within one poll interval, without a restart:+ - the mode (and the switch) takes effect on the next action on every socket;+ - client publish is refused from the moment the mode becomes `enforce`, and allowed again+ when it leaves it;+ - origins apply to new websocket handshakes; open connections are not re-checked.+- Entering `enforce` at runtime disconnects every socket once (close code `4100`, reason+ `auth_enforced`). Clients reconnect on their own after their reconnect delay and every+ subscription made while auth was looser is authorized again.+- Because the key is passed to SocketCluster whenever one is set, tokens are verified even+ while auth is off, so switching on needs no restart. With a key, the internal endpoints+ also work while auth is off.+- While a change propagates (up to one interval) the API and the socket server can briefly+ disagree. Switching on is safe because `/publish` is already open. Switching off from+ `enforce` can refuse the API's websocket publishes until the next poll; switch to `log`+ first, or lower the interval, if that matters.++Without a key, or with `SOCKETCLUSTER_CONFIG_POLL_SECONDS=0`, the server never polls and+uses the environment only.+## Modes| Mode | Token verification | Subscriptions | Client publish/transmit/invoke | Kick-out on expiry or identity change |@@ -118,7 +164,8 @@ X-Fleetbase-Signature: hex(HMAC_SHA256(key = publishKey, msg = timestamp + "." +```Requests more than 60 seconds away from the server clock, or with a bad signature, get-`401`. Without `SOCKETCLUSTER_AUTH_KEY` both endpoints answer `503`.+`401`. Without `SOCKETCLUSTER_AUTH_KEY` both endpoints answer `503`; with a key they work+whether or not auth is switched on.- `POST /publish` with `{"channels": ["order.x", "company.y"], "data": {...}}` (or`{"channel": "order.x", "data": {...}}`). Each channel is a non-empty string of at most@@ -126,7 +173,15 @@ Requests more than 60 seconds away from the server clock, or with a bad signaturmost 2 MB. Responses: `202 {"published": n}`, `400` for a bad body, `401`, `413`.- `GET /stats` (empty body, signed) returns uptime, mode, connected clients, cache sizeand counters (allowed and denied subscriptions, authorize calls, cache hits, timeouts,- kick-outs, publish requests).+ kick-outs, publish requests, config polls), plus:+ - `config`: `{enabled, mode, origins, source, last_sync_at, last_sync_error}`, where+ `source` is `env` until the first good config poll and `api` after it;+ - `denials`: the top 50 (would-)denials since start by count, as+ `{client, prefix, reason, count, last_at}`. `prefix` is the channel up to its first `.`+ (`other` when that does not look like a channel family, `null` for token rejections).+ Tokens, subjects, company ids and full channel names are never included.++ The console's Socket page shows this through the API.## Developmentdiff --git a/socket/lib/app.js b/socket/lib/app.jsindex 5c0d6af8..d1b72822 100644--- a/socket/lib/app.js+++ b/socket/lib/app.js@@ -3,7 +3,16 @@/*** Assembles the socket server: the public HTTP/WebSocket listener (health check plus* SocketCluster at /socketcluster/), the auth middleware, the internal publish/stats- * listener and, when SCC_STATE_SERVER_HOST is set, the SCC broker client.+ * listener, the config poller (when a key is configured) and, when SCC_STATE_SERVER_HOST+ * is set, the SCC broker client.+ *+ * Runtime config (enabled, mode, origins) is applied without a restart:+ * - the auth policy reads its mode per action;+ * - `agServer.allowClientPublish` is read by SocketCluster on every inbound #publish;+ * - `agServer.origins` / `agServer._allowAllOrigins` are read on every websocket handshake,+ * so an origins change applies to new connections (open ones are not re-checked).+ * Entering `enforce` at runtime disconnects every socket once, so clients reconnect and+ * every subscription made while auth was looser goes through the authorizer again.*/const http = require('http');@@ -14,6 +23,9 @@ const { Authorizer } = require('./authorizer');const { SocketAuthPolicy } = require('./middleware');const { createInternalHandler } = require('./internal');const { Stats } = require('./stats');+const { Denials } = require('./denials');+const { RuntimeConfig } = require('./runtime');+const { ConfigPoller } = require('./config-poller');const { createLogger, describeError } = require('./logger');function publicHandler(req, res) {@@ -57,21 +69,40 @@ function closeHttpServer(server) {});}+/**+ * Points SocketCluster's handshake origin check at a new origins value. These are plain+ * instance fields in socketcluster-server 17, read by verifyHandshake on every handshake.+ */+function applyOrigins(agServer, origins) {+ agServer.origins = origins;+ agServer._allowAllOrigins = origins.indexOf('*:*') !== -1;+}++/** Close code sent to sockets when the server switches to enforce at runtime. */+const ENFORCE_RECONNECT_CODE = 4100;+/*** @param {ReturnType<import('./config').loadConfig>} config* @param {object} [deps]* @param {object} [deps.logger]- * @param {typeof fetch} [deps.fetch] used for the authorize call+ * @param {typeof fetch} [deps.fetch] used for the authorize and config calls* @param {number} [deps.authorizeTimeoutMs]+ * @param {number} [deps.configPollIntervalMs] overrides SOCKETCLUSTER_CONFIG_POLL_SECONDS (tests)*/function createSocketServer(config, deps = {}) {const logger = deps.logger || createLogger({ level: config.logLevel });const stats = new Stats();+ const denials = new Denials();+ const runtime = new RuntimeConfig(config);+ const keyConfigured = config.authKey !== null;const httpServer = http.createServer(publicHandler);const agServer = socketClusterServer.attach(httpServer, buildServerOptions(config));+ applyOrigins(agServer, runtime.origins);- const authorizer = config.authEnabled+ // With a key the authorizer always exists; whether it is consulted depends on the+ // runtime mode, so switching auth on from the console needs no restart.+ const authorizer = keyConfigured? new Authorizer({url: config.authorizeUrl,authorizeKey: deriveKey(config.authKey, PURPOSE_AUTHORIZE),@@ -81,23 +112,61 @@ function createSocketServer(config, deps = {}) {}): null;- const policy = new SocketAuthPolicy({ config, authorizer, logger, stats });+ const policy = new SocketAuthPolicy({ config, authorizer, logger, stats, denials });agServer.setMiddleware(agServer.MIDDLEWARE_INBOUND, policy.inboundMiddleware());policy.attach(agServer);+ runtime.onChange((next, previous) => {+ policy.update(next);+ agServer.allowClientPublish = next.mode !== 'enforce';+ applyOrigins(agServer, next.origins);+ if (next.mode === 'enforce' && previous.mode !== 'enforce') {+ disconnectAll('auth_enforced');+ }+ });++ function disconnectAll(reason) {+ const sockets = Object.values(agServer.clients);+ stats.increment('runtime_reconnects', sockets.length);+ logger.info({ event: 'socket_reconnect_all', reason, clients: sockets.length });+ for (const socket of sockets) {+ try {+ socket.disconnect(ENFORCE_RECONNECT_CODE, reason);+ } catch (error) {+ logger.debug({ event: 'socket_disconnect_failed', error: describeError(error) });+ }+ }+ }++ const pollIntervalMs = deps.configPollIntervalMs !== undefined ? deps.configPollIntervalMs : config.configPollSeconds * 1000;+ const poller =+ keyConfigured && config.configUrl && pollIntervalMs > 0+ ? new ConfigPoller({+ url: config.configUrl,+ authorizeKey: deriveKey(config.authKey, PURPOSE_AUTHORIZE),+ intervalMs: pollIntervalMs,+ runtime,+ logger,+ fetch: deps.fetch,+ stats,+ })+ : null;+const gauges = () => ({- mode: config.mode,- auth_enabled: config.authEnabled,+ mode: runtime.mode,+ auth_enabled: runtime.enabled,clients: agServer.clientsCount,pending_clients: agServer.pendingClientsCount,authorize_cache_size: authorizer ? authorizer.cache.size : 0,authorize_inflight: authorizer ? authorizer.inflight.size : 0,+ config: runtime.snapshot(),+ denials: denials.top(),});const internalServer = http.createServer(createInternalHandler({agServer,- publishKey: config.authEnabled ? deriveKey(config.authKey, PURPOSE_PUBLISH) : null,+ publishKey: keyConfigured ? deriveKey(config.authKey, PURPOSE_PUBLISH) : null,stats,logger,gauges,@@ -124,6 +193,10 @@ function createSocketServer(config, deps = {}) {const internalPort = await listen(internalServer, config.internalPort);ports = { port, internalPort };+ if (poller) {+ poller.start();+ }+if (config.scc.stateServerHost) {// Lazily required: only multi-instance deployments need it.const sccBrokerClient = require('scc-broker-client');@@ -155,6 +228,9 @@ function createSocketServer(config, deps = {}) {}async function stop() {+ if (poller) {+ await poller.stop();+ }try {await agServer.close();} catch (error) {@@ -173,6 +249,9 @@ function createSocketServer(config, deps = {}) {internalServer,authorizer,policy,+ runtime,+ poller,+ denials,stats,logger,start,@@ -183,4 +262,4 @@ function createSocketServer(config, deps = {}) {};}-module.exports = { createSocketServer, publicHandler };+module.exports = { createSocketServer, publicHandler, applyOrigins, ENFORCE_RECONNECT_CODE };diff --git a/socket/lib/config-poller.js b/socket/lib/config-poller.jsnew file mode 100644index 00000000..c8e37474--- /dev/null+++ b/socket/lib/config-poller.js@@ -0,0 +1,163 @@+'use strict';++/**+ * Polls the API's socket config endpoint (`GET SOCKETCLUSTER_CONFIG_URL`, signed with the+ * authorize key, empty body) and hands every good answer to the RuntimeConfig. Polls run+ * one after another, never overlapping; the first runs as soon as the server starts.+ *+ * A failed poll (unreachable, timeout, non-200, malformed body) never changes the config:+ * the last good one stays in force and the reason is reported on /stats.+ */++const { signRequest } = require('./signing');+const { parseRemoteConfig } = require('./runtime');+const { describeError } = require('./logger');++const DEFAULT_TIMEOUT_MS = 2000;++class ConfigPoller {+ /**+ * @param {object} options+ * @param {string} options.url+ * @param {string} options.authorizeKey key derived for the "authorize" purpose+ * @param {number} options.intervalMs+ * @param {import('./runtime').RuntimeConfig} options.runtime+ * @param {object} options.logger+ * @param {number} [options.timeoutMs]+ * @param {typeof fetch} [options.fetch]+ * @param {import('./stats').Stats} [options.stats]+ */+ constructor({ url, authorizeKey, intervalMs, runtime, logger, timeoutMs = DEFAULT_TIMEOUT_MS, fetch: fetchImpl, stats } = {}) {+ if (!url) {+ throw new TypeError('ConfigPoller requires a url');+ }+ if (!authorizeKey) {+ throw new TypeError('ConfigPoller requires an authorizeKey');+ }+ if (!(intervalMs > 0)) {+ throw new TypeError('ConfigPoller requires a positive intervalMs');+ }+ this.url = url;+ this.authorizeKey = authorizeKey;+ this.intervalMs = intervalMs;+ this.runtime = runtime;+ this.logger = logger;+ this.timeoutMs = timeoutMs;+ this.fetch = fetchImpl || ((input, init) => globalThis.fetch(input, init));+ this.stats = stats || null;+ this.timer = null;+ this.running = false;+ this.current = null;+ }++ count(name) {+ if (this.stats) {+ this.stats.increment(name);+ }+ }++ /**+ * One poll. Never throws.+ *+ * @returns {Promise<{ ok: true, changed: boolean } | { ok: false, reason: string }>}+ */+ async poll() {+ this.count('config_polls');+ const result = await this.request();+ if (!result.ok) {+ this.count('config_poll_errors');+ if (this.runtime.lastSyncError !== result.reason) {+ this.logger.warn({ event: 'socket_config_sync_failed', reason: result.reason, source: this.runtime.source });+ }+ this.runtime.recordFailure(result.reason);+ return result;+ }+ const recovered = this.runtime.lastSyncError !== null;+ const previous = this.runtime.snapshot();+ const changed = this.runtime.applyRemote(result.value);+ if (changed) {+ const next = this.runtime.snapshot();+ this.logger.info({+ event: 'socket_config_applied',+ enabled: next.enabled,+ mode: next.mode,+ origins: next.origins,+ previous_enabled: previous.enabled,+ previous_mode: previous.mode,+ source: next.source,+ });+ } else if (recovered) {+ this.logger.info({ event: 'socket_config_sync_recovered' });+ }+ return { ok: true, changed };+ }++ async request() {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);+ try {+ const response = await this.fetch(this.url, {+ method: 'GET',+ headers: { Accept: 'application/json', ...signRequest(this.authorizeKey, '') },+ signal: controller.signal,+ });+ if (!response.ok) {+ await response.text().catch(() => {});+ return { ok: false, reason: `http_${response.status}` };+ }+ let payload;+ try {+ payload = await response.json();+ } catch (error) {+ if (controller.signal.aborted) {+ throw error;+ }+ return { ok: false, reason: 'bad_response' };+ }+ const parsed = parseRemoteConfig(payload);+ return parsed.ok ? parsed : { ok: false, reason: 'bad_response' };+ } catch (error) {+ if (controller.signal.aborted) {+ return { ok: false, reason: 'timeout' };+ }+ this.logger.debug({ event: 'socket_config_request_error', error: describeError(error) });+ return { ok: false, reason: 'unreachable' };+ } finally {+ clearTimeout(timer);+ }+ }++ start() {+ if (this.running) {+ return;+ }+ this.running = true;+ this.tick();+ }++ tick() {+ this.current = this.poll().finally(() => {+ this.current = null;+ if (this.running) {+ this.timer = setTimeout(() => this.tick(), this.intervalMs);+ if (typeof this.timer.unref === 'function') {+ this.timer.unref();+ }+ }+ });+ return this.current;+ }++ async stop() {+ this.running = false;+ if (this.timer) {+ clearTimeout(this.timer);+ this.timer = null;+ }+ if (this.current) {+ await this.current;+ }+ }+}++module.exports = { ConfigPoller, DEFAULT_TIMEOUT_MS };diff --git a/socket/lib/config.js b/socket/lib/config.jsindex f2b1c062..27874e0e 100644--- a/socket/lib/config.js+++ b/socket/lib/config.js@@ -16,6 +16,8 @@ const DEFAULT_INTERNAL_PORT = 8001;const DEFAULT_AUTHORIZE_URL = 'http://application:8000/int/v1/socket/authorize';const DEFAULT_SOCKET_CHANNEL_LIMIT = 1000;const DEFAULT_LOG_LEVEL = 2;+const DEFAULT_CONFIG_POLL_SECONDS = 30;+const DEFAULT_ORIGINS = '*:*';/*** Server options that this process controls itself. They are stripped from@@ -144,19 +146,45 @@ function parseOptions(raw) {}function parseAuthorizeUrl(raw) {- const value = isBlank(raw) ? DEFAULT_AUTHORIZE_URL : String(raw).trim();+ return parseHttpUrl('SOCKETCLUSTER_AUTHORIZE_URL', isBlank(raw) ? DEFAULT_AUTHORIZE_URL : String(raw).trim());+}++function parseHttpUrl(name, value) {let url;try {url = new URL(value);} catch (error) {- throw new ConfigError(`SOCKETCLUSTER_AUTHORIZE_URL is not a valid URL (got "${value}")`);+ throw new ConfigError(`${name} is not a valid URL (got "${value}")`);}if (url.protocol !== 'http:' && url.protocol !== 'https:') {- throw new ConfigError(`SOCKETCLUSTER_AUTHORIZE_URL must be http(s) (got "${value}")`);+ throw new ConfigError(`${name} must be http(s) (got "${value}")`);}return url.toString();}+/**+ * The API's socket config endpoint. Defaults to the authorize URL with its trailing+ * `/authorize` replaced by `/config`; an authorize URL with another shape needs an explicit+ * SOCKETCLUSTER_CONFIG_URL, and without one config polling stays off (with a warning).+ *+ * @returns {{ configUrl: string|null, warnings: string[] }}+ */+function resolveConfigUrl(raw, authorizeUrl) {+ if (!isBlank(raw)) {+ return { configUrl: parseHttpUrl('SOCKETCLUSTER_CONFIG_URL', String(raw).trim()), warnings: [] };+ }+ const url = new URL(authorizeUrl);+ if (!/\/authorize\/?$/.test(url.pathname)) {+ return {+ configUrl: null,+ warnings: ['SOCKETCLUSTER_AUTHORIZE_URL does not end in /authorize, so the config URL cannot be derived; set SOCKETCLUSTER_CONFIG_URL to manage socket auth from the console.'],+ };+ }+ url.pathname = url.pathname.replace(/\/authorize\/?$/, '/config');+ url.search = '';+ return { configUrl: url.toString(), warnings: [] };+}+function nullableString(raw) {return isBlank(raw) ? null : String(raw).trim();}@@ -184,6 +212,10 @@ function loadConfig(env = process.env) {const { mode, warnings: modeWarnings } = resolveMode(authKey !== null, env.SOCKETCLUSTER_AUTH_MODE, switchedOn);const { options, warnings: optionWarnings } = parseOptions(env.SOCKETCLUSTER_OPTIONS);+ const authorizeUrl = parseAuthorizeUrl(env.SOCKETCLUSTER_AUTHORIZE_URL);+ const { configUrl, warnings: configUrlWarnings } = resolveConfigUrl(env.SOCKETCLUSTER_CONFIG_URL, authorizeUrl);+ const requestedMode = isBlank(env.SOCKETCLUSTER_AUTH_MODE) ? null : String(env.SOCKETCLUSTER_AUTH_MODE).trim().toLowerCase();+const port = parsePort('SOCKETCLUSTER_PORT', env.SOCKETCLUSTER_PORT, DEFAULT_PORT);const internalPort = parsePort('SOCKETCLUSTER_INTERNAL_PORT', env.SOCKETCLUSTER_INTERNAL_PORT, DEFAULT_INTERNAL_PORT);if (port !== 0 && port === internalPort) {@@ -196,7 +228,12 @@ function loadConfig(env = process.env) {authKey,authEnabled: switchedOn && authKey !== null,mode,- authorizeUrl: parseAuthorizeUrl(env.SOCKETCLUSTER_AUTHORIZE_URL),+ // The mode asked for in the environment, used when the API's config switches auth on+ // without naming a mode. Already validated by resolveMode.+ requestedMode,+ authorizeUrl,+ configUrl,+ configPollSeconds: parsePositiveInt('SOCKETCLUSTER_CONFIG_POLL_SECONDS', env.SOCKETCLUSTER_CONFIG_POLL_SECONDS, DEFAULT_CONFIG_POLL_SECONDS),options,socketChannelLimit: parsePositiveInt('SOCKETCLUSTER_SOCKET_CHANNEL_LIMIT', env.SOCKETCLUSTER_SOCKET_CHANNEL_LIMIT, DEFAULT_SOCKET_CHANNEL_LIMIT),logLevel: parsePositiveInt('SOCKETCLUSTER_LOG_LEVEL', env.SOCKETCLUSTER_LOG_LEVEL, DEFAULT_LOG_LEVEL),@@ -214,13 +251,25 @@ function loadConfig(env = process.env) {pubSubBatchDuration: nullableNumber(env.SCC_PUB_SUB_BATCH_DURATION),brokerRetryDelay: nullableNumber(env.SCC_BROKER_RETRY_DELAY),}),- warnings: Object.freeze([...modeWarnings, ...optionWarnings]),+ warnings: Object.freeze([...modeWarnings, ...optionWarnings, ...(authKey !== null ? configUrlWarnings : [])]),});}+/**+ * The origins SocketCluster starts with: SOCKETCLUSTER_OPTIONS.origins, else its own default.+ */+function envOrigins(config) {+ const origins = config.options.origins;+ return typeof origins === 'string' || Array.isArray(origins) ? origins : DEFAULT_ORIGINS;+}+/*** Builds the options passed to socketcluster-server's attach(). The auth settings are* applied last so SOCKETCLUSTER_OPTIONS can never override them.+ *+ * The key is passed whenever one is configured, even while auth is switched off, so that+ * tokens can be verified as soon as the API's config switches auth on at runtime. What the+ * server does with a verified token is decided by the runtime mode (see lib/runtime.js).*/function buildServerOptions(config) {const options = {@@ -232,7 +281,7 @@ function buildServerOptions(config) {authVerifyAlgorithms: ['HS256'],allowClientPublish: config.mode !== 'enforce',};- if (config.authEnabled) {+ if (config.authKey !== null) {options.authKey = config.authKey;}return options;@@ -244,7 +293,11 @@ module.exports = {MODES,MIN_AUTH_KEY_LENGTH,DEFAULT_AUTHORIZE_URL,+ DEFAULT_CONFIG_POLL_SECONDS,+ DEFAULT_ORIGINS,loadConfig,+ resolveConfigUrl,+ envOrigins,resolveMode,buildServerOptions,};diff --git a/socket/lib/denials.js b/socket/lib/denials.jsnew file mode 100644index 00000000..94c19ff9--- /dev/null+++ b/socket/lib/denials.js@@ -0,0 +1,94 @@+'use strict';++/**+ * Aggregated (would-)denials since the server started, reported on /stats so an admin can+ * see which clients would lose which kinds of channels before switching to `enforce`.+ *+ * Each row is keyed by client tag, channel prefix and reason. Rows never hold a token, a+ * subject or company id, or a full channel name: the prefix is the channel up to its first+ * '.', and only when that looks like a channel family (`order`, `company`, ...); anything+ * else is reported as `other`. The number of distinct rows is capped, because the client+ * tag and the channel come from the client.+ */++const DEFAULT_MAX_ENTRIES = 1000;+const DEFAULT_TOP = 50;+const PREFIX_PATTERN = /^[a-z][a-z0-9_-]{0,31}$/i;+const REASON_PATTERN = /^[a-z0-9_]{1,64}$/;++function channelPrefix(channel) {+ if (typeof channel !== 'string' || channel === '') {+ return null;+ }+ const dot = channel.indexOf('.');+ if (dot === -1) {+ return 'other';+ }+ const prefix = channel.slice(0, dot);+ return PREFIX_PATTERN.test(prefix) ? prefix.toLowerCase() : 'other';+}++class Denials {+ constructor({ max = DEFAULT_MAX_ENTRIES, now = () => Date.now() } = {}) {+ this.max = max;+ this.now = now;+ this.rows = new Map();+ }++ get size() {+ return this.rows.size;+ }++ /**+ * @param {{ client: string|null, channel: string|null, reason: string }} denial+ */+ record({ client = null, channel = null, reason }) {+ const row = {+ client: typeof client === 'string' && client !== '' ? client : null,+ prefix: channelPrefix(channel),+ reason: typeof reason === 'string' && REASON_PATTERN.test(reason) ? reason : 'other',+ };+ const key = JSON.stringify([row.client, row.prefix, row.reason]);+ const existing = this.rows.get(key);+ if (existing) {+ existing.count += 1;+ existing.lastAt = this.now();+ return;+ }+ if (this.rows.size >= this.max) {+ this.evict();+ }+ this.rows.set(key, { ...row, count: 1, lastAt: this.now() });+ }++ /** Drops the row with the lowest count (the oldest among equals). */+ evict() {+ let victim = null;+ let lowest = Infinity;+ for (const [key, row] of this.rows) {+ if (row.count < lowest) {+ lowest = row.count;+ victim = key;+ }+ }+ this.rows.delete(victim);+ }++ /**+ * @returns {{ client: string|null, prefix: string|null, reason: string, count: number, last_at: string }[]}+ */+ top(limit = DEFAULT_TOP) {+ return [...this.rows.values()]+ .sort((a, b) => b.count - a.count || b.lastAt - a.lastAt)+ .slice(0, limit)+ .map((row) => ({+ client: row.client,+ prefix: row.prefix,+ reason: row.reason,+ count: row.count,+ last_at: new Date(row.lastAt).toISOString(),+ }));+ }+}++module.exports = { Denials, channelPrefix, DEFAULT_MAX_ENTRIES, DEFAULT_TOP };diff --git a/socket/lib/internal.js b/socket/lib/internal.jsindex 2dca1977..a91b5e86 100644--- a/socket/lib/internal.js+++ b/socket/lib/internal.js@@ -8,7 +8,12 @@* body {"channels": ["order.x", "company.y"], "data": {...}}* or {"channel": "order.x", "data": {...}}* 202 {"published": n} | 400 bad body | 401 bad signature | 413 body over 2 MB- * GET /stats signed with the publish key (empty body) -> counters JSON+ * GET /stats signed with the publish key (empty body) -> counters, the runtime config+ * and aggregated denials as JSON+ *+ * Both answer 503 when no SOCKETCLUSTER_AUTH_KEY is configured. With a key they work whether+ * or not socket auth is switched on, so the API can read /stats and switch publishing to+ * this endpoint the moment its own switch flips, before the socket server's next config poll.*/const { verifyRequest } = require('./signing');@@ -115,7 +120,7 @@ function parsePublishBody(raw) {* @param {object} options* @param {object} options.config* @param {object} options.agServer- * @param {string|null} options.publishKey null when auth is disabled+ * @param {string|null} options.publishKey null when no auth key is configured* @param {import('./stats').Stats} options.stats* @param {object} options.logger* @param {() => object} options.gauges live values merged into /stats@@ -133,7 +138,7 @@ function createInternalHandler({ agServer, publishKey, stats, logger, gauges = (return null;}if (!publishKey) {- sendJson(res, 503, { error: 'auth_disabled' });+ sendJson(res, 503, { error: 'auth_key_missing' });return null;}const verdict = verifyRequest(publishKey, {diff --git a/socket/lib/middleware.js b/socket/lib/middleware.jsindex fc35668c..d05b9b61 100644--- a/socket/lib/middleware.js+++ b/socket/lib/middleware.js@@ -71,17 +71,34 @@ class SocketAuthPolicy {* @param {import('./authorizer').Authorizer|null} options.authorizer null when auth is disabled* @param {object} options.logger* @param {import('./stats').Stats} options.stats+ * @param {import('./denials').Denials} [options.denials] aggregated for /stats*/- constructor({ config, authorizer, logger, stats }) {+ constructor({ config, authorizer, logger, stats, denials = null }) {this.mode = config.mode;this.authEnabled = config.authEnabled;this.authorizer = authorizer;this.logger = logger;this.stats = stats;+ this.denials = denials;this.clientTags = new WeakMap();this.identities = new WeakMap();}+ /**+ * Applies a runtime config change (see lib/runtime.js). Takes effect for the next+ * action on every socket.+ */+ update({ mode, enabled }) {+ this.mode = mode;+ this.authEnabled = enabled;+ }++ recordDenial(socket, channel, reason) {+ if (this.denials) {+ this.denials.record({ client: this.clientOf(socket), channel, reason });+ }+ }+clientOf(socket) {if (!socket || typeof socket !== 'object') {return null;@@ -97,6 +114,7 @@ class SocketAuthPolicy {*/logDeny({ socket, claims, channel = null, reason, action }) {this.stats.increment(this.mode === 'enforce' ? 'denied' : 'would_deny');+ this.recordDenial(socket, channel, reason);this.logger.info({event: 'socket_auth_deny',kind: claims ? claims.kind || null : null,@@ -170,6 +188,7 @@ class SocketAuthPolicy {return settle(action, 'allow');}this.stats.increment('tokens_rejected');+ this.recordDenial(action.socket, null, reason);this.logger.info({event: 'socket_auth_deny',kind: claims ? claims.kind || null : null,diff --git a/socket/lib/runtime.js b/socket/lib/runtime.jsnew file mode 100644index 00000000..6fc82827--- /dev/null+++ b/socket/lib/runtime.js@@ -0,0 +1,133 @@+'use strict';++/**+ * The part of the configuration that can change while the server runs: whether socket auth+ * is switched on, the mode, and the allowed origins.+ *+ * The environment gives the starting values. When a key is configured the server polls the+ * API's socket config endpoint (lib/config-poller.js) and every good answer replaces them;+ * when the API cannot be reached the last good answer stays in force. Listeners registered+ * with onChange() apply a change to SocketCluster and the auth policy (see lib/app.js).+ */++const { MODES, envOrigins } = require('./config');++const MAX_ORIGINS_LENGTH = 4096;++/**+ * Validates a config response from the API: `{enabled, mode, origins, updated_at}`.+ * `mode` and `origins` may be null, meaning "use the socket server's environment".+ *+ * @returns {{ ok: true, value: { enabled: boolean, mode: string|null, origins: string|null } } | { ok: false }}+ */+function parseRemoteConfig(payload) {+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {+ return { ok: false };+ }+ if (typeof payload.enabled !== 'boolean') {+ return { ok: false };+ }+ let mode = null;+ if (payload.mode !== undefined && payload.mode !== null) {+ if (typeof payload.mode !== 'string' || !MODES.includes(payload.mode)) {+ return { ok: false };+ }+ mode = payload.mode;+ }+ let origins = null;+ if (payload.origins !== undefined && payload.origins !== null) {+ // eslint-disable-next-line no-control-regex+ if (typeof payload.origins !== 'string' || payload.origins.length > MAX_ORIGINS_LENGTH || /[\u0000-\u001f\u007f]/.test(payload.origins)) {+ return { ok: false };+ }+ origins = payload.origins.trim() === '' ? null : payload.origins.trim();+ }+ return { ok: true, value: { enabled: payload.enabled, mode, origins } };+}++function sameOrigins(a, b) {+ return JSON.stringify(a) === JSON.stringify(b);+}++class RuntimeConfig {+ /**+ * @param {ReturnType<import('./config').loadConfig>} config+ * @param {{ now?: () => number }} [options]+ */+ constructor(config, { now = () => Date.now() } = {}) {+ this.now = now;+ this.keyConfigured = config.authKey !== null;+ this.requestedMode = config.requestedMode || null;+ this.envOrigins = envOrigins(config);+ this.state = Object.freeze({ enabled: config.authEnabled, mode: config.mode, origins: this.envOrigins });+ this.source = 'env';+ this.lastSyncAt = null;+ this.lastSyncError = null;+ this.listeners = [];+ }++ get enabled() {+ return this.state.enabled;+ }++ get mode() {+ return this.state.mode;+ }++ get origins() {+ return this.state.origins;+ }++ /**+ * @param {(next: object, previous: object) => void} listener+ */+ onChange(listener) {+ this.listeners.push(listener);+ }++ /**+ * Applies a validated remote config. Auth can only be on when this server has a key;+ * a remote `mode` of null falls back to SOCKETCLUSTER_AUTH_MODE, then `enforce`.+ *+ * @returns {boolean} whether anything changed+ */+ applyRemote(remote) {+ const enabled = this.keyConfigured && remote.enabled === true;+ const mode = enabled ? remote.mode || this.requestedMode || 'enforce' : 'off';+ const origins = remote.origins === null ? this.envOrigins : remote.origins;++ this.source = 'api';+ this.lastSyncAt = this.now();+ this.lastSyncError = null;++ const previous = this.state;+ if (previous.enabled === enabled && previous.mode === mode && sameOrigins(previous.origins, origins)) {+ return false;+ }+ this.state = Object.freeze({ enabled, mode, origins });+ for (const listener of this.listeners) {+ listener(this.state, previous);+ }+ return true;+ }++ /**+ * Records a failed sync. The current values (env or the last good remote config) stay.+ */+ recordFailure(reason) {+ this.lastSyncError = reason;+ }++ snapshot() {+ return {+ enabled: this.state.enabled,+ mode: this.state.mode,+ origins: this.state.origins,+ source: this.source,+ last_sync_at: this.lastSyncAt === null ? null : new Date(this.lastSyncAt).toISOString(),+ last_sync_error: this.lastSyncError,+ };+ }+}++module.exports = { RuntimeConfig, parseRemoteConfig, MAX_ORIGINS_LENGTH };diff --git a/socket/server.js b/socket/server.jsindex 6ec997a2..dbc96756 100644--- a/socket/server.js+++ b/socket/server.js@@ -6,6 +6,9 @@* Public listener (SOCKETCLUSTER_PORT, default 8000): GET /health-check, WebSocket at /socketcluster/* Internal listener (SOCKETCLUSTER_INTERNAL_PORT, 8001): signed POST /publish, signed GET /stats*+ * With SOCKETCLUSTER_AUTH_KEY set, the server polls the API's socket config endpoint and+ * applies enabled/mode/origins changes made in the console without a restart.+ ** See README.md for every environment variable and the auth modes.*/@@ -52,7 +55,9 @@ async function main() {mode: config.mode,auth_enabled: config.authEnabled,client_publish: config.mode !== 'enforce',- authorize_url: config.authEnabled ? redactUrl(config.authorizeUrl) : null,+ authorize_url: config.authKey !== null ? redactUrl(config.authorizeUrl) : null,+ config_url: server.poller ? redactUrl(config.configUrl) : null,+ config_poll_seconds: server.poller ? config.configPollSeconds : 0,scc: Boolean(config.scc.stateServerHost),});diff --git a/socket/test/config-poller.test.js b/socket/test/config-poller.test.jsnew file mode 100644index 00000000..e598df33--- /dev/null+++ b/socket/test/config-poller.test.js@@ -0,0 +1,181 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const { ConfigPoller } = require('../lib/config-poller');+const { RuntimeConfig } = require('../lib/runtime');+const { loadConfig } = require('../lib/config');+const { Stats } = require('../lib/stats');+const { deriveKey, verifyRequest, PURPOSE_AUTHORIZE } = require('../lib/signing');+const { captureLogger, delay, waitFor } = require('./helpers');++const KEY = 'k'.repeat(32);+const AUTHORIZE_KEY = deriveKey(KEY, PURPOSE_AUTHORIZE);+const URL_ = 'http://api.test/int/v1/socket/config';++function jsonResponse(payload, status = 200) {+ return {+ ok: status >= 200 && status < 300,+ status,+ json: async () => payload,+ text: async () => JSON.stringify(payload),+ };+}++function setup(fetchImpl, overrides = {}) {+ const runtime = new RuntimeConfig(loadConfig({ SOCKETCLUSTER_AUTH_KEY: KEY }));+ const { records, logger } = captureLogger();+ const stats = new Stats();+ const poller = new ConfigPoller({ url: URL_, authorizeKey: AUTHORIZE_KEY, intervalMs: 10, runtime, logger, fetch: fetchImpl, stats, ...overrides });+ return { runtime, poller, logs: records, stats };+}++test('the constructor requires a url, a key and a positive interval', () => {+ const runtime = new RuntimeConfig(loadConfig({}));+ const base = { url: URL_, authorizeKey: AUTHORIZE_KEY, intervalMs: 10, runtime, logger: captureLogger().logger };+ assert.throws(() => new ConfigPoller({ ...base, url: '' }), /url/);+ assert.throws(() => new ConfigPoller({ ...base, authorizeKey: '' }), /authorizeKey/);+ assert.throws(() => new ConfigPoller({ ...base, intervalMs: 0 }), /intervalMs/);+ assert.throws(() => new ConfigPoller(), /url/);+ assert.equal(new ConfigPoller(base).stats, null);+});++test('a poll is a signed GET with an empty body, and a good answer is applied', async () => {+ const requests = [];+ const { runtime, poller, logs, stats } = setup(async (url, init) => {+ requests.push({ url, init });+ return jsonResponse({ enabled: true, mode: 'log', origins: 'console.example:*', updated_at: null });+ });++ assert.deepEqual(await poller.poll(), { ok: true, changed: true });+ assert.equal(requests[0].url, URL_);+ assert.equal(requests[0].init.method, 'GET');+ assert.equal(requests[0].init.body, undefined);+ const verdict = verifyRequest(AUTHORIZE_KEY, {+ timestamp: requests[0].init.headers['X-Fleetbase-Timestamp'],+ signature: requests[0].init.headers['X-Fleetbase-Signature'],+ rawBody: '',+ });+ assert.equal(verdict.ok, true);++ assert.equal(runtime.mode, 'log');+ assert.equal(runtime.origins, 'console.example:*');+ const applied = logs.find((record) => record.event === 'socket_config_applied');+ assert.deepEqual(+ { enabled: applied.enabled, mode: applied.mode, previous_mode: applied.previous_mode, source: applied.source },+ { enabled: true, mode: 'log', previous_mode: 'off', source: 'api' }+ );+ assert.equal(JSON.stringify(logs).includes(KEY), false);++ assert.deepEqual(await poller.poll(), { ok: true, changed: false });+ assert.equal(logs.filter((record) => record.event === 'socket_config_applied').length, 1);+ assert.equal(stats.get('config_polls'), 2);+});++test('failures keep the last good config and are logged once per reason', async () => {+ let answer = () => jsonResponse({ enabled: true, mode: 'log', origins: null });+ const { runtime, poller, logs, stats } = setup(async (url, init) => answer(init));+ await poller.poll();++ const cases = [+ [() => jsonResponse({ error: 'x' }, 500), 'http_500'],+ [() => jsonResponse({ enabled: 'nope' }), 'bad_response'],+ [+ () => ({+ ok: true,+ status: 200,+ json: async () => {+ throw new SyntaxError('Unexpected token');+ },+ }),+ 'bad_response',+ ],+ [+ () => {+ throw new TypeError('fetch failed');+ },+ 'unreachable',+ ],+ ];+ for (const [next, reason] of cases) {+ answer = next;+ assert.deepEqual(await poller.poll(), { ok: false, reason });+ assert.equal(runtime.mode, 'log', `${reason} keeps the last good config`);+ assert.equal(runtime.lastSyncError, reason);+ }+ assert.deepEqual(+ logs.filter((record) => record.event === 'socket_config_sync_failed').map((record) => record.reason),+ ['http_500', 'bad_response', 'unreachable'],+ 'a repeated reason is not logged again'+ );+ assert.equal(stats.get('config_poll_errors'), 4);++ answer = () => jsonResponse({ enabled: true, mode: 'log', origins: null });+ await poller.poll();+ assert.equal(runtime.lastSyncError, null);+ assert.ok(logs.some((record) => record.event === 'socket_config_sync_recovered'));+});++test('a non-200 whose body cannot be read is still a clean failure', async () => {+ const { poller } = setup(async () => ({ ok: false, status: 401, text: async () => Promise.reject(new Error('gone')) }));+ assert.deepEqual(await poller.poll(), { ok: false, reason: 'http_401' });+});++test('a slow API times out', async () => {+ const waitForAbort = (url, init) =>+ new Promise((resolve, reject) => {+ init.signal.addEventListener('abort', () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' })));+ });+ const { poller } = setup(waitForAbort, { timeoutMs: 20 });+ assert.deepEqual(await poller.poll(), { ok: false, reason: 'timeout' });++ // A body that stalls past the timeout counts as a timeout too.+ const { poller: stalled } = setup(async (url, init) => ({+ ok: true,+ status: 200,+ json: () =>+ new Promise((resolve, reject) => {+ init.signal.addEventListener('abort', () => reject(new Error('aborted')));+ }),+ }), { timeoutMs: 20 });+ assert.deepEqual(await stalled.poll(), { ok: false, reason: 'timeout' });+});++test('start() polls at once and then on the interval, never overlapping; stop() ends it', async () => {+ let active = 0;+ let maxActive = 0;+ let calls = 0;+ const { poller } = setup(async () => {+ calls += 1;+ active += 1;+ maxActive = Math.max(maxActive, active);+ await delay(15);+ active -= 1;+ return jsonResponse({ enabled: false });+ });++ poller.start();+ poller.start();+ assert.equal(calls, 1, 'the first poll runs immediately, once');+ await waitFor(() => calls >= 4, 2000, 'repeated polls');+ assert.equal(maxActive, 1);++ await poller.stop();+ const stoppedAt = calls;+ await delay(60);+ assert.equal(calls, stoppedAt);+ assert.equal(poller.timer, null);+ await poller.stop();+});++test('the default fetch is the global fetch', async () => {+ const original = globalThis.fetch;+ globalThis.fetch = async () => jsonResponse({ enabled: true, mode: 'enforce' });+ try {+ const { runtime, poller } = setup(undefined);+ await poller.poll();+ assert.equal(runtime.mode, 'enforce');+ } finally {+ globalThis.fetch = original;+ }+});diff --git a/socket/test/config.test.js b/socket/test/config.test.jsindex c11c88d2..87a7793b 100644--- a/socket/test/config.test.js+++ b/socket/test/config.test.js@@ -2,7 +2,7 @@const test = require('node:test');const assert = require('node:assert/strict');-const { loadConfig, resolveMode, buildServerOptions, parseSwitch, ConfigError, DEFAULT_AUTHORIZE_URL } = require('../lib/config');+const { loadConfig, resolveMode, buildServerOptions, parseSwitch, ConfigError, DEFAULT_AUTHORIZE_URL, envOrigins } = require('../lib/config');const KEY = 'k'.repeat(32);@@ -53,9 +53,10 @@ test('the switch keeps auth off by default, even with a key and a mode', () => {// An unknown mode is still a configuration error while switched off.assert.throws(() => loadConfig({ SOCKETCLUSTER_AUTH_MODE: 'strict' }), ConfigError);- // The key is not handed to SocketCluster while auth is off, and clients may publish.+ // The key is handed to SocketCluster even while auth is off, so tokens verify as soon as+ // the API's config switches auth on at runtime. Clients may publish while off.const options = buildServerOptions(keyed);- assert.equal(options.authKey, undefined);+ assert.equal(options.authKey, KEY);assert.equal(options.allowClientPublish, true);});@@ -155,3 +156,42 @@ test('SCC settings are read from the environment', () => {assert.equal(config.scc.stateServerPort, 7777);assert.equal(config.scc.clientPoolSize, null);});++test('the config URL defaults to the authorize URL with /authorize replaced by /config', () => {+ assert.equal(loadConfig({}).configUrl, 'http://application:8000/int/v1/socket/config');+ assert.equal(loadConfig({ SOCKETCLUSTER_AUTHORIZE_URL: 'https://api.internal/int/v1/socket/authorize/?x=1' }).configUrl, 'https://api.internal/int/v1/socket/config');+ assert.equal(loadConfig({ SOCKETCLUSTER_CONFIG_URL: ' https://api.internal/custom/config ' }).configUrl, 'https://api.internal/custom/config');+ assert.throws(() => loadConfig({ SOCKETCLUSTER_CONFIG_URL: 'not a url' }), ConfigError);+ assert.throws(() => loadConfig({ SOCKETCLUSTER_CONFIG_URL: 'ftp://x/config' }), ConfigError);+});++test('an authorize URL that does not end in /authorize leaves the config URL unset', () => {+ const keyed = loadConfig({ SOCKETCLUSTER_AUTH_KEY: KEY, SOCKETCLUSTER_AUTHORIZE_URL: 'https://api.internal/socket-auth' });+ assert.equal(keyed.configUrl, null);+ assert.ok(keyed.warnings.some((w) => w.includes('SOCKETCLUSTER_CONFIG_URL')));++ // Without a key there is no polling, so no warning about it either.+ const keyless = loadConfig({ SOCKETCLUSTER_AUTHORIZE_URL: 'https://api.internal/socket-auth' });+ assert.equal(keyless.configUrl, null);+ assert.equal(keyless.warnings.some((w) => w.includes('SOCKETCLUSTER_CONFIG_URL')), false);+});++test('the config poll interval defaults to 30 seconds; 0 disables polling', () => {+ assert.equal(loadConfig({}).configPollSeconds, 30);+ assert.equal(loadConfig({ SOCKETCLUSTER_CONFIG_POLL_SECONDS: '0' }).configPollSeconds, 0);+ assert.equal(loadConfig({ SOCKETCLUSTER_CONFIG_POLL_SECONDS: '5' }).configPollSeconds, 5);+ assert.throws(() => loadConfig({ SOCKETCLUSTER_CONFIG_POLL_SECONDS: '-1' }), ConfigError);+ assert.throws(() => loadConfig({ SOCKETCLUSTER_CONFIG_POLL_SECONDS: 'often' }), ConfigError);+});++test('the requested mode is kept for runtime use, even while switched off', () => {+ assert.equal(loadConfig({}).requestedMode, null);+ assert.equal(loadConfig({ SOCKETCLUSTER_AUTH_KEY: KEY, SOCKETCLUSTER_AUTH_MODE: ' LOG ' }).requestedMode, 'log');+});++test('envOrigins reads SOCKETCLUSTER_OPTIONS.origins, else the SocketCluster default', () => {+ assert.equal(envOrigins(loadConfig({})), '*:*');+ assert.equal(envOrigins(loadConfig({ SOCKETCLUSTER_OPTIONS: '{"origins":"a.example:*"}' })), 'a.example:*');+ assert.deepEqual(envOrigins(loadConfig({ SOCKETCLUSTER_OPTIONS: '{"origins":["a.example:*"]}' })), ['a.example:*']);+ assert.equal(envOrigins(loadConfig({ SOCKETCLUSTER_OPTIONS: '{"origins":42}' })), '*:*');+});diff --git a/socket/test/denials.test.js b/socket/test/denials.test.jsnew file mode 100644index 00000000..374141a1--- /dev/null+++ b/socket/test/denials.test.js@@ -0,0 +1,64 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const { Denials, channelPrefix, DEFAULT_TOP } = require('../lib/denials');++test('channelPrefix keeps the channel family and never an id', () => {+ assert.equal(channelPrefix('order.order_abc123'), 'order');+ assert.equal(channelPrefix('Company.x'), 'company');+ assert.equal(channelPrefix('install.company-uuid.ext'), 'install');+ assert.equal(channelPrefix('fleetbase.install'), 'fleetbase');+ assert.equal(channelPrefix('order_abc123'), 'other', 'no dot: the whole name may be an id');+ assert.equal(channelPrefix(`${'a'.repeat(40)}.x`), 'other');+ assert.equal(channelPrefix('9abc.x'), 'other');+ assert.equal(channelPrefix('.x'), 'other');+ assert.equal(channelPrefix(''), null);+ assert.equal(channelPrefix(null), null);+ assert.equal(channelPrefix(42), null);+});++test('denials are aggregated by client, prefix and reason', () => {+ let clock = Date.UTC(2026, 9, 15);+ const denials = new Denials({ now: () => clock });+ denials.record({ client: 'console/1.0', channel: 'order.a', reason: 'not_found' });+ clock += 1000;+ denials.record({ client: 'console/1.0', channel: 'order.b', reason: 'not_found' });+ denials.record({ client: 'console/1.0', channel: 'company.c', reason: 'not_found' });+ denials.record({ client: null, channel: null, reason: 'bad_iss' });+ denials.record({ client: '', channel: 'x.y', reason: 'Not A Reason!' });+ denials.record({ channel: 'x.y', reason: 'no_token' });++ assert.equal(denials.size, 5);+ const [first, ...rest] = denials.top();+ assert.deepEqual(first, { client: 'console/1.0', prefix: 'order', reason: 'not_found', count: 2, last_at: new Date(clock).toISOString() });+ assert.equal(rest.length, 4);+ assert.ok(rest.some((row) => row.client === null && row.prefix === null && row.reason === 'bad_iss'));+ assert.ok(rest.some((row) => row.client === null && row.prefix === 'x' && row.reason === 'other'));+});++test('top() sorts by count, then most recent, and is limited', () => {+ let clock = 0;+ const denials = new Denials({ now: () => ++clock });+ for (let i = 0; i < DEFAULT_TOP + 10; i += 1) {+ denials.record({ client: `c${i}`, channel: 'order.x', reason: 'not_found' });+ }+ denials.record({ client: 'c3', channel: 'order.x', reason: 'not_found' });+ const top = denials.top();+ assert.equal(top.length, DEFAULT_TOP);+ assert.equal(top[0].client, 'c3');+ assert.equal(top[1].client, `c${DEFAULT_TOP + 9}`, 'ties: most recent first');+ assert.equal(denials.top(2).length, 2);+});++test('the number of rows is capped by evicting the least frequent', () => {+ const denials = new Denials({ max: 3 });+ denials.record({ client: 'a', channel: 'order.x', reason: 'r' });+ denials.record({ client: 'a', channel: 'order.x', reason: 'r' });+ denials.record({ client: 'b', channel: 'order.x', reason: 'r' });+ denials.record({ client: 'c', channel: 'order.x', reason: 'r' });+ denials.record({ client: 'c', channel: 'order.x', reason: 'r' });+ denials.record({ client: 'd', channel: 'order.x', reason: 'r' });+ assert.equal(denials.size, 3);+ assert.deepEqual(denials.top().map((row) => row.client).sort(), ['a', 'c', 'd']);+});diff --git a/socket/test/helpers.js b/socket/test/helpers.jsindex 68f0afd5..fa8c2858 100644--- a/socket/test/helpers.js+++ b/socket/test/helpers.js@@ -90,14 +90,41 @@ function memoryAuthEngine(initialToken = null) {};}+const DEFAULT_REMOTE_CONFIG = () => ({ enabled: true, mode: null, origins: null, updated_at: null });+/**- * A stand-in for the API authorize endpoint. `decide(body)` returns the JSON response- * (or { status, body } for a non-200); it may be async to simulate a slow API.+ * A stand-in for the API's socket endpoints, both signed with the authorize key:+ * - POST .../authorize: `decide(body)` returns the JSON response (or { status, body } for a+ * non-200); it may be async to simulate a slow API. Calls are recorded in `calls`.+ * - GET .../config: `remoteConfig()` returns the JSON response, { status, body }, or+ * 'hangup' to drop the connection. Calls are recorded in `configCalls`.*/-async function startFakeAuthorizer(decide) {+async function startFakeAuthorizer(decide, remoteConfig = DEFAULT_REMOTE_CONFIG) {const calls = [];+ const configCalls = [];const authorizeKey = deriveKey(AUTH_KEY, PURPOSE_AUTHORIZE);const server = http.createServer((req, res) => {+ if (req.url.split('?')[0].endsWith('/config')) {+ req.resume();+ req.on('end', () => {+ const verdict = verifyRequest(authorizeKey, {+ timestamp: req.headers['x-fleetbase-timestamp'],+ signature: req.headers['x-fleetbase-signature'],+ rawBody: '',+ });+ configCalls.push({ method: req.method, signatureOk: verdict.ok });+ const result = verdict.ok ? remoteConfig() : { status: 401, body: { error: 'invalid_signature' } };+ if (result === 'hangup') {+ res.destroy();+ return;+ }+ const status = result && result.status ? result.status : 200;+ const payload = result && result.status ? result.body : result;+ res.writeHead(status, { 'Content-Type': 'application/json' });+ res.end(JSON.stringify(payload));+ });+ return;+ }const chunks = [];req.on('data', (chunk) => chunks.push(chunk));req.on('end', async () => {@@ -139,6 +166,7 @@ async function startFakeAuthorizer(decide) {return {url: `http://127.0.0.1:${port}/int/v1/socket/authorize`,calls,+ configCalls,close: () =>new Promise((resolve) => {server.close(() => resolve());@@ -151,9 +179,12 @@ const denyEverything = () => ({ allow: false, ttl: 30, reason: 'not_allowed' });/*** Starts a real socket server on ephemeral ports with a fake authorize endpoint.+ *+ * Config polling is off unless `remoteConfig` is given: then the server polls the fake+ * config endpoint every `pollIntervalMs` (default 50 ms).*/-async function startServer({ env = {}, decide = denyEverything, authorizeTimeoutMs } = {}) {- const fake = await startFakeAuthorizer(decide);+async function startServer({ env = {}, decide = denyEverything, authorizeTimeoutMs, remoteConfig, pollIntervalMs = 50 } = {}) {+ const fake = await startFakeAuthorizer(decide, remoteConfig);const config = loadConfig({SOCKETCLUSTER_PORT: '0',SOCKETCLUSTER_INTERNAL_PORT: '0',@@ -163,16 +194,16 @@ async function startServer({ env = {}, decide = denyEverything, authorizeTimeout...env,});const { records, logger } = captureLogger();- const server = createSocketServer(config, { logger, authorizeTimeoutMs });+ const server = createSocketServer(config, { logger, authorizeTimeoutMs, configPollIntervalMs: remoteConfig ? pollIntervalMs : 0 });const { port, internalPort } = await server.start();const clients = [];- async function connect({ token = null, query = {} } = {}) {+ async function connect({ token = null, query = {}, autoReconnect = false } = {}) {const socket = socketClusterClient.create({hostname: '127.0.0.1',port,path: '/socketcluster/',- autoReconnect: false,+ autoReconnect,ackTimeout: 5000,authEngine: memoryAuthEngine(token),query: { client: 'test/1.0', ...query },@@ -206,7 +237,63 @@ async function startServer({ env = {}, decide = denyEverything, authorizeTimeoutawait fake.close();}- return { port, internalPort, config, server, logs: records, fake, connect, internalRequest, close };+ async function stats() {+ const response = await internalRequest('/stats', { method: 'GET' });+ assertOk(response.status === 200, `GET /stats answered ${response.status}`);+ return response.json();+ }++ return { port, internalPort, config, server, logs: records, fake, connect, internalRequest, stats, close };+}++function assertOk(condition, message) {+ if (!condition) {+ throw new Error(message);+ }+}++/** Resolves once `predicate()` is truthy, polling every 10 ms. */+function waitFor(predicate, ms = 3000, label = 'condition') {+ return withTimeout(+ (async () => {+ while (!(await predicate())) {+ await delay(10);+ }+ })(),+ ms,+ label+ );+}++/**+ * Attempts a raw websocket handshake with the given Origin header and resolves with the+ * HTTP status: 101 when SocketCluster accepts the origin, 403 when it refuses it.+ */+function handshakeStatus(port, origin) {+ return new Promise((resolve, reject) => {+ const req = http.request({+ host: '127.0.0.1',+ port,+ path: '/socketcluster/',+ headers: {+ Connection: 'Upgrade',+ Upgrade: 'websocket',+ 'Sec-WebSocket-Version': '13',+ 'Sec-WebSocket-Key': crypto.randomBytes(16).toString('base64'),+ Origin: origin,+ },+ });+ req.on('upgrade', (res, socket) => {+ socket.destroy();+ resolve(res.statusCode);+ });+ req.on('response', (res) => {+ res.resume();+ resolve(res.statusCode);+ });+ req.on('error', reject);+ req.end();+ });}/**@@ -232,6 +319,8 @@ module.exports = {nowSeconds,withTimeout,delay,+ waitFor,+ handshakeStatus,captureLogger,memoryAuthEngine,startFakeAuthorizer,diff --git a/socket/test/runtime.test.js b/socket/test/runtime.test.jsnew file mode 100644index 00000000..67b20be8--- /dev/null+++ b/socket/test/runtime.test.js@@ -0,0 +1,120 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const { loadConfig } = require('../lib/config');+const { RuntimeConfig, parseRemoteConfig, MAX_ORIGINS_LENGTH } = require('../lib/runtime');++const KEY = 'k'.repeat(32);++function runtimeFor(env, now = () => Date.UTC(2026, 9, 15)) {+ return new RuntimeConfig(loadConfig(env), { now });+}++test('parseRemoteConfig accepts the API shape, with null meaning "use the environment"', () => {+ assert.deepEqual(parseRemoteConfig({ enabled: true, mode: 'log', origins: 'a.example:*', updated_at: 'x' }), {+ ok: true,+ value: { enabled: true, mode: 'log', origins: 'a.example:*' },+ });+ assert.deepEqual(parseRemoteConfig({ enabled: false }), { ok: true, value: { enabled: false, mode: null, origins: null } });+ assert.deepEqual(parseRemoteConfig({ enabled: true, mode: null, origins: ' ' }).value, { enabled: true, mode: null, origins: null });+ assert.equal(parseRemoteConfig({ enabled: true, origins: ' b.example:* ' }).value.origins, 'b.example:*');+});++test('parseRemoteConfig rejects anything else', () => {+ for (const payload of [+ null,+ 'enabled',+ [],+ {},+ { enabled: 'true' },+ { enabled: true, mode: 'strict' },+ { enabled: true, mode: 1 },+ { enabled: true, origins: 42 },+ { enabled: true, origins: 'a\nb' },+ { enabled: true, origins: 'a'.repeat(MAX_ORIGINS_LENGTH + 1) },+ ]) {+ assert.deepEqual(parseRemoteConfig(payload), { ok: false }, JSON.stringify(payload));+ }+});++test('the environment is the starting config', () => {+ const runtime = runtimeFor({ SOCKETCLUSTER_AUTH_ENABLED: 'true', SOCKETCLUSTER_AUTH_KEY: KEY, SOCKETCLUSTER_OPTIONS: '{"origins":"env.example:*"}' });+ assert.equal(runtime.enabled, true);+ assert.equal(runtime.mode, 'enforce');+ assert.equal(runtime.origins, 'env.example:*');+ assert.deepEqual(runtime.snapshot(), { enabled: true, mode: 'enforce', origins: 'env.example:*', source: 'env', last_sync_at: null, last_sync_error: null });+});++test('applyRemote: enabled with a mode, a null mode falling back to the env mode, then enforce', () => {+ const logEnv = runtimeFor({ SOCKETCLUSTER_AUTH_KEY: KEY, SOCKETCLUSTER_AUTH_MODE: 'log' });+ assert.equal(logEnv.mode, 'off');+ assert.equal(logEnv.applyRemote({ enabled: true, mode: null, origins: null }), true);+ assert.equal(logEnv.mode, 'log');+ logEnv.applyRemote({ enabled: true, mode: 'enforce', origins: null });+ assert.equal(logEnv.mode, 'enforce');++ const bare = runtimeFor({ SOCKETCLUSTER_AUTH_KEY: KEY });+ bare.applyRemote({ enabled: true, mode: null, origins: null });+ assert.equal(bare.enabled, true);+ assert.equal(bare.mode, 'enforce');+});++test('applyRemote: disabled forces off whatever the mode; no key never enables', () => {+ const runtime = runtimeFor({ SOCKETCLUSTER_AUTH_ENABLED: 'true', SOCKETCLUSTER_AUTH_KEY: KEY });+ runtime.applyRemote({ enabled: false, mode: 'enforce', origins: null });+ assert.equal(runtime.enabled, false);+ assert.equal(runtime.mode, 'off');++ const keyless = runtimeFor({});+ keyless.applyRemote({ enabled: true, mode: 'enforce', origins: null });+ assert.equal(keyless.enabled, false);+ assert.equal(keyless.mode, 'off');+});++test('applyRemote: origins override the environment until cleared', () => {+ const runtime = runtimeFor({ SOCKETCLUSTER_AUTH_KEY: KEY, SOCKETCLUSTER_OPTIONS: '{"origins":"env.example:*"}' });+ runtime.applyRemote({ enabled: false, mode: null, origins: 'console.example:*' });+ assert.equal(runtime.origins, 'console.example:*');+ runtime.applyRemote({ enabled: false, mode: null, origins: null });+ assert.equal(runtime.origins, 'env.example:*');+});++test('listeners run only when something changes, with the next and previous state', () => {+ let clock = 1000;+ const runtime = runtimeFor({ SOCKETCLUSTER_AUTH_KEY: KEY }, () => clock);+ const changes = [];+ runtime.onChange((next, previous) => changes.push([previous.mode, next.mode]));++ assert.equal(runtime.applyRemote({ enabled: false, mode: null, origins: null }), false, 'same as env');+ assert.equal(runtime.source, 'api');+ assert.equal(runtime.snapshot().last_sync_at, new Date(1000).toISOString());++ clock = 2000;+ assert.equal(runtime.applyRemote({ enabled: true, mode: 'log', origins: null }), true);+ assert.equal(runtime.applyRemote({ enabled: true, mode: 'log', origins: null }), false);+ assert.equal(runtime.applyRemote({ enabled: true, mode: 'log', origins: 'x.example:*' }), true);+ assert.deepEqual(changes, [+ ['off', 'log'],+ ['log', 'log'],+ ]);+ assert.equal(runtime.snapshot().last_sync_at, new Date(2000).toISOString());+});++test('a failed sync keeps the current config and is reported until the next good one', () => {+ const runtime = runtimeFor({ SOCKETCLUSTER_AUTH_KEY: KEY });+ runtime.applyRemote({ enabled: true, mode: 'log', origins: null });+ runtime.recordFailure('timeout');+ assert.equal(runtime.mode, 'log');+ assert.equal(runtime.snapshot().last_sync_error, 'timeout');+ assert.equal(runtime.snapshot().source, 'api');+ runtime.applyRemote({ enabled: true, mode: 'log', origins: null });+ assert.equal(runtime.snapshot().last_sync_error, null);+});++test('the clock defaults to Date.now', () => {+ const runtime = new RuntimeConfig(loadConfig({ SOCKETCLUSTER_AUTH_KEY: KEY }));+ const before = Date.now();+ runtime.applyRemote({ enabled: true, mode: null, origins: null });+ assert.ok(Date.parse(runtime.snapshot().last_sync_at) >= before - 1000);+});diff --git a/socket/test/server.test.js b/socket/test/server.test.jsindex 07543589..a56fcfab 100644--- a/socket/test/server.test.js+++ b/socket/test/server.test.js@@ -8,7 +8,8 @@const test = require('node:test');const assert = require('node:assert/strict');const http = require('http');-const { startServer, signJwt, userClaims, nowSeconds, trySubscribe, withTimeout, delay, AUTH_KEY } = require('./helpers');+const { startServer, signJwt, userClaims, nowSeconds, trySubscribe, withTimeout, delay, waitFor, handshakeStatus, AUTH_KEY } = require('./helpers');+const { ENFORCE_RECONNECT_CODE } = require('../lib/app');const { deriveKey, PURPOSE_AUTHORIZE } = require('../lib/signing');const allowOrders = (body) =>@@ -209,10 +210,26 @@ test('switched off with a key and enforce requested: everything is allowed, as bassert.equal(env.fake.calls.length, 0);assert.equal(denyLogs(env.logs).length, 0);- // The signed internal publish endpoint stays closed until the switch is on.+ // With a key the signed internal publish endpoint is open even while the switch is off,+ // so the API can publish through it as soon as its own switch flips, before this+ // server's next config poll. Unsigned requests are still refused.const publish = await env.internalRequest('/publish', { body: { channels: ['order.anything'], data: {} } });- assert.equal(publish.status, 503);+ assert.equal(publish.status, 202);await publish.text();+ const unsigned = await env.internalRequest('/publish', { body: { channels: ['order.anything'], data: {} }, key: null });+ assert.equal(unsigned.status, 401);+ await unsigned.text();+});++test('switched off with a key: tokens are verified, so auth can be switched on at runtime', async (t) => {+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_ENABLED: 'false' } });+ t.after(() => env.close());++ const { socket, status } = await env.connect({ token: signJwt(userClaims()) });+ assert.equal(status.isAuthenticated, true, 'the key reaches SocketCluster whenever one is configured');+ assert.equal((await trySubscribe(socket, 'order.not_mine')).ok, true);+ assert.equal(env.fake.calls.length, 0);+ assert.equal(env.server.poller, null, 'polling is off in this test');});test('off mode with a key: tokens are verified but nothing is denied', async (t) => {@@ -448,6 +465,8 @@ test('GET /stats is signed and reports counters', async (t) => {assert.equal(stats.counters.publish_requests, 1);assert.equal(stats.counters.internal_unauthorized, 1);assert.equal(typeof stats.uptime_seconds, 'number');+ assert.deepEqual(stats.config, { enabled: true, mode: 'enforce', origins: '*:*', source: 'env', last_sync_at: null, last_sync_error: null });+ assert.deepEqual(stats.denials, []);const wrongMethod = await env.internalRequest('/stats', { method: 'POST' });assert.equal(wrongMethod.status, 405);@@ -465,3 +484,232 @@ test('the internal endpoints are not served on the public port', async (t) => {assert.equal(response.status, 404);await response.text();});++/*+ * Runtime config: the server polls the fake API's GET .../config every 50 ms.+ */++/** A mutable remote config the fake API serves; `set()` changes what the next poll sees. */+function remote(initial) {+ let current = initial;+ const fn = () => current;+ fn.set = (next) => {+ current = next;+ };+ return fn;+}++async function syncedAfter(env, count) {+ await waitFor(() => env.fake.configCalls.length > count && env.server.poller.current === null, 3000, 'a config poll');+}++test('config poll: changes from the API are applied without a restart', async (t) => {+ const config = remote({ enabled: true, mode: 'log', origins: null, updated_at: '2026-10-15T00:00:00Z' });+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_ENABLED: 'false' }, remoteConfig: config, decide: allowOrders });+ t.after(() => env.close());++ await waitFor(() => env.server.runtime.mode === 'log', 3000, 'log mode from the API');+ assert.ok(env.fake.configCalls.every((call) => call.method === 'GET' && call.signatureOk), 'polls are signed with the authorize key');++ let stats = await env.stats();+ assert.equal(stats.mode, 'log');+ assert.equal(stats.auth_enabled, true);+ assert.equal(stats.config.source, 'api');+ assert.equal(stats.config.enabled, true);+ assert.equal(stats.config.mode, 'log');+ assert.equal(stats.config.last_sync_error, null);+ assert.ok(Date.parse(stats.config.last_sync_at) > 0);+ assert.ok(env.logs.some((record) => record.event === 'socket_config_applied' && record.mode === 'log' && record.previous_mode === 'off'));++ // Switched off again from the console: everything is allowed and nothing is logged.+ config.set({ enabled: false, mode: 'enforce', origins: null, updated_at: null });+ await waitFor(() => env.server.runtime.mode === 'off', 3000, 'off from the API');+ stats = await env.stats();+ assert.equal(stats.auth_enabled, false);+ const { socket } = await env.connect();+ assert.equal((await trySubscribe(socket, 'order.anything')).ok, true);+ assert.equal(denyLogs(env.logs).length, 0);+});++test('config poll: an API mode of null falls back to SOCKETCLUSTER_AUTH_MODE', async (t) => {+ const env = await startServer({+ env: { SOCKETCLUSTER_AUTH_ENABLED: 'false', SOCKETCLUSTER_AUTH_MODE: 'log' },+ remoteConfig: remote({ enabled: true, mode: null, origins: null, updated_at: null }),+ });+ t.after(() => env.close());++ await waitFor(() => env.server.runtime.enabled, 3000, 'enabled from the API');+ assert.equal(env.server.runtime.mode, 'log');+});++test('config poll: an unreachable API keeps the last good config', async (t) => {+ const config = remote({ enabled: true, mode: 'log', origins: null, updated_at: null });+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_ENABLED: 'false' }, remoteConfig: config });+ t.after(() => env.close());++ await waitFor(() => env.server.runtime.mode === 'log', 3000, 'log mode from the API');++ config.set({ status: 503, body: { error: 'down' } });+ await waitFor(() => env.server.runtime.lastSyncError === 'http_503', 3000, 'a failed poll');+ let stats = await env.stats();+ assert.equal(stats.config.mode, 'log');+ assert.equal(stats.config.enabled, true);+ assert.equal(stats.config.source, 'api');+ assert.equal(stats.config.last_sync_error, 'http_503');++ config.set('hangup');+ await waitFor(() => env.server.runtime.lastSyncError === 'unreachable', 3000, 'an unreachable API');+ config.set({ enabled: 'yes', mode: 'sideways' });+ await waitFor(() => env.server.runtime.lastSyncError === 'bad_response', 3000, 'a malformed answer');+ assert.equal(env.server.runtime.mode, 'log', 'a malformed answer changes nothing');+ assert.equal(env.logs.filter((record) => record.event === 'socket_config_sync_failed').length, 3, 'one warning per distinct failure');++ // Recovery clears the error.+ config.set({ enabled: true, mode: 'log', origins: null, updated_at: null });+ await waitFor(() => env.server.runtime.lastSyncError === null, 3000, 'recovery');+ stats = await env.stats();+ assert.equal(stats.config.last_sync_error, null);+ assert.ok(stats.counters.config_poll_errors >= 3);+});++test('config poll: an API that never answered leaves the environment config in force', async (t) => {+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_MODE: 'log' }, remoteConfig: remote('hangup') });+ t.after(() => env.close());++ await waitFor(() => env.server.runtime.lastSyncError === 'unreachable', 3000, 'a failed poll');+ const stats = await env.stats();+ assert.deepEqual(+ { enabled: stats.config.enabled, mode: stats.config.mode, source: stats.config.source, last_sync_at: stats.config.last_sync_at },+ { enabled: true, mode: 'log', source: 'env', last_sync_at: null }+ );+});++test('config poll: without a key there is no polling, as before', async (t) => {+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_KEY: '' }, remoteConfig: remote({ enabled: true, mode: 'enforce', origins: null }) });+ t.after(() => env.close());++ assert.equal(env.server.poller, null);+ await delay(300);+ assert.equal(env.fake.configCalls.length, 0);+ assert.equal(env.server.runtime.mode, 'off');+ const stats = await env.internalRequest('/stats', { method: 'GET' });+ assert.equal(stats.status, 503);+ await stats.text();+});++test('config poll: enabling at runtime starts verifying and authorizing subscriptions', async (t) => {+ const config = remote({ enabled: false, mode: null, origins: null, updated_at: null });+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_ENABLED: 'false' }, remoteConfig: config, decide: allowOrders });+ t.after(() => env.close());++ await syncedAfter(env, 0);+ const token = signJwt(userClaims());+ const before = await env.connect({ token });+ assert.equal((await trySubscribe(before.socket, 'order.someone_else')).ok, true, 'off: allowed without asking');+ assert.equal(env.fake.calls.length, 0);++ // Switch on (mode null -> enforce). Sockets are disconnected once so their old+ // subscriptions are authorized again on reconnect.+ const closed = before.socket.listener('close').once();+ config.set({ enabled: true, mode: null, origins: null, updated_at: null });+ await waitFor(() => env.server.runtime.mode === 'enforce', 3000, 'enforce from the API');+ const { code } = await withTimeout(closed, 3000, 'disconnect on entering enforce');+ assert.equal(code, ENFORCE_RECONNECT_CODE);+ assert.ok(env.logs.some((record) => record.event === 'socket_reconnect_all' && record.reason === 'auth_enforced'));++ const after = await env.connect({ token });+ assert.equal(after.status.isAuthenticated, true);+ const denied = await trySubscribe(after.socket, 'order.someone_else');+ assert.equal(denied.ok, false);+ assert.equal(denied.error.reason, 'not_found');+ assert.equal((await trySubscribe(after.socket, 'order.allowed_1')).ok, true);+ assert.equal(env.fake.calls.length, 2, 'the API is asked once enabled');+ assert.ok(env.fake.calls.every((call) => call.signatureOk));++ const anonymous = await env.connect();+ assert.equal((await trySubscribe(anonymous.socket, 'company.company-uuid-1')).ok, false);++ const stats = await env.stats();+ assert.equal(stats.counters.runtime_reconnects, 1);+});++test('config poll: switching to enforce blocks client publish', async (t) => {+ const config = remote({ enabled: true, mode: 'log', origins: null, updated_at: null });+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_MODE: 'log' }, remoteConfig: config });+ t.after(() => env.close());++ await syncedAfter(env, 0);+ const first = await env.connect({ token: signJwt(userClaims()) });+ await first.socket.invokePublish('user.user-uuid-1', { x: 1 });+ assert.equal(env.server.agServer.allowClientPublish, true);++ config.set({ enabled: true, mode: 'enforce', origins: null, updated_at: null });+ await waitFor(() => env.server.runtime.mode === 'enforce', 3000, 'enforce from the API');+ assert.equal(env.server.agServer.allowClientPublish, false);++ const second = await env.connect({ token: signJwt(userClaims()) });+ await assert.rejects(second.socket.invokePublish('user.user-uuid-1', { x: 1 }), /Client publish feature is disabled/);++ // And back to log: client publish works again.+ config.set({ enabled: true, mode: 'log', origins: null, updated_at: null });+ await waitFor(() => env.server.runtime.mode === 'log', 3000, 'log from the API');+ assert.equal(env.server.agServer.allowClientPublish, true);+ await second.socket.invokePublish('user.user-uuid-1', { x: 2 });+});++test('config poll: an origins change applies to new handshakes, and null restores the environment value', async (t) => {+ const config = remote({ enabled: false, mode: null, origins: null, updated_at: null });+ const env = await startServer({+ env: { SOCKETCLUSTER_AUTH_ENABLED: 'false', SOCKETCLUSTER_OPTIONS: JSON.stringify({ origins: 'env.example.com:*' }) },+ remoteConfig: config,+ });+ t.after(() => env.close());++ await syncedAfter(env, 0);+ assert.equal(await handshakeStatus(env.port, 'https://env.example.com'), 101);+ assert.equal(await handshakeStatus(env.port, 'https://console.example.com'), 403);++ config.set({ enabled: false, mode: null, origins: 'console.example.com:*', updated_at: null });+ await waitFor(() => env.server.runtime.origins === 'console.example.com:*', 3000, 'origins from the API');+ assert.equal(await handshakeStatus(env.port, 'https://console.example.com'), 101);+ assert.equal(await handshakeStatus(env.port, 'https://env.example.com'), 403);+ assert.equal((await env.stats()).config.origins, 'console.example.com:*');++ config.set({ enabled: false, mode: null, origins: '*:*', updated_at: null });+ await waitFor(() => env.server.runtime.origins === '*:*', 3000, 'all origins from the API');+ assert.equal(await handshakeStatus(env.port, 'https://anything.example.org'), 101);++ config.set({ enabled: false, mode: null, origins: null, updated_at: null });+ await waitFor(() => env.server.runtime.origins === 'env.example.com:*', 3000, 'env origins restored');+ assert.equal(await handshakeStatus(env.port, 'https://anything.example.org'), 403);+});++test('GET /stats aggregates denials without tokens, subjects or channel ids', async (t) => {+ const env = await startServer({ env: { SOCKETCLUSTER_AUTH_MODE: 'log' }, decide: allowOrders });+ t.after(() => env.close());++ const token = signJwt(userClaims());+ const anonymous = await env.connect({ query: { client: 'navigator/2.1.0' } });+ await trySubscribe(anonymous.socket, 'order.order_secret_1');+ await trySubscribe(anonymous.socket, 'order.order_secret_2');+ await trySubscribe(anonymous.socket, 'nodotchannelid123');+ const user = await env.connect({ token });+ await trySubscribe(user.socket, 'order.someone_else_42');+ await user.socket.invokePublish('company.company-uuid-1', { x: 1 });+ await env.connect({ token: signJwt(userClaims({ iss: 'someone-else' })) });++ const stats = await env.stats();+ const rows = Object.fromEntries(stats.denials.map((row) => [`${row.client}|${row.prefix}|${row.reason}`, row]));+ assert.equal(rows['navigator/2.1.0|order|no_token'].count, 2);+ assert.equal(rows['navigator/2.1.0|other|no_token'].count, 1);+ assert.equal(rows['test/1.0|order|not_found'].count, 1);+ assert.equal(rows['test/1.0|company|client_publish_disabled'].count, 1);+ assert.equal(rows['test/1.0|null|bad_iss'].count, 1);+ assert.deepEqual(Object.keys(stats.denials[0]).sort(), ['client', 'count', 'last_at', 'prefix', 'reason']);+ assert.equal(stats.denials[0].count, 2, 'sorted by count');++ const raw = JSON.stringify(stats);+ for (const secret of [token, 'order_secret_1', 'someone_else_42', 'nodotchannelid123', 'user-uuid-1', 'company-uuid-1', 'company_abc123', AUTH_KEY]) {+ assert.equal(raw.includes(secret), false, `/stats leaks ${secret}`);+ }+});