<div align="center">

# securequ

High‑level encrypted & compressed HTTP request + chunked upload toolkit for browser ↔ server applications.

</div>

> Provides an additional application‑layer privacy/integrity envelope. Always deploy behind HTTPS.

<p align="center">
<a href="https://www.npmjs.com/package/securequ"><img src="https://img.shields.io/npm/v/securequ.svg" alt="npm version" /></a>
<a href="#"><img src="https://img.shields.io/badge/status-active-green" alt="status" /></a>
<a href="#security"><img src="https://img.shields.io/badge/focus-security-blue" alt="focus" /></a>
</p>

## Table of Contents

- [securequ](#securequ)
  - [Table of Contents](#table-of-contents)
  - [Overview](#overview)
  - [Why securequ?](#why-securequ)
  - [Core Concepts (Abstracted)](#core-concepts-abstracted)
  - [Security (Summary)](#security-summary)
  - [Performance Snapshot](#performance-snapshot)
  - [Install](#install)
  - [Minimal Server (Express)](#minimal-server-express)
  - [Minimal Client](#minimal-client)
  - [Client Hooks (Selected)](#client-hooks-selected)
  - [API Surface (High Level)](#api-surface-high-level)
    - [Server Response Model](#server-response-model)
  - [File Upload Overview](#file-upload-overview)
  - [Configuration (Essentials)](#configuration-essentials)
  - [Error Semantics](#error-semantics)
  - [Performance Guidance](#performance-guidance)
  - [Troubleshooting](#troubleshooting)
  - [FAQ](#faq)
  - [Versioning \& Stability](#versioning--stability)
  - [Contributing](#contributing)
  - [Security Reporting](#security-reporting)
  - [Disclaimer](#disclaimer)
  - [License](#license)

## Overview

securequ places a compact, binary, encrypted envelope around HTTP request/response bodies and coordinates secure, chunked file uploads. A lightweight, ephemeral token (internally named `signeture`) is established via a handshake per client origin and renewed automatically when necessary. Development mode keeps the ergonomics of plain JSON while production mode obfuscates both payload bodies and (optionally) query parameters.

Key capabilities:
- Application‑layer confidentiality & integrity (in addition to transport‑layer TLS)
- Binary serialization + compression for efficient payload transfer
- Short‑lived opaque token automatically refreshed
- File uploads with controlled chunk sizing, size limits, optional first‑chunk file‑type validation, and progress events
- Minimal routing utilities and lifecycle hooks—framework agnostic
- Consistent TypeScript surface

## Why securequ?

| Need                                          | Plain fetch + JSON   | securequ               |
| --------------------------------------------- | -------------------- | ---------------------- |
| Hide request structure from casual inspection | ✗                    | ✓ (encrypted envelope) |
| Automatic compression + binary serialization  | Partial (manual)     | ✓ built‑in             |
| Short‑lived opaque request token              | Custom work          | ✓ baked in             |
| Client lifecycle hooks                        | Manual wiring        | ✓ hooks API            |
| Validated chunked uploads + progress          | Manual / library mix | ✓ integrated           |

Use it when you want an extra (opaque) layer plus structured uploads without re‑inventing crypto + binary packing. If HTTPS + standard auth covers all your needs and you prefer transparency, you may not need this.

## Core Concepts (Abstracted)

| Concept            | Summary                                                                                 |
| ------------------ | --------------------------------------------------------------------------------------- |
| Pre‑shared secret  | Static value per allowed origin (server‑side registration)                              |
| Handshake          | Lightweight exchange producing a short‑lived opaque token (auto refreshed)              |
| Encrypted envelope | Bodies (and in production, query params) serialized → compressed → encrypted            |
| Development mode   | Skips encryption for non‑handshake application requests to aid debugging                |
| Hooks              | Extensibility points for request & upload lifecycle events                              |
| Chunked upload     | Deterministic splitting + metadata negotiation + ordered transfer + completion callback |

## Security (Summary)

Implemented (High Level):
- Symmetric encryption with authenticated integrity (AEAD style)
- Short token lifetime, minimizing replay viability
- Payload and (production) query obfuscation
- Optional file‑type validation via first‑chunk signature scanning

Operator Responsibilities:
- Enforce HTTPS and standard secure headers
- Generate long, random client secrets and rotate periodically
- Layer proper authentication/authorization (sessions, tokens, etc.)
- Validate and sanitize business data in handlers

Out of Scope:
- Forward secrecy / per‑message key rotation
- Fine‑grained end‑user authentication
- True streaming (payloads are presently buffered)
- Built‑in rate limiting / abuse controls

## Performance Snapshot

- Compression + binary encoding reduce large structured bodies vs raw JSON
- Overhead is minimal for medium/large payloads; for tiny payloads (< 200B) you may prefer plain requests
- Chunk size is adaptive (you can override) to balance memory and progress smoothness
- File type detection (if enabled) inspects only the first chunk

## Install

```bash
npm install securequ
```

Peer/runtime deps are installed automatically (libsodium, fflate, msgpackr, path-to-regexp, xanfetch).

## Minimal Server (Express)

```ts
import express from 'express';
import { SecurequServer } from 'securequ';

const api = new SecurequServer({
  mode: 'production',
  basepath: '/api',
  clients: [{ origin: 'https://app.example.com' | "*", secret: process.env.APP_CLIENT_SECRET! }],
  upload: {
    chunk: async (chunk, meta) => { /* store chunk */ return true; },
    complete: async (meta) => { /* stitch & persist */ return `/files/${meta.fileid}`; },
    failed: async (meta) => boolean
  }
});

api.post('/echo', ({ body }) => { throw { ok: true, body }; });

const app = express();
app.use('/api/*', express.raw({ type: 'application/octet-stream', limit: '20mb' }), async (req, res) => {
  const r = await api.listen(req.originalUrl, {
    body: req.body,
    headers: req.headers,
  }, req);
  res.status(r.status).end(r.content);
});
app.listen(4000);
```

## Minimal Client

```ts
import { SecurequClient } from 'securequ';

const client = new SecurequClient({
  url: 'https://api.example.com/api',
  secret: '<client-secret>'
});

// Simple request
const res = await client.post('echo', { body: { hello: 'world' } });
console.log(res);

// File upload with progress
async function uploadFile(file: File) {
  const result = await client.upload(file, p => console.log('progress %', p));
  console.log(result);
}
```

## Client Hooks (Selected)

```ts
hooks: {
  beforeRequest: (path, init) => init,
  afterResponse: (resp) => {},
  beforeUpload: (file, fileId) => file,
  afterUpload: (response, file) => {},
  beforeUploadChunk: (chunk, idx, total) => {},
  afterUploadChunk: (resp, idx, total) => {},
}
```

## API Surface (High Level)

```ts
// Client
client.get(path, init?)
client.post(path, init?)
client.put(path, init?)
client.delete(path, init?)
client.upload(file, onProgress?)

// Server
server.get(path, handler)
server.post(path, handler)
server.put(path, handler)
server.delete(path, handler)
server.listen(url, listenerInfo)

// Utilities (optional direct use)
import { crypto, compresor } from 'securequ';
```

### Server Response Model

Handlers conclude by `throw`ing:
- Plain object / primitive → serialized (dev) or encrypted (prod) with 200 status
- `Response` instance → its status/body is used (still wrapped if necessary)
- `Error` → message returned with a not‑found style status (configurable via customization if you wrap upstream)

This pattern deliberately short‑circuits route evaluation and keeps handler code linear.

## File Upload Overview

- Client sends metadata first
- Server accepts and tracks state
- Client streams fixed‑size chunks sequentially
- Final chunk triggers assembly + returned path / identifier
- A failure notification allows cleanup

## Configuration (Essentials)

```ts
// Server
new SecurequServer({
  mode: 'production' | 'development',
  basepath: '/api',
  clients: [{ origin, secret }],
  upload?: { maxFilesize?, checkFileType?, chunk(), complete(), failed? },
  accept?: (info: HandlerInfo, metadata?: Metadata) => boolean | Promise<boolean>
});

// Client
new SecurequClient({
  url: 'https://host/api',
  secret: '<pre-shared>',
  chunkSize?: number,
  hooks?: { ... }
});
```

## Error Semantics

- Success: `success: true`, `data` contains decrypted payload
- Expired token is auto‑recovered (one retry) by re-handshaking
- Server thrown `Error` surfaces message (wrapped) to client

## Performance Guidance

- Use production mode for real benchmarking (encryption path active)
- Keep secrets long & random (>= 32 chars)
- Tune `chunkSize` only if you need very granular progress events

## Troubleshooting

| Symptom                          | Possible Cause                       | Suggested Fix                                                     |
| -------------------------------- | ------------------------------------ | ----------------------------------------------------------------- |
| `Signeture expired` loops        | Clock skew or token window too short | Ensure system clocks are synced; minimize artificial delays       |
| Always 404 / Not found           | Route not registered before `listen` | Register handlers before attaching middleware                     |
| Plain text visible in production | App running in development mode      | Set `mode: 'production'` in server config                         |
| Upload stops mid‑way             | Page navigation / tab close          | Use `beforeunload` UI warning or resume strategy (future roadmap) |
| File type rejected               | Magic bytes not recognized           | Disable `checkFileType` or extend scanner if needed               |
| High CPU for tiny payloads       | Compression/encryption overhead      | Bypass securequ for very small trivial requests                   |

If an issue isn’t listed: enable development mode locally to inspect raw (unencrypted) bodies for debugging, then switch back.

## FAQ

**Does this replace TLS?**  
No. It layers *on top* of TLS.

**Can I plug into another HTTP framework?**  
Yes—adapt the raw body + headers and call `server.listen()`.

**How do I add auth?**  
Put your auth tokens/data *inside* the encrypted body or add middleware before calling `listen`.

**TypeScript support?**  
Fully typed. Route handlers get a typed `info` object; client responses are typed with a generic shape (`SecurequClientResponse`).

**Can I inspect payloads in production?**  
Not without decrypting. Use development mode locally when introspection is needed.

**Is there resume upload support?**  
Not yet; planned. You can implement partial detection using hooks + server state.

**How big can files be?**  
Limited by your configured `maxFilesize` (KB) and infrastructure memory / timeout constraints.

## Versioning & Stability

The project follows semantic versioning principles as features mature. Prior to a formal `1.x` stability declaration, minor releases may introduce carefully documented adjustments. Pin exact versions in sensitive production environments.

## Contributing

1. Fork & create a feature branch
2. Add or adjust tests where behavior changes
3. Ensure TypeScript builds without errors
4. Open a PR with a concise rationale

Please avoid including sensitive implementation details in public issue titles (describe at a high level instead).

## Security Reporting

If you believe you have discovered a vulnerability, please refrain from opening a public issue. Instead contact the maintainer privately (add a SECURITY.md for formal process if publishing broadly). Provide a minimal, reproducible scenario.

## Disclaimer

securequ provides an additional obfuscation + encryption layer. It is not a substitute for robust authentication, authorization, or transport security practices. Combine with TLS, secret rotation, and standard security controls.

## License

No license file included. Add one (e.g., MIT) before publishing publicly.

---
Issues & contributions welcome.

