npm package: @schafevormfenster/auth
Description: Token-based identity and access control - access token validation and permission checking
Latest version: 0.2.0

# Auth Layer

Token-based authentication and authorization for secure API access.

## Quick Start

```typescript
import {
  checkAccessToken,
  checkWriteAccessToken,
  extractBearerToken,
} from "@schafevormfenster/auth";

// Read endpoint — path token (read-path auth mode)
export async function GET(request: Request, { params }: { params: { token: string } }) {
  checkAccessToken(params.token); // Throws 401 if invalid
  const data = await fetchData();
  return Response.json(data);
}

// Read-alternative POST — path token (read-path auth mode)
export async function POST(request: Request, { params }: { params: { token: string } }) {
  checkAccessToken(params.token); // Same as GET, path token for read
  const body = await request.json();
  return Response.json(await fetchDataWithFilters(body));
}

// Write endpoint — Authorization header (write-header auth mode)
export async function POST(request: Request) {
  checkWriteAccessToken(extractBearerToken(request.headers.get("Authorization")));
  const body = await request.json();
  return Response.json(await createData(body), { status: 201 });
}
```

**Environment Setup:**
```bash
# .env
READ_ACCESS_TOKENS=read-token-1,read-token-2
WRITE_ACCESS_TOKENS=write-token-1,write-token-2
ADMIN_ACCESS_TOKENS=admin-token-1
```

## Installation

```bash
pnpm add @schafevormfenster/auth
```

### TypeScript Sources (Optional)

For faster development with Vite, use TypeScript sources directly:

```typescript
// 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). Use for read-path auth mode.

- **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

#### `extractBearerToken(authorizationHeader?: string | null): string`

Extracts a token from an HTTP `Authorization` header value.
Accepts both `Bearer <token>` (prefix stripped) and raw `<token>` formats.

- **Throws**: `ApiErrorConstructor(401)` if header is missing or empty

Compose with `checkWriteAccessToken` for write endpoints:

```typescript
checkWriteAccessToken(extractBearerToken(request.headers.get("Authorization")));
```

#### `getTokenPermissions(token: string): TokenPermissions`

Returns permission object for a token.

### Types

```typescript
interface TokenPermissions {
  read: boolean;
  write: boolean;
  admin: boolean;
  notify: 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](./CONTRIBUTING.md)** - Comprehensive guide for developers and AI assistants
- **Example Implementation** - See `apps/web/app/api/auth-examples/` for working examples

## License

MIT