mcpField
A
azure-web-pubsub-ts

azure-web-pubsub-ts

github.com/sickn33開発48.7k59 回インストール今日更新
リポジトリ

azure-web-pubsub-ts について

Azure Web PubSubのTypeScript SDKは、サーバー側の管理、クライアント側のリアルタイムメッセージング、Expressのイベント処理を提供します。WebSocket接続を使い、グループ単位の送信や接続管理を行えます。

主な機能

  1. 01クライアントアクセストークンの生成
  2. 02ブロードキャストと宛先指定送信
  3. 03グループと接続の管理
  4. 04クライアント接続イベントの処理
  5. 05Expressイベントハンドラーの追加

活用シーン

  1. 01リアルタイムチャットルームの構築
  2. 02ユーザーやグループへのメッセージ送信
  3. 03ExpressでのWeb PubSubイベント処理

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/sickn33/agentic-awesome-skills --skill azure-web-pubsub-ts

インストール後、Claude Code で/azure-web-pubsub-tsを入力して読み込まれたか確認します。

詳細

Azure Web PubSub SDKs for TypeScript

WebSocket 接続と pub/sub パターンによるリアルタイムメッセージングです。

インストール

# Server-side management
npm install @azure/web-pubsub @azure/identity

# Client-side real-time messaging
npm install @azure/web-pubsub-client

# Express middleware for event handlers
npm install @azure/web-pubsub-express

環境変数

WEBPUBSUB_CONNECTION_STRING=Endpoint=https://<resource>.webpubsub.azure.com;AccessKey=<key>;Version=1.0;
WEBPUBSUB_ENDPOINT=https://<resource>.webpubsub.azure.com

サーバー側:WebPubSubServiceClient

認証
import { WebPubSubServiceClient, AzureKeyCredential } from "@azure/web-pubsub";
import { DefaultAzureCredential } from "@azure/identity";

// Connection string
const client = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_CONNECTION_STRING!,
  "chat"  // hub name
);

// DefaultAzureCredential (recommended)
const client2 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  new DefaultAzureCredential(),
  "chat"
);

// AzureKeyCredential
const client3 = new WebPubSubServiceClient(
  process.env.WEBPUBSUB_ENDPOINT!,
  new AzureKeyCredential("<access-key>"),
  "chat"
);
クライアントアクセストークンの生成
// Basic token
const token = await client.getClientAccessToken();
// token.url contains a bearer credential: return only to the authorized client, never log it.

// Token with user ID
const userToken = await client.getClientAccessToken({
  userId: "user123",
});

// Token with permissions
const permToken = await client.getClientAccessToken({
  userId: "user123",
  roles: [
    "webpubsub.joinLeaveGroup.chat-room",
    "webpubsub.sendToGroup.chat-room",  // specific group
  ],
  groups: ["chat-room"],  // auto-join on connect
  expirationTimeInMinutes: 60,
});
メッセージの送信
// Broadcast to all connections in hub
await client.sendToAll({ message: "Hello everyone!" });
await client.sendToAll("Plain text", { contentType: "text/plain" });

// Send to specific user (all their connections)
await client.sendToUser("user123", { message: "Hello!" });

// Send to specific connection
await client.sendToConnection("connectionId", { data: "Direct message" });

// Send with filter (OData syntax)
await client.sendToAll({ message: "Filtered" }, {
  filter: "userId ne 'admin'",
});
グループ管理
const group = client.group("chat-room");

// Add user/connection to group
await group.addUser("user123");
await group.addConnection("connectionId");

// Remove from group
await group.removeUser("user123");

// Send to group
await group.sendToAll({ message: "Group message" });

// Close all connections in group
await group.closeAllConnections({ reason: "Maintenance" });
接続管理
// Check existence
const userExists = await client.userExists("user123");
const connExists = await client.connectionExists("connectionId");

// Close connections
await client.closeConnection("connectionId", { reason: "Kicked" });
await client.closeUserConnections("user123");
await client.closeAllConnections();

// Permissions
await client.grantPermission("connectionId", "sendToGroup", { targetName: "chat" });
await client.revokePermission("connectionId", "sendToGroup", { targetName: "chat" });

クライアント側:WebPubSubClient

接続
import { WebPubSubClient } from "@azure/web-pubsub-client";

// Direct URL
const client = new WebPubSubClient("<client-access-url>");

// Dynamic URL from negotiate endpoint
const client2 = new WebPubSubClient({
  getClientAccessUrl: async () => {
    const response = await fetch("/negotiate");
    const { url } = await response.json();
    return url;
  },
});

// Register handlers BEFORE starting
client.on("connected", (e) => {
  console.log(`Connected: ${e.connectionId}`);
});

client.on("group-message", (e) => {
  console.log(`${e.message.group}: ${e.message.data}`);
});

await client.start();
メッセージの送信
// Join group first
await client.joinGroup("chat-room");

// Send to group
await client.sendToGroup("chat-room", "Hello!", "text");
await client.sendToGroup("chat-room", { type: "message", content: "Hi" }, "json");

// Send options
await client.sendToGroup("chat-room", "Hello", "text", {
  noEcho: true,        // Don't echo back to sender
  fireAndForget: true, // Don't wait for ack
});

// Send event to server
await client.sendEvent("userAction", { action: "typing" }, "json");
イベントハンドラー
// Connection lifecycle
client.on("connected", (e) => {
  console.log(`Connected: ${e.connectionId}, User: ${e.userId}`);
});

client.on("disconnected", (e) => {
  console.log(`Disconnected: ${e.message}`);
});

client.on("stopped", () => {
  console.log("Client stopped");
});

// Messages
client.on("group-message", (e) => {
  console.log(`[${e.message.group}] ${e.message.fromUserId}: ${e.message.data}`);
});

client.on("server-message", (e) => {
  console.log(`Server: ${e.message.data}`);
});

// Rejoin failure
client.on("rejoin-group-failed", (e) => {
  console.log(`Failed to rejoin ${e.group}: ${e.error}`);
});

Express イベントハンドラー

import express from "express";
import { WebPubSubEventHandler } from "@azure/web-pubsub-express";

const app = express();

const handler = new WebPubSubEventHandler("chat", {
  path: "/api/webpubsub/hubs/chat/",
  
  // Blocking: approve/reject connection
  handleConnect: (req, res) => {
    if (!req.claims?.sub) {
      res.fail(401, "Authentication required");
      return;
    }
    res.success({
      userId: req.claims.sub[0],
      groups: ["general"],
      roles: ["webpubsub.sendToGroup.general"],
    });
  },
  
  // Blocking: handle custom events
  handleUserEvent: (req, res) => {
    console.log(`Event from ${req.context.userId}:`, req.data);
    res.success(`Received: ${req.data}`, "text");
  },
  
  // Non-blocking
  onConnected: (req) => {
    console.log(`Client connected: ${req.context.connectionId}`);
  },
  
  onDisconnected: (req) => {
    console.log(`Client disconnected: ${req.context.connectionId}`);
  },
});

app.use(handler.getMiddleware());

// Negotiate endpoint
app.get("/negotiate", async (req, res) => {
  if (!req.user?.id) return res.status(401).end();
  const token = await serviceClient.getClientAccessToken({
    userId: req.user.id, // prerequisite: verified authenticated application session
  });
  res.json({ url: token.url });
});

app.listen(8080);

主な型

// Server
import {
  WebPubSubServiceClient,
  WebPubSubGroup,
  GenerateClientTokenOptions,
  HubSendToAllOptions,
} from "@azure/web-pubsub";

// Client
import {
  WebPubSubClient,
  WebPubSubClientOptions,
  OnConnectedArgs,
  OnGroupDataMessageArgs,
} from "@azure/web-pubsub-client";

// Express
import {
  WebPubSubEventHandler,
  ConnectRequest,
  UserEventRequest,
  ConnectResponseHandler,
} from "@azure/web-pubsub-express";

ベストプラクティス

  1. Entra ID 認証を使用する - 本番環境では DefaultAzureCredential を使用します
  2. 開始前にハンドラーを登録する - 初期イベントを取りこぼさないようにします
  3. チャネルにはグループを使用する - トピックやルームごとにメッセージを整理します
  4. 再接続を処理する - クライアントはデフォルトで自動再接続します
  5. handleConnect で検証する - 認証されていない接続は早い段階で拒否します
  6. noEcho を使用する - 必要に応じて、送信者へのメッセージのエコーバックを防ぎます

使用するタイミング

このスキルは、概要で説明されているワークフローまたはアクションを実行する場合に適用できます。

制限事項

  • このスキルは、タスクが上記の説明の範囲に明確に該当する場合にのみ使用してください。
  • 出力を、環境固有の検証、テスト、または専門家によるレビューの代わりとして扱わないでください。
  • 必要な入力、権限、安全上の境界、または成功基準が不足している場合は、停止して確認を求めてください。

negotiate の例には、実際のアプリケーション認証ミドルウェアが必要です。ID が存在しない場合は、フェイルクローズにしてください。信頼できるサーバーセッションからユーザーとグループの所属情報を解決し、要求されたすべてのグループを認可したうえで、有効期限の短いグループ固有のロールのみを発行してください。グループ単位の権限を主張しながら、ワイルドカードロールを付与してはいけません。トークンや接続 URL はベアラーシークレットです。レスポンスやログで保護し、ソケットへの接続をすべてのグループに対する認可として扱わないでください。ブロードキャストやグループ変更は、ユーザーに許可された対象とコンテンツの範囲に限定してください。

コメント