@kodelyth/synology-chat 2026.5.42 → 2026.6.2
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/klaw.plugin.json +22 -1
- package/package.json +19 -3
- package/api.ts +0 -3
- package/channel-plugin-api.ts +0 -1
- package/contract-api.ts +0 -1
- package/index.ts +0 -16
- package/setup-api.ts +0 -1
- package/setup-entry.ts +0 -9
- package/src/accounts.ts +0 -151
- package/src/approval-auth.test.ts +0 -17
- package/src/approval-auth.ts +0 -22
- package/src/channel.integration.test.ts +0 -204
- package/src/channel.test-mocks.ts +0 -176
- package/src/channel.test.ts +0 -693
- package/src/channel.ts +0 -435
- package/src/client.test.ts +0 -399
- package/src/client.ts +0 -326
- package/src/config-schema.ts +0 -11
- package/src/core.test.ts +0 -427
- package/src/gateway-runtime.ts +0 -212
- package/src/inbound-context.ts +0 -10
- package/src/inbound-event.ts +0 -175
- package/src/runtime.ts +0 -8
- package/src/security-audit.test.ts +0 -72
- package/src/security-audit.ts +0 -28
- package/src/security.ts +0 -107
- package/src/session-key.ts +0 -21
- package/src/setup-surface.ts +0 -334
- package/src/test-http-utils.ts +0 -75
- package/src/types.ts +0 -59
- package/src/webhook-handler.test.ts +0 -644
- package/src/webhook-handler.ts +0 -652
- package/tsconfig.json +0 -16
package/klaw.plugin.json
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
"activation": {
|
|
4
4
|
"onStartup": false
|
|
5
5
|
},
|
|
6
|
-
"channels": [
|
|
6
|
+
"channels": [
|
|
7
|
+
"synology-chat"
|
|
8
|
+
],
|
|
7
9
|
"channelEnvVars": {
|
|
8
10
|
"synology-chat": [
|
|
9
11
|
"SYNOLOGY_CHAT_TOKEN",
|
|
@@ -18,5 +20,24 @@
|
|
|
18
20
|
"type": "object",
|
|
19
21
|
"additionalProperties": false,
|
|
20
22
|
"properties": {}
|
|
23
|
+
},
|
|
24
|
+
"channelConfigs": {
|
|
25
|
+
"synology-chat": {
|
|
26
|
+
"schema": {
|
|
27
|
+
"$schema": "http://json-schema.org/draft-07/schema#",
|
|
28
|
+
"type": "object",
|
|
29
|
+
"properties": {
|
|
30
|
+
"dangerouslyAllowNameMatching": {
|
|
31
|
+
"type": "boolean"
|
|
32
|
+
},
|
|
33
|
+
"dangerouslyAllowInheritedWebhookPath": {
|
|
34
|
+
"type": "boolean"
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
"additionalProperties": {}
|
|
38
|
+
},
|
|
39
|
+
"label": "Synology Chat",
|
|
40
|
+
"description": "Connect your Synology NAS Chat to Klaw with full agent capabilities."
|
|
41
|
+
}
|
|
21
42
|
}
|
|
22
43
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kodelyth/synology-chat",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.6.2",
|
|
4
4
|
"description": "Synology Chat channel plugin for Klaw",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
},
|
|
9
9
|
"type": "module",
|
|
10
10
|
"devDependencies": {
|
|
11
|
-
"@kodelyth/plugin-sdk": "
|
|
11
|
+
"@kodelyth/plugin-sdk": "workspace:*"
|
|
12
12
|
},
|
|
13
13
|
"klaw": {
|
|
14
14
|
"extensions": [
|
|
@@ -38,9 +38,25 @@
|
|
|
38
38
|
"release": {
|
|
39
39
|
"publishToClawHub": true,
|
|
40
40
|
"publishToNpm": true
|
|
41
|
-
}
|
|
41
|
+
},
|
|
42
|
+
"runtimeExtensions": [
|
|
43
|
+
"./dist/index.js"
|
|
44
|
+
],
|
|
45
|
+
"runtimeSetupEntry": "./dist/setup-entry.js"
|
|
42
46
|
},
|
|
43
47
|
"dependencies": {
|
|
44
48
|
"zod": "4.4.3"
|
|
49
|
+
},
|
|
50
|
+
"files": [
|
|
51
|
+
"dist/**",
|
|
52
|
+
"klaw.plugin.json"
|
|
53
|
+
],
|
|
54
|
+
"peerDependencies": {
|
|
55
|
+
"klaw": ">=2026.5.39"
|
|
56
|
+
},
|
|
57
|
+
"peerDependenciesMeta": {
|
|
58
|
+
"klaw": {
|
|
59
|
+
"optional": true
|
|
60
|
+
}
|
|
45
61
|
}
|
|
46
62
|
}
|
package/api.ts
DELETED
package/channel-plugin-api.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { synologyChatPlugin } from "./src/channel.js";
|
package/contract-api.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { collectSynologyChatSecurityAuditFindings } from "./src/security-audit.js";
|
package/index.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { defineBundledChannelEntry } from "klaw/plugin-sdk/channel-entry-contract";
|
|
2
|
-
|
|
3
|
-
export default defineBundledChannelEntry({
|
|
4
|
-
id: "synology-chat",
|
|
5
|
-
name: "Synology Chat",
|
|
6
|
-
description: "Native Synology Chat channel plugin for Klaw",
|
|
7
|
-
importMetaUrl: import.meta.url,
|
|
8
|
-
plugin: {
|
|
9
|
-
specifier: "./channel-plugin-api.js",
|
|
10
|
-
exportName: "synologyChatPlugin",
|
|
11
|
-
},
|
|
12
|
-
runtime: {
|
|
13
|
-
specifier: "./api.js",
|
|
14
|
-
exportName: "setSynologyRuntime",
|
|
15
|
-
},
|
|
16
|
-
});
|
package/setup-api.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export { synologyChatSetupAdapter, synologyChatSetupWizard } from "./src/setup-surface.js";
|
package/setup-entry.ts
DELETED
package/src/accounts.ts
DELETED
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Account resolution: reads config from channels.synology-chat,
|
|
3
|
-
* merges per-account overrides, falls back to environment variables.
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import {
|
|
7
|
-
DEFAULT_ACCOUNT_ID,
|
|
8
|
-
listCombinedAccountIds,
|
|
9
|
-
resolveMergedAccountConfig,
|
|
10
|
-
type KlawConfig,
|
|
11
|
-
} from "klaw/plugin-sdk/account-resolution";
|
|
12
|
-
import { resolveDangerousNameMatchingEnabled } from "klaw/plugin-sdk/dangerous-name-runtime";
|
|
13
|
-
import type {
|
|
14
|
-
SynologyChatChannelConfig,
|
|
15
|
-
ResolvedSynologyChatAccount,
|
|
16
|
-
SynologyWebhookPathSource,
|
|
17
|
-
} from "./types.js";
|
|
18
|
-
|
|
19
|
-
/** Extract the channel config from the full Klaw config object. */
|
|
20
|
-
function getChannelConfig(cfg: KlawConfig): SynologyChatChannelConfig | undefined {
|
|
21
|
-
return cfg?.channels?.["synology-chat"] as SynologyChatChannelConfig | undefined;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function resolveImplicitAccountId(channelCfg: SynologyChatChannelConfig): string | undefined {
|
|
25
|
-
return channelCfg.token || process.env.SYNOLOGY_CHAT_TOKEN ? DEFAULT_ACCOUNT_ID : undefined;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
function getRawAccountConfig(
|
|
29
|
-
channelCfg: SynologyChatChannelConfig,
|
|
30
|
-
accountId: string,
|
|
31
|
-
): SynologyChatChannelConfig {
|
|
32
|
-
if (accountId === DEFAULT_ACCOUNT_ID) {
|
|
33
|
-
return channelCfg;
|
|
34
|
-
}
|
|
35
|
-
return channelCfg.accounts?.[accountId] ?? {};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
function hasExplicitWebhookPath(rawAccount: SynologyChatChannelConfig | undefined): boolean {
|
|
39
|
-
return typeof rawAccount?.webhookPath === "string" && rawAccount.webhookPath.trim().length > 0;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
function resolveWebhookPathSource(params: {
|
|
43
|
-
accountId: string;
|
|
44
|
-
channelCfg: SynologyChatChannelConfig;
|
|
45
|
-
rawAccount: SynologyChatChannelConfig;
|
|
46
|
-
}): SynologyWebhookPathSource {
|
|
47
|
-
if (hasExplicitWebhookPath(params.rawAccount)) {
|
|
48
|
-
return "explicit";
|
|
49
|
-
}
|
|
50
|
-
if (params.accountId !== DEFAULT_ACCOUNT_ID && hasExplicitWebhookPath(params.channelCfg)) {
|
|
51
|
-
return "inherited-base";
|
|
52
|
-
}
|
|
53
|
-
return "default";
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** Parse allowedUserIds from string or array to string[]. */
|
|
57
|
-
function parseAllowedUserIds(raw: string | string[] | undefined): string[] {
|
|
58
|
-
if (!raw) {
|
|
59
|
-
return [];
|
|
60
|
-
}
|
|
61
|
-
if (Array.isArray(raw)) {
|
|
62
|
-
return raw.filter(Boolean);
|
|
63
|
-
}
|
|
64
|
-
return raw
|
|
65
|
-
.split(",")
|
|
66
|
-
.map((s) => s.trim())
|
|
67
|
-
.filter(Boolean);
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
function parseRateLimitPerMinute(raw: string | undefined): number {
|
|
71
|
-
if (raw == null) {
|
|
72
|
-
return 30;
|
|
73
|
-
}
|
|
74
|
-
const trimmed = raw.trim();
|
|
75
|
-
if (!/^-?\d+$/.test(trimmed)) {
|
|
76
|
-
return 30;
|
|
77
|
-
}
|
|
78
|
-
return Number.parseInt(trimmed, 10);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* List all configured account IDs for this channel.
|
|
83
|
-
* Returns ["default"] if there's a base config, plus any named accounts.
|
|
84
|
-
*/
|
|
85
|
-
export function listAccountIds(cfg: KlawConfig): string[] {
|
|
86
|
-
const channelCfg = getChannelConfig(cfg);
|
|
87
|
-
if (!channelCfg) {
|
|
88
|
-
return [];
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
return listCombinedAccountIds({
|
|
92
|
-
configuredAccountIds: Object.keys(channelCfg.accounts ?? {}),
|
|
93
|
-
implicitAccountId: resolveImplicitAccountId(channelCfg),
|
|
94
|
-
});
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Resolve a specific account by ID with full defaults applied.
|
|
99
|
-
* Falls back to env vars for the "default" account.
|
|
100
|
-
*/
|
|
101
|
-
export function resolveAccount(
|
|
102
|
-
cfg: KlawConfig,
|
|
103
|
-
accountId?: string | null,
|
|
104
|
-
): ResolvedSynologyChatAccount {
|
|
105
|
-
const channelCfg = getChannelConfig(cfg) ?? {};
|
|
106
|
-
const id = accountId || DEFAULT_ACCOUNT_ID;
|
|
107
|
-
const accountOverrides =
|
|
108
|
-
id === DEFAULT_ACCOUNT_ID ? undefined : (channelCfg.accounts?.[id] ?? undefined);
|
|
109
|
-
const rawAccount = getRawAccountConfig(channelCfg, id);
|
|
110
|
-
const merged = resolveMergedAccountConfig<Record<string, unknown> & SynologyChatChannelConfig>({
|
|
111
|
-
channelConfig: channelCfg as Record<string, unknown> & SynologyChatChannelConfig,
|
|
112
|
-
accounts: channelCfg.accounts as
|
|
113
|
-
| Record<string, Partial<Record<string, unknown> & SynologyChatChannelConfig>>
|
|
114
|
-
| undefined,
|
|
115
|
-
accountId: id,
|
|
116
|
-
});
|
|
117
|
-
|
|
118
|
-
// Env var fallbacks (primarily for the "default" account)
|
|
119
|
-
const envToken = process.env.SYNOLOGY_CHAT_TOKEN ?? "";
|
|
120
|
-
const envIncomingUrl = process.env.SYNOLOGY_CHAT_INCOMING_URL ?? "";
|
|
121
|
-
const envNasHost = process.env.SYNOLOGY_NAS_HOST ?? "localhost";
|
|
122
|
-
const envAllowedUserIds = process.env.SYNOLOGY_ALLOWED_USER_IDS ?? "";
|
|
123
|
-
const envRateLimitValue = parseRateLimitPerMinute(process.env.SYNOLOGY_RATE_LIMIT);
|
|
124
|
-
const envBotName = process.env.KLAW_BOT_NAME ?? "Klaw";
|
|
125
|
-
const webhookPathSource = resolveWebhookPathSource({ accountId: id, channelCfg, rawAccount });
|
|
126
|
-
const dangerouslyAllowInheritedWebhookPath =
|
|
127
|
-
rawAccount.dangerouslyAllowInheritedWebhookPath ??
|
|
128
|
-
channelCfg.dangerouslyAllowInheritedWebhookPath ??
|
|
129
|
-
false;
|
|
130
|
-
|
|
131
|
-
// Merge: account override > base channel config > env var
|
|
132
|
-
return {
|
|
133
|
-
accountId: id,
|
|
134
|
-
enabled: merged.enabled ?? true,
|
|
135
|
-
token: merged.token ?? envToken,
|
|
136
|
-
incomingUrl: merged.incomingUrl ?? envIncomingUrl,
|
|
137
|
-
nasHost: merged.nasHost ?? envNasHost,
|
|
138
|
-
webhookPath: merged.webhookPath ?? "/webhook/synology",
|
|
139
|
-
webhookPathSource,
|
|
140
|
-
dangerouslyAllowNameMatching: resolveDangerousNameMatchingEnabled({
|
|
141
|
-
providerConfig: channelCfg,
|
|
142
|
-
accountConfig: accountOverrides,
|
|
143
|
-
}),
|
|
144
|
-
dangerouslyAllowInheritedWebhookPath,
|
|
145
|
-
dmPolicy: merged.dmPolicy ?? "allowlist",
|
|
146
|
-
allowedUserIds: parseAllowedUserIds(merged.allowedUserIds ?? envAllowedUserIds),
|
|
147
|
-
rateLimitPerMinute: merged.rateLimitPerMinute ?? envRateLimitValue,
|
|
148
|
-
botName: merged.botName ?? envBotName,
|
|
149
|
-
allowInsecureSsl: merged.allowInsecureSsl ?? false,
|
|
150
|
-
};
|
|
151
|
-
}
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from "vitest";
|
|
2
|
-
import { synologyChatApprovalAuth } from "./approval-auth.js";
|
|
3
|
-
|
|
4
|
-
describe("synologyChatApprovalAuth", () => {
|
|
5
|
-
it("authorizes numeric Synology Chat user ids", () => {
|
|
6
|
-
const cfg = { channels: { "synology-chat": { allowedUserIds: ["123"] } } };
|
|
7
|
-
|
|
8
|
-
expect(
|
|
9
|
-
synologyChatApprovalAuth.authorizeActorAction({
|
|
10
|
-
cfg,
|
|
11
|
-
senderId: "123",
|
|
12
|
-
action: "approve",
|
|
13
|
-
approvalKind: "plugin",
|
|
14
|
-
}),
|
|
15
|
-
).toEqual({ authorized: true });
|
|
16
|
-
});
|
|
17
|
-
});
|
package/src/approval-auth.ts
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
createResolvedApproverActionAuthAdapter,
|
|
3
|
-
resolveApprovalApprovers,
|
|
4
|
-
} from "klaw/plugin-sdk/approval-auth-runtime";
|
|
5
|
-
import { resolveAccount } from "./accounts.js";
|
|
6
|
-
|
|
7
|
-
function normalizeSynologyChatApproverId(value: string | number): string | undefined {
|
|
8
|
-
const trimmed = String(value).trim();
|
|
9
|
-
return /^\d+$/.test(trimmed) ? trimmed : undefined;
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export const synologyChatApprovalAuth = createResolvedApproverActionAuthAdapter({
|
|
13
|
-
channelLabel: "Synology Chat",
|
|
14
|
-
resolveApprovers: ({ cfg, accountId }) => {
|
|
15
|
-
const account = resolveAccount(cfg ?? {}, accountId);
|
|
16
|
-
return resolveApprovalApprovers({
|
|
17
|
-
allowFrom: account.allowedUserIds,
|
|
18
|
-
normalizeApprover: normalizeSynologyChatApproverId,
|
|
19
|
-
});
|
|
20
|
-
},
|
|
21
|
-
normalizeSenderId: (value) => normalizeSynologyChatApproverId(value),
|
|
22
|
-
});
|
|
@@ -1,204 +0,0 @@
|
|
|
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
|
-
});
|
|
@@ -1,176 +0,0 @@
|
|
|
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
|
-
}));
|