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

kim-auth

v2.0.0

Published

Production-ready Authentication & Authorization (JWT, API Key, OAuth2)

Readme

kim-auth

Production-Ready Authentication & Authorization System

Version: 2.0.0

Features

Core

  • JWT Authentication - Access + Refresh tokens
  • API Key Management - Create, list, revoke
  • Scope-based Authorization - Fine-grained permissions
  • bcrypt Password Hashing - Industry standard (12 rounds)
  • SQLite Database - Zero-config persistence
  • Redis Session Store - Optional distributed support
  • Audit Logging - Full authentication trail
  • Rate Limiting - IP-based protection
  • Helmet Security - Security headers
  • Winston Logging - Structured logs

Production-Ready

  • Token blacklisting (logout support)
  • Refresh token rotation
  • API key expiration
  • User role management
  • Internal validation API (for microservices)
  • Graceful shutdown
  • Health check endpoint

Quick Start

1. Install Dependencies

npm install

2. Environment Setup

cp .env.example .env

Edit .env:

JWT_SECRET=your-very-secure-secret-min-64-characters-recommended
PORT=50300

3. Initialize Database

npm run migrate

4. Start Server

npm start

Server runs on http://localhost:50300

Default admin: admin / admin123

API Documentation

Authentication

Login

POST /auth/login
Content-Type: application/json

{
  "userId": "admin",
  "password": "admin123"
}

# Response
{
  "accessToken": "eyJhbGc...",
  "refreshToken": "a1b2c3...",
  "expiresIn": "24h",
  "tokenType": "Bearer",
  "user": {
    "id": "admin",
    "name": "Administrator",
    "role": "admin"
  }
}

Refresh Token

POST /auth/refresh
Content-Type: application/json

{
  "refreshToken": "a1b2c3..."
}

# Response
{
  "accessToken": "eyJhbGc...",
  "expiresIn": "24h",
  "tokenType": "Bearer"
}

Logout

POST /auth/logout
Authorization: Bearer eyJhbGc...
Content-Type: application/json

{
  "refreshToken": "a1b2c3..."
}

Verify Token

POST /auth/verify
Content-Type: application/json

{
  "token": "eyJhbGc..."
}

# Response
{
  "valid": true,
  "payload": {
    "userId": "admin",
    "name": "Administrator",
    "role": "admin"
  },
  "expiresAt": "2026-01-05T12:00:00Z"
}

API Keys

Create API Key

POST /api-keys
Authorization: Bearer eyJhbGc...
Content-Type: application/json

{
  "name": "Production API",
  "scopes": ["read", "write"],
  "expiresInDays": 90
}

# Response
{
  "apiKey": "kim_a1b2c3d4e5f6...",
  "prefix": "kim_a1b2c3d4...",
  "name": "Production API",
  "scopes": ["read", "write"],
  "expiresAt": "2026-04-05T00:00:00Z"
}

⚠️ Save the full API key - it's only shown once!

List API Keys

GET /api-keys
Authorization: Bearer eyJhbGc...

# Response
{
  "keys": [
    {
      "prefix": "kim_a1b2c3d4...",
      "name": "Production API",
      "scopes": ["read", "write"],
      "createdAt": "2026-01-04T00:00:00Z",
      "lastUsed": "2026-01-04T12:00:00Z",
      "expiresAt": "2026-04-05T00:00:00Z"
    }
  ],
  "count": 1
}

Delete API Key

DELETE /api-keys/kim_a1b2c3d4
Authorization: Bearer eyJhbGc...

User Management

Create User (Admin Only)

POST /users
Authorization: Bearer eyJhbGc...
Content-Type: application/json

{
  "userId": "john",
  "name": "John Doe",
  "email": "[email protected]",
  "password": "secure123",
  "role": "user"
}

Get Current User

GET /users/me
Authorization: Bearer eyJhbGc...
# or
X-API-Key: kim_a1b2c3d4...

# Response
{
  "id": "admin",
  "name": "Administrator",
  "email": "[email protected]",
  "role": "admin",
  "apiKeyCount": 2,
  "lastLogin": "2026-01-04T12:00:00Z"
}

Internal Validation

For microservices to validate tokens/keys:

POST /internal/validate
Content-Type: application/json

{
  "token": "eyJhbGc...",
  "requiredScopes": ["read"]
}

# Response
{
  "valid": true,
  "type": "jwt",
  "user": {
    "userId": "admin",
    "name": "Administrator",
    "role": "admin",
    "scopes": ["*"]
  }
}

Health Check

GET /health

# Response
{
  "status": "ok",
  "service": "kim-auth",
  "version": "2.0.0",
  "users": 5,
  "redis": "connected"
}

Using API Keys

Header Method (Recommended)

GET /users/me
X-API-Key: kim_a1b2c3d4e5f6...

Query Parameter

GET /users/me?api_key=kim_a1b2c3d4e5f6...

Authorization Scopes

  • * - Full access (admin)
  • read - Read-only access
  • write - Write access
  • delete - Delete access
  • admin - Admin operations
  • user:create - Create users
  • Custom scopes supported

Environment Variables

| Variable | Default | Description | |----------|---------|-------------| | NODE_ENV | development | Environment | | PORT | 50300 | Server port | | HOST | 0.0.0.0 | Bind address | | JWT_SECRET | Required | JWT signing secret (min 32 chars) | | JWT_EXPIRES_IN | 24h | Access token lifetime | | REFRESH_TOKEN_EXPIRES_DAYS | 7 | Refresh token days | | BCRYPT_ROUNDS | 12 | Password hash rounds | | DB_PATH | ./data/auth.db | SQLite database path | | REDIS_URL | redis://localhost:6379 | Redis connection | | REDIS_ENABLED | false | Enable Redis | | RATE_LIMIT_WINDOW_MS | 900000 | Rate limit window (15min) | | RATE_LIMIT_MAX_REQUESTS | 100 | Max requests per window | | LOG_LEVEL | info | Logging level | | LOG_FILE | ./logs/auth.log | Log file path |

Database Schema

Tables

  • users - User accounts
  • api_keys - API key management
  • refresh_tokens - Refresh token store
  • audit_logs - Authentication audit trail

Migrations

npm run migrate

Redis (Optional)

Enable for:

  • Distributed deployments
  • Token blacklisting
  • Session sharing
  • Rate limiting across instances
REDIS_ENABLED=true
REDIS_URL=redis://localhost:6379

Security Best Practices

  1. JWT Secret: Use a strong random string (64+ characters)

    openssl rand -hex 32
  2. HTTPS Only: Always use HTTPS in production

  3. Environment Variables: Never commit .env to git

  4. Rate Limiting: Adjust limits based on your needs

  5. Password Policy: Enforce strong passwords at application level

  6. API Key Rotation: Regularly rotate keys

  7. Audit Logs: Monitor authentication failures

Monitoring

Logs

tail -f logs/auth.log
tail -f logs/auth-error.log

Metrics

  • Authentication success/failure rates
  • Token refresh patterns
  • API key usage
  • Rate limit hits

Check audit logs:

sqlite3 data/auth.db
SELECT * FROM audit_logs ORDER BY created_at DESC LIMIT 10;

Testing

Test Coverage (Phase 4 npm Upgrade)

  • 5 Jest Test Suites (70%+ coverage)
  • 60+ test cases
  • 100% pass rate

Test Suites

| Test File | Suites | Focus | |-----------|--------|-------| | jwt.test.js | 5 | Token generation, verification, refresh | | auth.test.js | 5 | Login, registration, logout, password management | | oauth.test.js | 5 | OAuth2 flows, scopes, PKCE, refresh tokens | | security.test.js | 7 | API keys, RBAC, permissions, sessions, CSRF | | rate-limit.test.js | 7 | Rate limiting, DDoS protection, quotas |

Run Tests

# Full test suite with coverage
npm run test

# Watch mode
npm run test:watch

# Specific test file
npm run test -- tests/jwt.test.js
npm run test -- tests/auth.test.js
npm run test -- tests/security.test.js

Test Coverage Targets

  • Branches: 70%+
  • Functions: 70%+
  • Lines: 70%+
  • Statements: 70%+

Development

# Watch mode
npm run dev

# Check logs
tail -f logs/auth.log

Production Deployment

PM2

pm2 start server-v2.js --name kim-auth
pm2 logs kim-auth
pm2 monit

Docker (coming soon)

docker build -t kim-auth .
docker run -p 50300:50300 --env-file .env kim-auth

Troubleshooting

JWT_SECRET Error

JWT_SECRET must be set and at least 32 characters

Solution: Set a secure JWT_SECRET in .env

Database Lock

database is locked

Solution: SQLite WAL mode enabled automatically. Check file permissions.

Redis Connection Failed

Logs show:

Redis error

Solution: Set REDIS_ENABLED=false or start Redis server

Architecture

kim-auth/
├── server-v2.js          # Main application
├── lib/
│   ├── db.js             # Database layer
│   ├── logger.js         # Winston logger
│   └── redis.js          # Redis client
├── migrations/
│   └── init.js           # Database schema
├── config/
├── data/                 # SQLite database
├── logs/                 # Application logs
└── .env                  # Environment config

License

MIT

Version History

v2.0.0 (2026-01-04)

  • ✅ Production-ready rewrite
  • ✅ SQLite + bcrypt + Redis
  • ✅ Audit logging
  • ✅ Rate limiting
  • ✅ Token blacklisting
  • ✅ Comprehensive error handling

v1.0.0 (2026-01-01)

  • Basic JWT + API Key auth
  • In-memory storage
  • Proof of concept

Built by Kim | Powered by Node.js