1.0.2 โ€ข Published 7 months ago

encstream v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
7 months ago

๐Ÿ” EncStream

npm version downloads license

โœจ Features

  • ๐Ÿ”’ End-to-End Encryption: AES-256-GCM encryption for all API requests
  • ๐Ÿš€ Next.js App Router Ready: Built specifically for modern Next.js applications
  • ๐ŸŽฏ Zero Config: Works out of the box with sensible defaults
  • ๐Ÿ” Debug Mode: Built-in debugging tools for development
  • ๐Ÿ“ TypeScript Support: Full type definitions included
  • ๐Ÿ›ก๏ธ Security First: Request signing and timestamp validation

๐Ÿ“ฆ Installation

npm install encstream

๐Ÿš€ Quick Start

1. Set Up Environment Variables

# .env.local
ENCRYPTION_KEY=your-secret-key-min-32-chars-long!!
API_BASE_URL=http://localhost:3000  # Your API base URL

2. Create Proxy Route

// app/api/proxy/route.ts
import { NextResponse } from 'next/server';
import { Encryptor } from 'encstream';

const secretKey = process.env.ENCRYPTION_KEY!;
const baseUrl = process.env.API_BASE_URL || 'http://localhost:3000';

const encryptor = new Encryptor({
  secretKey,
  debug: true // Enable for development
});

export async function POST(request: Request) {
  try {
    const encryptedPayload = await request.json();
    
    // Validate payload structure
    if (!encryptedPayload?.data || !encryptedPayload?.signature) {
      throw new Error('Invalid encrypted payload structure');
    }

    // Decrypt and extract request details
    const decrypted = await encryptor.decrypt(encryptedPayload);
    const { target, data } = decrypted as { target: string; data: any };

    if (!target) {
      throw new Error('Missing target endpoint');
    }

    // Forward request to actual endpoint
    const response = await fetch(`${baseUrl}${target}`, {
      method: data.method || 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
      ...(data.body ? { body: data.body } : {}),
    });

    const responseData = await response.json();
    const encryptedResponse = await encryptor.encrypt(responseData);
    
    return NextResponse.json(encryptedResponse);
  } catch (error: any) {
    console.error('Proxy error:', error);
    return NextResponse.json(
      { error: error.message || 'Proxy request failed' },
      { status: 400 }
    );
  }
}

3. Create Client Component

// components/SecureForm.tsx
'use client';

import { useState } from 'react';
import { useEncStream } from 'encstream';

const config = {
  secretKey: process.env.NEXT_PUBLIC_ENCRYPTION_KEY!,
  debug: true // Enable for development
};

export default function SecureForm() {
  const [message, setMessage] = useState('');
  const { makeSecureRequest } = useEncStream(config);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      const response = await makeSecureRequest('/api/users', {
        method: 'POST',
        body: JSON.stringify({ message })
      });
      console.log('Response:', response);
    } catch (err) {
      console.error('Error:', err);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
      />
      <button type="submit">Send Secure Request</button>
    </form>
  );
}

๐Ÿ› ๏ธ Advanced Usage

Custom Headers

const response = await makeSecureRequest('/api/data', {
  method: 'POST',
  headers: {
    'Custom-Header': 'value'
  },
  body: JSON.stringify(data)
});

TypeScript Support

import { EncStreamConfig, SecureResponse } from 'encstream';

interface UserData {
  id: string;
  name: string;
}

const response = await makeSecureRequest<UserData>('/api/user');
// response is typed as SecureResponse<UserData>

๐Ÿ”’ Security Features

Encryption Process

  1. Request Encryption:

    • AES-256-GCM encryption
    • Unique IV per request
    • Timestamp validation
    • Request signing
  2. Proxy Handling:

    • Payload validation
    • Signature verification
    • Secure decryption
    • Endpoint forwarding
  3. Response Encryption:

    • Secure response encryption
    • Integrity checks
    • New IV per response

๐Ÿค Contributing

We welcome contributions! Here's how you can help:

  1. ๐Ÿ› Report Bugs: Open an issue with detailed information
  2. ๐Ÿ’ก Suggest Features: Share your ideas in issues
  3. ๐Ÿ”ง Submit PRs: Check our contributing guidelines
  4. ๐Ÿ“š Improve Docs: Help us make docs better
  5. โญ Star the Project: Show your support!

See CONTRIBUTING.md for details.

๐Ÿ“ License

MIT


1.0.2

7 months ago

1.0.1

7 months ago

1.0.0

7 months ago