@kodelyth/synology-chat 2026.5.39 → 2026.5.42
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/api.ts +3 -0
- package/channel-plugin-api.ts +1 -0
- package/contract-api.ts +1 -0
- package/dist/api.js +3 -0
- package/dist/channel-DL2_2tLQ.js +1233 -0
- package/dist/channel-plugin-api.js +2 -0
- package/dist/contract-api.js +2 -0
- package/dist/index.js +18 -0
- package/dist/security-audit-Zu_nkF2x.js +14 -0
- package/dist/setup-api.js +2 -0
- package/dist/setup-entry.js +11 -0
- package/dist/setup-surface-BHDzBWdx.js +334 -0
- package/index.ts +16 -0
- package/klaw.plugin.json +1 -22
- package/package.json +3 -3
- package/setup-api.ts +1 -0
- package/setup-entry.ts +9 -0
- package/src/accounts.ts +151 -0
- package/src/approval-auth.test.ts +17 -0
- package/src/approval-auth.ts +22 -0
- package/src/channel.integration.test.ts +204 -0
- package/src/channel.test-mocks.ts +176 -0
- package/src/channel.test.ts +693 -0
- package/src/channel.ts +435 -0
- package/src/client.test.ts +399 -0
- package/src/client.ts +326 -0
- package/src/config-schema.ts +11 -0
- package/src/core.test.ts +427 -0
- package/src/gateway-runtime.ts +212 -0
- package/src/inbound-context.ts +10 -0
- package/src/inbound-event.ts +175 -0
- package/src/runtime.ts +8 -0
- package/src/security-audit.test.ts +72 -0
- package/src/security-audit.ts +28 -0
- package/src/security.ts +107 -0
- package/src/session-key.ts +21 -0
- package/src/setup-surface.ts +334 -0
- package/src/test-http-utils.ts +75 -0
- package/src/types.ts +59 -0
- package/src/webhook-handler.test.ts +644 -0
- package/src/webhook-handler.ts +652 -0
- package/tsconfig.json +16 -0
- package/api.js +0 -7
- package/channel-plugin-api.js +0 -7
- package/contract-api.js +0 -7
- package/index.js +0 -7
- package/setup-api.js +0 -7
- package/setup-entry.js +0 -7
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
3
|
+
import {
|
|
4
|
+
buildChannelInboundEventContextMock,
|
|
5
|
+
dispatchReplyWithBufferedBlockDispatcher,
|
|
6
|
+
finalizeInboundContextMock,
|
|
7
|
+
registerPluginHttpRouteMock,
|
|
8
|
+
resolveAgentRouteMock,
|
|
9
|
+
setSynologyRuntimeConfigForTest,
|
|
10
|
+
} from "./channel.test-mocks.js";
|
|
11
|
+
import { makeFormBody, makeReq, makeRes } from "./test-http-utils.js";
|
|
12
|
+
|
|
13
|
+
type _RegisteredRoute = {
|
|
14
|
+
path: string;
|
|
15
|
+
accountId: string;
|
|
16
|
+
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
let createSynologyChatPlugin: typeof import("./channel.js").createSynologyChatPlugin;
|
|
20
|
+
|
|
21
|
+
function makeStartContext<T>(cfg: T, accountId: string, abortSignal: AbortSignal) {
|
|
22
|
+
setSynologyRuntimeConfigForTest(cfg);
|
|
23
|
+
return {
|
|
24
|
+
cfg,
|
|
25
|
+
accountId,
|
|
26
|
+
log: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
|
|
27
|
+
abortSignal,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function requireRecord(value: unknown, label: string): Record<string, unknown> {
|
|
32
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
33
|
+
throw new Error(`expected ${label} to be a record`);
|
|
34
|
+
}
|
|
35
|
+
return value as Record<string, unknown>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function requireMockCall<TArgs extends unknown[]>(
|
|
39
|
+
mock: { mock: { calls: TArgs[] } },
|
|
40
|
+
index: number,
|
|
41
|
+
label: string,
|
|
42
|
+
): TArgs {
|
|
43
|
+
const call = mock.mock.calls[index];
|
|
44
|
+
if (!call) {
|
|
45
|
+
throw new Error(`expected ${label}`);
|
|
46
|
+
}
|
|
47
|
+
return call;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
describe("Synology channel wiring integration", () => {
|
|
51
|
+
beforeAll(async () => {
|
|
52
|
+
({ createSynologyChatPlugin } = await import("./channel.js"));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
beforeEach(() => {
|
|
56
|
+
registerPluginHttpRouteMock.mockClear();
|
|
57
|
+
dispatchReplyWithBufferedBlockDispatcher.mockClear();
|
|
58
|
+
buildChannelInboundEventContextMock.mockClear();
|
|
59
|
+
finalizeInboundContextMock.mockClear();
|
|
60
|
+
resolveAgentRouteMock.mockClear();
|
|
61
|
+
setSynologyRuntimeConfigForTest({});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it("registers real webhook handler with resolved account config and enforces allowlist", async () => {
|
|
65
|
+
const plugin = createSynologyChatPlugin();
|
|
66
|
+
const abortController = new AbortController();
|
|
67
|
+
const cfg = {
|
|
68
|
+
channels: {
|
|
69
|
+
"synology-chat": {
|
|
70
|
+
enabled: true,
|
|
71
|
+
accounts: {
|
|
72
|
+
alerts: {
|
|
73
|
+
enabled: true,
|
|
74
|
+
token: "valid-token",
|
|
75
|
+
incomingUrl: "https://nas.example.com/incoming",
|
|
76
|
+
webhookPath: "/webhook/synology-alerts",
|
|
77
|
+
dmPolicy: "allowlist",
|
|
78
|
+
allowedUserIds: ["456"],
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
},
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const started = plugin.gateway.startAccount(
|
|
86
|
+
makeStartContext(cfg, "alerts", abortController.signal),
|
|
87
|
+
);
|
|
88
|
+
expect(registerPluginHttpRouteMock).toHaveBeenCalledTimes(1);
|
|
89
|
+
|
|
90
|
+
const firstCall = registerPluginHttpRouteMock.mock.calls[0];
|
|
91
|
+
if (!firstCall) {
|
|
92
|
+
throw new Error("Expected registerPluginHttpRoute to be called");
|
|
93
|
+
}
|
|
94
|
+
const registered = firstCall[0];
|
|
95
|
+
expect(registered.path).toBe("/webhook/synology-alerts");
|
|
96
|
+
expect(registered.accountId).toBe("alerts");
|
|
97
|
+
|
|
98
|
+
const req = makeReq(
|
|
99
|
+
"POST",
|
|
100
|
+
makeFormBody({
|
|
101
|
+
token: "valid-token",
|
|
102
|
+
user_id: "123",
|
|
103
|
+
username: "unauthorized-user",
|
|
104
|
+
text: "Hello",
|
|
105
|
+
}),
|
|
106
|
+
);
|
|
107
|
+
const res = makeRes();
|
|
108
|
+
await registered.handler(req, res);
|
|
109
|
+
|
|
110
|
+
expect(res.status).toBe(403);
|
|
111
|
+
expect(res.body).toContain("not authorized");
|
|
112
|
+
expect(dispatchReplyWithBufferedBlockDispatcher).not.toHaveBeenCalled();
|
|
113
|
+
abortController.abort();
|
|
114
|
+
await started;
|
|
115
|
+
});
|
|
116
|
+
|
|
117
|
+
it("isolates same user_id across different accounts", async () => {
|
|
118
|
+
const plugin = createSynologyChatPlugin();
|
|
119
|
+
const alphaAbortController = new AbortController();
|
|
120
|
+
const betaAbortController = new AbortController();
|
|
121
|
+
const cfg = {
|
|
122
|
+
channels: {
|
|
123
|
+
"synology-chat": {
|
|
124
|
+
enabled: true,
|
|
125
|
+
accounts: {
|
|
126
|
+
alpha: {
|
|
127
|
+
enabled: true,
|
|
128
|
+
token: "token-alpha",
|
|
129
|
+
incomingUrl: "https://nas.example.com/incoming-alpha",
|
|
130
|
+
webhookPath: "/webhook/synology-alpha",
|
|
131
|
+
dmPolicy: "open",
|
|
132
|
+
allowedUserIds: ["*"],
|
|
133
|
+
},
|
|
134
|
+
beta: {
|
|
135
|
+
enabled: true,
|
|
136
|
+
token: "token-beta",
|
|
137
|
+
incomingUrl: "https://nas.example.com/incoming-beta",
|
|
138
|
+
webhookPath: "/webhook/synology-beta",
|
|
139
|
+
dmPolicy: "open",
|
|
140
|
+
allowedUserIds: ["*"],
|
|
141
|
+
},
|
|
142
|
+
},
|
|
143
|
+
},
|
|
144
|
+
},
|
|
145
|
+
session: {
|
|
146
|
+
dmScope: "main" as const,
|
|
147
|
+
},
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
const alphaStarted = plugin.gateway.startAccount(
|
|
151
|
+
makeStartContext(cfg, "alpha", alphaAbortController.signal),
|
|
152
|
+
);
|
|
153
|
+
const betaStarted = plugin.gateway.startAccount(
|
|
154
|
+
makeStartContext(cfg, "beta", betaAbortController.signal),
|
|
155
|
+
);
|
|
156
|
+
|
|
157
|
+
expect(registerPluginHttpRouteMock).toHaveBeenCalledTimes(2);
|
|
158
|
+
const [alphaRoute] = requireMockCall(registerPluginHttpRouteMock, 0, "alpha Synology route");
|
|
159
|
+
const [betaRoute] = requireMockCall(registerPluginHttpRouteMock, 1, "beta Synology route");
|
|
160
|
+
|
|
161
|
+
const alphaReq = makeReq(
|
|
162
|
+
"POST",
|
|
163
|
+
makeFormBody({
|
|
164
|
+
token: "token-alpha",
|
|
165
|
+
user_id: "123",
|
|
166
|
+
username: "alice",
|
|
167
|
+
text: "alpha secret",
|
|
168
|
+
}),
|
|
169
|
+
);
|
|
170
|
+
const alphaRes = makeRes();
|
|
171
|
+
await alphaRoute.handler(alphaReq, alphaRes);
|
|
172
|
+
|
|
173
|
+
const betaReq = makeReq(
|
|
174
|
+
"POST",
|
|
175
|
+
makeFormBody({
|
|
176
|
+
token: "token-beta",
|
|
177
|
+
user_id: "123",
|
|
178
|
+
username: "bob",
|
|
179
|
+
text: "beta secret",
|
|
180
|
+
}),
|
|
181
|
+
);
|
|
182
|
+
const betaRes = makeRes();
|
|
183
|
+
await betaRoute.handler(betaReq, betaRes);
|
|
184
|
+
|
|
185
|
+
expect(alphaRes.status).toBe(204);
|
|
186
|
+
expect(betaRes.status).toBe(204);
|
|
187
|
+
expect(dispatchReplyWithBufferedBlockDispatcher).toHaveBeenCalledTimes(2);
|
|
188
|
+
expect(finalizeInboundContextMock).toHaveBeenCalledTimes(2);
|
|
189
|
+
|
|
190
|
+
const [alphaCtx] = requireMockCall(finalizeInboundContextMock, 0, "alpha inbound context");
|
|
191
|
+
const [betaCtx] = requireMockCall(finalizeInboundContextMock, 1, "beta inbound context");
|
|
192
|
+
const alphaContext = requireRecord(alphaCtx, "alpha inbound context");
|
|
193
|
+
expect(alphaContext.AccountId).toBe("alpha");
|
|
194
|
+
expect(alphaContext.SessionKey).toBe("agent:agent-alpha:synology-chat:alpha:direct:123");
|
|
195
|
+
const betaContext = requireRecord(betaCtx, "beta inbound context");
|
|
196
|
+
expect(betaContext.AccountId).toBe("beta");
|
|
197
|
+
expect(betaContext.SessionKey).toBe("agent:agent-beta:synology-chat:beta:direct:123");
|
|
198
|
+
|
|
199
|
+
alphaAbortController.abort();
|
|
200
|
+
betaAbortController.abort();
|
|
201
|
+
await alphaStarted;
|
|
202
|
+
await betaStarted;
|
|
203
|
+
});
|
|
204
|
+
});
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import type { Mock } from "vitest";
|
|
3
|
+
import { vi } from "vitest";
|
|
4
|
+
|
|
5
|
+
type RegisteredRoute = {
|
|
6
|
+
path: string;
|
|
7
|
+
accountId: string;
|
|
8
|
+
handler: (req: IncomingMessage, res: ServerResponse) => Promise<void>;
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
export const registerPluginHttpRouteMock: Mock<(params: RegisteredRoute) => () => void> = vi.fn(
|
|
12
|
+
() => vi.fn(),
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
export const dispatchReplyWithBufferedBlockDispatcher: Mock<
|
|
16
|
+
() => Promise<{ counts: Record<string, number> }>
|
|
17
|
+
> = vi.fn().mockResolvedValue({ counts: {} });
|
|
18
|
+
export const finalizeInboundContextMock: Mock<
|
|
19
|
+
(ctx: Record<string, unknown>) => Record<string, unknown>
|
|
20
|
+
> = vi.fn((ctx) => ctx);
|
|
21
|
+
export const buildChannelInboundEventContextMock: Mock<
|
|
22
|
+
(params: {
|
|
23
|
+
channel: string;
|
|
24
|
+
accountId?: string;
|
|
25
|
+
timestamp?: number;
|
|
26
|
+
from: string;
|
|
27
|
+
sender: { id: string; name?: string };
|
|
28
|
+
conversation: { kind: string; label?: string };
|
|
29
|
+
route: {
|
|
30
|
+
accountId?: string;
|
|
31
|
+
routeSessionKey: string;
|
|
32
|
+
dispatchSessionKey?: string;
|
|
33
|
+
};
|
|
34
|
+
reply: { to: string; originatingTo: string };
|
|
35
|
+
message: {
|
|
36
|
+
rawBody: string;
|
|
37
|
+
bodyForAgent?: string;
|
|
38
|
+
commandBody?: string;
|
|
39
|
+
};
|
|
40
|
+
extra?: Record<string, unknown>;
|
|
41
|
+
}) => Record<string, unknown>
|
|
42
|
+
> = vi.fn((params) =>
|
|
43
|
+
finalizeInboundContextMock({
|
|
44
|
+
Body: params.message.rawBody,
|
|
45
|
+
BodyForAgent: params.message.bodyForAgent ?? params.message.rawBody,
|
|
46
|
+
RawBody: params.message.rawBody,
|
|
47
|
+
CommandBody: params.message.commandBody ?? params.message.rawBody,
|
|
48
|
+
From: params.from,
|
|
49
|
+
To: params.reply.to,
|
|
50
|
+
SessionKey: params.route.dispatchSessionKey ?? params.route.routeSessionKey,
|
|
51
|
+
AccountId: params.route.accountId ?? params.accountId,
|
|
52
|
+
OriginatingChannel: params.channel,
|
|
53
|
+
OriginatingTo: params.reply.originatingTo,
|
|
54
|
+
ChatType: params.conversation.kind,
|
|
55
|
+
SenderName: params.sender.name,
|
|
56
|
+
SenderId: params.sender.id,
|
|
57
|
+
Provider: params.channel,
|
|
58
|
+
Surface: params.channel,
|
|
59
|
+
ConversationLabel: params.conversation.label,
|
|
60
|
+
Timestamp: params.timestamp,
|
|
61
|
+
...params.extra,
|
|
62
|
+
}),
|
|
63
|
+
);
|
|
64
|
+
export const resolveAgentRouteMock: Mock<
|
|
65
|
+
(params: { accountId?: string }) => { agentId: string; sessionKey: string; accountId: string }
|
|
66
|
+
> = vi.fn((params) => {
|
|
67
|
+
const accountId = params.accountId?.trim() || "default";
|
|
68
|
+
return {
|
|
69
|
+
agentId: `agent-${accountId}`,
|
|
70
|
+
sessionKey: `agent:agent-${accountId}:main`,
|
|
71
|
+
accountId,
|
|
72
|
+
};
|
|
73
|
+
});
|
|
74
|
+
let mockRuntimeConfig: unknown = {};
|
|
75
|
+
|
|
76
|
+
export function setSynologyRuntimeConfigForTest(cfg: unknown): void {
|
|
77
|
+
mockRuntimeConfig = cfg;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async function readRequestBodyWithLimitForTest(req: IncomingMessage): Promise<string> {
|
|
81
|
+
return await new Promise<string>((resolve, reject) => {
|
|
82
|
+
const chunks: Buffer[] = [];
|
|
83
|
+
req.on("data", (chunk) => {
|
|
84
|
+
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
|
85
|
+
});
|
|
86
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
87
|
+
req.on("error", reject);
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
vi.mock("klaw/plugin-sdk/setup", async () => {
|
|
92
|
+
const actual = await vi.importActual<object>("klaw/plugin-sdk/setup");
|
|
93
|
+
return {
|
|
94
|
+
...actual,
|
|
95
|
+
DEFAULT_ACCOUNT_ID: "default",
|
|
96
|
+
};
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
vi.mock("klaw/plugin-sdk/channel-config-schema", async () => {
|
|
100
|
+
const actual = await vi.importActual<object>("klaw/plugin-sdk/channel-config-schema");
|
|
101
|
+
return {
|
|
102
|
+
...actual,
|
|
103
|
+
buildChannelConfigSchema: vi.fn((schema: unknown) => ({ schema })),
|
|
104
|
+
};
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
vi.mock("klaw/plugin-sdk/webhook-ingress", async () => {
|
|
108
|
+
const actual = await vi.importActual<object>("klaw/plugin-sdk/webhook-ingress");
|
|
109
|
+
return {
|
|
110
|
+
...actual,
|
|
111
|
+
registerPluginHttpRoute: registerPluginHttpRouteMock,
|
|
112
|
+
readRequestBodyWithLimit: vi.fn(readRequestBodyWithLimitForTest),
|
|
113
|
+
isRequestBodyLimitError: vi.fn(() => false),
|
|
114
|
+
requestBodyErrorToText: vi.fn(() => "Request body too large"),
|
|
115
|
+
createFixedWindowRateLimiter: vi.fn(() => ({
|
|
116
|
+
isRateLimited: vi.fn(() => false),
|
|
117
|
+
size: vi.fn(() => 0),
|
|
118
|
+
clear: vi.fn(),
|
|
119
|
+
})),
|
|
120
|
+
};
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
vi.mock("./client.js", () => ({
|
|
124
|
+
sendMessage: vi.fn().mockResolvedValue(true),
|
|
125
|
+
sendFileUrl: vi.fn().mockResolvedValue(true),
|
|
126
|
+
resolveLegacyWebhookNameToChatUserId: vi.fn().mockResolvedValue(undefined),
|
|
127
|
+
}));
|
|
128
|
+
|
|
129
|
+
vi.mock("./runtime.js", () => ({
|
|
130
|
+
getSynologyRuntime: vi.fn(() => ({
|
|
131
|
+
config: { current: vi.fn(() => mockRuntimeConfig) },
|
|
132
|
+
channel: {
|
|
133
|
+
routing: {
|
|
134
|
+
resolveAgentRoute: resolveAgentRouteMock,
|
|
135
|
+
},
|
|
136
|
+
reply: {
|
|
137
|
+
finalizeInboundContext: finalizeInboundContextMock,
|
|
138
|
+
dispatchReplyWithBufferedBlockDispatcher,
|
|
139
|
+
},
|
|
140
|
+
session: {
|
|
141
|
+
resolveStorePath: vi.fn(() => "/tmp/klaw/synology-chat-sessions.json"),
|
|
142
|
+
recordInboundSession: vi.fn(async () => undefined),
|
|
143
|
+
},
|
|
144
|
+
turn: {
|
|
145
|
+
run: vi.fn(async (params) => {
|
|
146
|
+
const input = await params.adapter.ingest(params.raw);
|
|
147
|
+
if (!input) {
|
|
148
|
+
return { admission: { kind: "drop", reason: "ingest-null" }, dispatched: false };
|
|
149
|
+
}
|
|
150
|
+
const resolved = await params.adapter.resolveTurn(input, {
|
|
151
|
+
kind: "message",
|
|
152
|
+
canStartAgentTurn: true,
|
|
153
|
+
});
|
|
154
|
+
const dispatchResult = await resolved.dispatchReplyWithBufferedBlockDispatcher({
|
|
155
|
+
ctx: resolved.ctxPayload,
|
|
156
|
+
cfg: mockRuntimeConfig,
|
|
157
|
+
dispatcherOptions: {
|
|
158
|
+
...resolved.dispatcherOptions,
|
|
159
|
+
deliver: resolved.delivery.deliver,
|
|
160
|
+
onError: resolved.delivery.onError,
|
|
161
|
+
},
|
|
162
|
+
});
|
|
163
|
+
return {
|
|
164
|
+
admission: { kind: "dispatch" },
|
|
165
|
+
dispatched: true,
|
|
166
|
+
dispatchResult,
|
|
167
|
+
ctxPayload: resolved.ctxPayload,
|
|
168
|
+
routeSessionKey: resolved.routeSessionKey,
|
|
169
|
+
};
|
|
170
|
+
}),
|
|
171
|
+
buildContext: buildChannelInboundEventContextMock,
|
|
172
|
+
},
|
|
173
|
+
},
|
|
174
|
+
})),
|
|
175
|
+
setSynologyRuntime: vi.fn(),
|
|
176
|
+
}));
|