# WRNexusJS 0.7 Security and Performance Foundation

WRNexusJS 0.7 makes the secure and fast path the framework default. This document maps the 21 production-hardening areas to concrete packages, runtime behavior, diagnostics, and release gates. Application-specific authorization, infrastructure capacity, CSP allowlists, malware engines, Redis/CDN adapters, and deployment configuration still require project review.

## Default production targets

- LCP <= 2.5 s, INP <= 200 ms, CLS <= 0.1.
- Long tasks <= 50 ms.
- Preferred initial route JavaScript <= 50 KiB compressed-equivalent source budget.
- Preferred critical route CSS <= 25 KiB.
- Sensitive responses use private/no-store policies.
- Static pages are classified so builds can avoid unnecessary client runtime work.

## 1. Framework targets and budgets

Implemented in `@wrnexus/core/performance` and the production build report. Budgets now cover route JS, CSS, HTML, images, hydration, SSR, LCP, INP, CLS, TTFB, long tasks, hydration boundaries, and request count. Builds can warn or fail through `performance.enforcement`.

## 2. Compiler and template security

- Context-aware URL attributes reject dangerous protocols in SSR and reactive updates.
- Static `javascript:`, `vbscript:`, `file:`, unsafe `data:` URLs are compiler diagnostics.
- Client functions using dynamic-code or unsafe DOM HTML sinks are rejected.
- Environment-derived secrets cannot enter client state; sensitive values cannot use browser persistence.
- Server/client state and function boundaries remain compiler-enforced.
- Hydration/store payloads use bounded, HTML-safe serialization with redaction and prototype-pollution checks.

## 3. Browser security headers

`@wrnexus/core` provides CSP, Trusted Types, HSTS, COOP, CORP, Referrer-Policy, Permissions-Policy, X-Content-Type-Options, frame protection, Origin-Agent-Cluster, and DNS-prefetch controls. `@wrnexus/security` adds balanced, strict, and API presets. CSP is nonce-aware and can run report-only.

## 4. Sessions and authentication

The core session layer now supports idle and absolute expiry policies, sliding access, configurable secure cookie defaults, and server-side session backends. `@wrnexus/auth` remains responsible for password/passkey/MFA/account flows. Credentials must remain in Secure, HttpOnly cookies, not browser storage.

## 5. CSRF, CORS, and authorization

CSRF validates token, Origin, and Fetch Metadata for unsafe methods. CORS remains opt-in and exact-origin capable. `@wrnexus/authz` and tenant middleware provide server-side policy and tenant scope; UI hiding is never treated as authorization.

## 6. Gateway and API hardening

Gateway and app runtime support URL/header/query/body limits, timeouts, concurrency limits, host allowlists, Fetch Metadata, IP rate limits, trusted forwarding, access logs, request IDs, and WebSocket origin/message/queue controls.

## 7. SSRF protection

`@wrnexus/security/safeFetch` validates protocol/host, resolves every address, blocks loopback/private/link-local/multicast ranges, revalidates redirects, limits redirects and response size, applies timeouts, and never forwards credentials unless explicitly allowed.

## 8. File-upload security

Core upload primitives support extension and MIME allowlists, size/aggregate limits, random filenames, path safety, inspector and malware-scanner adapters, response hardening, and controlled download disposition. Production applications connect their antivirus/CDR engine through the scanner interface.

## 9. Database performance and security

`instrumentDb` adds query timeout, max-row enforcement, slow-query reporting, duplicate/N+1 detection, SELECT-star and unbounded-query warnings, and per-request query records. Existing drivers continue parameterized query handling and transaction support.

## 10. SSR and server performance

Existing streaming responses, request-local dedupe, route caching primitives, and static manifests remain. The compiler now classifies routes as static, static-interactive, request SSR, authenticated SSR, streaming SSR, or dynamic; the production build report records prerenderability and runtime needs.

## 11. Hydration and CSR performance

WRNexusJS now defaults navigation to `auto`: non-interactive static markup ships no framework JavaScript and uses native document navigation. Interactive routes receive only the runtimes their rendered markers require. Explicit `client` and `document` modes remain available. Partial hydration boundaries, lazy hydration strategies, keyed list preservation, direct reactive DOM updates, batched signal work, navigation cancellation, page-store disposal, and delegated framework event handling remain. Hydration duration emits `wrnexus:hydrated` telemetry.

## 12. Bundle and build optimization

Production builds are minified, content-hashed where assets are emitted, server/client separated, and measured through `build-report.json`. Package runtimes remain independently emitted and immutable. Runtime classification and budget failures are release-visible. Persistent build-cache and deployment adapters remain configurable.

## 13. CSS performance

Styles remain production-minified and package-aware. `auditCssPerformance` detects `transition: all`, expensive blur/shadow patterns, broad universal selectors, and duplicate keyframes while preserving the existing design-token, contrast, and Tailwind source audits.

## 14. Images, icons, and fonts

`@wrnexus/image` creates validated responsive image attributes, deduplicated srcsets, sizes, dimensions, loading/decoding/fetch-priority policies, secure remote-host rules, and LCP/oversizing audits. Existing font helpers retain self-hosting/preload/CSP support. UI packages continue per-icon imports rather than a whole-library browser bundle.

## 15. HTTP delivery

The runtime negotiates Brotli first and gzip fallback, avoids recompressing unsuitable responses, supports ETags/conditional requests, immutable versioned framework assets, cache-control helpers including stale-while-revalidate/stale-if-error, preload/modulepreload, and proxy-aware HTTPS handling.

## 16. Realtime and WebSocket security

Rooms now support authentication requirements, max message bytes, messages/second, room/user connection quotas, maximum JSON depth, message schema/authorization predicates, prototype-pollution rejection, violation callbacks, origin validation, and gateway queue limits. Pub/sub bridge behavior remains available for horizontal scaling.

## 17. Observability

`@wrnexus/observability` provides counters, gauges, histograms, HTTP middleware, request/error/active-request metrics, same-origin Web Vitals ingestion, an opt-in browser collector, and exporter adapters. It avoids collecting request bodies or user identifiers by default.

## 18. DevToolbar

Security checks now include secret query parameters, insecure forms, missing CSRF, CSP nonce issues, inline styles, mixed content, unsandboxed iframes, sensitive local storage, and leaked hydration fields. Performance checks cover total/JS transfer, slow resources, DOM size, hydration count, oversized images, render-blocking assets, and long tasks.

## 19. Tests and release gates

`validate:0.7`, `security:framework`, `benchmark:framework`, typecheck, lint, tests, formatting, UI reference verification, and package staging run before release. New package tests cover serialization, prototype pollution, URL policy, caching, images, metrics, Web Vitals, benchmarks, and realtime limits.

## 20. Supply-chain security

The release remains private/restricted, requires aligned versions and an explicit migration, checks for secret-like files and dangerous static URLs, generates CycloneDX `SBOM-0.7.0.cdx.json`, verifies staged package contents, requires clean/pushed Git state, and verifies registry privacy after publication. Registry MFA and short-lived publishing credentials remain operational requirements.

## 21. New packages

- `@wrnexus/security`: security policy, secure serialization, URL validation, request limits, secure cookies, SSRF-safe fetch.
- `@wrnexus/cache`: bounded tag cache, deduplication, response caching, ETag, stale policies and invalidation.
- `@wrnexus/image`: responsive image planning and audits.
- `@wrnexus/observability`: metrics, request instrumentation, Web Vitals, exporters.
- `@wrnexus/benchmark`: deterministic benchmarks and regression budgets.

## Production configuration baseline

```ts
export default {
  navigation: { mode: "auto" },
  security: {
    headers: true,
    requestLimits: {
      maxUrlLength: 8192,
      maxHeaderCount: 100,
      maxHeaderBytes: 32768,
      maxQueryParameters: 100,
      maxBodyBytes: 10485760,
      timeoutMs: 30000,
      maxConcurrent: 1000,
      fetchMetadata: true,
    },
    contentSecurityPolicy: { enabled: true, useDefaults: true },
    trustedTypes: { enabled: true, requireForScript: true },
    hsts: { enabled: true, maxAge: 63072000, includeSubDomains: true, preload: true },
  },
  performance: {
    enforcement: "error",
    analyze: true,
    budgets: {
      routeJsBytes: 51200,
      routeCssBytes: 25600,
      hydrationMs: 200,
      serverRenderMs: 500,
      lcpMs: 2500,
      inpMs: 200,
      cls: 0.1,
      ttfbMs: 800,
    },
  },
  observability: {
    enabled: true,
    serverTiming: true,
    sampleRate: 0.1,
    webVitals: true,
  },
};
```

Use report-only CSP and warning-level performance enforcement while migrating an existing application, then enforce after resolving findings.
