# Security Policy

RESTForge is a commercial backend framework distributed on npm for authorized evaluators and licensees. This document describes the security posture of the package, how to report vulnerabilities, and how to interpret results from automated security scanners.

---

## Supported Versions

Security updates are provided for the two most recent minor releases on the stable channel, plus the latest beta channel.

| Version | Channel | Supported |
|---------|---------|-----------|
| 4.2.x   | stable  | Yes       |
| 4.1.x   | stable  | Yes       |
| < 4.1   | legacy  | No        |

Users on older versions are encouraged to upgrade to a supported release.

---

## Reporting a Vulnerability

If a security vulnerability is discovered in RESTForge, please report it privately rather than opening a public issue.

- Primary contact: [restforge.dev/security](https://restforge.dev)
- Email: security@restforge.dev

Please include the following information in the report:

- Affected version
- Minimum reproducible steps
- Impact assessment (confidentiality, integrity, availability)
- Suggested mitigation, if any

The team acknowledges reports within 3 business days and provides a remediation timeline within 10 business days for valid vulnerabilities. Coordinated disclosure is preferred, with public advisory published after a fix is available.

---

## Automated Scanner Findings

Automated supply-chain scanners such as Socket.dev, Snyk, and similar services may flag the following characteristics of this package. These are **intentional design decisions** and are not security vulnerabilities.

### Obfuscated Code

Production builds of RESTForge are obfuscated using `javascript-obfuscator` to protect proprietary logic and license enforcement code. Obfuscation is applied with two intensity levels:

- **Strong obfuscation** — applied only to security-critical files (license validation, integrity checks, trusted keys)
- **Moderate obfuscation** — applied to general source files to reduce false-positive detection by antivirus tools

Obfuscation is a standard practice for commercial Node.js packages and does not indicate malicious behavior. The obfuscation configuration is deterministic and produces verifiable output from the same source input.

### Install Scripts

The package defines one `preinstall` script: `scripts/check-install.js`. This script performs a single, non-destructive action:

- Displays an informational warning when the package is installed globally, recommending local installation for version pinning

The script does not perform network requests, filesystem modifications outside the installation directory, or privilege escalation. The full source is included in the published package and can be inspected before installation.

### Network Access

RESTForge is a REST API framework. Network access is a functional requirement for:

- HTTP server on configured port
- Database connections (PostgreSQL, MySQL, Oracle)
- Redis client for cache, distributed locking, and BullMQ
- Optional Kafka producer and consumer
- AWS S3 client for optional Excel export storage
- License validation against the configured license server

No telemetry, analytics, or unsolicited outbound requests are performed. All network destinations are configured explicitly by the application operator.

### Dynamic Code Execution

The presence of dynamic evaluation patterns (`eval`, `Function`, array-based string decoding) in the published package is a standard artifact of JavaScript obfuscation output. No dynamic code evaluation of user input or untrusted data occurs at runtime.

### Commercial License

The `license` field in `package.json` points to `LICENSE.md` rather than using a standard SPDX identifier, because RESTForge is distributed under a proprietary commercial license. See [LICENSE.md](./LICENSE.md) for the full license agreement.

---

## Package Integrity

Every published build includes `integrity-manifest.json`, a cryptographic manifest of distributed files generated at build time. The runtime performs integrity verification on startup using `scripts/verify-integrity.js` to detect tampering.

To verify a downloaded package manually:

```bash
node scripts/verify-integrity.js
```

A successful verification confirms that the installed package matches the manifest generated during publication.

---

## Runtime Security Characteristics

- **No known CVEs** — scanned against public vulnerability databases at publish time
- **No embedded credentials** — all secrets (database passwords, license keys, AWS credentials) are supplied via environment variables or configuration files at runtime
- **Parameterized queries** — all generated database queries use prepared statements or parameterized execution to prevent SQL injection
- **Input validation** — endpoint payloads are validated against declarative schemas before reaching database or business logic layers
- **Rate limiting and idempotency** — built-in primitives are available but must be enabled explicitly per endpoint

---

## Default Security Configuration

The following defaults apply when corresponding environment variables are not explicitly set. Values reflect the runtime middleware implementation in this release. Operators are encouraged to review and override based on their threat model and compliance requirements.

### CORS

- `CORS_ENABLED`: `true` (backward-compatible default — CORS is active when the variable is not set)
- `CORS_ORIGINS`: `*` (all origins permitted; set to a comma-separated allowlist for production)
- Allowed methods: `GET, POST, PUT, DELETE, OPTIONS`
- Allowed request headers: `Origin, X-Requested-With, Content-Type, Accept, Authorization, X-API-Key, X-Request-Mode, X-Request-ID, Idempotency-Key`
- Exposed response headers: `Idempotent-Replayed, Idempotency-Key`
- When a disallowed origin issues a preflight `OPTIONS`, the response is `HTTP 403`. Non-preflight requests proceed without CORS headers and are blocked client-side by the browser.

### Security Headers (Helmet)

- `HELMET_ENABLED`: `false` (security headers are not emitted by default; operators behind a reverse proxy or framework that already injects headers can leave this unset)

When `HELMET_ENABLED=true`, the following headers are added to every response:

| Header | Value |
|--------|-------|
| `X-Content-Type-Options` | `nosniff` |
| `X-Frame-Options` | `DENY` |
| `X-XSS-Protection` | `0` (legacy auditor disabled) |
| `Strict-Transport-Security` | `max-age=15552000; includeSubDomains` (180 days) |
| `Referrer-Policy` | `no-referrer` |
| `X-Permitted-Cross-Domain-Policies` | `none` |
| `X-Download-Options` | `noopen` |
| `Content-Security-Policy` | `default-src 'none'` |
| `X-DNS-Prefetch-Control` | `off` |

The `X-Powered-By` header is always removed when this middleware is active.

### Rate Limiting

- `RATE_LIMIT_ENABLED`: `false`
- `RATE_LIMIT_WINDOW_MS`: `60000` (60 seconds)
- `RATE_LIMIT_MAX_REQUESTS`: `100` requests per IP per window
- Storage backend: in-memory (single mode) or Redis Lua script (cluster mode, Redis required)
- Response headers always set when enabled: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
- When the limit is exceeded, response is `HTTP 429` with `Retry-After` header

### Idempotency

- `IDEMPOTENCY_ENABLED`: `false`
- `IDEMPOTENCY_TTL`: `300` seconds (cached response retention)
- Idempotency key header: `Idempotency-Key` (maximum 255 characters)
- Protected mutation actions (`POST` only): `create`, `create-composite`, `adjust`, `update-composite`
- Storage backend: Redis (requires `CACHE_ENABLED=true`)
- Replay returns the original status code with header `Idempotent-Replayed: true`
- Conflicting body for the same key returns `HTTP 422 Idempotency-Key conflict`

### File Upload (Excel import)

- Maximum file size: `10 MB` (compile-time constant)
- Maximum files per request: `1`
- Allowed MIME types: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`, `application/vnd.ms-excel`
- Allowed file extensions: `.xlsx`, `.xls`
- Stored filename pattern: `upload-<timestamp>-<8-byte-random-hex><ext>` (random suffix prevents collision and disclosure of original filename)
- `UPLOAD_DIR`: override the upload destination directory (default: `<package-root>/temp/uploads/<project>`)

### Body Parser

- JSON payload limit: `10 MB`
- URL-encoded payload limit: `10 MB`
- Invalid JSON returns `HTTP 400` with body `{ "success": false, "error": "Invalid JSON payload", ... }`

### API Key

- Authentication header: `X-API-Key`
- Comparison: `crypto.timingSafeEqual` (constant-time, hardened in v4.3.0 — see CHANGELOG)
- Source: CLI argument `--key=<value>` or `key` field in the project config file
- Missing or mismatched key returns `HTTP 401 Unauthorized`

### JWT

RESTForge runtime does not perform JSON Web Token signing or verification natively. Operators that require JWT-based authentication should implement it at the processor or application middleware layer using a vetted library such as `jsonwebtoken`.

---

## Third-Party Dependencies

RESTForge depends on well-established packages maintained by the Node.js ecosystem. The full dependency list is declared in `package.json`. Dependency updates follow these guidelines:

- Security patches are applied within the minor version range on each release
- Major version upgrades are evaluated on each minor release of RESTForge
- Deprecated or unmaintained dependencies are replaced at the earliest stable release

---

## Disclaimer

The security measures described above represent the framework's design intent. End-user applications built with RESTForge remain responsible for their own security posture, including authentication, authorization, network perimeter, secret management, and deployment hardening. See the user guide for recommended production configurations.

---

Copyright © 2026 RESTForge Development Team. All rights reserved.
