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

sedric-sdk-audit

v1.0.5

Published

The `Sedric SDK` is a standalone Node.js SDK designed to provide audit logging capabilities with a focus on high throughput (up to 100,000 requests per minute). The SDK leverages Drizzle ORM for writing audit logs to a PostgreSQL database.

Downloads

42

Readme

Sedric SDK

The Sedric SDK is a standalone Node.js SDK designed to provide audit logging capabilities with a focus on high throughput (up to 100,000 requests per minute). The SDK leverages Drizzle ORM for writing audit logs to a PostgreSQL database.

Prerequisites

  • Node.js v18.x or later
  • TypeScript v5.x or later
  • npm (Node Package Manager)
  • PostgreSQL database
  • VPN access (if required for database testing)

Installation

To use the Sedric SDK in your Node.js project, first install it via npm:

npm install @sedric/sdk-audit
Usage
Import and use the SDK in your project:

typescript
Copy code
import { trackInsert, trackUpdate, trackDelete, logAuditEvent } from '@sedric/sdk-audit';

// Example usage
await trackInsert({
  userId: 'user-123',
  tableName: 'users',
  newData: { name: 'John Doe', email: '[email protected]' },
  transactionId: 'txn-001',
  username: 'johndoe',
  role: 'admin',
});
Development
Setting Up the Project
Clone the repository:

bash
Copy code
git clone https://github.com/your-username/sedric-sdk-audit.git
cd sedric-sdk-audit
Install dependencies:

bash
Copy code
npm install
Run the tests:

bash
Copy code
npm test
Running the SDK Locally
To run the SDK locally with ts-node, use the following command:

bash
Copy code
ts-node --esm src/index.ts
Version Management
We use SemVer (Semantic Versioning) for versioning the SDK:

MAJOR version: Incompatible API changes
MINOR version: New functionality added in a backwards-compatible manner
PATCH version: Backwards-compatible bug fixes
Publishing the SDK to npm
Step 1: Bump the Version
Use npm version to update the version:

For a major release:

bash
Copy code
npm version major
For a minor release:

bash
Copy code
npm version minor
For a patch release:

bash
Copy code
npm version patch
This command will:

Update the version field in package.json.
Create a new Git commit with the version bump.
Create a Git tag for the release.
Step 2: Build the SDK
Ensure your TypeScript code is compiled before publishing:

bash
Copy code
npm run build
This should compile the code into the dist/ folder.

Step 3: Publish to npm
To publish the SDK, run:

bash
Copy code
npm publish
Make sure you are logged in to npm:

bash
Copy code
npm login
If your package is scoped (e.g., @sedric/sdk-audit), ensure you publish it as a public package:

bash
Copy code
npm publish --access public
Step 4: Push Changes to GitHub
After publishing, push the changes and tags to GitHub:

bash
Copy code
git push origin main --tags
Releasing Beta Versions
For beta or pre-release versions, use the following command:

bash
Copy code
npm version prerelease --preid=beta
npm publish --tag beta
This allows you to publish a version like 1.0.1-beta.0.

Managing npm Tags
latest: The default and stable version.
beta: The latest beta version for testing.
To update the latest tag to a specific version:

bash
Copy code
npm dist-tag add @sedric/[email protected] latest
To remove a tag:

bash
Copy code
npm dist-tag rm @sedric/sdk-audit beta
Changelog
Ensure that every release includes an updated CHANGELOG.md documenting all changes. Use Keep a Changelog format.

#run localy postgres script for testing
# CREATE TABLE IF NOT EXISTS audit_logs (
#   id TEXT,
#   table_name TEXT NOT NULL,
#   action TEXT NOT NULL,
#   changed_data TEXT DEFAULT NULL, -- Matches the updated default value
#   timestamp TIMESTAMP DEFAULT NOW(),
#   user_id TEXT NOT NULL,
#   username TEXT NOT NULL,
#   role TEXT NOT NULL
# );

# -- Create index on `table_name` for faster filtering by table
# CREATE INDEX IF NOT EXISTS idx_audit_logs_table_name ON audit_logs (table_name);

# -- Create index on `timestamp` for faster filtering by time range
# CREATE INDEX IF NOT EXISTS idx_audit_logs_timestamp ON audit_logs (timestamp);

# -- Create index on `user_id` for faster queries related to a specific user
# CREATE INDEX IF NOT EXISTS idx_audit_logs_user_id ON audit_logs (user_id);


## example how to implement sdk in existing project
/**
 * Middleware to enable audit logging.
 *
 * @param {boolean} enabled - Flag to enable or disable logging.
 * @returns {Function} Middleware function to handle audit logging.
 *
 * The middleware configures logging based on the `enabled` parameter and attaches
 * a listener to the response's 'finish' event to track insert operations.
 *
 * Example usage:
 * ```typescript
 * app.use(auditLoggingMiddleware(true));
 * ```
 *
 * The listener logs an insert operation with the following details:
 * - `userId`: ID of the user making the request, or 'system' if not available.
 * - `tableName`: Name of the table being modified (example in this case).
 * - `newData`: New data being inserted (example data in this case).
 * - `transactionId`: ID of the transaction (example in this case).
 * - `username`: Name of the user making the request, or 'system' if not available.
 * - `role`: Role of the user making the request, or 'system' if not available.
 */
 middleware/audit-logging-middleware.ts
import { configureLogging, trackInsert, trackUpdate, trackDelete } from '../services/audit-logger';

export const auditLoggingMiddleware = (enabled: boolean) => {
  configureLogging(enabled);

  return async (req: any, res: any, next: any) => {
    // Example usage:
    res.on('finish', async () => {
      // Optionally flush logs after the response is sent.
      await trackInsert({
        userId: req.user?.id || 'system',
        tableName: 'example',
        newData: { key: 'value' },
        transactionId: 'tx_example',
        username: req.user?.name || 'system',
        role: req.user?.role || 'system',
      });
    });

    next();
  };
};

Apply Middleware
Apply the middleware in your server setup:

typescript
Copy code
// server.ts

import { auditLoggingMiddleware } from './middleware/audit-logging-middleware';

const app = express();

// Enable or disable logging globally
app.use(auditLoggingMiddleware(true)); // Pass `false` to disable

app.listen(3000, () => {
  console.log('Server running on port 3000');
});
License
MIT License. See the LICENSE file for details.