auth-runtime/README.md

104 lines
2.1 KiB
Markdown

# @clawd/auth-runtime
Shared TypeScript auth runtime for OpenClaw skills.
## Features
- Token caching with configurable TTL
- Automatic token refresh
- Session-expired auto retry (401/403)
- Environment-based configuration
- Type-safe API
## Installation
```bash
bun add file:../../_shared/auth-runtime
```
## Usage
```typescript
import {
createEnvConfig,
getAccessToken,
requestApiWithAutoRefresh,
} from '@clawd/auth-runtime';
const config = createEnvConfig();
const token = await getAccessToken(false, config);
const result = await requestApiWithAutoRefresh(
'POST',
`${config.authBase}/ecom/tasks/scrape`,
false,
config,
JSON.stringify({ url: 'https://detail.1688.com/offer/123.html' }),
token,
);
```
## API
### Functions
#### `createEnvConfig(): EnvConfig`
Create configuration from environment variables:
- `AUTH_BASE`: Auth base URL (default: https://api-gw-test.yuanwei-lnc.com)
- `CLIENT_KEY`: Client key (required)
- `AUTH_CACHE_DIR`: Cache directory (default: /tmp/skill-auth-cache)
- `AUTH_MIN_TTL_SEC`: Minimum token TTL in seconds (default: 60)
#### `getAccessToken(dryRun, config): Promise<string>`
Get access token with caching.
#### `refreshAccessToken(dryRun, config): Promise<string>`
Refresh access token (bypass cache).
#### `fetchSessionJson(dryRun, config): Promise<SessionResponse>`
Fetch session JSON from auth endpoint.
#### `requestApi(method, url, authToken?, body?): Promise<ApiResponse>`
Make HTTP request with optional authorization header.
#### `isRetryableSessionError(response): boolean`
Check whether response likely indicates expired runtime session.
#### `requestApiWithAutoRefresh(method, url, dryRun, config, body?, accessToken?): Promise<ApiResponse>`
Call API with one automatic token refresh + retry on session-expired style errors.
### Types
#### `EnvConfig`
Environment configuration.
#### `SessionResponse`
Session response from auth endpoint.
#### `CachedTokenData`
Cached token data.
#### `HttpMethod`
Supported HTTP methods.
#### `ApiResponse`
HTTP response.
## Building
```bash
bun run build
```