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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@well-prado/blok-admin-dashboard

v1.0.14

Published

Complete admin dashboard system for Blok Framework applications with authentication, user management, and security features

Readme

@well-prado/blok-admin-dashboard

Complete admin dashboard with authentication, user management, security, and database operations for Blok Framework.

npm version License: MIT

Overview

The @well-prado/blok-admin-dashboard is a comprehensive backend solution that provides everything you need to build secure, scalable admin applications. It includes 25+ pre-built nodes, 15+ workflows, complete authentication system, user management, security features, and database operations.

Features

  • 🔐 Complete Authentication System - Login, register, session management, password reset
  • 👥 User Management - CRUD operations, role management, profile updates
  • 🛡️ Advanced Security - Rate limiting, audit logging, request interception, 2FA
  • 📊 Database Operations - SQLite with Drizzle ORM, migrations, schemas
  • 📧 Email Integration - Templated emails, verification, notifications
  • 🔍 Workflow Discovery - Automatic API documentation and type generation
  • 📝 Audit Logging - Complete activity tracking and system logs
  • High Performance - Optimized queries, caching, connection pooling

Installation

npm install @well-prado/blok-admin-dashboard

Or use the CLI for automatic setup:

npx @well-prado/blok-cli install admin-dashboard

Quick Start

1. Basic Setup

// src/index.ts
import { AdminDashboard } from "@well-prado/blok-admin-dashboard";

const dashboard = new AdminDashboard({
  database: {
    url: "file:./database/app.db",
  },
  auth: {
    sessionDuration: 3600, // 1 hour
    requireEmailVerification: true,
  },
  security: {
    rateLimiting: true,
    auditLogging: true,
  },
});

// Start the server
dashboard.start(4000);

2. With Custom Configuration

import { AdminDashboard, AdminConfig } from "@well-prado/blok-admin-dashboard";

const config: AdminConfig = {
  database: {
    url: process.env.DATABASE_URL || "file:./database/app.db",
    enableWAL: true,
    connectionPooling: true,
  },
  auth: {
    sessionDuration: 7200, // 2 hours
    passwordMinLength: 8,
    requireEmailVerification: false,
    allowRegistration: true,
  },
  security: {
    rateLimiting: {
      enabled: true,
      windowMs: 15 * 60 * 1000, // 15 minutes
      maxRequests: 100,
    },
    auditLogging: true,
    requestInterception: true,
  },
  email: {
    provider: "smtp",
    config: {
      host: process.env.SMTP_HOST,
      port: parseInt(process.env.SMTP_PORT || "587"),
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
    },
  },
};

const dashboard = new AdminDashboard(config);
dashboard.start(process.env.PORT || 4000);

Architecture

Node Categories

The package includes 25+ nodes organized into 8 categories:

🔐 Authentication Nodes (7 nodes)

  • authentication-checker - Validates user sessions and permissions
  • password-hash - Secure password hashing with bcrypt
  • password-verify - Password verification and validation
  • user-login - User login with session creation
  • user-logout - Session cleanup and logout
  • user-register - New user registration with validation

👥 Database Nodes (4 nodes)

  • user-find - Find users by various criteria
  • user-list - Paginated user listings with filtering
  • user-update - Update user information with validation
  • user-delete - Safe user deletion with audit trail

🛡️ Security Nodes (6 nodes)

  • audit-logger - Log all system activities
  • rate-limiter - Prevent abuse with configurable limits
  • request-interceptor - Inspect and modify requests
  • system-action-logger - Track administrative actions
  • two-factor-auth - TOTP-based 2FA implementation

✅ Validation Nodes (3 nodes)

  • email-validator - Email format and domain validation
  • input-sanitizer - Clean and sanitize user inputs
  • password-validator - Password strength validation

📧 Email Nodes (3 nodes)

  • EmailServiceManager - Multi-provider email handling
  • EmailTemplates - Template management and rendering
  • EmailVerification - Email verification workflows

📊 Profile Nodes (3 nodes)

  • profile-image-upload - Handle avatar uploads
  • theme-preference-update - User theme preferences
  • user-profile-update - Complete profile management

🔍 Meta Nodes (2 nodes)

  • workflow-discovery - Automatic API documentation

🔔 Notification Nodes (5 nodes)

  • clear-all-notifications - Bulk notification management
  • create-notification - Create system notifications
  • get-user-notifications - Fetch user notifications
  • mark-notification-read - Mark notifications as read

Workflow Categories

The package includes 15+ workflows organized by functionality:

Authentication Workflows

  • auth/login - User login with session creation
  • auth/logout - Session cleanup
  • auth/register - User registration
  • auth/verify-session - Session validation
  • auth/protected-example - Protected route example

Admin Workflows

  • admin/dashboard - Admin dashboard data
  • admin/user-management - User CRUD operations
  • admin/user-role-management - Role assignments
  • admin/admin-logs - System activity logs

Profile Workflows

  • profile/profile-update - User profile updates
  • profile/profile-image-upload - Avatar management
  • profile/theme-preferences - Theme settings

Security Workflows

  • security/audit-logs - Security event logs
  • security/two-factor-auth - 2FA setup and verification
  • security/rate-limit-test - Rate limiting demonstrations

Database Schema

The package includes complete database schemas with migrations:

Users Table

CREATE TABLE users (
  id TEXT PRIMARY KEY,
  email TEXT UNIQUE NOT NULL,
  password_hash TEXT NOT NULL,
  name TEXT NOT NULL,
  role TEXT DEFAULT 'user',
  avatar TEXT,
  email_verified BOOLEAN DEFAULT FALSE,
  theme_preference TEXT DEFAULT 'system',
  notification_preferences TEXT DEFAULT '{}',
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

Sessions Table

CREATE TABLE sessions (
  id TEXT PRIMARY KEY,
  user_id TEXT NOT NULL,
  expires_at DATETIME NOT NULL,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
);

Audit Logs Table

CREATE TABLE audit_logs (
  id TEXT PRIMARY KEY,
  user_id TEXT,
  action TEXT NOT NULL,
  resource TEXT,
  resource_id TEXT,
  details TEXT,
  ip_address TEXT,
  user_agent TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

System Logs Table

CREATE TABLE system_logs (
  id TEXT PRIMARY KEY,
  level TEXT NOT NULL,
  message TEXT NOT NULL,
  category TEXT,
  user_id TEXT,
  session_id TEXT,
  metadata TEXT,
  created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);

API Endpoints

Authentication Endpoints

POST /auth/login

Login with email and password.

Request:

{
  "email": "[email protected]",
  "password": "securepassword"
}

Response:

{
  "success": true,
  "data": {
    "user": {
      "id": "user_123",
      "email": "[email protected]",
      "name": "John Doe",
      "role": "user"
    },
    "session": {
      "id": "session_456",
      "expiresAt": "2024-01-01T12:00:00Z"
    }
  }
}

POST /auth/register

Register a new user.

Request:

{
  "email": "[email protected]",
  "password": "securepassword",
  "name": "Jane Doe"
}

POST /auth/logout

Logout and destroy session.

Request:

{
  "sessionId": "session_456"
}

User Management Endpoints

GET /admin/users

Get paginated list of users (admin only).

Query Parameters:

  • page - Page number (default: 1)
  • limit - Items per page (default: 10)
  • search - Search term
  • role - Filter by role

Response:

{
  "success": true,
  "data": {
    "users": [...],
    "pagination": {
      "page": 1,
      "limit": 10,
      "total": 50,
      "totalPages": 5
    }
  }
}

PUT /admin/users/:id

Update user information (admin only).

DELETE /admin/users/:id

Delete user (admin only).

Profile Endpoints

GET /profile

Get current user profile.

PUT /profile

Update current user profile.

Request:

{
  "name": "Updated Name",
  "themePreference": "dark",
  "notificationPreferences": {
    "email": true,
    "push": false
  }
}

POST /profile/avatar

Upload profile avatar.

Security Endpoints

GET /admin/audit-logs

Get audit logs (admin only).

GET /admin/system-logs

Get system logs (admin only).

POST /security/2fa/setup

Setup two-factor authentication.

POST /security/2fa/verify

Verify 2FA token.

Configuration Options

Complete Configuration

interface AdminConfig {
  // Database configuration
  database: {
    url: string;
    enableWAL?: boolean;
    connectionPooling?: boolean;
    maxConnections?: number;
    queryTimeout?: number;
  };

  // Authentication settings
  auth: {
    sessionDuration?: number; // seconds
    passwordMinLength?: number;
    passwordRequireSpecialChar?: boolean;
    requireEmailVerification?: boolean;
    allowRegistration?: boolean;
    maxLoginAttempts?: number;
    lockoutDuration?: number; // seconds
  };

  // Security configuration
  security: {
    rateLimiting?: {
      enabled: boolean;
      windowMs: number;
      maxRequests: number;
    };
    auditLogging?: boolean;
    requestInterception?: boolean;
    corsOrigins?: string[];
    trustedProxies?: string[];
  };

  // Email configuration
  email: {
    provider: "smtp" | "sendgrid" | "mailgun";
    config: {
      // SMTP configuration
      host?: string;
      port?: number;
      secure?: boolean;
      auth?: {
        user: string;
        pass: string;
      };
      // Or API key for other providers
      apiKey?: string;
    };
    templates?: {
      welcome?: string;
      passwordReset?: string;
      emailVerification?: string;
    };
  };

  // Server configuration
  server: {
    port?: number;
    host?: string;
    cors?: {
      origin: string | string[];
      credentials: boolean;
    };
    bodyParser?: {
      limit: string;
    };
  };
}

Advanced Usage

Custom Nodes

Extend the dashboard with custom nodes:

import { AdminDashboard, BaseNode } from "@well-prado/blok-admin-dashboard";

class CustomReportNode extends BaseNode {
  async handle(input: any) {
    // Custom logic here
    return {
      success: true,
      data: { report: "Generated report data" },
    };
  }
}

const dashboard = new AdminDashboard(config);
dashboard.registerNode("custom-report", CustomReportNode);

Custom Workflows

Add custom workflows:

const customWorkflow = {
  name: "custom-analytics",
  steps: [
    {
      node: "authentication-checker",
      config: { requireAuth: true, requiredRole: "admin" },
    },
    {
      node: "custom-report",
      config: { reportType: "analytics" },
    },
  ],
};

dashboard.registerWorkflow(customWorkflow);

Middleware

Add custom middleware:

dashboard.use((req, res, next) => {
  console.log(`${req.method} ${req.path}`);
  next();
});

// Authentication middleware
dashboard.use("/admin/*", async (req, res, next) => {
  const session = await validateSession(req);
  if (!session || session.user.role !== "admin") {
    return res.status(403).json({ error: "Admin access required" });
  }
  next();
});

Database Operations

Direct database access:

import { database } from "@well-prado/blok-admin-dashboard";
import { users, sessions } from "@well-prado/blok-admin-dashboard/schemas";

// Query users
const allUsers = await database.select().from(users);

// Create user
const newUser = await database.insert(users).values({
  id: generateId(),
  email: "[email protected]",
  passwordHash: await hashPassword("password"),
  name: "New User",
});

// Update user
await database
  .update(users)
  .set({ name: "Updated Name" })
  .where(eq(users.id, userId));

// Delete user
await database.delete(users).where(eq(users.id, userId));

Security Features

Rate Limiting

Configurable rate limiting per endpoint:

const config = {
  security: {
    rateLimiting: {
      enabled: true,
      windowMs: 15 * 60 * 1000, // 15 minutes
      maxRequests: 100,
      skipSuccessfulRequests: false,
      skipFailedRequests: false,
    },
  },
};

Audit Logging

All actions are automatically logged:

// Automatically logged actions:
// - User login/logout
// - User creation/update/deletion
// - Admin actions
// - Security events
// - System errors

// Custom audit logging
import { auditLogger } from "@well-prado/blok-admin-dashboard";

await auditLogger.log({
  userId: "user_123",
  action: "CUSTOM_ACTION",
  resource: "custom_resource",
  resourceId: "resource_456",
  details: { customData: "value" },
});

Two-Factor Authentication

Built-in TOTP-based 2FA:

// Setup 2FA for user
const setup2FA = useWorkflowMutation("security/two-factor-auth");
const { qrCode, secret } = await setup2FA.mutateAsync({ action: "setup" });

// Verify 2FA token
const verify2FA = useWorkflowMutation("security/two-factor-auth");
const result = await verify2FA.mutateAsync({
  action: "verify",
  token: "123456",
});

Email Integration

SMTP Configuration

const config = {
  email: {
    provider: "smtp",
    config: {
      host: "smtp.gmail.com",
      port: 587,
      secure: false,
      auth: {
        user: "[email protected]",
        pass: "your-app-password",
      },
    },
  },
};

Email Templates

Customize email templates:

const config = {
  email: {
    templates: {
      welcome: `
        <h1>Welcome to {{appName}}!</h1>
        <p>Hello {{userName}}, welcome to our platform.</p>
      `,
      passwordReset: `
        <h1>Password Reset</h1>
        <p>Click <a href="{{resetLink}}">here</a> to reset your password.</p>
      `,
    },
  },
};

Sending Emails

import { emailService } from "@well-prado/blok-admin-dashboard";

await emailService.send({
  to: "[email protected]",
  subject: "Welcome!",
  template: "welcome",
  data: {
    userName: "John Doe",
    appName: "My App",
  },
});

Monitoring and Logging

System Logs

View system logs:

import { systemLogger } from "@well-prado/blok-admin-dashboard";

// Log custom events
systemLogger.info("Custom event", {
  category: "CUSTOM",
  userId: "user_123",
  metadata: { customData: "value" },
});

// Query logs
const logs = await systemLogger.query({
  level: "error",
  category: "AUTH",
  startDate: new Date("2024-01-01"),
  endDate: new Date("2024-01-31"),
});

Health Checks

Built-in health check endpoints:

# Check system health
GET /health

# Response
{
  "status": "healthy",
  "timestamp": "2024-01-01T12:00:00Z",
  "checks": {
    "database": "healthy",
    "email": "healthy",
    "cache": "healthy"
  }
}

Testing

Unit Tests

import { AdminDashboard } from "@well-prado/blok-admin-dashboard";
import { createTestConfig } from "@well-prado/blok-admin-dashboard/testing";

describe("Admin Dashboard", () => {
  let dashboard: AdminDashboard;

  beforeEach(() => {
    dashboard = new AdminDashboard(createTestConfig());
  });

  test("should authenticate user", async () => {
    const result = await dashboard.executeWorkflow("auth/login", {
      email: "[email protected]",
      password: "password",
    });

    expect(result.success).toBe(true);
    expect(result.data.user.email).toBe("[email protected]");
  });
});

Integration Tests

import request from "supertest";
import { AdminDashboard } from "@well-prado/blok-admin-dashboard";

describe("API Integration", () => {
  let app: AdminDashboard;

  beforeAll(async () => {
    app = new AdminDashboard(testConfig);
    await app.start();
  });

  test("POST /auth/login", async () => {
    const response = await request(app.server).post("/auth/login").send({
      email: "[email protected]",
      password: "password",
    });

    expect(response.status).toBe(200);
    expect(response.body.success).toBe(true);
  });
});

Deployment

Production Configuration

const productionConfig = {
  database: {
    url: process.env.DATABASE_URL,
    enableWAL: true,
    connectionPooling: true,
    maxConnections: 20,
  },
  auth: {
    sessionDuration: 3600, // 1 hour
    requireEmailVerification: true,
  },
  security: {
    rateLimiting: {
      enabled: true,
      windowMs: 15 * 60 * 1000,
      maxRequests: 1000,
    },
    auditLogging: true,
    corsOrigins: [process.env.FRONTEND_URL],
  },
  server: {
    port: process.env.PORT || 4000,
    host: "0.0.0.0",
  },
};

Docker Deployment

FROM node:18-alpine

WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

COPY . .
RUN npm run build

EXPOSE 4000
CMD ["npm", "start"]

Environment Variables

# Database
DATABASE_URL=file:./database/app.db

# Authentication
SESSION_DURATION=3600
REQUIRE_EMAIL_VERIFICATION=true

# Email
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
[email protected]
SMTP_PASS=your-app-password

# Security
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# Server
PORT=4000
NODE_ENV=production

Migration Guide

From v0.x to v1.x

  1. Update configuration format:

    // Old
    const config = {
      databaseUrl: "file:./app.db",
      sessionDuration: 3600,
    };
    
    // New
    const config = {
      database: { url: "file:./app.db" },
      auth: { sessionDuration: 3600 },
    };
  2. Update imports:

    // Old
    import { AdminDashboard } from "@well-prado/blok-admin-dashboard/core";
    
    // New
    import { AdminDashboard } from "@well-prado/blok-admin-dashboard";

Troubleshooting

Common Issues

  1. Database connection errors

    • Check file permissions for SQLite database
    • Ensure database directory exists
    • Verify connection string format
  2. Authentication failures

    • Check session configuration
    • Verify password hashing
    • Ensure cookies are being sent
  3. Email sending failures

    • Verify SMTP credentials
    • Check firewall settings
    • Test with email provider's test tools

Debug Mode

Enable debug logging:

DEBUG=blok-admin:* npm start

Performance Tips

  1. Database Optimization

    • Enable WAL mode for better concurrency
    • Use connection pooling
    • Add appropriate indexes
  2. Caching

    • Enable session caching
    • Cache frequently accessed data
    • Use Redis for distributed caching
  3. Rate Limiting

    • Configure appropriate limits
    • Use distributed rate limiting for multiple servers

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Related Packages