npm package: @jessica-mulein/quasor
Description: A high-security AEAD (Authenticated Encryption with Associated Data) implementation in TypeScript
Author: Jessica Mulein
Latest version: 6.1.5

# Quasor: A High-Security AEAD

**Version 6.1.4, TypeScript Edition with WASM Acceleration**

## 1. Overview

Quasor is an experimental, high-security Authenticated Encryption with Associated Data (AEAD) scheme implemented in TypeScript with optional **WebAssembly acceleration**. It is designed for modern applications where robustness, defense-in-depth, and resistance to common implementation pitfalls are critical. This TypeScript implementation is byte-for-byte compatible with the [original Rust implementation](https://github.com/Digital-Defiance/Quasor) and passes all Known Answer Tests (KATs).

The construction is based on a **duplex sponge** using **SHAKE256**, providing a strong foundation for post-quantum security. The **v6.1.4** release includes **WebAssembly acceleration** providing up to **682x performance improvement** over pure TypeScript, while maintaining full compatibility and automatic fallback.

**⚠️ Warning:** Quasor is a research-grade cipher. It has not undergone formal, third-party cryptographic review. It should be used for experimental, educational, or research purposes, not for production systems handling sensitive data.

## 2. Performance Tiers

Quasor automatically selects the best available engine for both one-shot and streaming operations:

| **Engine**        | **Throughput** | **Environment**   | **Setup Required**           |
| ----------------- | -------------- | ----------------- | ---------------------------- |
| **🚀 WASM**       | **~440 MB/s**  | Node.js & Browser | WASM files (included in NPM) |
| **🔧 TypeScript** | ~1.1 MB/s      | Universal         | None (automatic fallback)    |

**Performance boost: Up to 682x faster with WASM for all operations!**

## 3. Core Features

- **🚀 WASM Acceleration**: Optional WebAssembly engine providing up to 682x performance boost for both one-shot and streaming operations
- **🔧 Automatic Fallback**: Pure TypeScript engine for universal compatibility
- **Post-Quantum Resistance**: The core cipher uses a SHAKE256 sponge, which is built on a 1600-bit permutation, providing a high security margin against both classical and quantum cryptanalysis.
- **Nonce-Misuse Resistance**: Implements a **Synthetic Initialization Vector (SIV)** mechanism using a keyed BLAKE3 hash. The nonce is derived deterministically from the message and associated data.
- **Forward Secrecy & Key Erasure**: An automatic **rekeying** mechanism is integrated into the duplexing process. After every 1 MiB of data, the sponge's internal state is used to generate a new key, and the old key material is cryptographically erased.
- **Memory-Hard Key Derivation**: Uses **Argon2id** with its recommended secure defaults to derive the master encryption key from a user-provided password.
- **WASM-Accelerated Streaming API**: A chunk-based processing API for large files with optional WASM acceleration to minimize memory usage while maximizing performance.
- **Side-Channel Resistant**: Critical comparisons (e.g., tag verification) are performed using constant-time functions to protect against timing attacks.
- **Secure Memory Management**: The implementation uses secure memory management practices to overwrite sensitive key material as soon as it goes out of scope.

## 4. Cryptographic Construction

Quasor is a stateful AEAD built on the following primitives:

| **Role**                   | **Primitive**                                                                            | **Rationale**                                                                         |
| -------------------------- | ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| **Password Hashing**       | Argon2id via hash-wasm                                                                   | Memory-hard KDF to protect user passwords.                                            |
| **Nonce Derivation (SIV)** | BLAKE3 (Keyed) via @noble/hashes/blake3                                                  | Extremely fast, parallelizable hash for deriving a unique nonce from message content. |
| **Core Cipher**            | SHAKE256 Duplex via custom tiny-keccak-sponge implementation to mimic rust's tiny-keccak | A single, elegant primitive for providing both confidentiality and authentication.    |

The high-level process is as follows:

1. A master key `K` is derived from a password and salt using **Argon2id** via hash-wasm.
2. A nonce `N` is derived via `N = BLAKE3(K, len(AD) || AD || len(P) || P)`.
3. A SHAKE256 sponge is initialized by absorbing `K`, `N`, and `AD`.
4. The plaintext is processed sequentially in efficient 1KB chunks, duplexing with the sponge to produce ciphertext. The sponge is automatically re-keyed every 1 MiB.
5. A final authentication tag `T` is squeezed from the sponge's state.

For a complete technical description, see the [**SPEC.md**](https://github.com/Digital-Defiance/Quasor/blob/main/SPEC.md) file.

## 5. Usage Example

### Basic Usage (Automatic Engine Selection)

```typescript
import { Quasor } from '@jessica-mulein/quasor';

async function main() {
  // 1. Quasor automatically selects the fastest available engine
  // (WASM if available, TypeScript fallback)
  const quasor = await Quasor.new(
    new TextEncoder().encode('a_very_strong_password'),
    new TextEncoder().encode('a_unique_salt_for_this_user')
  );

  const plaintext = new TextEncoder().encode(
    'This data is highly confidential.'
  );
  const associatedData = new TextEncoder().encode('message_id:12345');

  // 2. Encrypt the data (WASM acceleration if available)
  const [ciphertext, tag, nonce] = await quasor.encrypt(
    plaintext,
    associatedData
  );

  // 3. Decrypt the data
  const decrypted = await quasor.decrypt(
    nonce,
    ciphertext,
    associatedData,
    tag
  );

  console.log('Decryption successful!');
  console.log('Original:', new TextDecoder().decode(plaintext));
  console.log('Decrypted:', new TextDecoder().decode(decrypted));
}

main().catch(console.error);
```

### Engine Selection and Performance Check

```typescript
import {
  Quasor,
  engineManager,
  QuasorEngine,
  getQuasorEngineStatus,
} from '@jessica-mulein/quasor';

async function performanceExample() {
  // Check current engine status
  const status = await getQuasorEngineStatus();
  console.log('Active engine:', status.activeEngine);
  console.log('Performance:', status.performance.estimatedSpeedup);

  // Force specific engine if needed
  engineManager.setPreferredEngine(QuasorEngine.AUTO); // Recommended
  // engineManager.setPreferredEngine(QuasorEngine.WASM);      // Force WASM
  // engineManager.setPreferredEngine(QuasorEngine.TYPESCRIPT); // Force TypeScript

  const quasor = await Quasor.new(password, salt);
  // Will use the selected engine preference
}
```

### Web Browser Setup

For web applications, you need to serve the WASM files:

```bash
# Copy WASM files to your web server
cp node_modules/@jessica-mulein/quasor/wasm/* public/wasm/
```

See the [Web Integration Guide](./docs/guides/WEB_INTEGRATION_GUIDE.md) for complete web setup instructions.

## 6. Building and Testing

This project is built using Nx with TypeScript. The implementation is compatible with Node.js and modern browsers.

### Prerequisites

- Node.js 18+
- npm or yarn

### Installation

```bash
# Clone the repository
git clone https://github.com/Digital-Defiance/Quasor-TS.git
cd Quasor-TS

# Install dependencies
npm install
```

### Building

```bash
# Build TypeScript only
npx nx build quasor

# Build WASM (for maximum performance)
npm run build:wasm

# Build everything (recommended)
npm run build
```

### Testing

```bash
# Run all tests (includes WASM tests if built)
npm test

# Run TypeScript tests only
npm run test:ts

# Run WASM performance tests
npm run test:wasm
```

### Benchmarks

```bash
# Run all benchmarks (WASM + TypeScript)
npm run bench

# Run WASM benchmarks (fastest)
npm run bench:wasm

# Run TypeScript benchmarks
npm run bench:ts
```

### Linting

```bash
# Run ESLint
npx nx lint quasor

# Fix linting issues automatically
npx nx lint quasor --fix
```

## 7. Project Structure

```
Quasor-TS/
├── quasor/                          # Main library package
│   ├── src/
│   │   ├── lib/
│   │   │   ├── quasor.ts           # Main Quasor implementation
│   │   │   ├── engine-config.ts    # Engine selection and management
│   │   │   ├── wasm-quasor.ts      # WASM integration layer
│   │   │   ├── quasor.spec.ts      # Test suite with KAT
│   │   │   ├── quasor.bench.ts     # Performance benchmarks
│   │   │   └── wasm-performance.spec.ts # WASM performance tests
│   │   ├── wasm/                   # WASM files (included in NPM package)
│   │   └── index.ts               # Export definitions
│   └── package.json
├── wasm-keccak/                    # Keccak WASM implementation
├── quasor-wasm/                    # Quasor WASM implementation
├── build-wasm.ps1                 # WASM build script
├── docs/                          # Documentation guides
├── BENCHMARKS.md                  # Performance benchmarks
└── README.md                      # This file
```

## 8. Security Considerations

- **Research-Grade**: This implementation is for research and educational purposes only.
- **No Formal Review**: Has not undergone formal cryptographic review.
- **Memory Safety**: Uses secure memory management practices but depends on JavaScript's garbage collection.
- **Timing Attacks**: Implements constant-time comparisons where possible.
- **Key Material**: Automatically zeroes key material when possible.

## 8. Performance

The v6.1.4 implementation includes several major optimizations developed through extensive benchmarking and testing:

### Core Optimizations

- **Highly Optimized Byte Operations**: Eliminated expensive BigInt operations in buffer manipulation
- **Cached Buffer Views**: Pre-allocated buffer views for direct byte access in Keccak state
- **Unrolled XOR Operations**: 4-byte vectorized XOR for improved throughput
- **Optimized Keccak Implementation**: Streamlined permutation with pre-computed constants and efficient rotation
- **Reduced Memory Allocations**: Cached domain separation constants and counter bytes
- **Efficient Buffer Management**: Direct byte-level operations without repeated view creation
- **Buffer Pooling**: Reusable buffer pool for KeccakState cloning to reduce allocations

### Latest Performance Results

For detailed benchmark results, see [BENCHMARKS.md](./BENCHMARKS.md).

**WASM Performance Summary:**

- **One-shot Operations**: 285-577 MB/s (WASM-accelerated, up to 565x faster)
- **Streaming Operations**: 300-475 MB/s (WASM-accelerated, up to 460x faster)
- **TypeScript Baseline**: ~1.1 MB/s (universal compatibility)
- **Automatic Selection**: The fastest available engine is used by default

The WASM implementation provides exceptional performance for both one-shot and streaming operations while maintaining full cryptographic compatibility and universal fallback support.

## 9. Documentation

For additional documentation and guides:

- **[BENCHMARKS.md](./BENCHMARKS.md)** - Detailed performance benchmarks and comparisons
- **[docs/](./docs/)** - Additional documentation
  - **[Web Integration Guide](./docs/guides/WEB_INTEGRATION_GUIDE.md)** - Complete guide for using Quasor in web browsers
  - **[Performance Guide](./docs/guides/performance/PERFORMANCE_GUIDE.md)** - Performance optimization and engine selection
  - **[WASM Build Guide](./docs/guides/building/WASM_BUILD_GUIDE.md)** - Building WASM modules from source

## 10. Compatibility

This TypeScript implementation:

- ✅ Passes all Known Answer Tests (KATs) from the Rust reference
- ✅ Produces identical ciphertext and tags for the same inputs
- ✅ Uses the same cryptographic primitives and constants
- ✅ Implements the same domain separation and rekeying logic
- ✅ Compatible with Node.js and modern browsers

## 11. Contributing

Contributions are welcome! Please ensure that:

1. All tests pass (`npx nx test quasor`)
2. Code follows the established patterns
3. New features include appropriate tests
4. Changes maintain compatibility with the Rust reference

## 12. License

This project maintains the same license as the original Rust implementation. See LICENSE file for details.

## 13. References

- [Original Rust Implementation](https://github.com/Digital-Defiance/Quasor)
- [Quasor Specification](https://github.com/Digital-Defiance/Quasor/blob/main/SPEC.md)
- [SHAKE256 Specification](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf)
- [Argon2 Specification](https://tools.ietf.org/html/rfc9106)
- [BLAKE3 Specification](https://github.com/BLAKE3-team/BLAKE3-specs)