-
Notifications
You must be signed in to change notification settings - Fork 4.3k
feat(root): add @novu/chat-sdk-adapter Chat SDK platform adapter fixes NV-8063 #11593
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 1 commit
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
3fd05cd
feat(root): add @chat-adapter/novu Chat SDK platform adapter fixes NV…
scopsy a5bcaac
chore(root): rename package to @novu/chat-sdk-adapter fixes NV-8063
scopsy 934fd65
refactor(root): use official @chat-adapter/state-memory; fix adapter …
scopsy 4ead536
feat(chat-adapter): expose Novu subscriber via getNovuContext and get…
scopsy fbe1465
fix
scopsy 960a8fb
feat(chat-adapter): add card reply testing to playground fixes NV-8063
scopsy 16eda18
feat(chat-adapter): expand NovuContext and wire outbound files fixes …
scopsy f3b9514
Update agent.ts
scopsy b987ef7
fix(chat-adapter): optimistic snapshot patches and review fixes NV-8063
scopsy c530b5a
fix(chat-adapter): address PR review for dedupe, HMAC, and fetchMessa…
scopsy 20a7e51
style(chat-adapter): align quote style with monorepo biome config
scopsy 04d8843
Update settings.json
scopsy 5e7d1f5
Update package.json
scopsy 1b7c84a
Update package.json
scopsy dff2934
chore(chat-adapter): release v0.0.2
scopsy e6a3334
chore(chat-adapter): align package metadata with Chat SDK guidelines …
scopsy File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| tsconfig.tsbuildinfo |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| # @chat-adapter/novu | ||
|
|
||
| A [Chat SDK](https://www.npmjs.com/package/chat) platform adapter that exposes **all of Novu's | ||
| normalized chat channels — Slack, WhatsApp, Microsoft Teams, Telegram, and Email — as a single | ||
| platform**. Novu does the per-channel normalization (one `Conversation` + `Subscriber` + history) | ||
| and calls your bridge; your Chat SDK app is the brain. One handler set serves every channel with no | ||
| per-channel code. | ||
|
|
||
| ``` | ||
| End-user channels ──platform webhooks──▶ NOVU (normalize) ──POST AgentBridgeRequest (HMAC)──▶ | ||
| your Chat SDK app (@chat-adapter/novu) ──AgentReplyPayload → POST /v1/agents/:id/reply──▶ NOVU ──▶ channel | ||
| ``` | ||
|
|
||
| ## Install | ||
|
|
||
| ```bash | ||
| npm install @chat-adapter/novu chat | ||
| ``` | ||
|
|
||
| `chat` is a peer dependency. `react` is an optional peer (only needed for JSX cards). | ||
|
|
||
| ## Usage | ||
|
|
||
| ```ts | ||
| import { Chat } from 'chat'; | ||
| import { createNovuAdapter, createMemoryState, getNovuContext } from '@chat-adapter/novu'; | ||
|
|
||
| const novu = createNovuAdapter({ | ||
| apiKey: process.env.NOVU_SECRET_KEY!, // Authorization for reply POSTs | ||
| agentIdentifier: 'support-agent', | ||
| bridgeSecret: process.env.NOVU_SECRET_KEY!, // verifies inbound HMAC | ||
| // apiBaseUrl: 'https://eu.api.novu.co', // defaults to https://api.novu.co | ||
| // bridgeUrl: 'https://my-app.com/api/novu',// optional boot-time bridge registration | ||
| }); | ||
|
|
||
| const chat = new Chat({ | ||
| userName: 'support', | ||
| adapters: { novu }, | ||
| state: createMemoryState(), // zero-deps, single-instance; use a shared state adapter for multi-instance | ||
| }); | ||
|
|
||
| chat.onNewMention(async (thread, message) => { | ||
| await thread.post(`Hi! You said: ${message.text}`); | ||
| }); | ||
|
|
||
| chat.onSubscribedMessage(async (thread, message) => { | ||
| await thread.post(`echo: ${message.text}`); | ||
|
|
||
| // Opt-in, Novu-only capabilities: | ||
| const ctx = getNovuContext(thread); | ||
| if (ctx.platform === 'whatsapp') { | ||
| await ctx.trigger('escalation-email', { payload: { text: message.text } }); | ||
| } | ||
| }); | ||
|
|
||
| await chat.initialize(); | ||
| ``` | ||
|
|
||
| Wire the webhook route to `novu.handleWebhook(request)` (any Web `Request`/`Response` runtime — | ||
| Next.js route handlers, Hono, etc.). | ||
|
|
||
| ## Behavior & v1 scope | ||
|
|
||
| - **In:** messages, button actions, reactions, full Novu history, subscriber identity, platform | ||
| awareness, dedup (per `deliveryId`). | ||
| - **Out:** markdown, cards, edits (in-place), reaction adds, edit-based streaming (via the chat | ||
| package's built-in cadence), plus opt-in `getNovuContext().trigger / setMetadata / resolve`. | ||
| - **Routing:** an ongoing conversation (`messageCount > 1` or non-empty history) is pre-subscribed → | ||
| `onSubscribedMessage`; a brand-new conversation routes to `onNewMention` (channels) or | ||
| `onDirectMessage` (DMs, via `platformContext.isDM`). | ||
| - **Security:** the inbound HMAC (`novu-signature`) is verified over the raw body; the reply URL is | ||
| **derived from your config** and the request's `replyUrl` is ignored, so a forged request can never | ||
| exfiltrate your `apiKey`. | ||
| - **Not implemented in v1:** `deleteMessage`, modals, outbound-initiated DMs (`openDM`), code-driven | ||
| channel provisioning, Novu-side turn serialization. | ||
|
|
||
| ## State | ||
|
|
||
| `createMemoryState()` is in-process and safe for a single instance. For horizontally-scaled or | ||
| serverless bridges with more than one warm instance, pass a shared state adapter | ||
| (e.g. `@chat-adapter/state-ioredis`) to `new Chat({ state })` so locks and dedup are correct. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| { | ||
| "name": "@chat-adapter/novu", | ||
| "version": "0.0.1", | ||
| "private": true, | ||
| "type": "module", | ||
| "description": "Novu adapter for the Chat SDK — expose all of Novu's normalized chat channels (Slack, WhatsApp, Teams, Telegram, Email) as a single Chat SDK platform adapter", | ||
| "main": "dist/index.js", | ||
| "types": "dist/index.d.ts", | ||
| "files": [ | ||
| "dist/" | ||
| ], | ||
| "scripts": { | ||
| "afterinstall": "pnpm build", | ||
| "prebuild": "rimraf dist tsconfig.tsbuildinfo", | ||
| "build": "tsc -p tsconfig.json", | ||
| "watch:build": "tsc -p tsconfig.json -w", | ||
| "test": "vitest run", | ||
| "test:watch": "vitest", | ||
| "check": "biome check .", | ||
| "check:fix": "biome check --write ." | ||
| }, | ||
| "peerDependencies": { | ||
| "chat": ">=4.30.0", | ||
| "react": ">=18.0.0 || >=19.0.0" | ||
| }, | ||
| "peerDependenciesMeta": { | ||
| "react": { | ||
| "optional": true | ||
| } | ||
| }, | ||
| "devDependencies": { | ||
| "@types/react": "^19.0.0", | ||
| "chat": "4.30.0", | ||
| "rimraf": "~3.0.2", | ||
| "typescript": "5.6.2", | ||
| "vitest": "^1.2.1" | ||
| }, | ||
| "nx": { | ||
| "tags": [ | ||
| "type:package" | ||
| ] | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| { | ||
| "name": "@chat-adapter/novu", | ||
| "sourceRoot": "packages/chat-adapter/src", | ||
| "projectType": "library", | ||
| "targets": { | ||
| "build": { | ||
| "executor": "nx:run-commands", | ||
| "options": { | ||
| "command": "pnpm --filter @chat-adapter/novu run build", | ||
| "cwd": "{workspaceRoot}" | ||
| } | ||
| }, | ||
| "test": { | ||
| "executor": "nx:run-commands", | ||
| "options": { | ||
| "command": "pnpm --filter @chat-adapter/novu run test", | ||
| "cwd": "{workspaceRoot}" | ||
| } | ||
| }, | ||
| "lint": { | ||
| "executor": "nx:run-commands", | ||
| "options": { | ||
| "command": "npx biome lint packages/chat-adapter" | ||
| } | ||
| } | ||
| }, | ||
| "tags": ["type:package"] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| import { createHmac } from 'node:crypto'; | ||
| import { Chat } from 'chat'; | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
| import { createNovuAdapter } from './index.js'; | ||
| import { createMemoryState } from './state-memory.js'; | ||
| import type { AgentBridgeRequest } from './types.js'; | ||
|
|
||
| const BRIDGE_SECRET = 'bridge-secret'; | ||
| const API_KEY = 'api-key'; | ||
|
|
||
| function sign(body: string, secret = BRIDGE_SECRET): string { | ||
| const ts = Date.now(); | ||
| const hmac = createHmac('sha256', secret).update(`${ts}.${body}`).digest('hex'); | ||
|
|
||
| return `t=${ts},v1=${hmac}`; | ||
| } | ||
|
|
||
| function bridgeRequest(overrides: Partial<AgentBridgeRequest> = {}): AgentBridgeRequest { | ||
| return { | ||
| version: 1, | ||
| timestamp: new Date().toISOString(), | ||
| deliveryId: `d-${Math.random()}`, | ||
| event: 'onMessage', | ||
| agentId: 'support-agent', | ||
| replyUrl: 'https://attacker.example.com/steal', | ||
| conversationId: 'conv-1', | ||
| integrationIdentifier: 'slack-prod', | ||
| action: null, | ||
| message: { | ||
| text: 'hello', | ||
| platformMessageId: 'pm-1', | ||
| author: { userId: 'u1', userName: 'alice', fullName: 'Alice', isBot: false }, | ||
| timestamp: new Date().toISOString(), | ||
| }, | ||
| reaction: null, | ||
| conversation: { | ||
| identifier: 'conv-1', | ||
| status: 'open', | ||
| metadata: {}, | ||
| messageCount: 2, | ||
| createdAt: new Date().toISOString(), | ||
| lastActivityAt: new Date().toISOString(), | ||
| }, | ||
| subscriber: { subscriberId: 'sub-1', firstName: 'Alice' }, | ||
| history: [{ role: 'user', type: 'text', content: 'earlier', createdAt: new Date().toISOString() }], | ||
| platform: 'slack', | ||
| platformContext: { threadId: 'pm-1', channelId: 'C1', isDM: false }, | ||
| ...overrides, | ||
| }; | ||
| } | ||
|
|
||
| async function deliver(adapter: ReturnType<typeof createNovuAdapter>, req: AgentBridgeRequest): Promise<Response> { | ||
| const body = JSON.stringify(req); | ||
| const request = new Request('https://bridge.example.com/api/novu', { | ||
| method: 'POST', | ||
| headers: { 'content-type': 'application/json', 'novu-signature': sign(body) }, | ||
| body, | ||
| }); | ||
|
|
||
| return adapter.handleWebhook(request); | ||
| } | ||
|
|
||
| describe('Novu adapter end-to-end', () => { | ||
| let fetchMock: ReturnType<typeof vi.fn>; | ||
|
|
||
| beforeEach(() => { | ||
| fetchMock = vi.fn( | ||
| async () => new Response(JSON.stringify({ messageId: 'm-1', platformThreadId: 't-1' }), { status: 200 }) | ||
| ); | ||
| }); | ||
|
|
||
| function buildChat() { | ||
| const adapter = createNovuAdapter({ | ||
| apiKey: API_KEY, | ||
| agentIdentifier: 'support-agent', | ||
| bridgeSecret: BRIDGE_SECRET, | ||
| fetch: fetchMock as unknown as typeof fetch, | ||
| }); | ||
| const chat = new Chat({ userName: 'support', adapters: { novu: adapter }, state: createMemoryState() }); | ||
|
|
||
| return { adapter, chat }; | ||
| } | ||
|
|
||
| it('routes an ongoing conversation to onSubscribedMessage and replies via the derived URL', async () => { | ||
| const { adapter, chat } = buildChat(); | ||
| const seen: string[] = []; | ||
| chat.onSubscribedMessage(async (thread, message) => { | ||
| seen.push(message.text); | ||
| await thread.post(`echo: ${message.text}`); | ||
| }); | ||
| await chat.initialize(); | ||
|
|
||
| const res = await deliver(adapter, bridgeRequest()); | ||
| expect(res.status).toBe(200); | ||
| expect(seen).toEqual(['hello']); | ||
|
|
||
| expect(fetchMock).toHaveBeenCalledTimes(1); | ||
| const [url, init] = fetchMock.mock.calls[0]!; | ||
| // Reply went to the derived URL, NOT the attacker-controlled replyUrl in the request. | ||
| expect(url).toBe('https://api.novu.co/v1/agents/support-agent/reply'); | ||
| expect((init.headers as Record<string, string>).authorization).toBe(`ApiKey ${API_KEY}`); | ||
| expect(JSON.parse(init.body as string)).toMatchObject({ | ||
| conversationId: 'conv-1', | ||
| integrationIdentifier: 'slack-prod', | ||
| reply: { markdown: 'echo: hello' }, | ||
| }); | ||
| }); | ||
|
|
||
| it('routes a brand-new channel conversation to onNewMention', async () => { | ||
| const { adapter, chat } = buildChat(); | ||
| const mentions: string[] = []; | ||
| chat.onNewMention(async (_thread, message) => { | ||
| mentions.push(message.text); | ||
| }); | ||
| chat.onSubscribedMessage(async () => { | ||
| throw new Error('should not be subscribed on first message'); | ||
| }); | ||
| await chat.initialize(); | ||
|
|
||
| await deliver( | ||
| adapter, | ||
| bridgeRequest({ conversation: { ...bridgeRequest().conversation, messageCount: 1 }, history: [] }) | ||
| ); | ||
|
|
||
| expect(mentions).toEqual(['hello']); | ||
| }); | ||
|
|
||
| it('rejects an invalid signature with 401 and does not dispatch', async () => { | ||
| const { adapter, chat } = buildChat(); | ||
| const handler = vi.fn(); | ||
| chat.onSubscribedMessage(handler); | ||
| await chat.initialize(); | ||
|
|
||
| const body = JSON.stringify(bridgeRequest()); | ||
| const request = new Request('https://bridge.example.com/api/novu', { | ||
| method: 'POST', | ||
| headers: { 'content-type': 'application/json', 'novu-signature': sign(body, 'wrong-secret') }, | ||
| body, | ||
| }); | ||
| const res = await adapter.handleWebhook(request); | ||
|
|
||
| expect(res.status).toBe(401); | ||
| expect(handler).not.toHaveBeenCalled(); | ||
| expect(fetchMock).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('dedupes a replayed deliveryId (same delivery processed once)', async () => { | ||
| const { adapter, chat } = buildChat(); | ||
| const handler = vi.fn(); | ||
| chat.onSubscribedMessage(handler); | ||
| await chat.initialize(); | ||
|
|
||
| const req = bridgeRequest({ deliveryId: 'fixed-delivery' }); | ||
| await deliver(adapter, req); | ||
| await deliver(adapter, req); | ||
|
|
||
| expect(handler).toHaveBeenCalledTimes(1); | ||
| }); | ||
| }); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.