# CyberShield JS — Usage Guide

## Installation

Copy the `cybershield-js/` folder into your project, then:

```bash
# If published to npm (future):
npm install cybershield-js

# Local usage — reference via relative path in package.json:
# "cybershield-js": "file:./cybershield-js"
```

---

## Express / Node.js

```js
const express    = require('express');
const cybershield = require('cybershield-js/express');

const app = express();
app.use(express.json());

// Add WAF middleware (before your routes)
app.use(cybershield({
  excludePaths: ['/health', '/metrics'],
  skipInDev: true,    // skip when NODE_ENV=development
}));

// Optional: mount admin panel
const adminPanel = require('cybershield-js/admin');
app.use('/cybershield-admin', adminPanel());

app.listen(3000);
```

---

## Fastify

```js
const fastify = require('fastify')();
const cybershield = require('cybershield-js');

fastify.register(cybershield.fastify, { excludePaths: ['/health'] });
// Register BEFORE @fastify/static so pages/assets get the security headers too.
```

---

## Next.js

Requires **Next.js >= 15.5** (middleware on the Node.js runtime).

`middleware.js` at the project root (next to `app/` or `pages/`):

```js
const { cybershieldNext } = require('cybershield-js/next');

module.exports.middleware = cybershieldNext({ excludePaths: ['/health'] });
module.exports.config = {
  runtime: 'nodejs',
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
```

TypeScript (`middleware.ts`):

```ts
import { cybershieldNext } from 'cybershield-js/next';

export const middleware = cybershieldNext();
export const config = {
  runtime: 'nodejs',
  matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'],
};
```

If you already have a middleware (redirects, auth, i18n…), wrap it with `withCybershield`
instead — do **not** just call `cybershieldNext()` inside it (it returns a function and its
result would be ignored):

```ts
import { NextResponse, type NextRequest } from 'next/server';
import { withCybershield } from 'cybershield-js/next';

export const middleware = withCybershield(async (req: NextRequest) => {
  // your logic; return a NextResponse
  return NextResponse.next();
});
export const config = { runtime: 'nodejs', matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };
```

Blocked requests get the WAF response (403 / redirect) and your handler is not run; for
allowed requests the security headers are added to **your** handler's response.

The WAF runs on every page and API route; headers are added to each response.
The request body is not read in middleware (URL, IP, user-agent and headers are checked).

---

## Any other frontend (React/Vue/Angular build, static site, Vite…)

Put CyberShield **in front** of the frontend — as a static server or a reverse proxy:

```js
const { createFrontendServer } = require('cybershield-js/frontend');

// 1. Serve a static build
createFrontendServer({ staticDir: './dist' }).listen(8080);

// 2. Or proxy an existing frontend (Nginx, Vite, ...)
createFrontendServer({
  target: 'http://127.0.0.1:3000',
  excludePaths: ['/assets', '/static'],   // skip the WAF for static assets
}).listen(8080);
```

The public domain must point to this server (the original frontend must not stay
directly reachable). It also works as an `(req, res)` handler: `app.use(cybershield.frontend({ staticDir: './dist' }))`.

---

## Which setup for which site?

The protections below are **HTTP response headers**: they must be added by whatever
sends the page. Installing the plugin in the API only protects the API.

| Your site                                              | What to use                                            |
|--------------------------------------------------------|--------------------------------------------------------|
| Express / Fastify app that serves the pages            | `cybershield-js/express` or `/fastify` (before static) |
| Next.js (>= 15.5)                                      | `cybershield-js/next` (`middleware`)                   |
| Static / SPA build, any host                           | `cybershield-js/frontend` in front of the site         |
| Frontend on Vercel / Netlify / Nginx / Cloudflare, no proxy wanted | Add the headers on the host (see below) — headers only, no WAF filtering |
| API only (separate from the pages)                     | Express / Fastify adapter on the API                   |

Headers to set on the host (clickjacking + MIME sniffing):

```
X-Frame-Options: SAMEORIGIN
Content-Security-Policy: frame-ancestors 'self'
X-Content-Type-Options: nosniff
```

Notes:
- `<meta>` tags do **not** work for these headers; `nosniff` and HSTS have no client-side equivalent.
- Setting headers on the host does not give WAF filtering (IP/country blocking, threats, bots): that requires requests to go through the plugin.

---

## Clickjacking protection

Enabled by the CyberShield API option, or locally in `config/settings.json`
(works even without a validated API key):

```json
{
  "clickjacking_protection": true,
  "frame_ancestors": ["https://partner.example.com"]
}
```

| `frame_ancestors`   | Result                                                                    |
|---------------------|---------------------------------------------------------------------------|
| _(not set)_         | `X-Frame-Options: SAMEORIGIN` + `frame-ancestors 'self'`                  |
| `["https://a.com"]` | `frame-ancestors 'self' https://a.com` (+ `X-Frame-Options: SAMEORIGIN`)  |
| `"none"`            | `X-Frame-Options: DENY` + `frame-ancestors 'none'`                        |

An existing `Content-Security-Policy` is kept: `frame-ancestors` is appended, and an
existing `frame-ancestors` directive is never overridden.

**Test it:** serve a page containing `<iframe src="https://your-site/">` from another
origin; the frame must stay empty and the console shows
`Refused to display ... frame-ancestors`. Check headers with `curl -I https://your-site/`.

---

## Configuration

### Via environment variables (recommended for production):

```bash
CYBERSHIELD_API_KEY=your-api-key
CYBERSHIELD_EMAIL=your@email.com
```

### Via admin panel:

Mount the admin router and open it in your browser:

```js
app.use('/cybershield-admin', require('cybershield-js/admin')());
// → http://localhost:3000/cybershield-admin
// Default password: admin (change it immediately!)
```

### Via code:

```js
const { config } = require('cybershield-js');

config.set('cybershield_api_key',       'your-api-key');
config.set('cybershield_email_address', 'your@email.com');
config.set('cybershield_site_url',      'https://yourdomain.com');
config.set('cybershield_api_key_status', 'valid');
```

Settings are persisted in `cybershield-js/config/settings.json`.

---

## Features

| Feature                  | Express / Fastify / Next.js |
|--------------------------|:---------------------------:|
| Request logging (API)    | ✓       |
| Security headers (clickjacking, nosniff, HSTS, XSS) | ✓ |
| IP blocking              | ✓       |
| Country blocking         | ✓       |
| Threat detection         | ✓       |
| Bot filtering            | ✓       |
| Input sanitization       | Express / Fastify only (request body is not read in Next.js middleware or frontend proxy) |
| Admin panel              | Express / Fastify only |
| Hourly key check (cron)  | ✓       |
