Token导航 LogoToken导航TokenDH.com
待分类敏感数据github未标认证来源可访问clear审计提醒

backend-websocket后端网络套接字

Agent Skill

用于辅助安全审计、权限检查、凭据风险、认证流程和常见漏洞排查。它适合让 Agent 梳理敏感配置、检查依赖风险、分析鉴权逻辑或生成安全复核清单。使用时不能把工具输出直接当最终结论,涉及密钥、令牌、用户数据或生产系统时,应先确认最小权限、脱敏方式和操作边界。

总安装

186

周安装

8

GitHub Stars

1

下载量

65
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:backend-websocket(后端网络套接字)
来源仓库:https://github.com/workshop-ventures/skills
仓库路径:skills/backend-websocket
安装命令:
npx skills add https://github.com/workshop-ventures/skills --skill backend-websocket
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/workshop-ventures/skills --skill backend-websocket

简介

backend-websocket 为 Koa 后端添加 WebSocket 支持,集成 JWT 认证和结构化消息处理。

  • 适用于实时通信场景如通知推送和协同编辑,需确保消息格式统一。
  • 通过 npx skills add 安装,需按步骤启用 websockify 和短 ID 生成器。
  • 首次连接必须发送 JWT 令牌,否则拒绝建立会话。
  • 建议实现心跳机制和异常断开处理保障连接稳定性。

SKILL.md

Backend WebSocket Support

This skill adds WebSocket support to a Koa backend with JWT authentication.

Overview

WebSocket connections require:

  1. JWT authentication as the first message
  2. Structured message format for all communication
  3. Proper cleanup on disconnect

Installation

npm install koa-websocket short-uuid @types/koa-websocket

Implementation

Step 1: Enable WebSocket Support

Update apps/backend/src/main.ts:

import Koa from 'koa';
import websockify from 'koa-websocket';
import short from 'short-uuid';

// Create websocket-enabled Koa app
const app = websockify(new Koa());

// ... rest of app setup ...

Step 2: Create Auth Middleware

Create apps/backend/src/middleware/wsAuth.ts:

import Koa from 'koa';
import short from 'short-uuid';
import { createLogger } from '../lib/logger';

const log = createLogger('ws-auth');

type WsNext = (ctx: Koa.Context) => Promise<void>;

// Your JWT verification function
async function verifyToken(token: string): Promise<{ uid: string; email: string }> {
  // Implement your JWT verification logic
  // This should throw if token is invalid
  throw new Error('Implement verifyToken');
}

/**
 * WebSocket authentication middleware
 * Requires JWT token as first message
 */
export async function wsAuthMiddleware(ctx: Koa.Context, next: WsNext): Promise<void> {
  // Generate unique ID for this connection
  ctx.websocket['_id'] = short.generate();

  log.debug({ connId: ctx.websocket['_id'] }, 'WebSocket connection received, waiting for auth');

  // First message must be authentication
  ctx.websocket.once('message', async (message) => {
    try {
      const data = JSON.parse(message.toString());

      if (data.type !== 'login' || !data.token) {
        log.warn({ connId: ctx.websocket['_id'] }, 'Invalid login message');
        ctx.websocket.send(JSON.stringify({
          type: 'error',
          message: 'First message must be login with token',
        }));
        ctx.websocket.close();
        return;
      }

      // Verify JWT token
      const user = await verifyToken(data.token);
      ctx.state.user = user;

      log.info({ connId: ctx.websocket['_id'], uid: user.uid }, 'WebSocket authenticated');

      ctx.websocket.send(JSON.stringify({
        type: 'auth',
        message: 'Authenticated',
      }));

      // Remove this listener and proceed to route handlers
      ctx.websocket.removeAllListeners('message');
      return next(ctx);

    } catch (err) {
      log.error({ err, connId: ctx.websocket['_id'] }, 'WebSocket auth failed');
      ctx.websocket.send(JSON.stringify({
        type: 'error',
        message: 'Authentication failed',
      }));
      ctx.websocket.close();
    }
  });
}

Step 3: Create WebSocket Route

Create apps/backend/src/routes/websocket/chat.ts:

import Router from '@koa/router';
import { createLogger } from '../../lib/logger';

const log = createLogger('ws-chat');
const router = new Router();

// Message type definitions
type IncomingMessage =
  | { type: 'chat'; message: string }
  | { type: 'typing'; isTyping: boolean }
  | { type: 'ping' };

type OutgoingMessage =
  | { type: 'chat'; message: string; from: string; timestamp: number }
  | { type: 'typing'; userId: string; isTyping: boolean }
  | { type: 'pong' }
  | { type: 'error'; message: string };

router.all('/chat', async (ctx) => {
  const user = ctx.state.user;
  const connId = ctx.websocket['_id'];

  log.info({ connId, uid: user.uid }, 'Chat WebSocket connected');

  // Handle incoming messages
  ctx.websocket.on('message', async (rawMessage) => {
    try {
      const message: IncomingMessage = JSON.parse(rawMessage.toString());

      switch (message.type) {
        case 'chat':
          // Process chat message
          const response: OutgoingMessage = {
            type: 'chat',
            message: `Echo: ${message.message}`,
            from: 'server',
            timestamp: Date.now(),
          };
          ctx.websocket.send(JSON.stringify(response));
          break;

        case 'typing':
          // Handle typing indicator
          log.debug({ connId, isTyping: message.isTyping }, 'Typing status');
          break;

        case 'ping':
          ctx.websocket.send(JSON.stringify({ type: 'pong' }));
          break;

        default:
          ctx.websocket.send(JSON.stringify({
            type: 'error',
            message: 'Unknown message type',
          }));
      }
    } catch (err) {
      log.error({ err, connId }, 'Error processing message');
      ctx.websocket.send(JSON.stringify({
        type: 'error',
        message: 'Invalid message format',
      }));
    }
  });

  // Handle disconnect
  ctx.websocket.on('close', () => {
    log.info({ connId, uid: user.uid }, 'Chat WebSocket disconnected');
    // Clean up any resources (e.g., remove from active users)
  });

  // Handle errors
  ctx.websocket.on('error', (err) => {
    log.error({ err, connId }, 'WebSocket error');
  });
});

export default router;

Step 4: Mount WebSocket Routes

Update apps/backend/src/main.ts:

import { wsAuthMiddleware } from './middleware/wsAuth';
import chatWsRoutes from './routes/websocket/chat';
import mount from 'koa-mount';

// WebSocket middleware (authentication)
app.ws.use(wsAuthMiddleware);

// Mount WebSocket routes
app.ws.use(mount('/ws', chatWsRoutes.middleware()));

Client-Side Usage

Connection Flow

class WebSocketClient {
  private ws: WebSocket | null = null;
  private authenticated = false;

  connect(url: string, token: string): Promise<void> {
    return new Promise((resolve, reject) => {
      this.ws = new WebSocket(url);

      this.ws.onopen = () => {
        // Send authentication message
        this.ws!.send(JSON.stringify({
          type: 'login',
          token: token,
        }));
      };

      this.ws.onmessage = (event) => {
        const message = JSON.parse(event.data);

        if (!this.authenticated) {
          if (message.type === 'auth') {
            this.authenticated = true;
            resolve();
          } else if (message.type === 'error') {
            reject(new Error(message.message));
          }
          return;
        }

        // Handle other messages
        this.handleMessage(message);
      };

      this.ws.onerror = (error) => {
        reject(error);
      };
    });
  }

  send(message: object): void {
    if (!this.authenticated || !this.ws) {
      throw new Error('Not connected');
    }
    this.ws.send(JSON.stringify(message));
  }

  private handleMessage(message: any): void {
    // Handle incoming messages
    console.log('Received:', message);
  }
}

// Usage
const client = new WebSocketClient();
await client.connect('wss://api.example.com/ws/chat', jwtToken);
client.send({ type: 'chat', message: 'Hello!' });

Message Format Convention

Always use structured messages:

// Incoming (client -> server)
{
  type: 'message_type',
  // ... payload fields
}

// Outgoing (server -> client)
{
  type: 'message_type',
  // ... payload fields
  timestamp?: number  // optional, for ordering
}

// Error responses
{
  type: 'error',
  message: 'Human readable error message'
}

Best Practices

1. Always Authenticate First

// Server: reject if first message isn't login
if (data.type !== 'login') {
  ctx.websocket.close();
  return;
}

2. Generate Connection IDs

ctx.websocket['_id'] = short.generate();
// Use in all logs for tracing

3. Type Your Messages

type IncomingMessage =
  | { type: 'chat'; message: string }
  | { type: 'ping' };

// Use discriminated unions for type safety

4. Handle Cleanup

ctx.websocket.on('close', () => {
  // Remove from active connections
  // Cancel any pending operations
  // Clean up subscriptions
});

5. Add Heartbeat/Ping

// Client sends ping periodically
setInterval(() => {
  ws.send(JSON.stringify({ type: 'ping' }));
}, 30000);

// Server responds with pong
case 'ping':
  ctx.websocket.send(JSON.stringify({ type: 'pong' }));
  break;

File Structure

apps/backend/src/
├── middleware/
│   └── wsAuth.ts           # WebSocket authentication
├── routes/
│   └── websocket/
│       ├── chat.ts         # Chat WebSocket routes
│       └── notifications.ts # Other WS routes
└── main.ts                 # Mount WS routes

Checklist

  1. Install dependencies: npm install koa-websocket short-uuid
  2. Wrap app with websockify() in main.ts
  3. Create middleware/wsAuth.ts for authentication
  4. Implement verifyToken() with your JWT logic
  5. Create WebSocket route files in routes/websocket/
  6. Mount routes with app.ws.use(mount(...))
  7. Test connection flow with client

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

27.09%
按下载量换算18

windsurf

22.25%
按下载量换算14

trae

19.8%
按下载量换算13

OpenCode

14.91%
按下载量换算10

Codex

7.91%
按下载量换算5

Antigravity

3.75%
按下载量换算2

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

可疑

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。来源安全扫描存在 warning/failed 结果,不能写成本站确认安全。

来源信息

继续浏览同类 Skills