npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

secure-offline-json-db

v1.0.0

Published

A secure offline JSON database with input validation, rate limiting, and logging.

Downloads

80

Readme

Secure Json Offline Database

secure-offline-json-db is an offline JSON database designed with security features such as input validation, rate limiting, file permissions, and logging. It allows you to store, retrieve, and manage records in a secure, JSON-based file system while preventing common attack vectors.

Features

Schema Validation: Uses Joi to validate records based on customizable schemas. Rate Limiting: Protects against overuse by rate limiting incoming requests. File Permissions: Ensures that the database file has strict read/write access. Logging: Integrates with morgan to log requests and monitor system access. CRUD Operations: Supports creating, reading, updating, and deleting records.

Installation

To install the package, run:

npm install secure-ofline-json-db

Usage

1. Initializing the Database

To use secure-offline-json-db, import the package and create an instance by passing the path to the JSON file and the Joi schema for record validation.

const JsonOfflineDb = require('secure-offline-json-db');
const Joi = require('joi');

// Define the schema for records
const recordSchema = Joi.object({
    id: Joi.number().required(),
    name: Joi.string().min(3).required(),
    age: Joi.number().integer().min(18).max(100).required(),
});

// Initialize the database
const db = new JsonOfflineDb('./db.json', recordSchema);

2. CRUD Operations

Read All Records To retrieve all records stored in the JSON database:

const records = db.read();
console.log(records);

Create a Record To add a new record to the database, pass the record object to the create method:

const newRecord = {
    id: 1,
    name: "John Doe",
    age: 25,
};

db.create(newRecord);

Update a Record To update an existing record, pass the id of the record and an object with the updated values:

const updatedRecord = db.update(1, { age: 26 });
console.log(updatedRecord);

Delete a Record

To delete a record by its id, use the delete method:

db.delete(1);
console.log("Record deleted successfully.");

3. Security Features

Input Validation

Records are validated against the schema you provide when initializing the database. If a record does not meet the validation criteria, an error will be thrown.

try {
    const invalidRecord = { id: 2, name: "A", age: 17 }; // Invalid record
    db.create(invalidRecord);
} catch (error) {
    console.error(error.message); // Validation error
}

Rate Limiting

To prevent excessive requests, secure-offline-json-db includes rate limiting. You can apply rate limiting to IP addresses before performing database operations.

await db.applyRateLimit(req.ip); // Rate limit applied

File Permissions The database file (db.json) is created with strict read/write permissions (owner-only). This prevents unauthorized access to the database file at the filesystem level.

Logging The package supports logging of incoming requests through morgan. You can log request data, errors, and response times to monitor activity.

const morgan = require('morgan');
app.use(morgan('dev')); // Logs HTTP requests

Using with Next.js

You can easily integrate secure-offline-json-db with a Next.js backend to manage your offline database. Below is an example of using the package in Next.js API routes.

  1. Install Next.js:

    npx create-next-app@latest
    cd my-nextjs-app
  2. Install secure-json-db within your Next.js project:

    npm install secure-json-db
  3. Create an API route in Next.js (pages/api/records.js):

    import JsonOfflineDb from 'secure-json-db';
    import Joi from 'joi';
    
    const recordSchema = Joi.object({
        id: Joi.number().required(),
        name: Joi.string().min(3).required(),
        age: Joi.number().integer().min(18).max(100).required(),
    });
    
    const db = new JsonOfflineDb('./db.json', recordSchema);
    
    export default async function handler(req, res) {
        const { method } = req;
    
        try {
            switch (method) {
                case 'GET':
                    const records = db.read();
                    res.status(200).json(records);
                    break;
                case 'POST':
                    const newRecord = db.create(req.body);
                    res.status(201).json(newRecord);
                    break;
                case 'PUT':
                    const updatedRecord = db.update(req.body.id, req.body);
                    res.status(200).json(updatedRecord);
                    break;
                case 'DELETE':
                    db.delete(req.body.id);
                    res.status(200).json({ message: "Record deleted" });
                    break;
                default:
                    res.setHeader('Allow', ['GET', 'POST', 'PUT', 'DELETE']);
                    res.status(405).end(`Method ${method} Not Allowed`);
            }
        } catch (error) {
            res.status(400).json({ error: error.message });
        }
    }
  4. Start the Next.js server:

    npm run dev

Now, you can interact with the secure JSON database via API routes in Next.js.


Using with React Native

You can access the secure-offline-json-db backend via API calls in a React Native app.

  1. Install axios in your React Native project:

    npm install axios
  2. Use the axios library to interact with the database:

    import axios from 'axios';
    import React, { useEffect, useState } from 'react';
    import { View, Text, FlatList, StyleSheet } from 'react-native';
    
    const App = () => {
        const [records, setRecords] = useState([]);
    
        useEffect(() => {
            axios.get('http://localhost:4000/api/records')
                .then(response => {
                    setRecords(response.data);
                })
                .catch(error => {
                    console.error('Error fetching records:', error);
                });
        }, []);
    
        return (
            <View style={styles.container}>
                <FlatList
                    data={records}
                    keyExtractor={item => item.id.toString()}
                    renderItem={({ item }) => (
                        <Text>{item.name} - {item.age} years old</Text>
                    )}
                />
            </View>
        );
    };
    
    const styles = StyleSheet.create({
        container: {
            flex: 1,
            justifyContent: 'center',
            padding: 16,
        },
    });
    
    export default App;

In this example, your React Native app makes requests to the secure-offline-json-db backend running on localhost:4000.


Security Best Practices

Rate Limiting: Ensure rate limiting is configured to prevent abuse. Environment Variables: Use environment variables for sensitive data. File Permissions: Ensure the database file is protected with restricted permissions. Validation: Always validate inputs to prevent invalid or malicious data from entering the system.


Changelog

1.0.0

  • Initial release with support for JSON storage, schema validation, rate limiting, and request logging.

License

MIT License