Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/FORMS_API.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const response = await fetch('http://localhost:8787/admin/forms', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': 'auth_token=your-session-token' // Include auth cookie
// Session cookie sent automatically with credentials: 'include'
},
body: new URLSearchParams({
name: 'contact_form',
Expand All @@ -57,7 +57,7 @@ const response = await fetch('http://localhost:8787/admin/forms', {

```bash
curl -X POST http://localhost:8787/admin/forms \
-H "Cookie: auth_token=your-session-token" \
-b cookies.txt \ # or Cookie: better-auth.session_token=...
-d "name=contact_form" \
-d "displayName=Contact Us" \
-d "description=Customer contact form" \
Expand Down
2 changes: 1 addition & 1 deletion docs/FORMS_COMPLETE_SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ POST /api/forms/:identifier/submit - Submit form data
```typescript
const response = await fetch('/admin/forms', {
method: 'POST',
headers: { 'Cookie': 'auth_token=...' },
credentials: 'include', // session cookie (better-auth.session_token) sent automatically
body: new URLSearchParams({
name: 'contact_form',
displayName: 'Contact Us',
Expand Down
2 changes: 1 addition & 1 deletion docs/FORMS_HEADLESS_FRONTEND.md
Original file line number Diff line number Diff line change
Expand Up @@ -693,7 +693,7 @@ If your form requires authentication:
```typescript
// React example with auth
const handleSubmit = async (submission: any) => {
const token = localStorage.getItem('auth_token')
// Session is in HTTP-only cookie; use credentials: 'include' so cookie is sent

const response = await fetch(`${apiUrl}${formData.submitUrl}`, {
method: 'POST',
Expand Down
2 changes: 1 addition & 1 deletion docs/ai/BREAKING_CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ export type {
User,
Role,
Permission,
JWTPayload,
// JWTPayload removed; session user shape from Better Auth

// Cloudflare types
Bindings,
Expand Down
4 changes: 2 additions & 2 deletions docs/ai/FEATURES_ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ The entire application is designed to run at the edge, providing:
## 2. Authentication & Security

### User Authentication
- **JWT-Based Auth**: Secure token management
- **Session-Based Auth (Better Auth)**: Secure session and cookie management
- **Session Management**:
- HTTP-only cookies
- Configurable expiration
Expand Down Expand Up @@ -682,7 +682,7 @@ sonic plugin # Manage plugins

**Stage 2: Authentication (100%)**
- User management
- JWT implementation
- Better Auth session implementation
- Role-based access
- Session handling

Expand Down
2 changes: 1 addition & 1 deletion docs/ai/ai-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ Based on comprehensive analysis of Strapi, Directus, and Payload CMS, SonicJS wi
- Built-in auth system
- Role-based access control (RBAC)
- Field-level permissions
- JWT tokens with Cloudflare Access integration
- Session-based auth (Better Auth) with Cloudflare Access integration

### Medium Priority Features
1. **Content Management**
Expand Down
2 changes: 1 addition & 1 deletion docs/ai/claude-memory.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
{
"id": "obs-4",
"entityId": "sonicjs-ai-project",
"content": "Features complete content management with collections, versioning, media library, JWT authentication with RBAC (admin/editor/author/viewer roles), plugin architecture, and template system.",
"content": "Features complete content management with collections, versioning, media library, session-based authentication (Better Auth) with RBAC (admin/editor/viewer roles), plugin architecture, and template system.",
"created": "2025-01-26T16:45:00Z"
},
{
Expand Down
14 changes: 4 additions & 10 deletions docs/ai/core-package-api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ await bootstrap.bootstrapCorePlugins()

#### requireAuth

Middleware that requires valid JWT authentication.
Middleware that requires valid session authentication (Better Auth). Reads `user` from context set by global session middleware.

```typescript
import { requireAuth } from '@sonicjs-cms/core'
Expand Down Expand Up @@ -231,22 +231,16 @@ app.use('/api/*', optionalAuth())

### AuthManager

Static class for authentication operations.
Static class for legacy auth operations (e.g. seed-admin). Sign-in/sign-up use Better Auth; do not use `generateToken`/`verifyToken` for new features.

```typescript
import { AuthManager } from '@sonicjs-cms/core'

// Hash password
// Hash password (legacy flows only)
const hash = await AuthManager.hashPassword('password123')

// Verify password
// Verify password (legacy flows only)
const valid = await AuthManager.verifyPassword('password123', hash)

// Generate JWT
const token = await AuthManager.generateToken({ userId, email, role })

// Verify JWT
const payload = await AuthManager.verifyToken(token)
```

### Logging Middleware
Expand Down
2 changes: 1 addition & 1 deletion docs/ai/plans/coverage-improvement-batch2-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ This plan outlines the next batch of unit tests to improve code coverage from th
|------|----------|
| `middleware/bootstrap.ts` | 100% |
| `middleware/plugin-middleware.ts` | 100% |
| `otp-login-plugin/otp-service.ts` | 100% |
| *(otp-login-plugin removed; OTP via Better Auth)* | — |
| `plugins/cache/services/cache-config.ts` | 100% |
| `services/cache.ts` | 100% |
| `services/collection-sync.ts` | 100% |
Expand Down
5 changes: 2 additions & 3 deletions docs/ai/plans/documentation-gap-analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,8 @@ Docs
│ │ ├── EasyMDE (exists)
│ │ ├── TinyMCE (exists)
│ │ └── Quill (exists)
│ ├── Auth Plugins
│ │ ├── OTP Login (exists)
│ │ └── Magic Link (exists)
│ ├── Auth (Better Auth)
│ │ └── Magic Link / Email OTP via config (see authentication docs)
│ └── Plugin Development (exists)
├── Reference
│ ├── API Reference (exists - needs expansion)
Expand Down
6 changes: 5 additions & 1 deletion docs/ai/plugins/plan-code-based-login.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# Code-Based Login (OTP) Plugin - Implementation Plan

## Overview
**Status: Obsolete.** The OTP Login and Magic Link plugins were removed. Email OTP and magic link are now provided via **Better Auth** plugins in app config. See [docs/authentication.md](../../authentication.md) for Magic Link and Email OTP setup with `auth.extendBetterAuth`. This plan is retained for historical context only.

---

## Overview (historical)

Create a passwordless authentication plugin that sends a 6-digit one-time password (OTP) code via email. Users enter their email, receive a code, and enter it to authenticate. This is simpler than magic links (no clicking links) and more user-friendly for mobile devices.

Expand Down
8 changes: 4 additions & 4 deletions docs/ai/project-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ This document outlines the systematic development plan for rebuilding SonicJS as

#### Stage 2 Deliverables
- [x] Hono.js REST API endpoints with OpenAPI schema
- [x] JWT-based authentication middleware
- [x] Session-based authentication middleware (Better Auth)
- [x] Role-based access control (RBAC) system
- [x] Request validation and security middleware
- [x] Admin dashboard interface (HTML/HTMX)
Expand All @@ -64,7 +64,7 @@ This document outlines the systematic development plan for rebuilding SonicJS as
- [x] Create Hono.js route structure and middleware
- [x] Implement auto-generated REST endpoints (foundation)
- [x] Set up OpenAPI schema generation
- [x] Create JWT authentication middleware
- [x] Create session auth middleware (Better Auth)
- [x] Implement session and token handling
- [x] Build user management system
- [x] Create role and permission system
Expand Down Expand Up @@ -396,7 +396,7 @@ Each stage should be completed and thoroughly tested before proceeding to the ne

### Stage 2 Complete ✅ (December 2024)

- **JWT Authentication**: Full token-based auth with HTTP-only cookies
- **Session Authentication (Better Auth)**: Session-based auth with HTTP-only cookies
- **Role-based Access Control**: Admin, editor, author, viewer roles with middleware protection
- **User Management**: Registration, login, logout, profile management with secure password hashing
- **API Foundation**: Schema-driven REST endpoints with Zod validation
Expand Down Expand Up @@ -445,7 +445,7 @@ Each stage should be completed and thoroughly tested before proceeding to the ne

- **Comprehensive Documentation**: Created complete documentation covering all aspects of SonicJS AI
- **Documentation Files Created**:
- `docs/authentication.md` - Complete authentication & security guide (JWT, RBAC, user management)
- `docs/authentication.md` - Complete authentication & security guide (Better Auth, RBAC, user management)
- `docs/deployment.md` - Production deployment guide (Cloudflare Workers, D1, R2)
- `docs/database.md` - Database operations & schema guide (Drizzle ORM, migrations, best practices)
- `docs/templating.md` - Template system documentation (components, HTMX integration, patterns)
Expand Down
4 changes: 2 additions & 2 deletions docs/ai/www-documentation-update-plan.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ The SonicJS documentation site (www folder) needs a comprehensive update to alig
- Media management with R2 storage
- Workflow system with scheduling
- Three-tiered caching
- JWT authentication with RBAC
- Session-based authentication (Better Auth) with RBAC

### Gap Analysis
1. **Outdated Content**: Many www pages reference old API patterns or missing features
Expand Down Expand Up @@ -204,7 +204,7 @@ The SonicJS documentation site (www folder) needs a comprehensive update to alig
**Current State**: Basic auth info
**Updates Needed**:
- Migrate content from docs/authentication.md
- Document JWT-based authentication
- Document session-based authentication (Better Auth)
- Explain token management (cookies + headers)
- Show login/logout/register flows
- Document password reset functionality
Expand Down
103 changes: 25 additions & 78 deletions docs/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,19 +15,20 @@ http://localhost:8787/api

## Authentication

Most API endpoints require authentication. SonicJS AI uses JWT (JSON Web Tokens) for authentication with HTTP-only cookies for web clients and Bearer tokens for API clients.
Most API endpoints require authentication. SonicJS uses **Better Auth** for sign-in and sessions. Authentication is session-cookie based (HTTP-only cookie `better-auth.session_token`).

### Getting an Access Token
### Sign-in (Better Auth)

**Endpoint:** `POST /auth/login`
**Endpoint:** `POST /auth/sign-in/email`

```bash
curl -X POST "http://localhost:8787/auth/login" \
curl -X POST "http://localhost:8787/auth/sign-in/email" \
-H "Content-Type: application/json" \
-d '{
"email": "admin@sonicjs.com",
"password": "sonicjs!"
}'
}' \
-c cookies.txt
```

**Request Body:**
Expand All @@ -38,62 +39,32 @@ curl -X POST "http://localhost:8787/auth/login" \
}
```

**Response (200 OK):**
```json
{
"user": {
"id": "admin-user-id",
"email": "admin@sonicjs.com",
"username": "admin",
"firstName": "Admin",
"lastName": "User",
"role": "admin"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJhZG1pbi11c2VyLWlkIiwiZW1haWwiOiJhZG1pbkBzb25pY2pzLmNvbSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTczMDk0MDAwMCwiaWF0IjoxNzMwODUzNjAwfQ.xyz"
}
```
On success, Better Auth sets a session cookie. Use `-c cookies.txt` (and `-b cookies.txt` on subsequent requests) to send the cookie with curl. In browsers, use `credentials: 'include'` so the cookie is sent automatically.

**Error Response (401 Unauthorized):**
```json
{
"error": "Invalid email or password"
}
```

### Using the Token
### Using the Session

Include the token in the Authorization header for all authenticated requests:
Include the session cookie on authenticated requests. In browsers, send credentials so the cookie is attached:

```http
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
```javascript
fetch('/api/...', { credentials: 'include' })
```

For browser-based applications, the token is automatically stored as an HTTP-only cookie named `auth_token`.

### Token Refresh

**Endpoint:** `POST /auth/refresh`

Requires existing valid authentication.
With curl, use the cookie file saved at sign-in:

```bash
curl -X POST "http://localhost:8787/auth/refresh" \
-H "Authorization: Bearer {token}"
curl -b cookies.txt "http://localhost:8787/auth/me"
```

**Response (200 OK):**
```json
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```
### Session Refresh

Session refresh is handled automatically by Better Auth. The endpoint `POST /auth/refresh` returns a message to that effect; no new token is issued.

### User Registration

**Endpoint:** `POST /auth/register`
**Endpoint:** `POST /auth/sign-up/email` (Better Auth)

```bash
curl -X POST "http://localhost:8787/auth/register" \
curl -X POST "http://localhost:8787/auth/sign-up/email" \
-H "Content-Type: application/json" \
-d '{
"email": "newuser@example.com",
Expand All @@ -109,36 +80,21 @@ curl -X POST "http://localhost:8787/auth/register" \
{
"email": "newuser@example.com",
"password": "securepassword123",
"username": "newuser",
"firstName": "John",
"lastName": "Doe"
"name": "John Doe"
}
```

**Response (201 Created):**
```json
{
"user": {
"id": "uuid-generated-id",
"email": "newuser@example.com",
"username": "newuser",
"firstName": "John",
"lastName": "Doe",
"role": "viewer"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
```
Optional fields (e.g. `username`, `firstName`, `lastName`) depend on your Better Auth user config. On success, Better Auth sets a session cookie. Use `-c cookies.txt` with curl to save it. See [authentication](authentication.md).

### Get Current User

**Endpoint:** `GET /auth/me`

Requires authentication.
Requires authentication (session cookie).

```bash
curl -X GET "http://localhost:8787/auth/me" \
-H "Authorization: Bearer {token}"
-b cookies.txt
```

**Response (200 OK):**
Expand All @@ -158,18 +114,9 @@ curl -X GET "http://localhost:8787/auth/me" \

### Logout

**Endpoint:** `POST /auth/logout` or `GET /auth/logout`

```bash
curl -X POST "http://localhost:8787/auth/logout"
```
**Endpoint:** `GET /auth/logout` or `POST /auth/logout`

**Response (200 OK):**
```json
{
"message": "Logged out successfully"
}
```
Calls Better Auth sign-out and redirects to the login page. Include the session cookie so the session can be cleared.

## API Endpoints

Expand Down Expand Up @@ -1199,7 +1146,7 @@ curl -X GET "http://localhost:8787/api/content?limit=10" -i

### v0.1.0 (Current)
- Initial API implementation
- JWT authentication
- Session-based authentication (Better Auth)
- Collections and content endpoints
- Media upload and management
- Three-tiered caching system
Expand Down
Loading