@schafevormfenster/auth
v0.1.4
Published
Token-based identity and access control - access token validation and permission checking
Readme
Auth Layer
Token-based authentication and authorization for secure API access.
Quick Start
import { checkAccessToken, checkWriteAccessToken, checkAdminAccessToken } from "@schafevormfenster/auth";
// Protect a read endpoint
export async function GET(request: Request) {
const token = request.headers.get('Authorization')?.replace('Bearer ', '');
checkAccessToken(token); // Throws 401 if invalid
const data = await fetchData();
return Response.json(data);
}
// Protect a write endpoint
export async function POST(request: Request) {
const token = request.headers.get('Authorization')?.replace('Bearer ', '');
checkWriteAccessToken(token); // Requires write or admin token
const body = await request.json();
return Response.json(await createData(body), { status: 201 });
}Environment Setup:
# .env
READ_ACCESS_TOKENS=read-token-1,read-token-2
WRITE_ACCESS_TOKENS=write-token-1,write-token-2
ADMIN_ACCESS_TOKENS=admin-token-1Installation
pnpm add @schafevormfenster/authTypeScript Sources (Optional)
For faster development with Vite, use TypeScript sources directly:
// vite.config.ts - Requires tsconfig "target": "ES2022"+
export default defineConfig({
resolve: { conditions: ['source', 'import', 'default'] }
});Benefits: Faster HMR, direct debugging, better tree-shaking.
Use Cases
1. Public API with Read Authentication
Protect public API endpoints that allow authenticated users to read data:
- Event listings
- User profiles (public data)
- Search endpoints
- Report generation
2. Content Management with Write Access
Secure endpoints that create, update, or delete resources:
- Blog post creation/editing
- User profile updates
- Image uploads
- Comment posting
3. Administrative Operations
Restrict sensitive operations to admin users only:
- Schema migrations
- User role management
- System configuration
- Data deletion/purging
4. Multi-Level API Security
Combine different permission levels in a single API:
- GET
/api/posts- Read access (list all posts) - POST
/api/posts- Write access (create new post) - DELETE
/api/posts/:id- Admin access (delete any post)
Features
- Hierarchical Permissions: Admin → Write → Read
- Zero Configuration: Works with environment variables
- Type-Safe: Full TypeScript support
- Flexible: Multiple tokens per permission level
- Secure: Never exposes tokens in logs or responses
- Tested: Comprehensive test coverage
API Reference
Functions
checkAccessToken(token?: string): void
Validates any valid token (read, write, or admin).
- Throws:
ApiErrorConstructor(401)if token is missing or invalid
checkWriteAccessToken(token?: string): void
Validates write or admin tokens. Read-only tokens are rejected.
- Throws:
ApiErrorConstructor(401)if token is invalid - Throws:
ApiErrorConstructor(403)if token lacks write permission
checkAdminAccessToken(token?: string): void
Validates admin tokens only. Write and read tokens are rejected.
- Throws:
ApiErrorConstructor(401)if token is invalid - Throws:
ApiErrorConstructor(403)if token lacks admin permission
getTokenPermissions(token: string): TokenPermissions
Returns permission object for a token.
interface TokenPermissions {
read: boolean;
write: boolean;
admin: boolean;
}Domain
Authentication & Authorization.
Purpose
This directory contains logic for verifying access tokens and checking permissions.
Responsibilities
- Token Verification: Validating access tokens.
- Permission Checks: Checking if a token has the required permissions (e.g., admin, write).
- Access Control: Enforcing security policies for API access.
Boundaries
- Usage: Used by the API layer (middleware or route handlers) to secure endpoints.
- No Business Logic: Focuses solely on identity and access, not domain business rules.
Documentation
- CONTRIBUTING.md - Comprehensive guide for developers and AI assistants
- Example Implementation - See
apps/web/app/api/auth-examples/for working examples
License
MIT
