Skip to content

Shared library @perfshop/shared-node

Status: shipped 2026-05-19 — Bricks B0 + B0bis + "Production-grade strict" mandate CLOSED 2026-05-20 (sub-sessions S1→S5c). Version: 0.2.0 · License: AGPL-3.0-or-later 4 consumers: scripts-ui, jmeter-ui, monitoring and test-ai (the authoritative list lives in shared-node/test/consumers-resolve-peers.test.js; admin, served by nginx, does not depend on it).

What's new in 0.2.0 (B0bis)

  • createSecurityHeaders({ frameOptions?, referrerPolicy?, contentTypeNosniff?, csp? }) — Express middleware that sets X-Frame-Options: DENY, X-Content-Type-Options: nosniff and Referrer-Policy: same-origin on every response. Content-Security-Policy is opt-in via opts.csp. At 0.2.0 (B0bis) CSP was not yet activated by the consumers — the UIs still injected an inline <script>. Mount at the top of the stack right after createSession.
  • dockerClient.containerLogs(name, n, opts?) — reads the last n lines of a container's stdout/stderr via GET /containers/{name}/logs (cap at 1000). Includes a timeoutMs (default 8 s) that the local helpers duplicated in jmeter-ui and monitoring were missing. Replaces both re-implementations.
  • Exported pure helper buildContainerLogsPath(name, n, timestamps?) — URL builder testable in isolation.
  • Migrated consumers: scripts-ui@2.1.x, jmeter-ui@1.1.x, monitoring@1.0.1 (partial — full Node 24 + node-fetch drop was the dedicated brick B0.1 ✅ shipped 2026-05-20 sub-session 5a Phase J — see "Sub-session 5 update" below).
  • No breaking change to the 0.1.0 surface.

Sub-session 4 update — strict CSP activated (CHANGELOG 1.5.0)

Since release 1.5.0 (2026-05-19, sub-sessions 3 then 4 "Strict commercial production"), CSP script-src 'self' is active on the 4 UIs (3 Node services + admin nginx). Prerequisites cleared:

  • Phase K.0: window.__CONFIG__ is delivered through a dedicated GET /config.js endpoint (Content-Type application/javascript) instead of a <!-- @CONFIG_INJECT@ --> sentinel rewritten on the fly. No inline script served by /.
  • Sub-session 3 Phases E + F: all JS lives in /js/*.js, all CSS in /css/*.css. No <style> nor <script> inline in any index.html.
  • Sub-session 4 Phase G: admin migrated — 15 onclick="" + 9 oninput="/onchange=" + 2 onerror="" removed. Event delegation via data-action= + addEventListener.

Canonical CSP_POLICY (9 directives)

default-src 'self';
img-src 'self' data:;
style-src 'self';
script-src 'self';
connect-src 'self';
font-src 'self';
frame-ancestors 'none';
base-uri 'self';
form-action 'self'

Zero unsafe-inline + unsafe-eval (zero-tolerance). For new UIs (test-ai B2, dataset-lab B3), wire createSecurityHeaders({ csp: CSP_POLICY }) directly from day 0 (cf. bootstrap example below).

Mandatory cross-component pin

shared-node/test/csp-policy-consistency.test.js enforces string-level consistency between the 4 sources (3 server.js + admin nginx.conf). Any policy change must be applied to the 4 sources simultaneously for the pin to stay green.

Sub-session 5 update — "Production-grade strict" mandate CLOSED (CHANGELOG 1.6.0, 2026-05-20)

Five sub-sessions (S1+S2 + S3 + S4 + S5a + S5b + S5c) brought the cluster from 0 to 461 / 461 green node:test anti-regression pins with cluster-wide lint 0/0/0. The 0.2.0 library surface is unchanged — every evolution lives at the consumer level.

Cross-platform convention file:../shared-node (Phase M)

The npm link moves from absolute Docker-only file:/shared-node to portable relative file:../shared-node. Benefits:

  • Resolves identically on host (<consumer>/../shared-node) and inside Docker (/app/../shared-node = /shared-node).
  • Fixes the "host npm install corrupts the lockfile" bug that prevented npm run lint on Windows.
  • Lets developers run npm ci --include=dev && npm run lint directly without Docker.

npm ci --omit=dev strict lockfile policy (Phases A + J + M)

All Dockerfiles and all command: bind-mount invocations now use npm ci --omit=dev (strict reproducible mode). npm install is banned — it would silently mutate the lockfile. Consequence: the lockfile MUST be regenerated inside Docker on every dependency change, via the per-consumer helpers below.

Lockfile regeneration helpers

Each Node consumer ships two cross-platform scripts:

# macOS / Linux / Git Bash
./scripts-ui/scripts/regen-lockfile.sh
./jmeter-ui/scripts/regen-lockfile.sh
./monitoring/scripts/regen-lockfile.sh

# Windows PowerShell
.\scripts-ui\scripts\regen-lockfile.ps1
.\jmeter-ui\scripts\regen-lockfile.ps1
.\monitoring\scripts\regen-lockfile.ps1

Each helper:

  1. Spawns a throwaway node:24.15.0-alpine container with shared-node/ bind-mounted at /shared-node.
  2. Runs npm install --package-lock-only --ignore-scripts which produces the canonical "../shared-node" path in the lockfile.
  3. Sanity-checks that no deep host-relative path (../../../../../shared-node) sneaked back in.

Cluster-wide anti-regression pins (461 green)

Component Pre-S5 Post-S5 Delta Notable pins
admin 46 65 +19 delete-confirm-r-ok (P.3) + modals-a11y (P.4 + R2-UX-MED-1) + emoji-aria-hidden (P.1 partial)
scripts-ui 50 105 +55 validation (26) + runs-purge + runs-id-regex (collision-safety) + dockerfile-builds + eslint-config-present
jmeter-ui 100 151 +51 jmx-parser + safe-scenario-path + scenarios-error-scope + frontend-error-console-symmetry + dockerfile-builds + eslint-config-present
monitoring 25 52 +27 no-node-fetch + docker-request-timeout (AbortController) + engines-node-24 + dockerfile-builds + eslint-config-present
shared-node 88 88 0 unchanged — 0.2.0 surface stable
Total 309 461 +152

Brick B0.1 ✅ shipped 2026-05-20 (sub-session 5a Phase J)

  • monitoring/Dockerfile node:20-alpine → node:24.15.0-alpine.
  • monitoring/package.json drops node-fetch (Node 24 exposes fetch as a global) + adds engines.node >=24 <25.
  • monitoring/src/server.js migrates loginRateLimit + chaosMetricsRateLimit inline (45 LOC) to the shared-node createRateLimit factory, and adds an AbortController + 5 s timeout on dockerRequest() (avoids freezing the metrics loop when the Docker daemon is under chaos).
  • Docker build context in docker-compose.{desktop,build}.yml moves from ./monitoring to . (repo root) so shared-node/ is COPY-able.

Enriched reference patterns

See, in the repository, memory/reference/pattern_node_ihm.md: the patterns to follow and those not to reproduce.

New positive patterns:

  • 22 file:../shared-node cross-platform

  • 23 Pure-module extraction for host testability (cf. src/lib/safe-scenario-path.js, src/lib/purge-stale-runs.js)

  • 24 Global Escape key handler + focus management modal (modals.js wireModalEscape)

  • 25 ESLint v9 flat config 3 file-type blocks + cross-file legacy script-mode globals

  • 26 t.mock.method() Node 24 for deterministic tests

New anti-patterns:

  • 44 Absolute Docker-only file:/shared-node

  • 45 npm install in Dockerfile / compose runtime

  • 46 Probabilistic "100 distinct IDs" tests without mock

  • 47 Pure logic locked behind a shared-node import chain

  • 48 Modal a11y debt (no role="dialog" + Escape + focus mgmt)

Why this library

scripts-ui and jmeter-ui were near-identical clones — same Express bootstrap, same session/CSRF/rate-limit middleware, same Docker UNIX-socket client, same server-side i18n. Cloning a third and then a fourth time — for the upcoming test-ai (brick B2) and dataset-lab (brick B3) components — would multiply the infrastructure-layer technical debt by four. @perfshop/shared-node extracts everything that is genuinely common and exposes it through small factory functions so each consumer can tune the parts that differ (cookie name, permission flag, i18n keys, public paths).

Result of the B0 migration:

  • scripts-ui/src/: 1144 → 860 LOC (-284, i.e. -25%)
  • jmeter-ui/src/: 1488 → 1265 LOC (-223, i.e. -15%)
  • 8 duplicated files removed (4 per service)

Installation

The library is not published on npm — every consumer references it via a local file link using the cross-platform relative path:

// scripts-ui/package.json or jmeter-ui/package.json or monitoring/package.json
{
  "dependencies": {
    "@perfshop/shared-node": "file:../shared-node"
  }
}

⚠️ Cross-platform convention since sub-session 5 Phase M (2026-05-20): the path is now relative file:../shared-node (not the absolute Docker-only file:/shared-node originally). It resolves the same on the dev host (<consumer>/../shared-node) AND inside Docker (/app/../shared-node = /shared-node, materialised by COPY shared-node/ /shared-node/). Migration driven by the "host npm install corrupts the lockfile" bug when the absolute path doesn't exist. See "Sub-session 5 update" below for the regeneration helpers.

How the library's dependencies resolve (2026-10-12)

@perfshop/shared-node imports express, express-session and session-file-store, declared as peerDependencies: the consumer installs them, in its own node_modules. But the library is installed as a link, and Node resolves the imports of a linked module from its real path (/shared-node) by default, where nothing is installed. Every consumer therefore runs with NODE_PRESERVE_SYMLINKS=1: the library's imports resolve from the link, i.e. from the consumer's node_modules — a single copy of Express per service.

  • Built image: ENV NODE_PRESERVE_SYMLINKS=1 in the consumer's Dockerfile.
  • Bind-mounted source (./shared-node:/shared-node): NODE_PRESERVE_SYMLINKS=1 in the service's environment.
  • The root .dockerignore keeps every node_modules out of the build context: an image depends on the git-tracked tree alone.
  • A consumer that imports a module of the library declares, in its own dependencies, the packages that module imports.

Without this setting, a fresh clone fell in a restart loop on ERR_MODULE_NOT_FOUND: Cannot find package 'express-session' imported from /shared-node/src/session.js (Scripts UI, JMeter UI, Test-AI). A development host did not see it: its local shared-node/node_modules, git-ignored, was copied into the images and mounted into the services.

Two guards: the offline pin shared-node/test/consumers-resolve-peers.test.js, and the trial node tools/tps/arbre-neuf.mjs, which builds and starts the consumers from a git tree alone, in a throwaway compose project (Docker and network needed).

On the host, the test suites run without this variable: they resolve from shared-node/node_modules, installed by npm ci in shared-node/ (see "Tests & lint").

Exported modules

Every module is reachable either from the barrel or via a sub-path:

// barrel
import { createI18n, createSession } from '@perfshop/shared-node';
// or sub-path
import { createI18n }    from '@perfshop/shared-node/i18n';
import { createSession } from '@perfshop/shared-node/session';
Module Sub-path Responsibility
config @perfshop/shared-node/config Env helpers: required, intOf, boolOf, oneOf, pickLang, sessionSecretOf, cookieFlagsOf. Fail-fast in production.
i18n @perfshop/shared-node/i18n createI18n({ i18nDir, lang }) → { t, errorPayload }. Loads public/i18n/{lang}.json once at boot, FR fallback.
session @perfshop/shared-node/session createSession({ cookieName, sessionsDir, secret, secure, sameSite, ttlMs }) — express-session + FileStore, 8 h rolling cookie. A logout stays final even with requests of the session in flight (destroyed ids refused on read, late file rewrites undone).
security @perfshop/shared-node/security createCsrfProtection({ errorPayload }) + createRateLimit({ windowMs, maxHits, errorPayload }) + createSecurityHeaders({ frameOptions?, referrerPolicy?, contentTypeNosniff?, csp? }) (0.2.0).
auth @perfshop/shared-node/auth createAuthRouter({ backendUrl, permissionFlag, errorPayload }) + createRequireAuth(...) + createApiAuthGate(...). The login immediately revokes the admin token issued by the backend (POST /api/admin/logout + X-Admin-Token, 3 s at most).
docker-client @perfshop/shared-node/docker-client dockerClient({ socketPath }) → { request, execSync, execAsync, execInspect, inspect, killProcess,containerLogs (0.2.0), demux }. Companion pure helper buildContainerLogsPath(name, n, timestamps?) is also exported. Pure HTTP — works on Synology DSM 7.

Complete bootstrap example

import express from 'express';

import { createI18n }            from '@perfshop/shared-node/i18n';
import { createSession }         from '@perfshop/shared-node/session';
import { createCsrfProtection,
         createRateLimit,
         createSecurityHeaders } from '@perfshop/shared-node/security';
import { createAuthRouter,
         createApiAuthGate }     from '@perfshop/shared-node/auth';
import { dockerClient }          from '@perfshop/shared-node/docker-client';
import { required, intOf, pickLang,
         sessionSecretOf, cookieFlagsOf } from '@perfshop/shared-node/config';

// 1. Config — fail-fast on missing required env vars
const PORT          = intOf('PORT', 3006);
const LANG          = pickLang('PERFSHOP_LANG');
const BACKEND_URL   = required('PERFSHOP_API_INTERNAL');
const SESSION_SECRET = sessionSecretOf({
  envVar:      'SESSION_SECRET',
  devDefaults: ['perfshop-dev-secret'],
});
const { secure, sameSite } = cookieFlagsOf();

// 2. i18n — loads public/i18n/{lang}.json + FR fallback
const { t, errorPayload } = createI18n({
  i18nDir: new URL('../public/i18n/', import.meta.url),
  lang:    LANG,
});

// 3. Session — UNIQUE cookie name per service
const session = createSession({
  cookieName:  'perfshop.testai.sid',
  sessionsDir: '/app/sessions',
  secret:      SESSION_SECRET,
  secure,
  sameSite,
});

// 4. Security
const csrf       = createCsrfProtection({ errorPayload });
const loginRate  = createRateLimit({ windowMs: 60_000, maxHits: 10, errorPayload });
// Sub-session 4 (1.5.0) — strict CSP (9 directives, zero unsafe-*).
// Wire from day 0 for new UIs (test-ai B2, dataset-lab B3):
const CSP_POLICY = [
  "default-src 'self'", "img-src 'self' data:", "style-src 'self'",
  "script-src 'self'", "connect-src 'self'", "font-src 'self'",
  "frame-ancestors 'none'", "base-uri 'self'", "form-action 'self'",
].join('; ');
const secHeaders = createSecurityHeaders({ csp: CSP_POLICY });

// 5. Auth — delegates to chaos-admin backend
const authRouter = createAuthRouter({
  backendUrl:     BACKEND_URL,
  permissionFlag: 'canAccessTestAi',
  errorPayload,
});
const apiGate    = createApiAuthGate({
  publicPaths: ['/auth/login', '/auth/logout'],
  errorPayload,
});

// 6. Wire into Express
const app = express();
app.set('trust proxy', 1);
app.disable('x-powered-by');
app.disable('etag');
app.use(express.json({ limit: '5mb' }));
app.use(session);
app.use(secHeaders);
app.use(csrf);
app.use('/api/auth/login', loginRate);
app.use('/api', apiGate);
app.use('/api/auth', authRouter);

app.listen(PORT);

Each PerfShop service must use a unique cookie name. Without it, all services share the default connect.sid and the cookie is overwritten cross-port on the same host (the port is not part of a cookie's origin per RFC 6265).

Service Cookie name
scripts-ui perfshop.scripts.sid
jmeter-ui perfshop.jmeter.sid
test-ai perfshop.testai.sid (reserved for B2)
dataset-lab perfshop.dataset.sid (reserved for B3)

Docker deployment — 3 modes

PerfShop ships in 3 different ways. The shared-node library reaches each container appropriately:

Mode Compose file Strategy
Desktop (Windows) docker-compose.desktop.yml scripts-ui, test-ai, monitoring: built image — build context = repo root + COPY shared-node/ + npm ci --omit=dev strict + ENV NODE_PRESERVE_SYMLINKS=1. jmeter-ui: bind-mounted source (./jmeter-ui:/app, ./shared-node:/shared-node:ro) for fast dev, command: "npm ci --omit=dev && node src/server.js" and NODE_PRESERVE_SYMLINKS=1 in its environment.
Linux / CI / VPS docker-compose.build.yml All four services (scripts-ui, jmeter-ui, test-ai, monitoring): built image — build context = repo root + COPY shared-node/ + npm ci --omit=dev + ENV NODE_PRESERVE_SYMLINKS=1 (self-contained image, safe for docker save/load).
NAS Synology docker-compose.yml jmeter-ui: volume bind ./shared-node:/shared-node:ro + command: "npm ci --omit=dev && node ..." (DSM 7 does not support native build). Other services consume pre-built images.

User-facing entrypoint:

git clone https://github.com/perfshop/perfshop.git
cd perfshop
./build.sh desktop   # or: ./build.sh unix

No human action required on the library.

Tests & lint

cd shared-node
npm install
npm run lint    # eslint + plugin-jsdoc — zero warning expected
npm test        # node:test runner

The suite covers:

  • config: env-var helpers + production fail-fast
  • i18n: loading, FR fallback, placeholder interpolation, frozen dictionaries
  • session: option validation + middleware signature + final logout under concurrency (30 requests in flight + logout, a file rewrite held until after destroy(), a destroyed id whose file comes back, no write after destroy())
  • security: CSRF GET/HEAD bypass, POST cross-origin blocked, per-IP rate limit + Retry-After, createSecurityHeaders signature
  • auth: full router against a mocked HTTP backend (200/400/401/402/403/500/503 timeout) + admin-token revocation (call and header, 403 included, bounded delay, non-blocking failure, token never logged)
  • docker-client: multi-frame demux + API surface + socket errors
  • csp-policy-consistency (cross-component, sub-session 4): assert that the 4 sources (scripts-ui/src/server.js, jmeter-ui/src/server.js, monitoring/src/server.js, admin/nginx.conf) declare the 9 canonical directives + 0 unsafe-* + 0 external URL (offline-ready consistency).
  • consumers-resolve-peers (cross-component, 2026-10-12): the consumers are the expected ones; the library declares as peerDependencies every package it imports; each consumer declares the packages imported by the library modules it imports; each Dockerfile sets ENV NODE_PRESERVE_SYMLINKS=1; every compose service that mounts shared-node sets the variable; the root .dockerignore excludes **/node_modules.

The exec paths against a real Docker daemon are validated by the runtime smoke test (scripts-ui in synchronous mode, jmeter-ui in asynchronous mode). In the stack, the consumers no longer reach the daemon socket: they pass the socket of the Docker relay as socketPath (perfshop-docker-relay, see Docker socket: the relay), and the relay's own suite (docker-relay/test/relay.test.js) runs this client as shipped against a fake daemon.

See also

In-repo documents (not part of the MkDocs site):

  • memory/briques/B0_shared_lib.md — B0 brick file (scope, DoD, gotchas)
  • memory/reference/pattern_node_ihm.md — reference skeleton for a PerfShop Node component
  • shared-node/README.md — internal README with detailed examples