Compare commits
6 Commits
main
...
worktree-a
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90120c58fb | ||
|
|
2274166c73 | ||
|
|
da35c608cf | ||
|
|
0a8ca373ed | ||
|
|
a64c0c3bb5 | ||
|
|
a1af91aad6 |
@ -42,11 +42,17 @@
|
||||
"dependencies": {
|
||||
"@agentclientprotocol/sdk": "^0.16.0",
|
||||
"@clack/prompts": "^1.1.0",
|
||||
"@fastify/cors": "^11.2.0",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/swagger": "^9.7.0",
|
||||
"@fastify/swagger-ui": "^5.2.5",
|
||||
"@hono/node-server": "^1.19.11",
|
||||
"@inquirer/prompts": "^8.3.2",
|
||||
"@zed-industries/claude-agent-acp": "^0.22.2",
|
||||
"diff": "^8.0.3",
|
||||
"fastest-levenshtein": "^1.0.16",
|
||||
"fastify": "^5.8.4",
|
||||
"fastify-type-provider-zod": "^6.1.0",
|
||||
"grammy": "^1.41.1",
|
||||
"hono": "^4.12.8",
|
||||
"nanoid": "^5.0.0",
|
||||
@ -57,6 +63,7 @@
|
||||
"pino": "^10.3.1",
|
||||
"pino-pretty": "^13.1.3",
|
||||
"pino-roll": "^4.0.0",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"shiki": "^4.0.2",
|
||||
"zod": "^3.25.0"
|
||||
},
|
||||
|
||||
539
pnpm-lock.yaml
generated
539
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@ -26,6 +26,7 @@ import {
|
||||
cmdTunnel,
|
||||
cmdOnboard,
|
||||
cmdDev,
|
||||
cmdRemote,
|
||||
} from './cli/commands/index.js'
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
@ -55,6 +56,7 @@ const commands: Record<string, () => Promise<void>> = {
|
||||
'tunnel': () => cmdTunnel(args),
|
||||
'onboard': () => cmdOnboard(),
|
||||
'dev': () => cmdDev(args),
|
||||
'remote': () => cmdRemote(args),
|
||||
'--daemon-child': async () => {
|
||||
const { startServer } = await import('./main.js')
|
||||
await startServer()
|
||||
|
||||
@ -19,3 +19,4 @@ export { cmdTunnel } from './tunnel.js'
|
||||
export { cmdOnboard } from './onboard.js'
|
||||
export { cmdDefault } from './default.js'
|
||||
export { cmdDev } from './dev.js'
|
||||
export { cmdRemote } from './remote.js'
|
||||
|
||||
166
src/cli/commands/remote.ts
Normal file
166
src/cli/commands/remote.ts
Normal file
@ -0,0 +1,166 @@
|
||||
import { readApiPort, readApiSecret, apiCall } from '../api-client.js'
|
||||
import qrcode from 'qrcode-terminal'
|
||||
|
||||
export async function cmdRemote(args: string[]): Promise<void> {
|
||||
// Parse flags
|
||||
const role = getFlag(args, '--role') ?? 'admin'
|
||||
const expire = getFlag(args, '--expire') ?? '24h'
|
||||
const scopes = getFlag(args, '--scopes')
|
||||
const name = getFlag(args, '--name')
|
||||
const noTunnel = args.includes('--no-tunnel')
|
||||
const noQr = args.includes('--no-qr')
|
||||
|
||||
// 1. Check API server is running
|
||||
const port = readApiPort()
|
||||
if (port === null) {
|
||||
console.error('API server not running. Start with: openacp start')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// Verify health
|
||||
try {
|
||||
const res = await fetch(`http://127.0.0.1:${port}/api/v1/system/health`)
|
||||
if (!res.ok) throw new Error('Health check failed')
|
||||
} catch {
|
||||
console.error(`API server not responding on port ${port}`)
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// 2. Read secret token
|
||||
const secret = readApiSecret()
|
||||
if (!secret) {
|
||||
console.error('Cannot read API secret. Is the instance set up?')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// 3. Generate name
|
||||
const now = new Date()
|
||||
const tokenName = name ?? formatTokenName(now)
|
||||
|
||||
// 4. Generate JWT via API
|
||||
const body: Record<string, unknown> = { role, name: tokenName, expire }
|
||||
if (scopes) {
|
||||
body.scopes = scopes.split(',').map((s) => s.trim())
|
||||
}
|
||||
|
||||
const tokenRes = await apiCall(port, '/api/v1/auth/tokens', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
|
||||
if (!tokenRes.ok) {
|
||||
const err = await tokenRes.json() as any
|
||||
console.error('Failed to generate token:', err.error?.message ?? JSON.stringify(err))
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const tokenData = await tokenRes.json() as {
|
||||
accessToken: string
|
||||
tokenId: string
|
||||
expiresAt: string
|
||||
refreshDeadline: string
|
||||
}
|
||||
|
||||
// 5. Tunnel handling
|
||||
let tunnelUrl: string | null = null
|
||||
if (!noTunnel) {
|
||||
tunnelUrl = await getTunnelUrl(port)
|
||||
}
|
||||
|
||||
// 6. Generate links
|
||||
const localLink = `http://localhost:${port}?token=${tokenData.accessToken}`
|
||||
const tunnelLink = tunnelUrl ? `${tunnelUrl}?token=${tokenData.accessToken}` : null
|
||||
const tunnelHost = tunnelUrl ? new URL(tunnelUrl).host : null
|
||||
const appLink = tunnelHost
|
||||
? `openacp://connect?host=${tunnelHost}&token=${tokenData.accessToken}`
|
||||
: `openacp://connect?host=localhost&port=${port}&token=${tokenData.accessToken}`
|
||||
|
||||
// 7. Output
|
||||
console.log('')
|
||||
console.log(' OpenACP Remote Access')
|
||||
console.log(' ' + '─'.repeat(50))
|
||||
console.log(` Token: ${tokenName}`)
|
||||
console.log(` Role: ${role}`)
|
||||
console.log(` Expires: ${formatDate(tokenData.expiresAt)} (${expire})`)
|
||||
console.log(` Refresh: until ${formatDate(tokenData.refreshDeadline)} (7d)`)
|
||||
console.log('')
|
||||
console.log(' Local:')
|
||||
console.log(` ${localLink}`)
|
||||
|
||||
if (tunnelLink) {
|
||||
console.log('')
|
||||
console.log(' Tunnel:')
|
||||
console.log(` ${tunnelLink}`)
|
||||
}
|
||||
|
||||
console.log('')
|
||||
console.log(' App:')
|
||||
console.log(` ${appLink}`)
|
||||
console.log('')
|
||||
|
||||
// 8. QR code
|
||||
if (!noQr) {
|
||||
const qrLink = tunnelLink ?? localLink
|
||||
qrcode.generate(qrLink, { small: true }, (qr) => {
|
||||
console.log(' Scan QR code to connect:')
|
||||
// Indent each line of QR code
|
||||
for (const line of qr.split('\n')) {
|
||||
console.log(` ${line}`)
|
||||
}
|
||||
console.log('')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function getFlag(args: string[], flag: string): string | undefined {
|
||||
const idx = args.indexOf(flag)
|
||||
if (idx !== -1 && idx + 1 < args.length) {
|
||||
return args[idx + 1]
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
function formatTokenName(date: Date): string {
|
||||
const hh = String(date.getHours()).padStart(2, '0')
|
||||
const mm = String(date.getMinutes()).padStart(2, '0')
|
||||
const dd = String(date.getDate()).padStart(2, '0')
|
||||
const mo = String(date.getMonth() + 1).padStart(2, '0')
|
||||
const yy = date.getFullYear()
|
||||
return `remote-${hh}h${mm}-${dd}-${mo}-${yy}`
|
||||
}
|
||||
|
||||
function formatDate(iso: string): string {
|
||||
try {
|
||||
return new Date(iso).toLocaleString()
|
||||
} catch {
|
||||
return iso
|
||||
}
|
||||
}
|
||||
|
||||
async function getTunnelUrl(port: number): Promise<string | null> {
|
||||
try {
|
||||
const res = await apiCall(port, '/api/v1/system/health')
|
||||
if (!res.ok) return null
|
||||
|
||||
const health = await res.json() as { tunnel?: { enabled: boolean; url?: string } }
|
||||
if (health.tunnel?.enabled && health.tunnel?.url) {
|
||||
return health.tunnel.url
|
||||
}
|
||||
|
||||
// Try to start tunnel
|
||||
try {
|
||||
const tunnelRes = await apiCall(port, '/api/v1/tunnel', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ port }) })
|
||||
if (tunnelRes.ok) {
|
||||
const data = await tunnelRes.json() as { publicUrl?: string }
|
||||
return data.publicUrl ?? null
|
||||
}
|
||||
} catch {
|
||||
// Tunnel start failed
|
||||
}
|
||||
|
||||
return null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
93
src/core/__tests__/instance-discovery.test.ts
Normal file
93
src/core/__tests__/instance-discovery.test.ts
Normal file
@ -0,0 +1,93 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
|
||||
import { discoverRunningInstances } from '../instance-discovery.js'
|
||||
import { mkdtemp, rm, writeFile, mkdir } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import http from 'node:http'
|
||||
|
||||
describe('instance-discovery', () => {
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'discovery-'))
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('returns empty array when no instances registered', async () => {
|
||||
const registryPath = join(tmpDir, 'instances.json')
|
||||
await writeFile(registryPath, JSON.stringify({ version: 1, instances: {} }))
|
||||
|
||||
const instances = await discoverRunningInstances(registryPath)
|
||||
expect(instances).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('returns empty when registry file missing', async () => {
|
||||
const instances = await discoverRunningInstances(join(tmpDir, 'nonexistent.json'))
|
||||
expect(instances).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('discovers a running instance with api.port file', async () => {
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.url?.startsWith('/api/v1/system/health')) {
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' })
|
||||
res.end(JSON.stringify({ status: 'ok' }))
|
||||
}
|
||||
})
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
|
||||
const port = (server.address() as any).port
|
||||
|
||||
try {
|
||||
const instanceRoot = join(tmpDir, 'instance1')
|
||||
await mkdir(instanceRoot, { recursive: true })
|
||||
await writeFile(join(instanceRoot, 'api.port'), String(port))
|
||||
await writeFile(join(instanceRoot, 'config.json'), JSON.stringify({ instanceName: 'Test Instance' }))
|
||||
|
||||
const registryPath = join(tmpDir, 'instances.json')
|
||||
await writeFile(registryPath, JSON.stringify({
|
||||
version: 1,
|
||||
instances: { test: { id: 'test', root: instanceRoot } },
|
||||
}))
|
||||
|
||||
const instances = await discoverRunningInstances(registryPath)
|
||||
expect(instances).toHaveLength(1)
|
||||
expect(instances[0].id).toBe('test')
|
||||
expect(instances[0].name).toBe('Test Instance')
|
||||
expect(instances[0].port).toBe(port)
|
||||
expect(instances[0].running).toBe(true)
|
||||
} finally {
|
||||
server.close()
|
||||
}
|
||||
})
|
||||
|
||||
it('skips instances without api.port file', async () => {
|
||||
const instanceRoot = join(tmpDir, 'stopped-instance')
|
||||
await mkdir(instanceRoot, { recursive: true })
|
||||
|
||||
const registryPath = join(tmpDir, 'instances.json')
|
||||
await writeFile(registryPath, JSON.stringify({
|
||||
version: 1,
|
||||
instances: { stopped: { id: 'stopped', root: instanceRoot } },
|
||||
}))
|
||||
|
||||
const instances = await discoverRunningInstances(registryPath)
|
||||
expect(instances).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('skips instances with api.port but failing health check', async () => {
|
||||
const instanceRoot = join(tmpDir, 'bad-instance')
|
||||
await mkdir(instanceRoot, { recursive: true })
|
||||
await writeFile(join(instanceRoot, 'api.port'), '99999') // non-existent port
|
||||
|
||||
const registryPath = join(tmpDir, 'instances.json')
|
||||
await writeFile(registryPath, JSON.stringify({
|
||||
version: 1,
|
||||
instances: { bad: { id: 'bad', root: instanceRoot } },
|
||||
}))
|
||||
|
||||
const instances = await discoverRunningInstances(registryPath)
|
||||
expect(instances).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
84
src/core/instance-discovery.ts
Normal file
84
src/core/instance-discovery.ts
Normal file
@ -0,0 +1,84 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
|
||||
export interface DiscoveredInstance {
|
||||
id: string
|
||||
root: string
|
||||
name: string
|
||||
port: number
|
||||
running: boolean
|
||||
}
|
||||
|
||||
interface RegistryFile {
|
||||
version: number
|
||||
instances: Record<string, { id: string; root: string }>
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover running OpenACP instances by reading the global registry
|
||||
* and checking each instance's api.port file + health endpoint.
|
||||
*/
|
||||
export async function discoverRunningInstances(
|
||||
registryPath: string,
|
||||
): Promise<DiscoveredInstance[]> {
|
||||
let registry: RegistryFile
|
||||
try {
|
||||
const data = await readFile(registryPath, 'utf-8')
|
||||
registry = JSON.parse(data)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
|
||||
const discovered: DiscoveredInstance[] = []
|
||||
|
||||
for (const entry of Object.values(registry.instances)) {
|
||||
try {
|
||||
const portStr = await readFile(join(entry.root, 'api.port'), 'utf-8')
|
||||
const port = parseInt(portStr.trim(), 10)
|
||||
if (isNaN(port)) continue
|
||||
|
||||
const isHealthy = await checkHealth(port)
|
||||
if (!isHealthy) continue
|
||||
|
||||
let name = entry.id
|
||||
try {
|
||||
const configData = await readFile(join(entry.root, 'config.json'), 'utf-8')
|
||||
const config = JSON.parse(configData)
|
||||
if (config.instanceName) {
|
||||
name = config.instanceName
|
||||
}
|
||||
} catch {
|
||||
// Config might not exist
|
||||
}
|
||||
|
||||
discovered.push({
|
||||
id: entry.id,
|
||||
root: entry.root,
|
||||
name,
|
||||
port,
|
||||
running: true,
|
||||
})
|
||||
} catch {
|
||||
// api.port doesn't exist — instance not running
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
return discovered
|
||||
}
|
||||
|
||||
async function checkHealth(port: number): Promise<boolean> {
|
||||
try {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), 3000)
|
||||
|
||||
const response = await fetch(`http://127.0.0.1:${port}/api/v1/system/health`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
clearTimeout(timeout)
|
||||
|
||||
return response.ok
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
234
src/plugins/api-server/__tests__/auth-integration.test.ts
Normal file
234
src/plugins/api-server/__tests__/auth-integration.test.ts
Normal file
@ -0,0 +1,234 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createHmac } from 'node:crypto'
|
||||
import Fastify, { type FastifyInstance } from 'fastify'
|
||||
import { createAuthPreHandler } from '../middleware/auth.js'
|
||||
import { TokenStore } from '../auth/token-store.js'
|
||||
import { signToken } from '../auth/jwt.js'
|
||||
import { authRoutesV1 } from '../routes/v1-auth.js'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
|
||||
const SECRET = 'a'.repeat(64)
|
||||
const JWT_SECRET = 'jwt-test-secret-for-integration'
|
||||
|
||||
describe('auth middleware integration', () => {
|
||||
let app: FastifyInstance
|
||||
let tokenStore: TokenStore
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'auth-int-'))
|
||||
tokenStore = new TokenStore(join(tmpDir, 'tokens.json'))
|
||||
await tokenStore.load()
|
||||
|
||||
app = Fastify()
|
||||
app.decorateRequest('auth', undefined as any)
|
||||
|
||||
const authPreHandler = createAuthPreHandler(() => SECRET, () => JWT_SECRET, tokenStore)
|
||||
|
||||
// Test route that requires auth
|
||||
app.get('/test', { preHandler: authPreHandler }, async (req) => ({ auth: req.auth }))
|
||||
|
||||
// Auth routes (without global auth for refresh)
|
||||
await app.register(
|
||||
(sub) => authRoutesV1(sub, { tokenStore, getJwtSecret: () => JWT_SECRET, authPreHandler }),
|
||||
{ prefix: '/api/v1/auth' },
|
||||
)
|
||||
|
||||
await app.ready()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await app.close()
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
// === Auth Middleware ===
|
||||
|
||||
it('authenticates with secret token', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'GET', url: '/test',
|
||||
headers: { authorization: `Bearer ${SECRET}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.auth.type).toBe('secret')
|
||||
expect(body.auth.scopes).toEqual(['*'])
|
||||
})
|
||||
|
||||
it('authenticates with valid JWT', async () => {
|
||||
const stored = tokenStore.create({ role: 'operator', name: 'test', expire: '24h' })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
const jwt = signToken({ sub: stored.id, role: 'operator', rfd }, JWT_SECRET, '24h')
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET', url: '/test',
|
||||
headers: { authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.auth.type).toBe('jwt')
|
||||
expect(body.auth.role).toBe('operator')
|
||||
expect(body.auth.tokenId).toBe(stored.id)
|
||||
})
|
||||
|
||||
it('rejects revoked JWT', async () => {
|
||||
const stored = tokenStore.create({ role: 'admin', name: 'revoke-test', expire: '24h' })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
const jwt = signToken({ sub: stored.id, role: 'admin', rfd }, JWT_SECRET, '24h')
|
||||
tokenStore.revoke(stored.id)
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET', url: '/test',
|
||||
headers: { authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects request with no token', async () => {
|
||||
const res = await app.inject({ method: 'GET', url: '/test' })
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
it('accepts token from query param', async () => {
|
||||
const res = await app.inject({ method: 'GET', url: `/test?token=${SECRET}` })
|
||||
expect(res.statusCode).toBe(200)
|
||||
})
|
||||
|
||||
it('resolves scope overrides from JWT', async () => {
|
||||
const stored = tokenStore.create({ role: 'viewer', name: 'scoped', expire: '24h', scopes: ['sessions:read'] })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
const jwt = signToken({ sub: stored.id, role: 'viewer', scopes: ['sessions:read'], rfd }, JWT_SECRET, '24h')
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET', url: '/test',
|
||||
headers: { authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.auth.scopes).toEqual(['sessions:read'])
|
||||
})
|
||||
|
||||
// === Token Generation ===
|
||||
|
||||
it('generates JWT with secret token', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'POST', url: '/api/v1/auth/tokens',
|
||||
headers: { authorization: `Bearer ${SECRET}`, 'content-type': 'application/json' },
|
||||
payload: { role: 'operator', name: 'gen-test', expire: '1h' },
|
||||
})
|
||||
expect(res.statusCode).toBe(201)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.accessToken).toBeDefined()
|
||||
expect(body.tokenId).toMatch(/^tok_/)
|
||||
expect(body.refreshDeadline).toBeDefined()
|
||||
})
|
||||
|
||||
it('rejects token generation with JWT (not secret)', async () => {
|
||||
const stored = tokenStore.create({ role: 'admin', name: 'jwt-gen', expire: '24h' })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
const jwt = signToken({ sub: stored.id, role: 'admin', rfd }, JWT_SECRET, '24h')
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST', url: '/api/v1/auth/tokens',
|
||||
headers: { authorization: `Bearer ${jwt}`, 'content-type': 'application/json' },
|
||||
payload: { role: 'viewer', name: 'should-fail', expire: '1h' },
|
||||
})
|
||||
expect(res.statusCode).toBe(403)
|
||||
})
|
||||
|
||||
// === Token Refresh ===
|
||||
|
||||
it('refreshes a valid (non-expired) JWT', async () => {
|
||||
const stored = tokenStore.create({ role: 'operator', name: 'refresh-test', expire: '24h' })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
const jwt = signToken({ sub: stored.id, role: 'operator', rfd }, JWT_SECRET, '24h')
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST', url: '/api/v1/auth/refresh',
|
||||
headers: { authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.accessToken).toBeDefined()
|
||||
expect(body.tokenId).toBe(stored.id)
|
||||
})
|
||||
|
||||
it('refreshes an expired JWT within refresh deadline', async () => {
|
||||
const stored = tokenStore.create({ role: 'admin', name: 'expired-refresh', expire: '24h' })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
|
||||
// Craft an expired token (exp in the past, but rfd in the future)
|
||||
const jwt = signToken({ sub: stored.id, role: 'admin', rfd }, JWT_SECRET, '1h')
|
||||
const parts = jwt.split('.')
|
||||
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString())
|
||||
payload.exp = Math.floor(Date.now() / 1000) - 60 // expired 1 minute ago
|
||||
const newBody = Buffer.from(JSON.stringify(payload)).toString('base64url')
|
||||
const sig = createHmac('sha256', JWT_SECRET).update(`${parts[0]}.${newBody}`).digest('base64url')
|
||||
const expiredJwt = `${parts[0]}.${newBody}.${sig}`
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST', url: '/api/v1/auth/refresh',
|
||||
headers: { authorization: `Bearer ${expiredJwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.accessToken).toBeDefined()
|
||||
expect(body.tokenId).toBe(stored.id)
|
||||
})
|
||||
|
||||
it('rejects refresh for revoked token', async () => {
|
||||
const stored = tokenStore.create({ role: 'admin', name: 'revoked-refresh', expire: '24h' })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
const jwt = signToken({ sub: stored.id, role: 'admin', rfd }, JWT_SECRET, '24h')
|
||||
tokenStore.revoke(stored.id)
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST', url: '/api/v1/auth/refresh',
|
||||
headers: { authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
it('rejects refresh past refresh deadline', async () => {
|
||||
const stored = tokenStore.create({ role: 'admin', name: 'past-deadline', expire: '24h' })
|
||||
// Set rfd to the past
|
||||
const pastRfd = Math.floor(Date.now() / 1000) - 3600
|
||||
const jwt = signToken({ sub: stored.id, role: 'admin', rfd: pastRfd }, JWT_SECRET, '24h')
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST', url: '/api/v1/auth/refresh',
|
||||
headers: { authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
// === /me ===
|
||||
|
||||
it('GET /me returns auth info for secret token', async () => {
|
||||
const res = await app.inject({
|
||||
method: 'GET', url: '/api/v1/auth/me',
|
||||
headers: { authorization: `Bearer ${SECRET}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.type).toBe('secret')
|
||||
expect(body.role).toBe('admin')
|
||||
})
|
||||
|
||||
it('GET /me returns auth info for JWT', async () => {
|
||||
const stored = tokenStore.create({ role: 'viewer', name: 'me-test', expire: '24h' })
|
||||
const rfd = Math.floor(new Date(stored.refreshDeadline).getTime() / 1000)
|
||||
const jwt = signToken({ sub: stored.id, role: 'viewer', rfd }, JWT_SECRET, '24h')
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'GET', url: '/api/v1/auth/me',
|
||||
headers: { authorization: `Bearer ${jwt}` },
|
||||
})
|
||||
expect(res.statusCode).toBe(200)
|
||||
const body = JSON.parse(res.body)
|
||||
expect(body.type).toBe('jwt')
|
||||
expect(body.role).toBe('viewer')
|
||||
})
|
||||
})
|
||||
206
src/plugins/api-server/__tests__/auth.test.ts
Normal file
206
src/plugins/api-server/__tests__/auth.test.ts
Normal file
@ -0,0 +1,206 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { createHmac } from 'node:crypto'
|
||||
import { getRoleScopes, hasScope, isValidRole } from '../auth/roles.js'
|
||||
import { TokenStore } from '../auth/token-store.js'
|
||||
import { signToken, verifyToken, verifyForRefresh } from '../auth/jwt.js'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
|
||||
// ========================
|
||||
// Roles
|
||||
// ========================
|
||||
|
||||
describe('roles', () => {
|
||||
it('admin has wildcard scope', () => {
|
||||
expect(getRoleScopes('admin')).toEqual(['*'])
|
||||
})
|
||||
|
||||
it('operator has session and agent scopes but not config:write', () => {
|
||||
const scopes = getRoleScopes('operator')
|
||||
expect(scopes).toContain('sessions:read')
|
||||
expect(scopes).toContain('sessions:write')
|
||||
expect(scopes).toContain('sessions:prompt')
|
||||
expect(scopes).not.toContain('config:write')
|
||||
expect(scopes).not.toContain('system:admin')
|
||||
})
|
||||
|
||||
it('viewer has read-only scopes', () => {
|
||||
const scopes = getRoleScopes('viewer')
|
||||
expect(scopes).toContain('sessions:read')
|
||||
expect(scopes).toContain('agents:read')
|
||||
expect(scopes).not.toContain('sessions:write')
|
||||
})
|
||||
|
||||
it('hasScope checks wildcard', () => {
|
||||
expect(hasScope(['*'], 'anything:here')).toBe(true)
|
||||
})
|
||||
|
||||
it('hasScope checks exact match', () => {
|
||||
expect(hasScope(['sessions:read', 'agents:read'], 'sessions:read')).toBe(true)
|
||||
expect(hasScope(['sessions:read'], 'sessions:write')).toBe(false)
|
||||
})
|
||||
|
||||
it('isValidRole validates role names', () => {
|
||||
expect(isValidRole('admin')).toBe(true)
|
||||
expect(isValidRole('operator')).toBe(true)
|
||||
expect(isValidRole('viewer')).toBe(true)
|
||||
expect(isValidRole('superadmin')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
// ========================
|
||||
// TokenStore
|
||||
// ========================
|
||||
|
||||
describe('TokenStore', () => {
|
||||
let store: TokenStore
|
||||
let tmpDir: string
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await mkdtemp(join(tmpdir(), 'token-store-'))
|
||||
store = new TokenStore(join(tmpDir, 'tokens.json'))
|
||||
await store.load()
|
||||
})
|
||||
|
||||
afterEach(async () => {
|
||||
await rm(tmpDir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
it('creates a token with generated ID', () => {
|
||||
const token = store.create({ role: 'admin', name: 'test-token', expire: '24h' })
|
||||
expect(token.id).toMatch(/^tok_/)
|
||||
expect(token.name).toBe('test-token')
|
||||
expect(token.role).toBe('admin')
|
||||
expect(token.revoked).toBe(false)
|
||||
})
|
||||
|
||||
it('refresh deadline is 7 days from creation', () => {
|
||||
const token = store.create({ role: 'admin', name: 'test', expire: '24h' })
|
||||
const created = new Date(token.createdAt).getTime()
|
||||
const deadline = new Date(token.refreshDeadline).getTime()
|
||||
const sevenDays = 7 * 24 * 60 * 60 * 1000
|
||||
expect(deadline - created).toBe(sevenDays)
|
||||
})
|
||||
|
||||
it('gets a token by ID', () => {
|
||||
const created = store.create({ role: 'viewer', name: 'get-test', expire: '1h' })
|
||||
const found = store.get(created.id)
|
||||
expect(found).toBeDefined()
|
||||
expect(found!.id).toBe(created.id)
|
||||
})
|
||||
|
||||
it('returns undefined for unknown token ID', () => {
|
||||
expect(store.get('tok_nonexistent')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('revokes a token', () => {
|
||||
const token = store.create({ role: 'admin', name: 'revoke-test', expire: '24h' })
|
||||
store.revoke(token.id)
|
||||
expect(store.get(token.id)!.revoked).toBe(true)
|
||||
})
|
||||
|
||||
it('lists non-revoked tokens', () => {
|
||||
store.create({ role: 'admin', name: 'tok-1', expire: '24h' })
|
||||
store.create({ role: 'viewer', name: 'tok-2', expire: '24h' })
|
||||
const tok3 = store.create({ role: 'operator', name: 'tok-3', expire: '24h' })
|
||||
store.revoke(tok3.id)
|
||||
expect(store.list()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('updates lastUsedAt', () => {
|
||||
const token = store.create({ role: 'admin', name: 'used-test', expire: '24h' })
|
||||
expect(token.lastUsedAt).toBeUndefined()
|
||||
store.updateLastUsed(token.id)
|
||||
expect(store.get(token.id)!.lastUsedAt).toBeDefined()
|
||||
})
|
||||
|
||||
it('persists to disk and loads back', async () => {
|
||||
store.create({ role: 'admin', name: 'persist-test', expire: '24h' })
|
||||
await store.save()
|
||||
|
||||
const store2 = new TokenStore(join(tmpDir, 'tokens.json'))
|
||||
await store2.load()
|
||||
expect(store2.list()).toHaveLength(1)
|
||||
expect(store2.list()[0].name).toBe('persist-test')
|
||||
})
|
||||
|
||||
it('cleanup removes tokens past refresh deadline', () => {
|
||||
const token = store.create({ role: 'admin', name: 'expired', expire: '24h' })
|
||||
const stored = store.get(token.id)!
|
||||
;(stored as any).refreshDeadline = new Date(Date.now() - 1000).toISOString()
|
||||
store.cleanup()
|
||||
expect(store.get(token.id)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
// ========================
|
||||
// JWT
|
||||
// ========================
|
||||
|
||||
const JWT_SECRET = 'test-secret-key-for-jwt-signing-minimum-length'
|
||||
|
||||
describe('JWT', () => {
|
||||
it('signs a token with correct format', () => {
|
||||
const token = signToken(
|
||||
{ sub: 'tok_123', role: 'admin', rfd: Math.floor(Date.now() / 1000) + 86400 * 7 },
|
||||
JWT_SECRET,
|
||||
'24h',
|
||||
)
|
||||
expect(token.split('.')).toHaveLength(3)
|
||||
})
|
||||
|
||||
it('verifies a valid token', () => {
|
||||
const rfd = Math.floor(Date.now() / 1000) + 86400 * 7
|
||||
const token = signToken({ sub: 'tok_123', role: 'operator', rfd }, JWT_SECRET, '24h')
|
||||
const payload = verifyToken(token, JWT_SECRET)
|
||||
expect(payload.sub).toBe('tok_123')
|
||||
expect(payload.role).toBe('operator')
|
||||
expect(payload.rfd).toBe(rfd)
|
||||
})
|
||||
|
||||
it('rejects an expired token', () => {
|
||||
const rfd = Math.floor(Date.now() / 1000) + 86400 * 7
|
||||
// Craft a token with exp set to 10 seconds ago
|
||||
const token = signToken({ sub: 'tok_123', role: 'admin', rfd }, JWT_SECRET, '1h')
|
||||
const parts = token.split('.')
|
||||
const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString())
|
||||
payload.exp = Math.floor(Date.now() / 1000) - 10
|
||||
const newBody = Buffer.from(JSON.stringify(payload)).toString('base64url')
|
||||
const sig = createHmac('sha256', JWT_SECRET).update(`${parts[0]}.${newBody}`).digest('base64url')
|
||||
const expiredToken = `${parts[0]}.${newBody}.${sig}`
|
||||
|
||||
expect(() => verifyToken(expiredToken, JWT_SECRET)).toThrow('JWT expired')
|
||||
})
|
||||
|
||||
it('rejects a token with wrong secret', () => {
|
||||
const rfd = Math.floor(Date.now() / 1000) + 86400 * 7
|
||||
const token = signToken({ sub: 'tok_123', role: 'admin', rfd }, JWT_SECRET, '24h')
|
||||
expect(() => verifyToken(token, 'wrong-secret')).toThrow()
|
||||
})
|
||||
|
||||
it('verifyForRefresh accepts expired token', () => {
|
||||
const rfd = Math.floor(Date.now() / 1000) + 86400 * 7
|
||||
const token = signToken({ sub: 'tok_123', role: 'admin', rfd }, JWT_SECRET, '0s')
|
||||
const payload = verifyForRefresh(token, JWT_SECRET)
|
||||
expect(payload.sub).toBe('tok_123')
|
||||
})
|
||||
|
||||
it('verifyForRefresh rejects wrong signature', () => {
|
||||
const rfd = Math.floor(Date.now() / 1000) + 86400 * 7
|
||||
const token = signToken({ sub: 'tok_123', role: 'admin', rfd }, JWT_SECRET, '24h')
|
||||
expect(() => verifyForRefresh(token, 'wrong-secret')).toThrow()
|
||||
})
|
||||
|
||||
it('includes scopes in payload', () => {
|
||||
const rfd = Math.floor(Date.now() / 1000) + 86400 * 7
|
||||
const token = signToken(
|
||||
{ sub: 'tok_123', role: 'viewer', scopes: ['sessions:read'], rfd },
|
||||
JWT_SECRET,
|
||||
'24h',
|
||||
)
|
||||
const payload = verifyToken(token, JWT_SECRET)
|
||||
expect(payload.scopes).toEqual(['sessions:read'])
|
||||
})
|
||||
})
|
||||
|
||||
93
src/plugins/api-server/__tests__/error-handler.test.ts
Normal file
93
src/plugins/api-server/__tests__/error-handler.test.ts
Normal file
@ -0,0 +1,93 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { globalErrorHandler, NotFoundError, AuthError } from '../middleware/error-handler.js'
|
||||
import { ZodError, z } from 'zod'
|
||||
|
||||
function mockReply() {
|
||||
const reply: any = {
|
||||
status: vi.fn().mockReturnThis(),
|
||||
send: vi.fn().mockReturnThis(),
|
||||
sent: false,
|
||||
}
|
||||
return reply
|
||||
}
|
||||
|
||||
describe('globalErrorHandler', () => {
|
||||
it('handles ZodError as 400 VALIDATION_ERROR', () => {
|
||||
const schema = z.object({ name: z.string() })
|
||||
let zodError: ZodError
|
||||
try {
|
||||
schema.parse({ name: 123 })
|
||||
} catch (e) {
|
||||
zodError = e as ZodError
|
||||
}
|
||||
|
||||
const reply = mockReply()
|
||||
globalErrorHandler(zodError!, {} as any, reply)
|
||||
|
||||
expect(reply.status).toHaveBeenCalledWith(400)
|
||||
expect(reply.send).toHaveBeenCalledWith({
|
||||
error: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: expect.any(String),
|
||||
statusCode: 400,
|
||||
details: expect.any(Array),
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('handles NotFoundError as 404', () => {
|
||||
const reply = mockReply()
|
||||
globalErrorHandler(new NotFoundError('SESSION_NOT_FOUND', 'Session not found'), {} as any, reply)
|
||||
|
||||
expect(reply.status).toHaveBeenCalledWith(404)
|
||||
expect(reply.send).toHaveBeenCalledWith({
|
||||
error: {
|
||||
code: 'SESSION_NOT_FOUND',
|
||||
message: 'Session not found',
|
||||
statusCode: 404,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('handles AuthError as 401', () => {
|
||||
const reply = mockReply()
|
||||
globalErrorHandler(new AuthError('UNAUTHORIZED', 'Invalid token'), {} as any, reply)
|
||||
|
||||
expect(reply.status).toHaveBeenCalledWith(401)
|
||||
expect(reply.send).toHaveBeenCalledWith({
|
||||
error: {
|
||||
code: 'UNAUTHORIZED',
|
||||
message: 'Invalid token',
|
||||
statusCode: 401,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('handles AuthError with 403 status', () => {
|
||||
const reply = mockReply()
|
||||
globalErrorHandler(new AuthError('FORBIDDEN', 'Insufficient permissions', 403), {} as any, reply)
|
||||
|
||||
expect(reply.status).toHaveBeenCalledWith(403)
|
||||
expect(reply.send).toHaveBeenCalledWith({
|
||||
error: {
|
||||
code: 'FORBIDDEN',
|
||||
message: 'Insufficient permissions',
|
||||
statusCode: 403,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
it('handles unknown errors as 500 INTERNAL_ERROR', () => {
|
||||
const reply = mockReply()
|
||||
globalErrorHandler(new Error('something broke'), {} as any, reply)
|
||||
|
||||
expect(reply.status).toHaveBeenCalledWith(500)
|
||||
expect(reply.send).toHaveBeenCalledWith({
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: 'Internal server error',
|
||||
statusCode: 500,
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
87
src/plugins/api-server/__tests__/server.test.ts
Normal file
87
src/plugins/api-server/__tests__/server.test.ts
Normal file
@ -0,0 +1,87 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { createApiServer, type ApiServerInstance } from '../server.js'
|
||||
|
||||
describe('createApiServer', () => {
|
||||
let server: ApiServerInstance | null = null
|
||||
|
||||
afterEach(async () => {
|
||||
if (server) {
|
||||
await server.stop()
|
||||
server = null
|
||||
}
|
||||
})
|
||||
|
||||
it('creates a Fastify instance', async () => {
|
||||
server = await createApiServer({ port: 0, host: '127.0.0.1', getSecret: () => 'test-secret' })
|
||||
expect(server.app).toBeDefined()
|
||||
expect(typeof server.app.printRoutes).toBe('function')
|
||||
})
|
||||
|
||||
it('starts and listens on a port', async () => {
|
||||
server = await createApiServer({ port: 0, host: '127.0.0.1', getSecret: () => 'test-secret' })
|
||||
const address = await server.start()
|
||||
expect(address.port).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('registerPlugin with auth adds routes that require authentication', async () => {
|
||||
const secret = 'test-health-secret'
|
||||
server = await createApiServer({ port: 0, host: '127.0.0.1', getSecret: () => secret })
|
||||
|
||||
// Register a test route with auth
|
||||
server.registerPlugin('/api/v1/test', async (app) => {
|
||||
app.get('/data', async () => ({ ok: true }))
|
||||
})
|
||||
|
||||
await server.start()
|
||||
|
||||
// Without auth — 401
|
||||
const noAuth = await server.app.inject({ method: 'GET', url: '/api/v1/test/data' })
|
||||
expect(noAuth.statusCode).toBe(401)
|
||||
|
||||
// With auth — 200
|
||||
const withAuth = await server.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/v1/test/data',
|
||||
headers: { authorization: `Bearer ${secret}` },
|
||||
})
|
||||
expect(withAuth.statusCode).toBe(200)
|
||||
})
|
||||
|
||||
it('registerPlugin adds authenticated routes', async () => {
|
||||
const secret = 'test-secret-abc'
|
||||
server = await createApiServer({ port: 0, host: '127.0.0.1', getSecret: () => secret })
|
||||
|
||||
server.registerPlugin('/api/test', async (app) => {
|
||||
app.get('/hello', async () => ({ message: 'hi' }))
|
||||
})
|
||||
|
||||
await server.start()
|
||||
|
||||
// Without auth — should 401
|
||||
const noAuth = await server.app.inject({ method: 'GET', url: '/api/test/hello' })
|
||||
expect(noAuth.statusCode).toBe(401)
|
||||
|
||||
// With auth — should 200
|
||||
const withAuth = await server.app.inject({
|
||||
method: 'GET',
|
||||
url: '/api/test/hello',
|
||||
headers: { authorization: `Bearer ${secret}` },
|
||||
})
|
||||
expect(withAuth.statusCode).toBe(200)
|
||||
expect(JSON.parse(withAuth.body).message).toBe('hi')
|
||||
})
|
||||
|
||||
it('registerPlugin with auth=false skips auth', async () => {
|
||||
server = await createApiServer({ port: 0, host: '127.0.0.1', getSecret: () => 'secret' })
|
||||
|
||||
server.registerPlugin('/api/public', async (app) => {
|
||||
app.get('/open', async () => ({ public: true }))
|
||||
}, { auth: false })
|
||||
|
||||
await server.start()
|
||||
|
||||
const response = await server.app.inject({ method: 'GET', url: '/api/public/open' })
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(JSON.parse(response.body).public).toBe(true)
|
||||
})
|
||||
})
|
||||
100
src/plugins/api-server/auth/jwt.ts
Normal file
100
src/plugins/api-server/auth/jwt.ts
Normal file
@ -0,0 +1,100 @@
|
||||
import { createHmac, timingSafeEqual } from 'node:crypto'
|
||||
import type { JwtPayload } from './types.js'
|
||||
|
||||
// Simple JWT implementation using Node.js crypto (no external dependency)
|
||||
// Supports HS256 only — sufficient for local/self-hosted use case
|
||||
|
||||
function base64url(input: string | Buffer): string {
|
||||
const buf = typeof input === 'string' ? Buffer.from(input) : input
|
||||
return buf.toString('base64url')
|
||||
}
|
||||
|
||||
function base64urlDecode(input: string): string {
|
||||
return Buffer.from(input, 'base64url').toString('utf-8')
|
||||
}
|
||||
|
||||
export interface SignPayload {
|
||||
sub: string
|
||||
role: string
|
||||
scopes?: string[]
|
||||
rfd: number
|
||||
}
|
||||
|
||||
function parseDurationToSeconds(expiresIn: string): number {
|
||||
const match = expiresIn.match(/^(\d+)(s|m|h|d)$/)
|
||||
if (!match) return 86400 // default 24h
|
||||
const value = parseInt(match[1], 10)
|
||||
switch (match[2]) {
|
||||
case 's': return value
|
||||
case 'm': return value * 60
|
||||
case 'h': return value * 3600
|
||||
case 'd': return value * 86400
|
||||
default: return 86400
|
||||
}
|
||||
}
|
||||
|
||||
export function signToken(payload: SignPayload, secret: string, expiresIn: string): string {
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const exp = now + parseDurationToSeconds(expiresIn)
|
||||
|
||||
const header = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))
|
||||
const body = base64url(JSON.stringify({
|
||||
...payload,
|
||||
iat: now,
|
||||
exp,
|
||||
}))
|
||||
|
||||
const signature = createHmac('sha256', secret)
|
||||
.update(`${header}.${body}`)
|
||||
.digest('base64url')
|
||||
|
||||
return `${header}.${body}.${signature}`
|
||||
}
|
||||
|
||||
export function verifyToken(token: string, secret: string): JwtPayload {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) throw new Error('Invalid JWT format')
|
||||
|
||||
const [header, body, signature] = parts
|
||||
|
||||
// Verify signature
|
||||
const expectedSig = createHmac('sha256', secret)
|
||||
.update(`${header}.${body}`)
|
||||
.digest('base64url')
|
||||
|
||||
const sigBuf = Buffer.from(signature, 'base64url')
|
||||
const expectedBuf = Buffer.from(expectedSig, 'base64url')
|
||||
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {
|
||||
throw new Error('Invalid JWT signature')
|
||||
}
|
||||
|
||||
const payload = JSON.parse(base64urlDecode(body)) as JwtPayload
|
||||
|
||||
// Check expiration
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
if (payload.exp && payload.exp < now) {
|
||||
throw new Error('JWT expired')
|
||||
}
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
export function verifyForRefresh(token: string, secret: string): JwtPayload {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) throw new Error('Invalid JWT format')
|
||||
|
||||
const [header, body, signature] = parts
|
||||
|
||||
// Verify signature only — ignore expiration
|
||||
const expectedSig = createHmac('sha256', secret)
|
||||
.update(`${header}.${body}`)
|
||||
.digest('base64url')
|
||||
|
||||
const sigBuf = Buffer.from(signature, 'base64url')
|
||||
const expectedBuf = Buffer.from(expectedSig, 'base64url')
|
||||
if (sigBuf.length !== expectedBuf.length || !timingSafeEqual(sigBuf, expectedBuf)) {
|
||||
throw new Error('Invalid JWT signature')
|
||||
}
|
||||
|
||||
return JSON.parse(base64urlDecode(body)) as JwtPayload
|
||||
}
|
||||
29
src/plugins/api-server/auth/roles.ts
Normal file
29
src/plugins/api-server/auth/roles.ts
Normal file
@ -0,0 +1,29 @@
|
||||
export const ROLES = {
|
||||
admin: ['*'],
|
||||
operator: [
|
||||
'sessions:read',
|
||||
'sessions:write',
|
||||
'sessions:prompt',
|
||||
'sessions:permission',
|
||||
'agents:read',
|
||||
'commands:execute',
|
||||
'system:health',
|
||||
],
|
||||
viewer: ['sessions:read', 'agents:read', 'system:health'],
|
||||
} as const
|
||||
|
||||
export type RoleName = keyof typeof ROLES
|
||||
|
||||
export function isValidRole(role: string): role is RoleName {
|
||||
return role in ROLES
|
||||
}
|
||||
|
||||
export function getRoleScopes(role: string): string[] {
|
||||
if (!isValidRole(role)) return []
|
||||
return [...ROLES[role]]
|
||||
}
|
||||
|
||||
export function hasScope(userScopes: string[], requiredScope: string): boolean {
|
||||
if (userScopes.includes('*')) return true
|
||||
return userScopes.includes(requiredScope)
|
||||
}
|
||||
102
src/plugins/api-server/auth/token-store.ts
Normal file
102
src/plugins/api-server/auth/token-store.ts
Normal file
@ -0,0 +1,102 @@
|
||||
import { readFile, writeFile } from 'node:fs/promises'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import type { StoredToken, CreateTokenOpts } from './types.js'
|
||||
|
||||
function logSaveError(err: unknown): void {
|
||||
console.error('[TokenStore] Failed to persist tokens to disk:', err)
|
||||
}
|
||||
|
||||
const REFRESH_DEADLINE_MS = 7 * 24 * 60 * 60 * 1000 // 7 days
|
||||
|
||||
function generateTokenId(): string {
|
||||
return `tok_${randomBytes(12).toString('hex')}`
|
||||
}
|
||||
|
||||
export function parseDuration(duration: string): number {
|
||||
const match = duration.match(/^(\d+)(m|h|d)$/)
|
||||
if (!match) throw new Error(`Invalid duration: ${duration}`)
|
||||
const value = parseInt(match[1], 10)
|
||||
switch (match[2]) {
|
||||
case 'm': return value * 60 * 1000
|
||||
case 'h': return value * 60 * 60 * 1000
|
||||
case 'd': return value * 24 * 60 * 60 * 1000
|
||||
default: throw new Error(`Invalid duration unit: ${match[2]}`)
|
||||
}
|
||||
}
|
||||
|
||||
export class TokenStore {
|
||||
private tokens = new Map<string, StoredToken>()
|
||||
|
||||
constructor(private filePath: string) {}
|
||||
|
||||
async load(): Promise<void> {
|
||||
try {
|
||||
const data = await readFile(this.filePath, 'utf-8')
|
||||
const parsed = JSON.parse(data) as { tokens: StoredToken[] }
|
||||
this.tokens.clear()
|
||||
for (const token of parsed.tokens) {
|
||||
this.tokens.set(token.id, token)
|
||||
}
|
||||
} catch {
|
||||
this.tokens.clear()
|
||||
}
|
||||
}
|
||||
|
||||
async save(): Promise<void> {
|
||||
const data = { tokens: Array.from(this.tokens.values()) }
|
||||
await writeFile(this.filePath, JSON.stringify(data, null, 2), 'utf-8')
|
||||
}
|
||||
|
||||
create(opts: CreateTokenOpts): StoredToken {
|
||||
const now = new Date()
|
||||
const token: StoredToken = {
|
||||
id: generateTokenId(),
|
||||
name: opts.name,
|
||||
role: opts.role,
|
||||
scopes: opts.scopes,
|
||||
createdAt: now.toISOString(),
|
||||
refreshDeadline: new Date(now.getTime() + REFRESH_DEADLINE_MS).toISOString(),
|
||||
revoked: false,
|
||||
}
|
||||
this.tokens.set(token.id, token)
|
||||
this.save().catch(logSaveError)
|
||||
return token
|
||||
}
|
||||
|
||||
get(id: string): StoredToken | undefined {
|
||||
return this.tokens.get(id)
|
||||
}
|
||||
|
||||
revoke(id: string): void {
|
||||
const token = this.tokens.get(id)
|
||||
if (token) {
|
||||
token.revoked = true
|
||||
this.save().catch(logSaveError)
|
||||
}
|
||||
}
|
||||
|
||||
list(): StoredToken[] {
|
||||
return Array.from(this.tokens.values()).filter((t) => !t.revoked)
|
||||
}
|
||||
|
||||
listAll(): StoredToken[] {
|
||||
return Array.from(this.tokens.values())
|
||||
}
|
||||
|
||||
updateLastUsed(id: string): void {
|
||||
const token = this.tokens.get(id)
|
||||
if (token) {
|
||||
token.lastUsedAt = new Date().toISOString()
|
||||
}
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
const now = Date.now()
|
||||
for (const [id, token] of this.tokens) {
|
||||
if (new Date(token.refreshDeadline).getTime() < now) {
|
||||
this.tokens.delete(id)
|
||||
}
|
||||
}
|
||||
this.save().catch(logSaveError)
|
||||
}
|
||||
}
|
||||
33
src/plugins/api-server/auth/types.ts
Normal file
33
src/plugins/api-server/auth/types.ts
Normal file
@ -0,0 +1,33 @@
|
||||
export interface StoredToken {
|
||||
id: string // tok_<random>
|
||||
name: string // "remote-14h30-31-03-2026"
|
||||
role: string // admin | operator | viewer
|
||||
scopes?: string[] // optional scope override
|
||||
createdAt: string // ISO 8601
|
||||
refreshDeadline: string // ISO 8601, 7 days from createdAt
|
||||
lastUsedAt?: string // ISO 8601
|
||||
revoked: boolean
|
||||
}
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string // tokenId
|
||||
role: string
|
||||
scopes?: string[]
|
||||
iat: number
|
||||
exp: number
|
||||
rfd: number // refresh deadline timestamp
|
||||
}
|
||||
|
||||
export interface CreateTokenOpts {
|
||||
role: string
|
||||
name: string
|
||||
expire: string // "24h", "7d", "30d"
|
||||
scopes?: string[]
|
||||
}
|
||||
|
||||
export interface TokenInfo {
|
||||
tokenId: string
|
||||
accessToken: string
|
||||
expiresAt: string
|
||||
refreshDeadline: string
|
||||
}
|
||||
@ -1,17 +1,75 @@
|
||||
import type { OpenACPPlugin, InstallContext } from '../../core/plugin/types.js'
|
||||
import type { OpenACPCore } from '../../core/core.js'
|
||||
import type { ApiConfig } from './api-server.js'
|
||||
import * as fs from 'node:fs'
|
||||
import * as path from 'node:path'
|
||||
import * as os from 'node:os'
|
||||
import * as crypto from 'node:crypto'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { createChildLogger } from '../../core/utils/log.js'
|
||||
|
||||
const log = createChildLogger({ module: 'api-server' })
|
||||
|
||||
const DEFAULT_PORT_FILE = path.join(os.homedir(), '.openacp', 'api.port')
|
||||
const DEFAULT_SECRET_FILE = path.join(os.homedir(), '.openacp', 'api-secret')
|
||||
const DEFAULT_JWT_SECRET_FILE = path.join(os.homedir(), '.openacp', 'jwt-secret')
|
||||
const DEFAULT_TOKENS_FILE = path.join(os.homedir(), '.openacp', 'tokens.json')
|
||||
|
||||
let cachedVersion: string | undefined
|
||||
function getVersion(): string {
|
||||
if (cachedVersion) return cachedVersion
|
||||
try {
|
||||
const __filename = fileURLToPath(import.meta.url)
|
||||
const pkgPath = path.resolve(path.dirname(__filename), '../../../package.json')
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'))
|
||||
cachedVersion = pkg.version ?? '0.0.0-dev'
|
||||
} catch {
|
||||
cachedVersion = '0.0.0-dev'
|
||||
}
|
||||
return cachedVersion!
|
||||
}
|
||||
|
||||
function loadOrCreateSecret(secretFilePath: string): string {
|
||||
const dir = path.dirname(secretFilePath)
|
||||
fs.mkdirSync(dir, { recursive: true })
|
||||
|
||||
try {
|
||||
const secret = fs.readFileSync(secretFilePath, 'utf-8').trim()
|
||||
if (secret) {
|
||||
// Warn if permissions too open
|
||||
try {
|
||||
const stat = fs.statSync(secretFilePath)
|
||||
const mode = stat.mode & 0o777
|
||||
if (mode & 0o077) {
|
||||
log.warn(
|
||||
{ path: secretFilePath, mode: '0' + mode.toString(8) },
|
||||
'API secret file has insecure permissions (should be 0600). Run: chmod 600 %s',
|
||||
secretFilePath,
|
||||
)
|
||||
}
|
||||
} catch { /* stat failed */ }
|
||||
return secret
|
||||
}
|
||||
} catch { /* file doesn't exist */ }
|
||||
|
||||
const secret = crypto.randomBytes(32).toString('hex')
|
||||
fs.writeFileSync(secretFilePath, secret, { mode: 0o600 })
|
||||
return secret
|
||||
}
|
||||
|
||||
export interface ApiConfig {
|
||||
port: number
|
||||
host: string
|
||||
}
|
||||
|
||||
function createApiServerPlugin(): OpenACPPlugin {
|
||||
let server: { start(): Promise<void>; stop?(): Promise<void> } | null = null
|
||||
let stopServer: (() => Promise<void>) | null = null
|
||||
|
||||
return {
|
||||
name: '@openacp/api-server',
|
||||
version: '1.0.0',
|
||||
description: 'REST API + SSE streaming server',
|
||||
description: 'REST API + SSE streaming server (Fastify)',
|
||||
essential: false,
|
||||
permissions: ['services:register', 'kernel:access', 'events:read'],
|
||||
|
||||
async install(ctx: InstallContext) {
|
||||
const { settings, legacyConfig, terminal } = ctx
|
||||
|
||||
@ -28,11 +86,7 @@ function createApiServerPlugin(): OpenACPPlugin {
|
||||
}
|
||||
}
|
||||
|
||||
// Save defaults
|
||||
await settings.setAll({
|
||||
port: 21420,
|
||||
host: '127.0.0.1',
|
||||
})
|
||||
await settings.setAll({ port: 21420, host: '127.0.0.1' })
|
||||
terminal.log.success('API server defaults saved')
|
||||
},
|
||||
|
||||
@ -80,33 +134,168 @@ function createApiServerPlugin(): OpenACPPlugin {
|
||||
|
||||
async setup(ctx) {
|
||||
const config = ctx.pluginConfig as Record<string, unknown>
|
||||
const core = ctx.core as OpenACPCore
|
||||
|
||||
// Lazy import to avoid loading unless needed
|
||||
const { ApiServer } = await import('./api-server.js')
|
||||
const portFilePath = DEFAULT_PORT_FILE
|
||||
const secretFilePath = DEFAULT_SECRET_FILE
|
||||
|
||||
const secret = loadOrCreateSecret(secretFilePath)
|
||||
const jwtSecret = loadOrCreateSecret(DEFAULT_JWT_SECRET_FILE)
|
||||
|
||||
// Initialize TokenStore
|
||||
const { TokenStore } = await import('./auth/token-store.js')
|
||||
const tokenStore = new TokenStore(DEFAULT_TOKENS_FILE)
|
||||
await tokenStore.load()
|
||||
|
||||
// Periodic cleanup of expired tokens (every hour)
|
||||
const cleanupInterval = setInterval(() => tokenStore.cleanup(), 60 * 60 * 1000)
|
||||
|
||||
const apiConfig: ApiConfig = {
|
||||
port: (config.port as number) ?? 0,
|
||||
host: (config.host as string) ?? '127.0.0.1',
|
||||
}
|
||||
|
||||
server = new ApiServer(ctx.core as OpenACPCore, apiConfig)
|
||||
// Lazy-import Fastify server + routes + SSE to avoid loading at module level
|
||||
const { createApiServer } = await import('./server.js')
|
||||
const { createApiServerService } = await import('./service.js')
|
||||
const { SSEManager } = await import('./sse-manager.js')
|
||||
const { StaticServer } = await import('./static-server.js')
|
||||
const { sessionRoutesV1 } = await import('./routes/v1-sessions.js')
|
||||
const { systemRoutesV1 } = await import('./routes/v1-system.js')
|
||||
const { agentRoutesV1 } = await import('./routes/v1-agents.js')
|
||||
const { configRoutesV1 } = await import('./routes/v1-config.js')
|
||||
const { topicRoutesV1 } = await import('./routes/v1-topics.js')
|
||||
const { tunnelRoutesV1 } = await import('./routes/v1-tunnel.js')
|
||||
const { notifyRoutesV1 } = await import('./routes/v1-notify.js')
|
||||
const { commandRoutesV1 } = await import('./routes/v1-commands.js')
|
||||
const { authRoutesV1 } = await import('./routes/v1-auth.js')
|
||||
|
||||
ctx.registerService('api-server', server)
|
||||
const startedAt = Date.now()
|
||||
const server = await createApiServer({
|
||||
port: apiConfig.port,
|
||||
host: apiConfig.host,
|
||||
getSecret: () => secret,
|
||||
getJwtSecret: () => jwtSecret,
|
||||
tokenStore,
|
||||
})
|
||||
|
||||
// Get topic manager if telegram plugin is loaded
|
||||
let topicManager: any = undefined
|
||||
try {
|
||||
const telegramService = ctx.getService('telegram') as any
|
||||
topicManager = telegramService?.topicManager
|
||||
} catch { /* telegram not loaded */ }
|
||||
|
||||
const routeDeps = { core, topicManager, startedAt, getVersion }
|
||||
|
||||
// Register v1 routes (all authenticated via plugin-level onRequest hook)
|
||||
server.registerPlugin('/api/v1/sessions', (app) => sessionRoutesV1(app, routeDeps))
|
||||
server.registerPlugin('/api/v1/agents', (app) => agentRoutesV1(app, routeDeps))
|
||||
server.registerPlugin('/api/v1/config', (app) => configRoutesV1(app, routeDeps))
|
||||
server.registerPlugin('/api/v1/topics', (app) => topicRoutesV1(app, routeDeps))
|
||||
server.registerPlugin('/api/v1/tunnel', (app) => tunnelRoutesV1(app, routeDeps))
|
||||
server.registerPlugin('/api/v1/notify', (app) => notifyRoutesV1(app, routeDeps))
|
||||
server.registerPlugin('/api/v1/commands', (app) => commandRoutesV1(app, routeDeps))
|
||||
// Auth routes registered WITHOUT global auth — refresh needs to accept expired JWTs
|
||||
server.registerPlugin('/api/v1/auth', (app) => authRoutesV1(app, {
|
||||
tokenStore,
|
||||
getJwtSecret: () => jwtSecret,
|
||||
authPreHandler: server.authPreHandler,
|
||||
}), { auth: false })
|
||||
|
||||
// System routes — health is unauthenticated, rest authenticated
|
||||
server.registerPlugin('/api/v1/system', (app) => systemRoutesV1(app, routeDeps), { auth: false })
|
||||
|
||||
// SSE endpoint (legacy, will be superseded by SSE adapter in Plan 3)
|
||||
const sseManager = new SSEManager(
|
||||
core.eventBus,
|
||||
() => {
|
||||
const sessions = core.sessionManager.listSessions()
|
||||
return {
|
||||
active: sessions.filter((s) => s.status === 'active' || s.status === 'initializing').length,
|
||||
total: sessions.length,
|
||||
}
|
||||
},
|
||||
startedAt,
|
||||
)
|
||||
|
||||
// Register SSE as authenticated Fastify route
|
||||
server.registerPlugin('/api/v1/events', async (app) => {
|
||||
app.get('/', async (request, reply) => {
|
||||
reply.hijack()
|
||||
const res = reply.raw
|
||||
sseManager.handleRequest(request.raw, res)
|
||||
})
|
||||
})
|
||||
|
||||
// Backward compatibility: redirect old /api/* to /api/v1/*
|
||||
server.app.addHook('onRequest', async (request, reply) => {
|
||||
const url = request.url
|
||||
if (url.startsWith('/api/') && !url.startsWith('/api/v1/') && !url.startsWith('/api/docs')) {
|
||||
// Map old paths to new v1 paths
|
||||
const newUrl = url.replace('/api/', '/api/v1/')
|
||||
return reply.redirect(newUrl, 301)
|
||||
}
|
||||
})
|
||||
|
||||
// Static file serving for UI dashboard
|
||||
const staticServer = new StaticServer()
|
||||
if (staticServer.isAvailable()) {
|
||||
server.app.addHook('onRequest', async (request, reply) => {
|
||||
// Only serve static files for non-API routes
|
||||
if (!request.url.startsWith('/api/')) {
|
||||
const served = staticServer.serve(request.raw, reply.raw)
|
||||
if (served) {
|
||||
reply.hijack()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
let actualPort = 0
|
||||
|
||||
// Register ApiServerService for other plugins
|
||||
const service = createApiServerService(server, {
|
||||
getPort: () => actualPort,
|
||||
getBaseUrl: () => `http://127.0.0.1:${actualPort}`,
|
||||
getTunnelUrl: () => core.tunnelService?.getPublicUrl() ?? null,
|
||||
})
|
||||
ctx.registerService('api-server', service)
|
||||
|
||||
// Start on system:ready
|
||||
ctx.on('system:ready', async () => {
|
||||
try {
|
||||
await server!.start()
|
||||
ctx.log.info('API server started')
|
||||
const addr = await server.start()
|
||||
actualPort = addr.port
|
||||
sseManager.setup()
|
||||
|
||||
// Write port file
|
||||
const portDir = path.dirname(portFilePath)
|
||||
fs.mkdirSync(portDir, { recursive: true })
|
||||
fs.writeFileSync(portFilePath, String(actualPort))
|
||||
|
||||
if (apiConfig.host !== '127.0.0.1' && apiConfig.host !== 'localhost') {
|
||||
log.warn('API server binding to non-localhost. Ensure api-secret file is secured.')
|
||||
}
|
||||
|
||||
log.info({ host: apiConfig.host, port: actualPort }, 'API server listening')
|
||||
} catch (err) {
|
||||
ctx.log.error(`API server failed to start: ${err}`)
|
||||
log.error(`API server failed to start: ${err}`)
|
||||
}
|
||||
})
|
||||
|
||||
stopServer = async () => {
|
||||
clearInterval(cleanupInterval)
|
||||
sseManager.stop()
|
||||
await tokenStore.save()
|
||||
try { fs.unlinkSync(portFilePath) } catch { /* ignore */ }
|
||||
await server.stop()
|
||||
}
|
||||
},
|
||||
|
||||
async teardown() {
|
||||
if (server) {
|
||||
await server.stop?.()
|
||||
if (stopServer) {
|
||||
await stopServer()
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
109
src/plugins/api-server/middleware/auth.ts
Normal file
109
src/plugins/api-server/middleware/auth.ts
Normal file
@ -0,0 +1,109 @@
|
||||
import type { FastifyReply, FastifyRequest, preHandlerHookHandler } from 'fastify'
|
||||
import { timingSafeEqual } from 'node:crypto'
|
||||
import { AuthError } from './error-handler.js'
|
||||
import { verifyToken } from '../auth/jwt.js'
|
||||
import { getRoleScopes, hasScope } from '../auth/roles.js'
|
||||
import type { TokenStore } from '../auth/token-store.js'
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
auth: {
|
||||
type: 'secret' | 'jwt'
|
||||
tokenId?: string
|
||||
role: string
|
||||
scopes: string[]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create auth pre-handler supporting both secret token and JWT auth.
|
||||
* When jwtSecret or tokenStore are not provided, only secret token auth works (Plan 1 stub mode).
|
||||
*/
|
||||
export function createAuthPreHandler(
|
||||
getSecret: () => string,
|
||||
getJwtSecret?: () => string,
|
||||
tokenStore?: TokenStore,
|
||||
): preHandlerHookHandler {
|
||||
return async function authPreHandler(request: FastifyRequest, _reply: FastifyReply) {
|
||||
const authHeader = request.headers.authorization
|
||||
const queryToken = (request.query as Record<string, string>)?.token
|
||||
const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : queryToken
|
||||
|
||||
if (!token) {
|
||||
throw new AuthError('UNAUTHORIZED', 'Missing authentication token')
|
||||
}
|
||||
|
||||
const secret = getSecret()
|
||||
|
||||
// Secret token check (timing-safe)
|
||||
if (token.length === secret.length && token.length > 0) {
|
||||
try {
|
||||
const tokenBuf = Buffer.from(token)
|
||||
const secretBuf = Buffer.from(secret)
|
||||
if (timingSafeEqual(tokenBuf, secretBuf)) {
|
||||
request.auth = { type: 'secret', role: 'admin', scopes: ['*'] }
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// Buffer comparison failed
|
||||
}
|
||||
}
|
||||
|
||||
// JWT verification (requires jwtSecret and tokenStore)
|
||||
if (getJwtSecret && tokenStore) {
|
||||
try {
|
||||
const payload = verifyToken(token, getJwtSecret())
|
||||
|
||||
// Check if token is revoked
|
||||
const storedToken = tokenStore.get(payload.sub)
|
||||
if (!storedToken || storedToken.revoked) {
|
||||
throw new AuthError('UNAUTHORIZED', 'Token revoked')
|
||||
}
|
||||
|
||||
// Update last used
|
||||
tokenStore.updateLastUsed(payload.sub)
|
||||
|
||||
// Resolve scopes: use token override or role defaults
|
||||
const scopes = payload.scopes ?? getRoleScopes(payload.role)
|
||||
|
||||
request.auth = {
|
||||
type: 'jwt',
|
||||
tokenId: payload.sub,
|
||||
role: payload.role,
|
||||
scopes,
|
||||
}
|
||||
return
|
||||
} catch (err) {
|
||||
if (err instanceof AuthError) throw err
|
||||
// Fall through to error below
|
||||
}
|
||||
}
|
||||
|
||||
throw new AuthError('UNAUTHORIZED', 'Invalid authentication token')
|
||||
}
|
||||
}
|
||||
|
||||
export function requireScopes(...scopes: string[]): preHandlerHookHandler {
|
||||
return async function scopeCheck(request: FastifyRequest, _reply: FastifyReply) {
|
||||
const { scopes: userScopes } = request.auth
|
||||
for (const scope of scopes) {
|
||||
if (!hasScope(userScopes, scope)) {
|
||||
throw new AuthError('FORBIDDEN', `Missing scope: ${scope}`, 403)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function requireRole(role: string): preHandlerHookHandler {
|
||||
const roleHierarchy: Record<string, number> = { viewer: 0, operator: 1, admin: 2 }
|
||||
|
||||
return async function roleCheck(request: FastifyRequest, _reply: FastifyReply) {
|
||||
const userLevel = roleHierarchy[request.auth.role] ?? -1
|
||||
const requiredLevel = roleHierarchy[role] ?? 999
|
||||
|
||||
if (userLevel < requiredLevel) {
|
||||
throw new AuthError('FORBIDDEN', `Requires ${role} role`, 403)
|
||||
}
|
||||
}
|
||||
}
|
||||
94
src/plugins/api-server/middleware/error-handler.ts
Normal file
94
src/plugins/api-server/middleware/error-handler.ts
Normal file
@ -0,0 +1,94 @@
|
||||
import type { FastifyError, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import { ZodError } from 'zod'
|
||||
|
||||
export interface ApiErrorResponse {
|
||||
error: {
|
||||
code: string
|
||||
message: string
|
||||
statusCode: number
|
||||
details?: unknown
|
||||
}
|
||||
}
|
||||
|
||||
export class NotFoundError extends Error {
|
||||
constructor(
|
||||
public code: string,
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'NotFoundError'
|
||||
}
|
||||
}
|
||||
|
||||
export class AuthError extends Error {
|
||||
constructor(
|
||||
public code: string,
|
||||
message: string,
|
||||
public statusCode: number = 401,
|
||||
) {
|
||||
super(message)
|
||||
this.name = 'AuthError'
|
||||
}
|
||||
}
|
||||
|
||||
export function globalErrorHandler(
|
||||
error: FastifyError | Error,
|
||||
_request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
): void {
|
||||
if (error instanceof ZodError) {
|
||||
reply.status(400).send({
|
||||
error: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: error.errors.map((e) => e.message).join(', '),
|
||||
statusCode: 400,
|
||||
details: error.errors,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (error instanceof NotFoundError) {
|
||||
reply.status(404).send({
|
||||
error: {
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
statusCode: 404,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if (error instanceof AuthError) {
|
||||
reply.status(error.statusCode).send({
|
||||
error: {
|
||||
code: error.code,
|
||||
message: error.message,
|
||||
statusCode: error.statusCode,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Fastify validation errors (from schema)
|
||||
if ('validation' in error && error.validation) {
|
||||
reply.status(400).send({
|
||||
error: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: error.message,
|
||||
statusCode: 400,
|
||||
details: error.validation,
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// Unknown error — don't leak details
|
||||
reply.status(500).send({
|
||||
error: {
|
||||
code: 'INTERNAL_ERROR',
|
||||
message: 'Internal server error',
|
||||
statusCode: 500,
|
||||
},
|
||||
})
|
||||
}
|
||||
9
src/plugins/api-server/routes/types.ts
Normal file
9
src/plugins/api-server/routes/types.ts
Normal file
@ -0,0 +1,9 @@
|
||||
import type { OpenACPCore } from '../../../core/core.js'
|
||||
import type { TopicManager } from '../../telegram/topic-manager.js'
|
||||
|
||||
export interface RouteDeps {
|
||||
core: OpenACPCore
|
||||
topicManager?: TopicManager
|
||||
startedAt: number
|
||||
getVersion: () => string
|
||||
}
|
||||
18
src/plugins/api-server/routes/v1-agents.ts
Normal file
18
src/plugins/api-server/routes/v1-agents.ts
Normal file
@ -0,0 +1,18 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
import { getAgentCapabilities } from '../../../core/agents/agent-registry.js'
|
||||
import { requireScopes } from '../middleware/auth.js'
|
||||
|
||||
export async function agentRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
const { core } = deps
|
||||
|
||||
app.get('/', { preHandler: requireScopes('agents:read') }, async () => {
|
||||
const agents = core.agentManager.getAvailableAgents()
|
||||
const defaultAgent = core.configManager.get().defaultAgent
|
||||
const agentsWithCaps = agents.map((a) => ({
|
||||
...a,
|
||||
capabilities: getAgentCapabilities(a.name),
|
||||
}))
|
||||
return { agents: agentsWithCaps, default: defaultAgent }
|
||||
})
|
||||
}
|
||||
127
src/plugins/api-server/routes/v1-auth.ts
Normal file
127
src/plugins/api-server/routes/v1-auth.ts
Normal file
@ -0,0 +1,127 @@
|
||||
import type { FastifyInstance, preHandlerHookHandler } from 'fastify'
|
||||
import type { TokenStore } from '../auth/token-store.js'
|
||||
import { signToken, verifyForRefresh } from '../auth/jwt.js'
|
||||
import { isValidRole } from '../auth/roles.js'
|
||||
import { AuthError, NotFoundError } from '../middleware/error-handler.js'
|
||||
import { requireScopes } from '../middleware/auth.js'
|
||||
import { parseDuration } from '../auth/token-store.js'
|
||||
|
||||
export interface AuthRouteDeps {
|
||||
tokenStore: TokenStore
|
||||
getJwtSecret: () => string
|
||||
authPreHandler: preHandlerHookHandler
|
||||
}
|
||||
|
||||
export async function authRoutesV1(app: FastifyInstance, deps: AuthRouteDeps): Promise<void> {
|
||||
const { tokenStore, getJwtSecret, authPreHandler } = deps
|
||||
|
||||
// POST /tokens — generate new JWT (secret token only, requires auth)
|
||||
app.post<{ Body: { role?: string; name?: string; expire?: string; scopes?: string[] } }>('/tokens', { preHandler: authPreHandler }, async (request, reply) => {
|
||||
if (request.auth.type !== 'secret') {
|
||||
throw new AuthError('FORBIDDEN', 'Only secret token can generate new tokens', 403)
|
||||
}
|
||||
|
||||
const { role = 'admin', name = 'api-token', expire = '24h', scopes } = request.body ?? {}
|
||||
|
||||
if (!isValidRole(role)) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'VALIDATION_ERROR', message: `Invalid role: ${role}`, statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
const storedToken = tokenStore.create({ role, name, expire, scopes })
|
||||
|
||||
const rfd = Math.floor(new Date(storedToken.refreshDeadline).getTime() / 1000)
|
||||
const accessToken = signToken(
|
||||
{ sub: storedToken.id, role: storedToken.role, scopes: storedToken.scopes, rfd },
|
||||
getJwtSecret(),
|
||||
expire,
|
||||
)
|
||||
|
||||
const expireMs = parseDuration(expire)
|
||||
|
||||
return reply.status(201).send({
|
||||
accessToken,
|
||||
tokenId: storedToken.id,
|
||||
expiresAt: new Date(Date.now() + expireMs).toISOString(),
|
||||
refreshDeadline: storedToken.refreshDeadline,
|
||||
})
|
||||
})
|
||||
|
||||
// GET /tokens — list active tokens
|
||||
app.get('/tokens', { preHandler: [authPreHandler, requireScopes('auth:manage')] }, async () => {
|
||||
const tokens = tokenStore.list()
|
||||
return {
|
||||
tokens: tokens.map((t) => ({
|
||||
id: t.id,
|
||||
name: t.name,
|
||||
role: t.role,
|
||||
scopes: t.scopes,
|
||||
createdAt: t.createdAt,
|
||||
refreshDeadline: t.refreshDeadline,
|
||||
lastUsedAt: t.lastUsedAt,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
// DELETE /tokens/:id — revoke token
|
||||
app.delete<{ Params: { id: string } }>('/tokens/:id', { preHandler: [authPreHandler, requireScopes('auth:manage')] }, async (request) => {
|
||||
const { id } = request.params
|
||||
const token = tokenStore.get(id)
|
||||
if (!token) {
|
||||
throw new NotFoundError('TOKEN_NOT_FOUND', `Token ${id} not found`)
|
||||
}
|
||||
tokenStore.revoke(id)
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
// POST /refresh — refresh JWT
|
||||
app.post('/refresh', async (request, reply) => {
|
||||
const authHeader = request.headers.authorization
|
||||
const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : null
|
||||
if (!token) {
|
||||
throw new AuthError('UNAUTHORIZED', 'Missing token')
|
||||
}
|
||||
|
||||
let payload
|
||||
try {
|
||||
payload = verifyForRefresh(token, getJwtSecret())
|
||||
} catch {
|
||||
throw new AuthError('UNAUTHORIZED', 'Invalid token signature')
|
||||
}
|
||||
|
||||
// Check revocation
|
||||
const storedToken = tokenStore.get(payload.sub)
|
||||
if (!storedToken || storedToken.revoked) {
|
||||
throw new AuthError('UNAUTHORIZED', 'Token revoked')
|
||||
}
|
||||
|
||||
// Check refresh deadline
|
||||
if (Date.now() > payload.rfd * 1000) {
|
||||
throw new AuthError('UNAUTHORIZED', 'Refresh deadline passed, generate a new token')
|
||||
}
|
||||
|
||||
const newToken = signToken(
|
||||
{ sub: payload.sub, role: payload.role, scopes: payload.scopes, rfd: payload.rfd },
|
||||
getJwtSecret(),
|
||||
'24h',
|
||||
)
|
||||
|
||||
return reply.send({
|
||||
accessToken: newToken,
|
||||
tokenId: payload.sub,
|
||||
expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
|
||||
refreshDeadline: storedToken.refreshDeadline,
|
||||
})
|
||||
})
|
||||
|
||||
// GET /me — current auth info (requires auth)
|
||||
app.get('/me', { preHandler: authPreHandler }, async (request) => {
|
||||
return {
|
||||
type: request.auth.type,
|
||||
tokenId: request.auth.tokenId,
|
||||
role: request.auth.role,
|
||||
scopes: request.auth.scopes,
|
||||
}
|
||||
})
|
||||
}
|
||||
60
src/plugins/api-server/routes/v1-commands.ts
Normal file
60
src/plugins/api-server/routes/v1-commands.ts
Normal file
@ -0,0 +1,60 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
import type { CommandRegistry } from '../../../core/command-registry.js'
|
||||
import { requireScopes } from '../middleware/auth.js'
|
||||
|
||||
export async function commandRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
const { core } = deps
|
||||
|
||||
// Get command registry from service registry
|
||||
const getCommandRegistry = (): CommandRegistry | undefined => {
|
||||
return core.lifecycleManager.serviceRegistry.get<CommandRegistry>('command-registry')
|
||||
}
|
||||
|
||||
// GET / — list all registered commands
|
||||
app.get('/', { preHandler: requireScopes('commands:execute') }, async (_request, reply) => {
|
||||
const registry = getCommandRegistry()
|
||||
if (!registry) {
|
||||
return reply.status(503).send({
|
||||
error: { code: 'SERVICE_UNAVAILABLE', message: 'Command registry not available', statusCode: 503 },
|
||||
})
|
||||
}
|
||||
const commands = registry.getAll()
|
||||
return {
|
||||
commands: commands.map((cmd: any) => ({
|
||||
name: cmd.name,
|
||||
description: cmd.description,
|
||||
usage: cmd.usage,
|
||||
category: cmd.category,
|
||||
pluginName: cmd.pluginName,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
// POST /execute — execute a command
|
||||
app.post<{ Body: { command?: string; sessionId?: string } }>('/execute', { preHandler: requireScopes('commands:execute') }, async (request, reply) => {
|
||||
const registry = getCommandRegistry()
|
||||
if (!registry) {
|
||||
return reply.status(503).send({
|
||||
error: { code: 'SERVICE_UNAVAILABLE', message: 'Command registry not available', statusCode: 503 },
|
||||
})
|
||||
}
|
||||
|
||||
const { command, sessionId } = request.body ?? {}
|
||||
|
||||
if (!command) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing command', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
const result = await registry.execute(command, {
|
||||
raw: command,
|
||||
sessionId: sessionId ?? null,
|
||||
channelId: 'api',
|
||||
userId: request.auth?.tokenId ?? 'secret',
|
||||
reply: async () => {},
|
||||
})
|
||||
return { result: result ?? { type: 'silent' } }
|
||||
})
|
||||
}
|
||||
134
src/plugins/api-server/routes/v1-config.ts
Normal file
134
src/plugins/api-server/routes/v1-config.ts
Normal file
@ -0,0 +1,134 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
|
||||
const SENSITIVE_KEYS = ['botToken', 'token', 'apiKey', 'secret', 'password', 'webhookSecret']
|
||||
|
||||
function redactConfig(config: unknown): unknown {
|
||||
const redacted = structuredClone(config)
|
||||
redactDeep(redacted as Record<string, unknown>)
|
||||
return redacted
|
||||
}
|
||||
|
||||
function redactDeep(obj: Record<string, unknown>): void {
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
if (SENSITIVE_KEYS.includes(key) && typeof value === 'string') {
|
||||
obj[key] = '***'
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
if (item && typeof item === 'object') redactDeep(item as Record<string, unknown>)
|
||||
}
|
||||
} else if (value && typeof value === 'object') {
|
||||
redactDeep(value as Record<string, unknown>)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
import { requireScopes, requireRole } from '../middleware/auth.js'
|
||||
|
||||
export async function configRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
const { core } = deps
|
||||
|
||||
// GET /editable — safe fields with metadata
|
||||
app.get('/editable', { preHandler: requireScopes('config:read') }, async () => {
|
||||
const { getSafeFields, resolveOptions, getConfigValue } = await import('../../../core/config/config-registry.js')
|
||||
const config = core.configManager.get()
|
||||
const safeFields = getSafeFields()
|
||||
|
||||
const fields = safeFields.map((def) => ({
|
||||
path: def.path,
|
||||
displayName: def.displayName,
|
||||
group: def.group,
|
||||
type: def.type,
|
||||
options: resolveOptions(def, config),
|
||||
value: getConfigValue(config, def.path),
|
||||
hotReload: def.hotReload,
|
||||
}))
|
||||
|
||||
return { fields }
|
||||
})
|
||||
|
||||
// GET / — full config (redacted)
|
||||
app.get('/', { preHandler: requireScopes('config:read') }, async () => {
|
||||
const config = core.configManager.get()
|
||||
return { config: redactConfig(config) }
|
||||
})
|
||||
|
||||
// PATCH / — update config field
|
||||
app.patch<{ Body: { path?: string; value?: unknown } }>('/', { preHandler: requireScopes('config:write') }, async (request, reply) => {
|
||||
const { path: configPath, value } = request.body ?? {}
|
||||
|
||||
if (!configPath) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing path', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
// Block prototype pollution
|
||||
const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
||||
const parts = configPath.split('.')
|
||||
if (parts.some((p) => BLOCKED_KEYS.has(p))) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Invalid config path', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
// Enforce safe-fields scope
|
||||
const { getFieldDef } = await import('../../../core/config/config-registry.js')
|
||||
const fieldDef = getFieldDef(configPath)
|
||||
if (!fieldDef || fieldDef.scope !== 'safe') {
|
||||
return reply.status(403).send({
|
||||
error: { code: 'FORBIDDEN', message: 'This config field cannot be modified via the API', statusCode: 403 },
|
||||
})
|
||||
}
|
||||
|
||||
// Pre-validate by cloning config and applying the change
|
||||
const currentConfig = core.configManager.get()
|
||||
const cloned = structuredClone(currentConfig) as Record<string, unknown>
|
||||
let target: Record<string, unknown> = cloned
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
const part = parts[i]
|
||||
if (target[part] && typeof target[part] === 'object' && !Array.isArray(target[part])) {
|
||||
target = target[part] as Record<string, unknown>
|
||||
} else if (target[part] === undefined || target[part] === null) {
|
||||
target[part] = {}
|
||||
target = target[part] as Record<string, unknown>
|
||||
} else {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Invalid config path', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const lastKey = parts[parts.length - 1]
|
||||
target[lastKey] = value
|
||||
|
||||
const { ConfigSchema } = await import('../../../core/config/config.js')
|
||||
const result = ConfigSchema.safeParse(cloned)
|
||||
if (!result.success) {
|
||||
return reply.status(400).send({
|
||||
error: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: 'Validation failed',
|
||||
statusCode: 400,
|
||||
details: result.error.issues.map((i) => ({ path: i.path.join('.'), message: i.message })),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Convert dot-path to nested object for save
|
||||
const updates: Record<string, unknown> = {}
|
||||
let updateTarget = updates
|
||||
for (let i = 0; i < parts.length - 1; i++) {
|
||||
updateTarget[parts[i]] = {}
|
||||
updateTarget = updateTarget[parts[i]] as Record<string, unknown>
|
||||
}
|
||||
updateTarget[lastKey] = value
|
||||
|
||||
await core.configManager.save(updates, configPath)
|
||||
|
||||
const { isHotReloadable } = await import('../../../core/config/config-registry.js')
|
||||
const needsRestart = !isHotReloadable(configPath)
|
||||
|
||||
return { ok: true, needsRestart, config: redactConfig(core.configManager.get()) }
|
||||
})
|
||||
}
|
||||
23
src/plugins/api-server/routes/v1-notify.ts
Normal file
23
src/plugins/api-server/routes/v1-notify.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
|
||||
export async function notifyRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
const { core } = deps
|
||||
|
||||
app.post<{ Body: { message?: string } }>('/', async (request, reply) => {
|
||||
const { message } = request.body ?? {}
|
||||
|
||||
if (!message) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing message', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
await core.notificationManager.notifyAll({
|
||||
sessionId: 'system',
|
||||
type: 'completed',
|
||||
summary: message,
|
||||
})
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
248
src/plugins/api-server/routes/v1-sessions.ts
Normal file
248
src/plugins/api-server/routes/v1-sessions.ts
Normal file
@ -0,0 +1,248 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
import { NotFoundError } from '../middleware/error-handler.js'
|
||||
import { requireScopes } from '../middleware/auth.js'
|
||||
import { createChildLogger } from '../../../core/utils/log.js'
|
||||
|
||||
const log = createChildLogger({ module: 'api-server' })
|
||||
|
||||
export async function sessionRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
const { core } = deps
|
||||
|
||||
// GET / — list sessions
|
||||
app.get('/', { preHandler: requireScopes('sessions:read') }, async () => {
|
||||
const sessions = core.sessionManager.listSessions()
|
||||
return {
|
||||
sessions: sessions.map((s) => ({
|
||||
id: s.id,
|
||||
agent: s.agentName,
|
||||
status: s.status,
|
||||
name: s.name ?? null,
|
||||
workspace: s.workingDirectory,
|
||||
createdAt: s.createdAt.toISOString(),
|
||||
dangerousMode: s.dangerousMode,
|
||||
queueDepth: s.queueDepth,
|
||||
promptRunning: s.promptRunning,
|
||||
lastActiveAt: core.sessionManager.getSessionRecord(s.id)?.lastActiveAt ?? null,
|
||||
})),
|
||||
}
|
||||
})
|
||||
|
||||
// GET /:id — session detail
|
||||
app.get<{ Params: { id: string } }>('/:id', { preHandler: requireScopes('sessions:read') }, async (request) => {
|
||||
const { id } = request.params
|
||||
const session = core.sessionManager.getSession(decodeURIComponent(id))
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session "${id}" not found`)
|
||||
}
|
||||
return {
|
||||
session: {
|
||||
id: session.id,
|
||||
agent: session.agentName,
|
||||
status: session.status,
|
||||
name: session.name ?? null,
|
||||
workspace: session.workingDirectory,
|
||||
createdAt: session.createdAt.toISOString(),
|
||||
dangerousMode: session.dangerousMode,
|
||||
queueDepth: session.queueDepth,
|
||||
promptRunning: session.promptRunning,
|
||||
threadId: session.threadId,
|
||||
channelId: session.channelId,
|
||||
agentSessionId: session.agentSessionId,
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
// POST / — create session
|
||||
app.post<{ Body: { agent?: string; workspace?: string; channel?: string } }>('/', { preHandler: requireScopes('sessions:write') }, async (request, reply) => {
|
||||
const { agent, workspace, channel } = request.body ?? {}
|
||||
|
||||
// Check max concurrent sessions
|
||||
const config = core.configManager.get()
|
||||
const activeSessions = core.sessionManager
|
||||
.listSessions()
|
||||
.filter((s) => s.status === 'active' || s.status === 'initializing')
|
||||
if (activeSessions.length >= config.security.maxConcurrentSessions) {
|
||||
return reply.status(429).send({
|
||||
error: {
|
||||
code: 'SESSION_LIMIT',
|
||||
message: `Max concurrent sessions (${config.security.maxConcurrentSessions}) reached. Cancel a session first.`,
|
||||
statusCode: 429,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// Resolve adapter
|
||||
let adapterId: string | null = null
|
||||
let adapter: any = null
|
||||
|
||||
if (channel) {
|
||||
if (!core.adapters.has(channel)) {
|
||||
const available = Array.from(core.adapters.keys()).join(', ') || 'none'
|
||||
return reply.status(400).send({
|
||||
error: {
|
||||
code: 'ADAPTER_NOT_FOUND',
|
||||
message: `Adapter '${channel}' is not connected. Available: ${available}`,
|
||||
statusCode: 400,
|
||||
},
|
||||
})
|
||||
}
|
||||
adapterId = channel
|
||||
adapter = core.adapters.get(channel) ?? null
|
||||
} else {
|
||||
const firstEntry = core.adapters.entries().next().value
|
||||
if (firstEntry) {
|
||||
;[adapterId, adapter] = firstEntry
|
||||
}
|
||||
}
|
||||
|
||||
const channelId = adapterId ?? 'api'
|
||||
const resolvedAgent = agent || config.defaultAgent
|
||||
const agentDef = core.agentCatalog.resolve(resolvedAgent)
|
||||
const resolvedWorkspace = core.configManager.resolveWorkspace(workspace || agentDef?.workingDirectory)
|
||||
|
||||
const session = await core.createSession({
|
||||
channelId,
|
||||
agentName: resolvedAgent,
|
||||
workingDirectory: resolvedWorkspace,
|
||||
createThread: !!adapter,
|
||||
initialName: `🔄 ${resolvedAgent} — New Session`,
|
||||
})
|
||||
|
||||
// If no adapter wired events (headless), auto-approve permissions
|
||||
if (!adapter) {
|
||||
session.agentInstance.onPermissionRequest = async (permReq) => {
|
||||
const allowOption = permReq.options.find((o) => o.isAllow)
|
||||
log.debug(
|
||||
{ sessionId: session.id, permissionId: permReq.id, option: allowOption?.id },
|
||||
'Auto-approving permission for API session',
|
||||
)
|
||||
return allowOption?.id ?? permReq.options[0]?.id ?? ''
|
||||
}
|
||||
}
|
||||
|
||||
// Warmup in background
|
||||
session.warmup().catch((err) =>
|
||||
log.warn({ err, sessionId: session.id }, 'API session warmup failed'),
|
||||
)
|
||||
|
||||
return reply.status(200).send({
|
||||
sessionId: session.id,
|
||||
agent: session.agentName,
|
||||
status: session.status,
|
||||
workspace: session.workingDirectory,
|
||||
})
|
||||
})
|
||||
|
||||
// POST /adopt — adopt external session
|
||||
app.post<{ Body: { agent?: string; agentSessionId?: string; cwd?: string; channel?: string } }>('/adopt', { preHandler: requireScopes('sessions:write') }, async (request, reply) => {
|
||||
const { agent, agentSessionId, cwd, channel } = request.body ?? {}
|
||||
|
||||
if (!agent || !agentSessionId) {
|
||||
return reply.status(400).send({
|
||||
error: {
|
||||
code: 'BAD_REQUEST',
|
||||
message: 'Missing required fields: agent, agentSessionId',
|
||||
statusCode: 400,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const result = await core.adoptSession(agent, agentSessionId, cwd ?? process.cwd(), channel)
|
||||
|
||||
if (result.ok) {
|
||||
return result
|
||||
} else {
|
||||
const status = result.error === 'session_limit' ? 429 : result.error === 'agent_not_supported' ? 400 : 500
|
||||
return reply.status(status).send(result)
|
||||
}
|
||||
})
|
||||
|
||||
// POST /:id/prompt — enqueue prompt
|
||||
app.post<{ Params: { id: string }; Body: { prompt?: string } }>('/:id/prompt', { preHandler: requireScopes('sessions:prompt') }, async (request, reply) => {
|
||||
const session = core.sessionManager.getSession(decodeURIComponent(request.params.id))
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session "${request.params.id}" not found`)
|
||||
}
|
||||
|
||||
if (session.status === 'cancelled' || session.status === 'finished' || session.status === 'error') {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'SESSION_INACTIVE', message: `Session is ${session.status}`, statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
const prompt = request.body?.prompt
|
||||
if (!prompt) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing prompt', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
session.enqueuePrompt(prompt).catch(() => {})
|
||||
return { ok: true, sessionId: session.id, queueDepth: session.queueDepth }
|
||||
})
|
||||
|
||||
// POST /:id/permission — resolve permission
|
||||
app.post<{ Params: { id: string }; Body: { permissionId?: string; optionId?: string } }>('/:id/permission', { preHandler: requireScopes('sessions:permission') }, async (request, reply) => {
|
||||
const session = core.sessionManager.getSession(decodeURIComponent(request.params.id))
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session "${request.params.id}" not found`)
|
||||
}
|
||||
|
||||
const { permissionId, optionId } = request.body ?? {}
|
||||
if (!permissionId || !optionId) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing permissionId or optionId', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
if (!session.permissionGate.isPending || session.permissionGate.requestId !== permissionId) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'NO_PENDING_PERMISSION', message: 'No matching pending permission request', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
session.permissionGate.resolve(optionId)
|
||||
return { ok: true }
|
||||
})
|
||||
|
||||
// PATCH /:id/dangerous — toggle dangerous mode
|
||||
app.patch<{ Params: { id: string }; Body: { enabled?: boolean } }>('/:id/dangerous', { preHandler: requireScopes('sessions:write') }, async (request, reply) => {
|
||||
const session = core.sessionManager.getSession(decodeURIComponent(request.params.id))
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session "${request.params.id}" not found`)
|
||||
}
|
||||
|
||||
const { enabled } = request.body ?? {}
|
||||
if (typeof enabled !== 'boolean') {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing enabled boolean', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
session.dangerousMode = enabled
|
||||
await core.sessionManager.patchRecord(session.id, { dangerousMode: enabled })
|
||||
return { ok: true, dangerousMode: enabled }
|
||||
})
|
||||
|
||||
// POST /:id/archive — archive session
|
||||
app.post<{ Params: { id: string } }>('/:id/archive', { preHandler: requireScopes('sessions:write') }, async (request, reply) => {
|
||||
const result = await core.archiveSession(decodeURIComponent(request.params.id))
|
||||
if (result.ok) {
|
||||
return result
|
||||
} else {
|
||||
return reply.status(400).send(result)
|
||||
}
|
||||
})
|
||||
|
||||
// DELETE /:id — cancel session
|
||||
app.delete<{ Params: { id: string } }>('/:id', { preHandler: requireScopes('sessions:write') }, async (request) => {
|
||||
const sessionId = decodeURIComponent(request.params.id)
|
||||
const session = core.sessionManager.getSession(sessionId)
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session "${sessionId}" not found`)
|
||||
}
|
||||
await core.sessionManager.cancelSession(sessionId)
|
||||
return { ok: true }
|
||||
})
|
||||
}
|
||||
48
src/plugins/api-server/routes/v1-system.ts
Normal file
48
src/plugins/api-server/routes/v1-system.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
import { requireScopes, requireRole } from '../middleware/auth.js'
|
||||
|
||||
export async function systemRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
const { core, startedAt, getVersion } = deps
|
||||
|
||||
// Health is unauthenticated (used for discovery)
|
||||
app.get('/health', async () => {
|
||||
const activeSessions = core.sessionManager.listSessions()
|
||||
const allRecords = core.sessionManager.listRecords()
|
||||
const mem = process.memoryUsage()
|
||||
const tunnel = core.tunnelService
|
||||
|
||||
return {
|
||||
status: 'ok',
|
||||
uptime: Date.now() - startedAt,
|
||||
version: getVersion(),
|
||||
memory: { rss: mem.rss, heapUsed: mem.heapUsed, heapTotal: mem.heapTotal },
|
||||
sessions: {
|
||||
active: activeSessions.filter((s) => s.status === 'active' || s.status === 'initializing').length,
|
||||
total: allRecords.length,
|
||||
},
|
||||
adapters: Array.from(core.adapters.keys()),
|
||||
tunnel: tunnel ? { enabled: true, url: tunnel.getPublicUrl() } : { enabled: false },
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/version', { preHandler: requireScopes('system:health') }, async () => ({ version: getVersion() }))
|
||||
|
||||
app.post('/restart', { preHandler: requireRole('admin') }, async (_request, reply) => {
|
||||
if (!core.requestRestart) {
|
||||
return reply.status(501).send({
|
||||
error: { code: 'NOT_AVAILABLE', message: 'Restart not available', statusCode: 501 },
|
||||
})
|
||||
}
|
||||
setImmediate(() => core.requestRestart!())
|
||||
return { ok: true, message: 'Restarting...' }
|
||||
})
|
||||
|
||||
app.get('/adapters', { preHandler: requireScopes('system:health') }, async () => {
|
||||
const adapters = Array.from(core.adapters.entries()).map(([name]) => ({
|
||||
name,
|
||||
type: 'built-in' as const,
|
||||
}))
|
||||
return { adapters }
|
||||
})
|
||||
}
|
||||
44
src/plugins/api-server/routes/v1-topics.ts
Normal file
44
src/plugins/api-server/routes/v1-topics.ts
Normal file
@ -0,0 +1,44 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
|
||||
export async function topicRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
if (!deps.topicManager) return
|
||||
|
||||
const topicManager = deps.topicManager
|
||||
|
||||
// GET / — list topics
|
||||
app.get<{ Querystring: { status?: string } }>('/', async (request) => {
|
||||
const statusParam = request.query.status
|
||||
const filter = statusParam ? { statuses: statusParam.split(',') } : undefined
|
||||
const topics = topicManager.listTopics(filter)
|
||||
return { topics }
|
||||
})
|
||||
|
||||
// POST /cleanup — cleanup topics
|
||||
app.post<{ Body: { statuses?: string[] } }>('/cleanup', async (request) => {
|
||||
const statuses = request.body?.statuses
|
||||
const result = await topicManager.cleanup(statuses)
|
||||
return result
|
||||
})
|
||||
|
||||
// DELETE /:sessionId — delete topic
|
||||
app.delete<{ Params: { sessionId: string }; Querystring: { force?: string } }>('/:sessionId', async (request, reply) => {
|
||||
const sessionId = decodeURIComponent(request.params.sessionId)
|
||||
const force = request.query.force === 'true'
|
||||
const result = await topicManager.deleteTopic(sessionId, force ? { confirmed: true } : undefined)
|
||||
|
||||
if (result.ok) {
|
||||
return result
|
||||
} else if (result.needsConfirmation) {
|
||||
return reply.status(409).send({
|
||||
error: 'Session is active',
|
||||
needsConfirmation: true,
|
||||
session: result.session,
|
||||
})
|
||||
} else if (result.error === 'Cannot delete system topic') {
|
||||
return reply.status(403).send({ error: result.error })
|
||||
} else {
|
||||
return reply.status(404).send({ error: result.error ?? 'Not found' })
|
||||
}
|
||||
})
|
||||
}
|
||||
81
src/plugins/api-server/routes/v1-tunnel.ts
Normal file
81
src/plugins/api-server/routes/v1-tunnel.ts
Normal file
@ -0,0 +1,81 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import type { RouteDeps } from './types.js'
|
||||
|
||||
export async function tunnelRoutesV1(app: FastifyInstance, deps: RouteDeps): Promise<void> {
|
||||
const { core } = deps
|
||||
|
||||
app.get('/', async () => {
|
||||
const tunnel = core.tunnelService
|
||||
if (tunnel) {
|
||||
return {
|
||||
enabled: true,
|
||||
url: tunnel.getPublicUrl(),
|
||||
provider: core.configManager.get().tunnel.provider,
|
||||
}
|
||||
}
|
||||
return { enabled: false }
|
||||
})
|
||||
|
||||
app.get('/list', async () => {
|
||||
const tunnel = core.tunnelService
|
||||
if (!tunnel) return []
|
||||
return tunnel.listTunnels()
|
||||
})
|
||||
|
||||
app.post<{ Body: { port?: number; label?: string; sessionId?: string } }>('/', async (request, reply) => {
|
||||
const tunnel = core.tunnelService
|
||||
if (!tunnel) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'TUNNEL_NOT_ENABLED', message: 'Tunnel service is not enabled', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
const { port, label, sessionId } = request.body ?? {}
|
||||
if (!port || typeof port !== 'number') {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'port is required and must be a number', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
try {
|
||||
const entry = await tunnel.addTunnel(port, { label, sessionId })
|
||||
return entry
|
||||
} catch (err) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'TUNNEL_ERROR', message: (err as Error).message, statusCode: 400 },
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
app.delete<{ Params: { port: string } }>('/:port', async (request, reply) => {
|
||||
const tunnel = core.tunnelService
|
||||
if (!tunnel) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'TUNNEL_NOT_ENABLED', message: 'Tunnel service is not enabled', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
const port = parseInt(request.params.port, 10)
|
||||
try {
|
||||
await tunnel.stopTunnel(port)
|
||||
return { ok: true }
|
||||
} catch (err) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'TUNNEL_ERROR', message: (err as Error).message, statusCode: 400 },
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// DELETE / — stop all user tunnels
|
||||
app.delete('/', async (_request, reply) => {
|
||||
const tunnel = core.tunnelService
|
||||
if (!tunnel) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'TUNNEL_NOT_ENABLED', message: 'Tunnel service is not enabled', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
const count = tunnel.listTunnels().length
|
||||
await tunnel.stopAllUser()
|
||||
return { ok: true, stopped: count }
|
||||
})
|
||||
}
|
||||
23
src/plugins/api-server/schemas/common.ts
Normal file
23
src/plugins/api-server/schemas/common.ts
Normal file
@ -0,0 +1,23 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
export const PaginationQuerySchema = z.object({
|
||||
limit: z.coerce.number().int().min(1).max(100).default(50),
|
||||
offset: z.coerce.number().int().min(0).default(0),
|
||||
})
|
||||
|
||||
export const IdParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
})
|
||||
|
||||
export const NameParamSchema = z.object({
|
||||
name: z.string().min(1),
|
||||
})
|
||||
|
||||
export const ApiErrorSchema = z.object({
|
||||
error: z.object({
|
||||
code: z.string(),
|
||||
message: z.string(),
|
||||
statusCode: z.number(),
|
||||
details: z.unknown().optional(),
|
||||
}),
|
||||
})
|
||||
86
src/plugins/api-server/server.ts
Normal file
86
src/plugins/api-server/server.ts
Normal file
@ -0,0 +1,86 @@
|
||||
import Fastify, { type FastifyInstance, type FastifyPluginAsync, type preHandlerHookHandler } from 'fastify'
|
||||
import fastifyCors from '@fastify/cors'
|
||||
import fastifySwagger from '@fastify/swagger'
|
||||
import fastifySwaggerUi from '@fastify/swagger-ui'
|
||||
import fastifyRateLimit from '@fastify/rate-limit'
|
||||
import { serializerCompiler, validatorCompiler } from 'fastify-type-provider-zod'
|
||||
import { globalErrorHandler } from './middleware/error-handler.js'
|
||||
import { createAuthPreHandler } from './middleware/auth.js'
|
||||
|
||||
export interface ApiServerOptions {
|
||||
port: number
|
||||
host: string
|
||||
getSecret: () => string
|
||||
getJwtSecret?: () => string
|
||||
tokenStore?: import('./auth/token-store.js').TokenStore
|
||||
logger?: boolean
|
||||
}
|
||||
|
||||
export interface ApiServerInstance {
|
||||
app: FastifyInstance
|
||||
authPreHandler: preHandlerHookHandler
|
||||
start(): Promise<{ port: number; host: string }>
|
||||
stop(): Promise<void>
|
||||
registerPlugin(prefix: string, plugin: FastifyPluginAsync, opts?: { auth?: boolean }): void
|
||||
}
|
||||
|
||||
export async function createApiServer(options: ApiServerOptions): Promise<ApiServerInstance> {
|
||||
const app = Fastify({ logger: options.logger ?? false })
|
||||
|
||||
// Zod validation
|
||||
app.setValidatorCompiler(validatorCompiler)
|
||||
app.setSerializerCompiler(serializerCompiler)
|
||||
|
||||
// Plugins
|
||||
await app.register(fastifyCors, { origin: true })
|
||||
await app.register(fastifyRateLimit, { max: 100, timeWindow: '1 minute' })
|
||||
await app.register(fastifySwagger, {
|
||||
openapi: {
|
||||
info: { title: 'OpenACP API', version: '1.0.0', description: 'OpenACP REST API' },
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' },
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
await app.register(fastifySwaggerUi, { routePrefix: '/api/docs' })
|
||||
|
||||
// Global error handler
|
||||
app.setErrorHandler(globalErrorHandler)
|
||||
|
||||
// Auth pre-handler (supports secret token + optional JWT)
|
||||
const authPreHandler = createAuthPreHandler(options.getSecret, options.getJwtSecret, options.tokenStore)
|
||||
|
||||
// Decorate request with auth object
|
||||
app.decorateRequest('auth', undefined as any)
|
||||
|
||||
// System routes are registered via index.ts (v1-system.ts) — not here
|
||||
// This avoids duplicate route registration
|
||||
|
||||
return {
|
||||
app,
|
||||
authPreHandler,
|
||||
|
||||
registerPlugin(prefix: string, plugin: FastifyPluginAsync, opts?: { auth?: boolean }) {
|
||||
const wrappedPlugin: FastifyPluginAsync = async (pluginApp, _opts) => {
|
||||
if (opts?.auth !== false) {
|
||||
pluginApp.addHook('onRequest', authPreHandler)
|
||||
}
|
||||
await plugin(pluginApp, _opts)
|
||||
}
|
||||
app.register(wrappedPlugin, { prefix })
|
||||
},
|
||||
|
||||
async start() {
|
||||
await app.ready()
|
||||
const address = await app.listen({ port: options.port, host: options.host })
|
||||
const url = new URL(address)
|
||||
return { port: Number(url.port), host: url.hostname }
|
||||
},
|
||||
|
||||
async stop() {
|
||||
await app.close()
|
||||
},
|
||||
}
|
||||
}
|
||||
32
src/plugins/api-server/service.ts
Normal file
32
src/plugins/api-server/service.ts
Normal file
@ -0,0 +1,32 @@
|
||||
import type { FastifyPluginAsync, preHandlerHookHandler } from 'fastify'
|
||||
import type { ApiServerInstance } from './server.js'
|
||||
import { requireScopes, requireRole } from './middleware/auth.js'
|
||||
|
||||
export interface ApiServerService {
|
||||
registerPlugin(prefix: string, plugin: FastifyPluginAsync, opts?: { auth?: boolean }): void
|
||||
authPreHandler: preHandlerHookHandler
|
||||
requireScopes(...scopes: string[]): preHandlerHookHandler
|
||||
requireRole(role: string): preHandlerHookHandler
|
||||
getPort(): number
|
||||
getBaseUrl(): string
|
||||
getTunnelUrl(): string | null
|
||||
}
|
||||
|
||||
export function createApiServerService(
|
||||
server: ApiServerInstance,
|
||||
opts: {
|
||||
getPort: () => number
|
||||
getBaseUrl: () => string
|
||||
getTunnelUrl: () => string | null
|
||||
},
|
||||
): ApiServerService {
|
||||
return {
|
||||
registerPlugin: server.registerPlugin.bind(server),
|
||||
authPreHandler: server.authPreHandler,
|
||||
requireScopes,
|
||||
requireRole,
|
||||
getPort: opts.getPort,
|
||||
getBaseUrl: opts.getBaseUrl,
|
||||
getTunnelUrl: opts.getTunnelUrl,
|
||||
}
|
||||
}
|
||||
248
src/plugins/sse-adapter/__tests__/sse-adapter.test.ts
Normal file
248
src/plugins/sse-adapter/__tests__/sse-adapter.test.ts
Normal file
@ -0,0 +1,248 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { EventBuffer } from '../event-buffer.js'
|
||||
import { ConnectionManager } from '../connection-manager.js'
|
||||
import { SSEAdapter } from '../adapter.js'
|
||||
import { serializeSSE, serializeOutgoingMessage, serializePermissionRequest } from '../event-serializer.js'
|
||||
import type { ServerResponse } from 'node:http'
|
||||
|
||||
// ========================
|
||||
// Event Serializer
|
||||
// ========================
|
||||
|
||||
describe('event-serializer', () => {
|
||||
it('serializes a basic SSE event', () => {
|
||||
const result = serializeSSE('message', 'evt_001', { type: 'text', content: 'Hello' })
|
||||
expect(result).toBe('event: message\nid: evt_001\ndata: {"type":"text","content":"Hello"}\n\n')
|
||||
})
|
||||
|
||||
it('serializes SSE event without ID', () => {
|
||||
const result = serializeSSE('heartbeat', undefined, { timestamp: '2026-03-31T00:00:00Z' })
|
||||
expect(result).toBe('event: heartbeat\ndata: {"timestamp":"2026-03-31T00:00:00Z"}\n\n')
|
||||
})
|
||||
|
||||
it('serializes outgoing text message', () => {
|
||||
const result = serializeOutgoingMessage('sess_1', 'evt_002', {
|
||||
type: 'text',
|
||||
text: 'Hello world',
|
||||
} as any)
|
||||
expect(result).toContain('event: message')
|
||||
expect(result).toContain('id: evt_002')
|
||||
expect(result).toContain('"type":"text"')
|
||||
expect(result).toContain('"sessionId":"sess_1"')
|
||||
})
|
||||
|
||||
it('serializes permission request', () => {
|
||||
const result = serializePermissionRequest('sess_1', 'evt_003', {
|
||||
id: 'perm_1',
|
||||
description: 'Run npm install',
|
||||
options: [{ id: 'allow', label: 'Allow', isAllow: true }],
|
||||
})
|
||||
expect(result).toContain('event: permission_request')
|
||||
expect(result).toContain('"id":"perm_1"')
|
||||
})
|
||||
})
|
||||
|
||||
// ========================
|
||||
// Event Buffer
|
||||
// ========================
|
||||
|
||||
describe('EventBuffer', () => {
|
||||
it('stores events per session', () => {
|
||||
const buffer = new EventBuffer(100)
|
||||
buffer.push('sess_1', { id: 'evt_1', data: 'hello' })
|
||||
buffer.push('sess_1', { id: 'evt_2', data: 'world' })
|
||||
buffer.push('sess_2', { id: 'evt_3', data: 'other' })
|
||||
|
||||
const events = buffer.getSince('sess_1', undefined)
|
||||
expect(events).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('returns events since a given ID', () => {
|
||||
const buffer = new EventBuffer(100)
|
||||
buffer.push('sess_1', { id: 'evt_1', data: 'a' })
|
||||
buffer.push('sess_1', { id: 'evt_2', data: 'b' })
|
||||
buffer.push('sess_1', { id: 'evt_3', data: 'c' })
|
||||
|
||||
const events = buffer.getSince('sess_1', 'evt_1')
|
||||
expect(events).toHaveLength(2)
|
||||
expect(events![0].id).toBe('evt_2')
|
||||
expect(events![1].id).toBe('evt_3')
|
||||
})
|
||||
|
||||
it('returns empty array for unknown session', () => {
|
||||
const buffer = new EventBuffer(100)
|
||||
expect(buffer.getSince('unknown', undefined)).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('evicts oldest events when buffer is full', () => {
|
||||
const buffer = new EventBuffer(3)
|
||||
buffer.push('sess_1', { id: 'evt_1', data: 'a' })
|
||||
buffer.push('sess_1', { id: 'evt_2', data: 'b' })
|
||||
buffer.push('sess_1', { id: 'evt_3', data: 'c' })
|
||||
buffer.push('sess_1', { id: 'evt_4', data: 'd' })
|
||||
|
||||
const all = buffer.getSince('sess_1', undefined)
|
||||
expect(all).toHaveLength(3)
|
||||
expect(all![0].id).toBe('evt_2')
|
||||
})
|
||||
|
||||
it('returns null when requested ID was evicted', () => {
|
||||
const buffer = new EventBuffer(2)
|
||||
buffer.push('sess_1', { id: 'evt_1', data: 'a' })
|
||||
buffer.push('sess_1', { id: 'evt_2', data: 'b' })
|
||||
buffer.push('sess_1', { id: 'evt_3', data: 'c' })
|
||||
|
||||
expect(buffer.getSince('sess_1', 'evt_1')).toBeNull()
|
||||
})
|
||||
|
||||
it('cleans up a session buffer', () => {
|
||||
const buffer = new EventBuffer(100)
|
||||
buffer.push('sess_1', { id: 'evt_1', data: 'a' })
|
||||
buffer.cleanup('sess_1')
|
||||
expect(buffer.getSince('sess_1', undefined)).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
// ========================
|
||||
// Connection Manager
|
||||
// ========================
|
||||
|
||||
function mockResponse(): ServerResponse {
|
||||
return {
|
||||
write: vi.fn().mockReturnValue(true),
|
||||
end: vi.fn(),
|
||||
on: vi.fn(),
|
||||
writableEnded: false,
|
||||
} as any
|
||||
}
|
||||
|
||||
describe('ConnectionManager', () => {
|
||||
let manager: ConnectionManager
|
||||
|
||||
beforeEach(() => {
|
||||
manager = new ConnectionManager()
|
||||
})
|
||||
|
||||
it('adds a connection and retrieves by session', () => {
|
||||
const res = mockResponse()
|
||||
const conn = manager.addConnection('sess_1', 'tok_1', res)
|
||||
expect(conn.id).toBeDefined()
|
||||
expect(conn.sessionId).toBe('sess_1')
|
||||
|
||||
const conns = manager.getConnectionsBySession('sess_1')
|
||||
expect(conns).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('supports multiple connections per session', () => {
|
||||
manager.addConnection('sess_1', 'tok_1', mockResponse())
|
||||
manager.addConnection('sess_1', 'tok_2', mockResponse())
|
||||
expect(manager.getConnectionsBySession('sess_1')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('removes a connection', () => {
|
||||
const conn = manager.addConnection('sess_1', 'tok_1', mockResponse())
|
||||
manager.removeConnection(conn.id)
|
||||
expect(manager.getConnectionsBySession('sess_1')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('broadcasts to all connections for a session', () => {
|
||||
const res1 = mockResponse()
|
||||
const res2 = mockResponse()
|
||||
manager.addConnection('sess_1', 'tok_1', res1)
|
||||
manager.addConnection('sess_1', 'tok_2', res2)
|
||||
|
||||
manager.broadcast('sess_1', 'event: test\ndata: hello\n\n')
|
||||
expect(res1.write).toHaveBeenCalledWith('event: test\ndata: hello\n\n')
|
||||
expect(res2.write).toHaveBeenCalledWith('event: test\ndata: hello\n\n')
|
||||
})
|
||||
|
||||
it('does not broadcast to other sessions', () => {
|
||||
const res1 = mockResponse()
|
||||
const res2 = mockResponse()
|
||||
manager.addConnection('sess_1', 'tok_1', res1)
|
||||
manager.addConnection('sess_2', 'tok_2', res2)
|
||||
|
||||
manager.broadcast('sess_1', 'event: test\ndata: hello\n\n')
|
||||
expect(res1.write).toHaveBeenCalled()
|
||||
expect(res2.write).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('disconnects all connections for a token', () => {
|
||||
const res1 = mockResponse()
|
||||
const res2 = mockResponse()
|
||||
manager.addConnection('sess_1', 'tok_1', res1)
|
||||
manager.addConnection('sess_2', 'tok_1', res2)
|
||||
manager.addConnection('sess_3', 'tok_2', mockResponse())
|
||||
|
||||
manager.disconnectByToken('tok_1')
|
||||
expect(res1.end).toHaveBeenCalled()
|
||||
expect(res2.end).toHaveBeenCalled()
|
||||
expect(manager.getConnectionsBySession('sess_1')).toHaveLength(0)
|
||||
expect(manager.getConnectionsBySession('sess_2')).toHaveLength(0)
|
||||
expect(manager.getConnectionsBySession('sess_3')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('returns empty array for unknown session', () => {
|
||||
expect(manager.getConnectionsBySession('unknown')).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
// ========================
|
||||
// SSE Adapter
|
||||
// ========================
|
||||
|
||||
describe('SSEAdapter', () => {
|
||||
let adapter: SSEAdapter
|
||||
let connectionManager: ConnectionManager
|
||||
let eventBuffer: EventBuffer
|
||||
|
||||
beforeEach(() => {
|
||||
connectionManager = new ConnectionManager()
|
||||
eventBuffer = new EventBuffer(100)
|
||||
adapter = new SSEAdapter(connectionManager, eventBuffer)
|
||||
})
|
||||
|
||||
it('has correct name and capabilities', () => {
|
||||
expect(adapter.name).toBe('sse')
|
||||
expect(adapter.capabilities.streaming).toBe(true)
|
||||
expect(adapter.capabilities.richFormatting).toBe(false)
|
||||
expect(adapter.capabilities.threads).toBe(true)
|
||||
})
|
||||
|
||||
it('sends message to all session connections', async () => {
|
||||
const res = mockResponse()
|
||||
connectionManager.addConnection('sess_1', 'tok_1', res)
|
||||
|
||||
await adapter.sendMessage('sess_1', { type: 'text', text: 'Hello' } as any)
|
||||
expect(res.write).toHaveBeenCalled()
|
||||
const written = (res.write as any).mock.calls[0][0] as string
|
||||
expect(written).toContain('event: message')
|
||||
})
|
||||
|
||||
it('buffers events for reconnect', async () => {
|
||||
connectionManager.addConnection('sess_1', 'tok_1', mockResponse())
|
||||
await adapter.sendMessage('sess_1', { type: 'text', text: 'Hello' } as any)
|
||||
|
||||
const buffered = eventBuffer.getSince('sess_1', undefined)
|
||||
expect(buffered).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('sends permission request', async () => {
|
||||
const res = mockResponse()
|
||||
connectionManager.addConnection('sess_1', 'tok_1', res)
|
||||
|
||||
await adapter.sendPermissionRequest('sess_1', {
|
||||
id: 'perm_1',
|
||||
description: 'Run npm install',
|
||||
options: [{ id: 'allow', label: 'Allow', isAllow: true }],
|
||||
})
|
||||
|
||||
const written = (res.write as any).mock.calls[0][0] as string
|
||||
expect(written).toContain('event: permission_request')
|
||||
})
|
||||
|
||||
it('createSessionThread returns sessionId', async () => {
|
||||
const threadId = await adapter.createSessionThread('sess_1', 'Test')
|
||||
expect(threadId).toBe('sess_1')
|
||||
})
|
||||
})
|
||||
88
src/plugins/sse-adapter/adapter.ts
Normal file
88
src/plugins/sse-adapter/adapter.ts
Normal file
@ -0,0 +1,88 @@
|
||||
import type { IChannelAdapter, AdapterCapabilities } from '../../core/channel.js'
|
||||
import type { OutgoingMessage, PermissionRequest, NotificationMessage } from '../../core/types.js'
|
||||
import type { ConnectionManager } from './connection-manager.js'
|
||||
import type { EventBuffer } from './event-buffer.js'
|
||||
import {
|
||||
generateEventId,
|
||||
serializeOutgoingMessage,
|
||||
serializePermissionRequest,
|
||||
serializeSSE,
|
||||
serializeHeartbeat,
|
||||
} from './event-serializer.js'
|
||||
|
||||
export class SSEAdapter implements IChannelAdapter {
|
||||
readonly name = 'sse'
|
||||
readonly capabilities: AdapterCapabilities = {
|
||||
streaming: true,
|
||||
richFormatting: false,
|
||||
threads: true,
|
||||
reactions: false,
|
||||
fileUpload: false,
|
||||
voice: false,
|
||||
}
|
||||
|
||||
private heartbeatInterval: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
constructor(
|
||||
private connectionManager: ConnectionManager,
|
||||
private eventBuffer: EventBuffer,
|
||||
) {}
|
||||
|
||||
async sendMessage(sessionId: string, message: OutgoingMessage): Promise<void> {
|
||||
const eventId = generateEventId()
|
||||
const serialized = serializeOutgoingMessage(sessionId, eventId, message)
|
||||
|
||||
this.eventBuffer.push(sessionId, { id: eventId, data: serialized })
|
||||
this.connectionManager.broadcast(sessionId, serialized)
|
||||
}
|
||||
|
||||
async sendPermissionRequest(sessionId: string, request: PermissionRequest): Promise<void> {
|
||||
const eventId = generateEventId()
|
||||
const serialized = serializePermissionRequest(sessionId, eventId, request)
|
||||
|
||||
this.eventBuffer.push(sessionId, { id: eventId, data: serialized })
|
||||
this.connectionManager.broadcast(sessionId, serialized)
|
||||
}
|
||||
|
||||
async sendNotification(notification: NotificationMessage): Promise<void> {
|
||||
const eventId = generateEventId()
|
||||
const sessionId = notification.sessionId
|
||||
const serialized = serializeSSE('notification', eventId, notification)
|
||||
|
||||
if (sessionId) {
|
||||
this.eventBuffer.push(sessionId, { id: eventId, data: serialized })
|
||||
this.connectionManager.broadcast(sessionId, serialized)
|
||||
}
|
||||
}
|
||||
|
||||
async createSessionThread(sessionId: string, _name: string): Promise<string> {
|
||||
return sessionId
|
||||
}
|
||||
|
||||
async renameSessionThread(_sessionId: string, _newName: string): Promise<void> {
|
||||
// No-op — client tracks via session_update events
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
this.heartbeatInterval = setInterval(() => {
|
||||
const heartbeat = serializeHeartbeat()
|
||||
for (const conn of this.connectionManager.listConnections()) {
|
||||
if (!conn.response.writableEnded) {
|
||||
try {
|
||||
conn.response.write(heartbeat)
|
||||
} catch {
|
||||
// Connection closed
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 30_000)
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
if (this.heartbeatInterval) {
|
||||
clearInterval(this.heartbeatInterval)
|
||||
this.heartbeatInterval = null
|
||||
}
|
||||
this.connectionManager.cleanup()
|
||||
}
|
||||
}
|
||||
106
src/plugins/sse-adapter/connection-manager.ts
Normal file
106
src/plugins/sse-adapter/connection-manager.ts
Normal file
@ -0,0 +1,106 @@
|
||||
import type { ServerResponse } from 'node:http'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
|
||||
export interface SSEConnection {
|
||||
id: string
|
||||
sessionId: string
|
||||
tokenId: string
|
||||
response: ServerResponse
|
||||
connectedAt: Date
|
||||
lastEventId?: string
|
||||
}
|
||||
|
||||
export class ConnectionManager {
|
||||
private connections = new Map<string, SSEConnection>()
|
||||
private sessionIndex = new Map<string, Set<string>>()
|
||||
|
||||
addConnection(sessionId: string, tokenId: string, response: ServerResponse): SSEConnection {
|
||||
const id = `conn_${randomBytes(8).toString('hex')}`
|
||||
const connection: SSEConnection = {
|
||||
id,
|
||||
sessionId,
|
||||
tokenId,
|
||||
response,
|
||||
connectedAt: new Date(),
|
||||
}
|
||||
|
||||
this.connections.set(id, connection)
|
||||
|
||||
let sessionConns = this.sessionIndex.get(sessionId)
|
||||
if (!sessionConns) {
|
||||
sessionConns = new Set()
|
||||
this.sessionIndex.set(sessionId, sessionConns)
|
||||
}
|
||||
sessionConns.add(id)
|
||||
|
||||
response.on('close', () => {
|
||||
this.removeConnection(id)
|
||||
})
|
||||
|
||||
return connection
|
||||
}
|
||||
|
||||
removeConnection(connectionId: string): void {
|
||||
const conn = this.connections.get(connectionId)
|
||||
if (!conn) return
|
||||
|
||||
this.connections.delete(connectionId)
|
||||
const sessionConns = this.sessionIndex.get(conn.sessionId)
|
||||
if (sessionConns) {
|
||||
sessionConns.delete(connectionId)
|
||||
if (sessionConns.size === 0) {
|
||||
this.sessionIndex.delete(conn.sessionId)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getConnectionsBySession(sessionId: string): SSEConnection[] {
|
||||
const connIds = this.sessionIndex.get(sessionId)
|
||||
if (!connIds) return []
|
||||
return Array.from(connIds)
|
||||
.map((id) => this.connections.get(id))
|
||||
.filter((c): c is SSEConnection => c !== undefined)
|
||||
}
|
||||
|
||||
broadcast(sessionId: string, serializedEvent: string): void {
|
||||
const connections = this.getConnectionsBySession(sessionId)
|
||||
for (const conn of connections) {
|
||||
if (!conn.response.writableEnded) {
|
||||
try {
|
||||
conn.response.write(serializedEvent)
|
||||
} catch {
|
||||
// Connection closed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
disconnectByToken(tokenId: string): void {
|
||||
const toRemove: string[] = []
|
||||
for (const [id, conn] of this.connections) {
|
||||
if (conn.tokenId === tokenId) {
|
||||
if (!conn.response.writableEnded) {
|
||||
conn.response.end()
|
||||
}
|
||||
toRemove.push(id)
|
||||
}
|
||||
}
|
||||
for (const id of toRemove) {
|
||||
this.removeConnection(id)
|
||||
}
|
||||
}
|
||||
|
||||
listConnections(): SSEConnection[] {
|
||||
return Array.from(this.connections.values())
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
for (const conn of this.connections.values()) {
|
||||
if (!conn.response.writableEnded) {
|
||||
conn.response.end()
|
||||
}
|
||||
}
|
||||
this.connections.clear()
|
||||
this.sessionIndex.clear()
|
||||
}
|
||||
}
|
||||
49
src/plugins/sse-adapter/event-buffer.ts
Normal file
49
src/plugins/sse-adapter/event-buffer.ts
Normal file
@ -0,0 +1,49 @@
|
||||
export interface BufferedEvent {
|
||||
id: string
|
||||
data: unknown
|
||||
}
|
||||
|
||||
export class EventBuffer {
|
||||
private buffers = new Map<string, BufferedEvent[]>()
|
||||
|
||||
constructor(private maxSize: number = 100) {}
|
||||
|
||||
push(sessionId: string, event: BufferedEvent): void {
|
||||
let buffer = this.buffers.get(sessionId)
|
||||
if (!buffer) {
|
||||
buffer = []
|
||||
this.buffers.set(sessionId, buffer)
|
||||
}
|
||||
|
||||
buffer.push(event)
|
||||
|
||||
while (buffer.length > this.maxSize) {
|
||||
buffer.shift()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get events since a given event ID.
|
||||
* Returns null if the requested ID was evicted (client missed too many events).
|
||||
* Returns all events if lastEventId is undefined.
|
||||
*/
|
||||
getSince(sessionId: string, lastEventId: string | undefined): BufferedEvent[] | null {
|
||||
const buffer = this.buffers.get(sessionId)
|
||||
if (!buffer || buffer.length === 0) return []
|
||||
|
||||
if (lastEventId === undefined) {
|
||||
return [...buffer]
|
||||
}
|
||||
|
||||
const index = buffer.findIndex((e) => e.id === lastEventId)
|
||||
if (index === -1) {
|
||||
return null // Event was evicted
|
||||
}
|
||||
|
||||
return buffer.slice(index + 1)
|
||||
}
|
||||
|
||||
cleanup(sessionId: string): void {
|
||||
this.buffers.delete(sessionId)
|
||||
}
|
||||
}
|
||||
70
src/plugins/sse-adapter/event-serializer.ts
Normal file
70
src/plugins/sse-adapter/event-serializer.ts
Normal file
@ -0,0 +1,70 @@
|
||||
import type { OutgoingMessage, PermissionRequest } from '../../core/types.js'
|
||||
|
||||
let eventCounter = 0
|
||||
|
||||
export function generateEventId(): string {
|
||||
return `evt_${Date.now()}_${++eventCounter}`
|
||||
}
|
||||
|
||||
export function serializeSSE(event: string, id: string | undefined, data: unknown): string {
|
||||
let result = `event: ${event}\n`
|
||||
if (id) {
|
||||
result += `id: ${id}\n`
|
||||
}
|
||||
result += `data: ${JSON.stringify(data)}\n\n`
|
||||
return result
|
||||
}
|
||||
|
||||
export function serializeOutgoingMessage(
|
||||
sessionId: string,
|
||||
eventId: string,
|
||||
message: OutgoingMessage,
|
||||
): string {
|
||||
return serializeSSE('message', eventId, {
|
||||
type: message.type,
|
||||
sessionId,
|
||||
text: message.text,
|
||||
metadata: message.metadata,
|
||||
timestamp: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
export function serializePermissionRequest(
|
||||
sessionId: string,
|
||||
eventId: string,
|
||||
request: PermissionRequest,
|
||||
): string {
|
||||
return serializeSSE('permission_request', eventId, {
|
||||
sessionId,
|
||||
id: request.id,
|
||||
description: request.description,
|
||||
options: request.options,
|
||||
})
|
||||
}
|
||||
|
||||
export function serializeSessionUpdate(
|
||||
sessionId: string,
|
||||
eventId: string,
|
||||
update: { status: string; name?: string },
|
||||
): string {
|
||||
return serializeSSE('session_update', eventId, { sessionId, ...update })
|
||||
}
|
||||
|
||||
export function serializeHeartbeat(): string {
|
||||
return serializeSSE('heartbeat', undefined, {
|
||||
timestamp: new Date().toISOString(),
|
||||
uptime: process.uptime(),
|
||||
})
|
||||
}
|
||||
|
||||
export function serializeConnected(connectionId: string, sessionId: string): string {
|
||||
return serializeSSE('connected', generateEventId(), {
|
||||
connectionId,
|
||||
sessionId,
|
||||
connectedAt: new Date().toISOString(),
|
||||
})
|
||||
}
|
||||
|
||||
export function serializeError(eventId: string, code: string, details?: Record<string, unknown>): string {
|
||||
return serializeSSE('error', eventId, { code, ...(details ?? {}) })
|
||||
}
|
||||
57
src/plugins/sse-adapter/index.ts
Normal file
57
src/plugins/sse-adapter/index.ts
Normal file
@ -0,0 +1,57 @@
|
||||
import type { OpenACPPlugin } from '../../core/plugin/types.js'
|
||||
import type { OpenACPCore } from '../../core/core.js'
|
||||
import type { ApiServerService } from '../api-server/service.js'
|
||||
|
||||
function createSSEAdapterPlugin(): OpenACPPlugin {
|
||||
let adapter: { stop(): Promise<void> } | null = null
|
||||
|
||||
return {
|
||||
name: '@openacp/sse-adapter',
|
||||
version: '1.0.0',
|
||||
description: 'SSE-based messaging adapter for app clients',
|
||||
essential: false,
|
||||
permissions: ['services:register', 'kernel:access', 'events:read'],
|
||||
pluginDependencies: { '@openacp/api-server': '*' },
|
||||
|
||||
async setup(ctx) {
|
||||
const core = ctx.core as OpenACPCore
|
||||
|
||||
const { SSEAdapter } = await import('./adapter.js')
|
||||
const { ConnectionManager } = await import('./connection-manager.js')
|
||||
const { EventBuffer } = await import('./event-buffer.js')
|
||||
const { createSSERoutes } = await import('./routes.js')
|
||||
|
||||
const connectionManager = new ConnectionManager()
|
||||
const eventBuffer = new EventBuffer(100)
|
||||
const sseAdapter = new SSEAdapter(connectionManager, eventBuffer)
|
||||
|
||||
// Register as adapter in core
|
||||
core.registerAdapter('sse', sseAdapter)
|
||||
|
||||
// Register routes into API server (if available)
|
||||
try {
|
||||
const apiService = ctx.getService<ApiServerService>('api-server')
|
||||
if (apiService) {
|
||||
apiService.registerPlugin('/api/v1/sse', (app) =>
|
||||
createSSERoutes(app, { connectionManager, eventBuffer, core }),
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
ctx.log.warn('API server service not available — SSE routes not registered')
|
||||
}
|
||||
|
||||
await sseAdapter.start()
|
||||
adapter = sseAdapter
|
||||
|
||||
ctx.log.info('SSE adapter started')
|
||||
},
|
||||
|
||||
async teardown() {
|
||||
if (adapter) {
|
||||
await adapter.stop()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default createSSEAdapterPlugin()
|
||||
153
src/plugins/sse-adapter/routes.ts
Normal file
153
src/plugins/sse-adapter/routes.ts
Normal file
@ -0,0 +1,153 @@
|
||||
import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'
|
||||
import type { OpenACPCore } from '../../core/core.js'
|
||||
import type { ConnectionManager } from './connection-manager.js'
|
||||
import type { EventBuffer } from './event-buffer.js'
|
||||
import { NotFoundError } from '../api-server/middleware/error-handler.js'
|
||||
import { serializeConnected, serializeError } from './event-serializer.js'
|
||||
|
||||
export interface SSERouteDeps {
|
||||
connectionManager: ConnectionManager
|
||||
eventBuffer: EventBuffer
|
||||
core: OpenACPCore
|
||||
}
|
||||
|
||||
export async function createSSERoutes(app: FastifyInstance, deps: SSERouteDeps): Promise<void> {
|
||||
const { connectionManager, eventBuffer, core } = deps
|
||||
|
||||
// GET /sessions/:id/stream — SSE event stream
|
||||
app.get<{ Params: { id: string }; Querystring: { token?: string } }>('/sessions/:id/stream', async (request: FastifyRequest, reply: FastifyReply) => {
|
||||
const id = decodeURIComponent((request.params as { id: string }).id)
|
||||
const session = core.sessionManager.getSession(id)
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session ${id} not found`)
|
||||
}
|
||||
|
||||
reply.hijack()
|
||||
const res = reply.raw
|
||||
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
'X-Accel-Buffering': 'no',
|
||||
})
|
||||
|
||||
const tokenId = (request as any).auth?.tokenId ?? 'secret'
|
||||
const conn = connectionManager.addConnection(id, tokenId, res)
|
||||
|
||||
res.write(serializeConnected(conn.id, id))
|
||||
|
||||
// Replay missed events if reconnecting
|
||||
const lastEventId = request.headers['last-event-id'] as string | undefined
|
||||
if (lastEventId) {
|
||||
const missed = eventBuffer.getSince(id, lastEventId)
|
||||
if (missed === null) {
|
||||
res.write(serializeError('reconnect', 'EVENTS_LOST', { message: 'Some events were missed' }))
|
||||
} else {
|
||||
for (const event of missed) {
|
||||
res.write(event.data as string)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// POST /sessions/:id/prompt — send message
|
||||
app.post<{ Params: { id: string }; Body: { prompt?: string; message?: string } }>('/sessions/:id/prompt', async (request, reply) => {
|
||||
const id = decodeURIComponent(request.params.id)
|
||||
const session = core.sessionManager.getSession(id)
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session ${id} not found`)
|
||||
}
|
||||
|
||||
const prompt = request.body?.prompt ?? request.body?.message
|
||||
if (!prompt) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing prompt', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
session.enqueuePrompt(prompt).catch(() => {})
|
||||
return { success: true, sessionId: id }
|
||||
})
|
||||
|
||||
// POST /sessions/:id/permission — resolve permission
|
||||
app.post<{ Params: { id: string }; Body: { permissionId?: string; optionId?: string } }>('/sessions/:id/permission', async (request, reply) => {
|
||||
const id = decodeURIComponent(request.params.id)
|
||||
const session = core.sessionManager.getSession(id)
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session ${id} not found`)
|
||||
}
|
||||
|
||||
const { permissionId, optionId } = request.body ?? {}
|
||||
if (!permissionId || !optionId) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing permissionId or optionId', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
if (!session.permissionGate.isPending || session.permissionGate.requestId !== permissionId) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'NO_PENDING_PERMISSION', message: 'No matching pending permission request', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
session.permissionGate.resolve(optionId)
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
// POST /sessions/:id/cancel — cancel session
|
||||
app.post<{ Params: { id: string } }>('/sessions/:id/cancel', async (request) => {
|
||||
const id = decodeURIComponent(request.params.id)
|
||||
const session = core.sessionManager.getSession(id)
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session ${id} not found`)
|
||||
}
|
||||
await core.sessionManager.cancelSession(id)
|
||||
return { success: true }
|
||||
})
|
||||
|
||||
// POST /sessions/:id/command — execute command in session context
|
||||
app.post<{ Params: { id: string }; Body: { command?: string } }>('/sessions/:id/command', async (request, reply) => {
|
||||
const id = decodeURIComponent(request.params.id)
|
||||
const session = core.sessionManager.getSession(id)
|
||||
if (!session) {
|
||||
throw new NotFoundError('SESSION_NOT_FOUND', `Session ${id} not found`)
|
||||
}
|
||||
|
||||
const { command } = request.body ?? {}
|
||||
if (!command) {
|
||||
return reply.status(400).send({
|
||||
error: { code: 'BAD_REQUEST', message: 'Missing command', statusCode: 400 },
|
||||
})
|
||||
}
|
||||
|
||||
const registry = core.lifecycleManager.serviceRegistry.get<any>('command-registry')
|
||||
if (!registry) {
|
||||
return reply.status(503).send({
|
||||
error: { code: 'SERVICE_UNAVAILABLE', message: 'Command registry not available', statusCode: 503 },
|
||||
})
|
||||
}
|
||||
|
||||
const result = await registry.execute(command, {
|
||||
raw: command,
|
||||
sessionId: id,
|
||||
channelId: 'sse',
|
||||
userId: (request as any).auth?.tokenId ?? 'secret',
|
||||
reply: async () => {},
|
||||
})
|
||||
return { result: result ?? { type: 'silent' } }
|
||||
})
|
||||
|
||||
// GET /connections — list active SSE connections (admin only)
|
||||
app.get('/connections', async () => {
|
||||
const connections = connectionManager.listConnections()
|
||||
return {
|
||||
connections: connections.map((c) => ({
|
||||
id: c.id,
|
||||
sessionId: c.sessionId,
|
||||
tokenId: c.tokenId,
|
||||
connectedAt: c.connectedAt.toISOString(),
|
||||
})),
|
||||
}
|
||||
})
|
||||
}
|
||||
4
src/types/qrcode-terminal.d.ts
vendored
Normal file
4
src/types/qrcode-terminal.d.ts
vendored
Normal file
@ -0,0 +1,4 @@
|
||||
declare module 'qrcode-terminal' {
|
||||
export function generate(text: string, opts?: { small?: boolean }, callback?: (qrcode: string) => void): void
|
||||
export function setErrorLevel(level: 'L' | 'M' | 'Q' | 'H'): void
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user