# Sumor - OAuth Authentication Framework

[![npm version](https://img.shields.io/npm/v/sumor.svg)](https://www.npmjs.com/package/sumor)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

A comprehensive OAuth 2.0 authentication framework for Express.js applications with role-based access control (RBAC). Sumor simplifies OAuth integration, token management, and permission-based route protection in multi-service architectures.

[中文文档](https://www.npmjs.com/package/sumor?activeTab=code)

## Key Features

- **OAuth 2.0 Complete Flow**: Full authorization code flow with automatic token exchange
- **Session & Token Management**: Secure token exchange, refresh via HTTP-only cookies
- **JWT Verification**: Built-in JWT validation using JWKS (JSON Web Key Set)
- **Role-Based Access Control (RBAC)**: Permission sync and runtime permission/role checks
- **TypeScript First**: Full TypeScript support with complete type definitions
- **Express Integration**: Drop-in middleware and pre-configured route setup
- **Permission Sync**: Register application permissions to the OAuth provider at startup
- **Mock Mode**: Zero-dependency local development without a real OAuth server
- **Web Client SDK**: Browser-side token refresh, user state, and permission utilities

## Installation

```bash
npm install sumor
```

## Architecture Overview

Sumor is split into two entry points:

| Entry       | Purpose                         |
| ----------- | ------------------------------- |
| `sumor`     | Server-side (Node.js / Express) |
| `sumor/web` | Client-side (browser)           |

```
Browser App
  │  (1) refreshToken() on init
  │  (2) login() → redirect to OAuth provider
  │  (3) OAuth callback → /api/oauth/callback
  │  (4) Subsequent requests carry HttpOnly cookie
  ▼
Your Express App
  ├── oauthRoutes          ← /api/oauth/* (token refresh, callback, logout)
  ├── loadJwtUserMiddleware ← validates JWT, injects req.jwtUser
  └── Your routes          ← access req.jwtUser, call OAuthService methods
  ▼
OAuth Provider
  └── issues JWT, manages users & permissions, exposes JWKS
```

---

## Server-Side Usage

### Install

```typescript
import { OAuthService, loadJwtUserMiddleware, oauthRoutes } from 'sumor'
```

### Exports

| Export                  | Type           | Description                           |
| ----------------------- | -------------- | ------------------------------------- |
| `OAuthService`          | Class          | Interact with the OAuth provider API  |
| `loadJwtUserMiddleware` | Middleware     | Validate JWT and inject `req.jwtUser` |
| `oauthRoutes`           | Express Router | Pre-configured OAuth routes           |

### Setup

Register the OAuth routes and middleware in your Express app:

```typescript
import express from 'express'
import { OAuthService, loadJwtUserMiddleware, oauthRoutes } from 'sumor'

const app = express()

// Register pre-configured OAuth routes (callback, token refresh, logout)
app.use('/api/oauth', oauthRoutes)

// JWT middleware: validates token and injects req.jwtUser for all routes below
app.use(loadJwtUserMiddleware)

// Your protected routes go here
app.use('/api/user', userRoutes)
```

> **Note:** Register `oauthRoutes` before `loadJwtUserMiddleware` so that OAuth callback endpoints (`/api/oauth/callback`) are publicly accessible.

### Sync Permissions on Startup

Register your application's permission definitions with the OAuth provider once on startup:

```typescript
const oauthService = new OAuthService()

await oauthService.updatePermissions({
  permissions: ['posts:view', 'posts:create', 'posts:edit', 'posts:delete'],
  permissionLabels: [{ module: 'posts', zh: '文章管理', en: 'Posts Management' }]
})
```

Permission strings follow the format `<module>:<operation>`.

### Access User Info in Routes

After `loadJwtUserMiddleware`, `req.jwtUser` contains the decoded JWT payload:

```typescript
app.get('/api/profile', (req, res) => {
  const { userId, roles, permissions, isVerified } = req.jwtUser

  res.json({
    userId,
    roles: roles?.split(',') ?? [],
    permissions: permissions?.split(',') ?? [],
    isVerified: isVerified === 1
  })
})
```

**`req.jwtUser` properties:**

| Property      | Type     | Description                        |
| ------------- | -------- | ---------------------------------- |
| `userId`      | `string` | Unique user identifier             |
| `roles`       | `string` | Comma-separated role IDs           |
| `permissions` | `string` | Comma-separated permission strings |
| `isVerified`  | `number` | `1` if verified, `0` otherwise     |
| `tenantId`    | `string` | Multi-tenant identifier            |
| `jti`         | `string` | JWT ID (session identifier)        |
| `exp`         | `number` | Token expiration timestamp         |
| `iat`         | `number` | Token issued-at timestamp          |

### OAuthService Methods

Create an instance anywhere in your server code — it reads configuration from environment variables automatically:

```typescript
const oauthService = new OAuthService()
```

#### `updatePermissions(config)`

Synchronize the application's permission definitions to the OAuth provider.

```typescript
await oauthService.updatePermissions({
  permissions: ['resource:view', 'resource:edit'],
  permissionLabels: [{ module: 'resource', zh: '资源管理', en: 'Resource Management' }]
})
```

#### `getUserInfo(userId)`

Fetch detailed information for a single user.

```typescript
const userInfo = await oauthService.getUserInfo('user-123')
// Returns: { userId, username, nickname, email, avatar, ... }
```

#### `getUsersInfo(userIds)`

Fetch information for multiple users in one call.

```typescript
const users = await oauthService.getUsersInfo(['user-1', 'user-2', 'user-3'])
// Returns: [{ userId, username, ... }, ...]
```

#### `searchUsers(searchTerm, limit)`

Search users by name or email.

```typescript
const results = await oauthService.searchUsers('alice', 20)
// Returns: [{ userId, username, email, ... }, ...]
```

#### `revokeSession(sessionId)`

Revoke (blacklist) a session on logout.

```typescript
await oauthService.revokeSession(req.jwtUser.jti)
```

#### `checkBlacklist(sessionId)`

Check whether a session has been revoked.

```typescript
const isRevoked = await oauthService.checkBlacklist(sessionId)
```

### Pre-configured OAuth Routes

`oauthRoutes` registers the following endpoints automatically:

| Method | Path                  | Auth required | Description                                            |
| ------ | --------------------- | ------------- | ------------------------------------------------------ |
| `GET`  | `/api/oauth/callback` | No            | Exchange authorization code for tokens                 |
| `PUT`  | `/api/oauth/token`    | No            | Refresh access token; returns user info and OAuth URLs |
| `POST` | `/api/oauth/logout`   | Yes           | Revoke session and clear cookies                       |

---

## Client-Side Usage (`sumor/web`)

### Install

```typescript
import {
  refreshToken,
  login,
  logout,
  hasPermission,
  hasRole,
  oauthUrl,
  oauthStore,
  axios
} from 'sumor/web'
import type { ApiResponse } from 'sumor/web'
```

### Exports

| Export          | Type           | Description                                           |
| --------------- | -------------- | ----------------------------------------------------- |
| `refreshToken`  | Function       | Refresh token and sync user state (call on app init)  |
| `login`         | Function       | Redirect to OAuth login page                          |
| `logout`        | Function       | Call logout endpoint and clear user state             |
| `hasPermission` | Function       | Check if the current user has a specific permission   |
| `hasRole`       | Function       | Check if the current user has a specific role         |
| `oauthStore`    | Singleton      | In-memory user and OAuth state store                  |
| `oauthUrl`      | Object         | Helpers to generate OAuth provider navigation URLs    |
| `axios`         | Axios instance | Pre-configured Axios with automatic 401 token refresh |
| `ApiResponse`   | Type           | Standard API response wrapper type                    |

### Initialize on App Start

Call `refreshToken()` once during application initialization to restore user state from the stored refresh token cookie:

```typescript
// main.ts (or App.vue onMounted)
import { refreshToken } from 'sumor/web'

await refreshToken()

// User state is now available via oauthStore
```

> In SSR environments, `refreshToken()` is a no-op and returns immediately.

### Login and Logout

```typescript
import { login, logout } from 'sumor/web'

// Redirect to OAuth authorization page
login()

// Logout: revokes session and clears user state
await logout()
```

### Subscribe to User Changes

Use `oauthStore` to read the current user and react to state changes:

```typescript
import { oauthStore } from 'sumor/web'

// Read current user
const user = oauthStore.getUser()
// { id, isVerified, roles, permissions } or null

// Subscribe to login/logout events
oauthStore.onUserChange(user => {
  if (user) {
    console.log('Logged in:', user.id)
  } else {
    console.log('Logged out')
  }
})
```

**`UserInfo` properties:**

| Property      | Type     | Description                        |
| ------------- | -------- | ---------------------------------- |
| `id`          | `string` | User ID                            |
| `isVerified`  | `number` | `1` if verified                    |
| `roles`       | `string` | Comma-separated role IDs           |
| `permissions` | `string` | Comma-separated permission strings |

### Permission and Role Checks

```typescript
import { hasPermission, hasRole } from 'sumor/web'

// Check a specific permission (module + operation)
if (hasPermission('posts', 'edit')) {
  // User can edit posts
}

// Check any permission in a module (wildcard)
if (hasPermission('posts', '*')) {
  // User has any posts permission
}

// Check role
if (hasRole('admin')) {
  // User is an admin
}
```

### OAuth URL Helpers

```typescript
import { oauthUrl } from 'sumor/web'

oauthUrl.avatar(userId) // URL for a user's avatar image
oauthUrl.user() // URL for the user profile page
oauthUrl.home() // URL for the OAuth provider home page
oauthUrl.site() // URL for the site management page
oauthUrl.feedback() // URL for the feedback page
```

In [Mock Mode](#mock-mode), these URLs point to placeholder pages served locally.

### Making Authenticated HTTP Requests

The exported `axios` instance automatically handles 401 responses by refreshing the token and retrying:

```typescript
import { axios } from 'sumor/web'
import type { ApiResponse } from 'sumor/web'

// GET
const { data } = await axios.get<ApiResponse<UserInfo>>('/api/user/info')

// POST
const { data } = await axios.post<ApiResponse<Item>>('/api/items', { name: 'My Item' })

// PUT
const { data } = await axios.put<ApiResponse<Item>>(`/api/items/${id}`, updates)

// DELETE
const { data } = await axios.delete<ApiResponse<null>>(`/api/items/${id}`)

// File upload with progress
await axios.post<ApiResponse<UploadResult>>('/api/upload', formData, {
  headers: { 'Content-Type': 'multipart/form-data' },
  onUploadProgress: e => {
    const percent = Math.round((e.loaded * 100) / (e.total ?? e.loaded))
    console.log(`Upload progress: ${percent}%`)
  }
})
```

**`ApiResponse<T>` type:**

```typescript
interface ApiResponse<T> {
  code: string // 'OK' on success
  message: string
  data: T
}
```

---

## Configuration

Sumor reads all configuration from environment variables. No explicit constructor arguments are required.

### Required Environment Variables

```bash
OAUTH_ENDPOINT=https://auth.example.com
OAUTH_CLIENT_KEY=your-app-client-id
OAUTH_CLIENT_SECRET=your-app-client-secret
OAUTH_REDIRECT_URI=http://localhost:3000/api/oauth/callback
```

| Variable              | Description                                            |
| --------------------- | ------------------------------------------------------ |
| `OAUTH_ENDPOINT`      | Base URL of the OAuth provider                         |
| `OAUTH_CLIENT_KEY`    | OAuth application client ID                            |
| `OAUTH_CLIENT_SECRET` | OAuth application client secret                        |
| `OAUTH_REDIRECT_URI`  | Callback URL (must match OAuth provider configuration) |

JWT tokens are verified using JWKS public keys fetched from `{OAUTH_ENDPOINT}/api/oauth/jwks` — no local secret is required.

---

## Mock Mode

Mock Mode allows local development without a running OAuth server. Enable it by setting `OAUTH_MOCK=true`. In this mode, Sumor issues locally signed JWT tokens using HS256 and exposes additional mock-only endpoints.

### How It Works

When `OAUTH_MOCK=true`:

- `oauthRoutes` registers extra sub-routes under `/api/oauth/mock/`
- The `PUT /api/oauth/token` route validates mock tokens locally instead of calling the OAuth provider
- `login()` on the web client calls `POST /api/oauth/mock/login` directly instead of redirecting to the OAuth provider
- `logout()` calls `POST /api/oauth/mock/logout` to clear cookies locally
- `oauthUrl.*` helpers return local placeholder pages instead of external OAuth URLs

### Mock Server Environment Variables

```bash
# Enable mock mode
OAUTH_MOCK=true

# Mock user configuration (all optional — defaults shown)
OAUTH_MOCK_USER_ID=mock-user-001
OAUTH_MOCK_USER_ROLES=admin
OAUTH_MOCK_USER_PERMISSIONS=
OAUTH_MOCK_USER_IS_VERIFIED=1
```

| Variable                      | Default         | Description                           |
| ----------------------------- | --------------- | ------------------------------------- |
| `OAUTH_MOCK`                  | `false`         | Set to `true` to enable mock mode     |
| `OAUTH_MOCK_USER_ID`          | `mock-user-001` | Mock user ID                          |
| `OAUTH_MOCK_USER_ROLES`       | `admin`         | Comma-separated mock roles            |
| `OAUTH_MOCK_USER_PERMISSIONS` | _(empty)_       | Comma-separated mock permissions      |
| `OAUTH_MOCK_USER_IS_VERIFIED` | `1`             | Mock verification status (`0` or `1`) |

### Mock Routes (registered only when `OAUTH_MOCK=true`)

| Method | Path                          | Description                                                 |
| ------ | ----------------------------- | ----------------------------------------------------------- |
| `POST` | `/api/oauth/mock/login`       | Issue mock tokens and return user info (no redirect needed) |
| `POST` | `/api/oauth/mock/logout`      | Clear mock token cookies                                    |
| `GET`  | `/api/oauth/mock/avatar/:id`  | Returns 404 (no avatar service in mock mode)                |
| `GET`  | `/api/oauth/mock/nav/:target` | Placeholder page for OAuth provider navigation links        |

### Example Mock Setup

#### Mock Users List

To populate the `getUserInfo()`, `getUsersInfo()`, and `searchUsers()` methods with test data, configure the `OAUTH_MOCK_USERS` environment variable with a JSON array of user objects.

**User object properties:**

```typescript
interface MockUser {
  userId: string // Required: unique user identifier
  username?: string // Optional: defaults to `user_{userId}`
  email?: string // Optional: defaults to `{userId}@example.com`
  name?: string // Optional: defaults to `User {userId}`
  avatar?: string // Optional: avatar URL
  phone?: string // Optional: phone number
  createdAt?: string // Optional: ISO 8601 timestamp
  updatedAt?: string // Optional: ISO 8601 timestamp
  isActive?: boolean // Optional: defaults to `true`
}
```

**Behavior:**

- `getUserInfo('user001')` returns the configured user object if it exists, otherwise generates a default user
- `getUsersInfo(['user001', 'unknown'])` returns configured users for known IDs and generated users for unknown IDs
- `searchUsers('alice')` searches configured users by userId, username, name, or email and returns matches

**Configuration example:**

```bash
export OAUTH_MOCK_USERS='[
  {"userId": "user001", "username": "alice", "email": "alice@example.com", "name": "Alice Wang"},
  {"userId": "user002", "username": "bob", "email": "bob@example.com", "name": "Bob Smith"}
]'
```

For comprehensive examples and usage patterns, refer to [Mock Users List Usage Guide](server/services/oauth/MOCK_USERS_USAGE.md).

**.env.development:**

```bash
OAUTH_MOCK=true
OAUTH_MOCK_USER_ID=dev-user-1
OAUTH_MOCK_USER_ROLES=admin
OAUTH_MOCK_USER_PERMISSIONS=posts:view,posts:edit,posts:delete
OAUTH_MOCK_USER_IS_VERIFIED=1
OAUTH_MOCK_USERS='[
  {
    "userId": "user001",
    "username": "alice",
    "email": "alice@example.com",
    "name": "Alice Wang",
    "avatar": "https://api.example.com/avatars/alice.jpg",
    "isActive": true
  },
  {
    "userId": "user002",
    "username": "bob",
    "email": "bob@example.com",
    "name": "Bob Smith"
  }
]'
```

No changes are needed in application code — the same `oauthRoutes`, `loadJwtUserMiddleware`, `login()`, and `logout()` calls work in both mock and production modes.

### Security Notice

Mock tokens are signed with a fixed HS256 secret and are identified by `iss: 'mock-oauth'` in the payload. **Never use `OAUTH_MOCK=true` in production.**

---

## Usage Examples

### Server — Protect a Route with Permission Check

```typescript
app.post('/api/posts', (req, res) => {
  const permissions = req.jwtUser.permissions?.split(',') ?? []

  if (!permissions.includes('posts:create')) {
    return res.status(403).json({ code: 'FORBIDDEN', message: 'Insufficient permissions' })
  }

  // Create post...
  res.json({ code: 'OK', data: { id: 'new-post-id' } })
})
```

### Server — Fetch User Details from OAuth Provider

```typescript
app.get('/api/posts/:id/author', async (req, res) => {
  const post = await db.findPost(req.params.id)
  const author = await oauthService.getUserInfo(post.authorId)

  res.json({ code: 'OK', data: author })
})
```

### Web — Vue Component with Login/Logout

```typescript
import { login, logout, oauthStore, hasPermission } from 'sumor/web'
import { ref, onMounted } from 'vue'

const user = ref(oauthStore.getUser())

onMounted(() => {
  oauthStore.onUserChange(u => {
    user.value = u
  })
})

const canEdit = () => hasPermission('posts', 'edit')
```

```html
<template>
  <button v-if="!user" @click="login">Login</button>
  <button v-else @click="logout">Logout</button>
  <button v-if="canEdit()" @click="editPost">Edit</button>
</template>
```

### Web — Vue Router Guard

```typescript
import { refreshToken, hasPermission } from 'sumor/web'

// Restore user state before mounting router
await refreshToken()

router.beforeEach(to => {
  if (to.meta.requiresPermission) {
    const [module, operation] = (to.meta.requiresPermission as string).split(':')
    if (!hasPermission(module, operation)) {
      return '/403'
    }
  }
})
```

---

## Security Considerations

- Tokens are stored in **HTTP-only cookies** and never exposed to JavaScript (XSS protection)
- Always use **HTTPS** in production
- JWT signatures are verified against JWKS public keys fetched from the OAuth provider
- Logout immediately **blacklists** the session on the OAuth provider
- Never enable `OAUTH_MOCK=true` outside of local development

---

## Troubleshooting

### `req.jwtUser` is `undefined`

Ensure that `loadJwtUserMiddleware` is registered before the routes that access `req.jwtUser`.

### Token verification fails

Ensure `OAUTH_ENDPOINT` points to the correct OAuth provider. Sumor fetches JWKS from `{OAUTH_ENDPOINT}/api/oauth/jwks`.

### `refreshToken()` returns without setting a user

The refresh token cookie may be absent or expired. The user needs to log in again via `login()`.

### 401 on protected routes in mock mode

Ensure `OAUTH_MOCK=true` is set both when the server starts and when checking tokens. Restart the server after changing this variable.

---

## License

MIT License — see [LICENSE](LICENSE) for details.
