Fix bin/publish: copy docs.dist from project root

Fix bin/publish: use correct .env path for rspade_system
Fix bin/publish script: prevent grep exit code 1 from terminating script

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-10-21 02:08:33 +00:00
commit f6fac6c4bc
79758 changed files with 10547827 additions and 0 deletions

View File

@@ -0,0 +1,142 @@
import * as fs from 'fs/promises';
import * as crypto from 'crypto';
import * as path from 'path';
import { Request, Response, NextFunction } from 'express';
import { Logger } from '../utils/logger';
import { Config } from '../utils/config';
interface AuthSession {
client_key: string;
server_key: string;
created_at: number;
workspace_path: string;
}
export class AuthValidator {
private logger: Logger;
private sessionsCache: Map<string, AuthSession> = new Map();
constructor() {
this.logger = new Logger('AuthValidator');
}
public async validateWebSocketAuth(sessionId: string, signature: string): Promise<boolean> {
try {
const session = await this.loadSession(sessionId);
if (!session) {
this.logger.warn(`Session not found: ${sessionId}`);
return false;
}
// For WebSocket, we'll validate a simple signature
// In production, this should include timestamp and nonce
const expectedSignature = crypto
.createHmac('sha256', session.server_key)
.update(sessionId)
.digest('hex');
return signature === expectedSignature;
} catch (error) {
this.logger.error('WebSocket auth validation failed:', error);
return false;
}
}
public authMiddleware() {
return async (req: Request, res: Response, next: NextFunction) => {
const sessionId = req.headers['x-session-id'] as string;
const signature = req.headers['x-auth-signature'] as string;
const timestamp = req.headers['x-timestamp'] as string;
if (!sessionId || !signature || !timestamp) {
res.status(401).json({
error: 'Missing authentication headers',
code: 401
});
return;
}
try {
const session = await this.loadSession(sessionId);
if (!session) {
res.status(401).json({
error: 'Session not found',
code: 401,
recoverable: true,
recovery: 'Create new session via POST /_ide/service/auth/create'
});
return;
}
// Validate signature
const method = req.method;
const path = req.path;
const body = JSON.stringify(req.body || {});
const signatureBase = `${method}\n${path}\n${timestamp}\n${body}`;
const expectedSignature = crypto
.createHmac('sha256', session.server_key)
.update(signatureBase)
.digest('hex');
if (signature !== expectedSignature) {
this.logger.warn('Invalid signature for session:', sessionId);
res.status(401).json({
error: 'Invalid signature',
code: 401
});
return;
}
// Check timestamp to prevent replay attacks (5 minute window)
const requestTime = parseInt(timestamp, 10);
const currentTime = Math.floor(Date.now() / 1000);
if (Math.abs(currentTime - requestTime) > 300) {
res.status(401).json({
error: 'Request timestamp expired',
code: 401
});
return;
}
// Attach session to request for use in routes
(req as any).session = session;
(req as any).sessionId = sessionId;
next();
} catch (error) {
this.logger.error('Auth middleware error:', error);
res.status(500).json({
error: 'Authentication error',
code: 500
});
}
};
}
private async loadSession(sessionId: string): Promise<AuthSession | null> {
// Check cache first
if (this.sessionsCache.has(sessionId)) {
return this.sessionsCache.get(sessionId)!;
}
try {
const sessionPath = path.join(Config.AUTH_SESSION_PATH, `auth-${sessionId}.json`);
const data = await fs.readFile(sessionPath, 'utf8');
const session = JSON.parse(data) as AuthSession;
// Cache the session
this.sessionsCache.set(sessionId, session);
return session;
} catch (error) {
if ((error as any).code === 'ENOENT') {
return null; // Session file doesn't exist
}
throw error;
}
}
public clearCache(): void {
this.sessionsCache.clear();
}
}

View File

@@ -0,0 +1,202 @@
import { WebSocketServer, WebSocket } from 'ws';
import * as http from 'http';
import { Logger } from '../utils/logger';
import { AuthValidator } from './auth';
export interface WebSocketMessage {
type: string;
data?: any;
timestamp?: number;
}
export class WebSocketHandler {
private wss: WebSocketServer | null = null;
private logger: Logger;
private clients: Map<string, WebSocket> = new Map();
private authValidator: AuthValidator;
constructor(authValidator: AuthValidator) {
this.logger = new Logger('WebSocketHandler');
this.authValidator = authValidator;
}
public initialize(server: http.Server): void {
this.wss = new WebSocketServer({
noServer: true,
path: '/_ide/debug/ws'
});
// Handle upgrade requests
server.on('upgrade', async (request, socket, head) => {
this.logger.info(`WebSocket upgrade request: ${request.url}`);
// Only handle our specific path
if (request.url !== '/_ide/debug/ws') {
socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
socket.destroy();
return;
}
// Accept all connections - auth will be done via first message
this.wss!.handleUpgrade(request, socket, head, (ws) => {
this.wss!.emit('connection', ws, request);
});
});
// Handle new connections
this.wss.on('connection', (ws: WebSocket, _request: http.IncomingMessage) => {
this.logger.info(`WebSocket client connected (awaiting auth)`);
let sessionId: string | null = null;
let authenticated = false;
// Handle incoming messages
ws.on('message', async (data) => {
try {
const message = JSON.parse(data.toString()) as WebSocketMessage;
// First message must be auth
if (!authenticated) {
if (message.type !== 'auth') {
this.logger.warn('First message was not auth, closing connection');
ws.close(1008, 'Authentication required');
return;
}
sessionId = message.data?.sessionId;
const signature = message.data?.signature;
if (!sessionId || !signature) {
this.logger.warn('Missing auth credentials');
ws.close(1008, 'Invalid authentication');
return;
}
const isValid = await this.authValidator.validateWebSocketAuth(sessionId, signature);
if (!isValid) {
this.logger.warn(`Invalid auth for session: ${sessionId}`);
ws.close(1008, 'Authentication failed');
return;
}
authenticated = true;
this.clients.set(sessionId, ws);
this.logger.info(`Client authenticated: ${sessionId}`);
// Send welcome message
this.sendMessage(ws, {
type: 'welcome',
data: {
message: 'Authenticated successfully',
sessionId: sessionId,
timestamp: Date.now()
}
});
return;
}
// Handle regular messages after auth
this.handleMessage(ws, sessionId!, message);
} catch (error) {
this.logger.error('Failed to parse WebSocket message:', error);
this.sendMessage(ws, {
type: 'error',
data: { message: 'Invalid message format' }
});
}
});
// Handle pong frames
ws.on('pong', () => {
if (sessionId) {
this.logger.debug(`Pong received from ${sessionId}`);
}
});
// Handle disconnection
ws.on('close', () => {
if (sessionId) {
this.logger.info(`WebSocket client disconnected: ${sessionId}`);
this.clients.delete(sessionId);
}
});
// Handle errors
ws.on('error', (error) => {
if (sessionId) {
this.logger.error(`WebSocket error for ${sessionId}:`, error);
this.clients.delete(sessionId);
}
});
});
// Start heartbeat
this.startHeartbeat();
}
private handleMessage(ws: WebSocket, sessionId: string, message: WebSocketMessage): void {
this.logger.debug(`Message from ${sessionId}: ${message.type}`);
switch (message.type) {
case 'ping':
// Respond to ping with pong
this.sendMessage(ws, {
type: 'pong',
data: {
originalData: message.data,
timestamp: Date.now()
}
});
break;
case 'hello':
// Handle hello message
this.sendMessage(ws, {
type: 'hello_response',
data: {
message: `Hello ${message.data?.name || 'client'}! Pong from debug proxy`,
timestamp: Date.now()
}
});
break;
default:
this.logger.warn(`Unknown message type: ${message.type}`);
this.sendMessage(ws, {
type: 'error',
data: { message: `Unknown message type: ${message.type}` }
});
}
}
private sendMessage(ws: WebSocket, message: WebSocketMessage): void {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(message));
}
}
private startHeartbeat(): void {
setInterval(() => {
this.clients.forEach((ws, sessionId) => {
if (ws.readyState === WebSocket.OPEN) {
ws.ping();
} else {
this.clients.delete(sessionId);
}
});
}, 30000); // 30 second heartbeat
}
public broadcast(message: WebSocketMessage): void {
this.clients.forEach((ws) => {
this.sendMessage(ws, message);
});
}
public sendToSession(sessionId: string, message: WebSocketMessage): void {
const ws = this.clients.get(sessionId);
if (ws) {
this.sendMessage(ws, message);
}
}
}