Files
adolf/extensions/nextcloud-talk/src/inbound.behavior.test.ts
alvis bedb527145
Some checks failed
ClawSweeper Dispatch / dispatch (push) Has been cancelled
CodeQL / Security High (actions) (push) Has been cancelled
CodeQL / Security High (channel-runtime-boundary) (push) Has been cancelled
CodeQL / Security High (core-auth-secrets) (push) Has been cancelled
CodeQL / Security High (mcp-process-tool-boundary) (push) Has been cancelled
CodeQL / Security High (network-ssrf-boundary) (push) Has been cancelled
CodeQL / Security High (plugin-trust-boundary) (push) Has been cancelled
CodeQL / Security High (process-exec-boundary) (push) Has been cancelled
Docs Sync Publish Repo / sync-publish-repo (push) Has been cancelled
Docs / docs (push) Has been cancelled
OpenClaw Stable Main Closeout / Resolve stable release closeout inputs (push) Has been cancelled
OpenClaw Stable Main Closeout / Verify stable main closeout (push) Has been cancelled
Workflow Sanity / no-tabs (push) Has been cancelled
Workflow Sanity / actionlint (push) Has been cancelled
Workflow Sanity / generated-doc-baselines (push) Has been cancelled
CI / runner-admission (push) Has been cancelled
CI / preflight (push) Has been cancelled
CI / security-fast (push) Has been cancelled
CI / pnpm-store-warmup (push) Has been cancelled
CI / build-artifacts (push) Has been cancelled
CI / native-i18n (push) Has been cancelled
CI / ${{ matrix.check_name }} (push) Has been cancelled
CI / ${{ matrix.checkName }} (push) Has been cancelled
CI / checks-node-compat-node22 (push) Has been cancelled
CI / check-bundled-channel-config-metadata (push) Has been cancelled
CI / check-dependencies (push) Has been cancelled
CI / check-guards (push) Has been cancelled
CI / check-lint (push) Has been cancelled
CI / check-prod-types (push) Has been cancelled
CI / check-shrinkwrap (push) Has been cancelled
CI / check-test-types (push) Has been cancelled
CI / check-additional-boundaries-a (push) Has been cancelled
CI / check-additional-boundaries-bcd (push) Has been cancelled
CI / check-additional-extension-bundled (push) Has been cancelled
CI / check-additional-extension-channels (push) Has been cancelled
CI / check-additional-extension-package-boundary (push) Has been cancelled
CI / check-additional-runtime-topology-architecture (push) Has been cancelled
CI / check-session-accessor-boundary (push) Has been cancelled
CI / check-session-transcript-reader-boundary (push) Has been cancelled
CI / check-docs (push) Has been cancelled
CI / skills-python (push) Has been cancelled
CI / macos-swift (push) Has been cancelled
CI / ios-build (push) Has been cancelled
CI / ci-timings-summary (push) Has been cancelled
Native App Locale Refresh / Refresh native fa (push) Has been cancelled
Native App Locale Refresh / Refresh native fr (push) Has been cancelled
Native App Locale Refresh / Refresh native hi (push) Has been cancelled
Native App Locale Refresh / Refresh native id (push) Has been cancelled
Native App Locale Refresh / Refresh native it (push) Has been cancelled
Native App Locale Refresh / Refresh native ja-JP (push) Has been cancelled
Control UI Locale Refresh / plan (push) Has been cancelled
Control UI Locale Refresh / Refresh ${{ matrix.locale }} (push) Has been cancelled
Control UI Locale Refresh / Commit control UI locale refresh (push) Has been cancelled
Live Media Runner Image / Build live media runner image (push) Has been cancelled
Native App Locale Refresh / Refresh native ar (push) Has been cancelled
Native App Locale Refresh / Refresh native de (push) Has been cancelled
Native App Locale Refresh / Refresh native es (push) Has been cancelled
Native App Locale Refresh / Refresh native ko (push) Has been cancelled
Native App Locale Refresh / Refresh native nl (push) Has been cancelled
Native App Locale Refresh / Refresh native pl (push) Has been cancelled
Native App Locale Refresh / Refresh native pt-BR (push) Has been cancelled
Native App Locale Refresh / Refresh native ru (push) Has been cancelled
Native App Locale Refresh / Refresh native sv (push) Has been cancelled
Native App Locale Refresh / Refresh native th (push) Has been cancelled
Native App Locale Refresh / Refresh native tr (push) Has been cancelled
Native App Locale Refresh / Refresh native uk (push) Has been cancelled
Native App Locale Refresh / Refresh native vi (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-CN (push) Has been cancelled
Native App Locale Refresh / Refresh native zh-TW (push) Has been cancelled
Native App Locale Refresh / Commit native locale refresh (push) Has been cancelled
Plugin Init Scaffold Validation / Validate provider scaffold (push) Has been cancelled
Plugin NPM Release / preview_plugins_npm (push) Has been cancelled
Plugin NPM Release / Validate release publish approval (push) Has been cancelled
Plugin NPM Release / preview_plugin_pack (push) Has been cancelled
Plugin NPM Release / publish_plugins_npm (push) Has been cancelled
Sandbox Common Smoke / sandbox-common-smoke (push) Has been cancelled
Website Installer Sync / static (push) Has been cancelled
Website Installer Sync / linux-docker (push) Has been cancelled
Website Installer Sync / macos-installer (push) Has been cancelled
Website Installer Sync / windows-installer (push) Has been cancelled
Website Installer Sync / sync-website (push) Has been cancelled
Vendor OpenClaw source as Adolf fork baseline
Adolf is a fork/vendored clone of github.com/openclaw/openclaw (v2026.6.11),
free to diverge. Tree copied sans upstream .git; upstream remote added for
future syncs. Node pinned to 24 (.nvmrc); engines already require >=22.19.
Preserves docs/ARCHITECTURE.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LeqyaxJF2nbRXJtae2kNB2
2026-07-05 09:36:54 +00:00

311 lines
10 KiB
TypeScript

// Nextcloud Talk tests cover inbound.behavior plugin behavior.
import { createPluginRuntimeMock } from "openclaw/plugin-sdk/channel-test-helpers";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { PluginRuntime, RuntimeEnv } from "../runtime-api.js";
import type { ResolvedNextcloudTalkAccount } from "./accounts.js";
import { handleNextcloudTalkInbound } from "./inbound.js";
import { setNextcloudTalkRuntime } from "./runtime.js";
import type { CoreConfig, NextcloudTalkInboundMessage } from "./types.js";
const {
createChannelPairingControllerMock,
resolveAllowlistProviderRuntimeGroupPolicyMock,
resolveDefaultGroupPolicyMock,
warnMissingProviderGroupPolicyFallbackOnceMock,
} = vi.hoisted(() => {
return {
createChannelPairingControllerMock: vi.fn(),
resolveAllowlistProviderRuntimeGroupPolicyMock: vi.fn(),
resolveDefaultGroupPolicyMock: vi.fn(),
warnMissingProviderGroupPolicyFallbackOnceMock: vi.fn(),
};
});
const sendMessageNextcloudTalkMock = vi.hoisted(() => vi.fn());
const resolveNextcloudTalkRoomKindMock = vi.hoisted(() => vi.fn());
vi.mock("../runtime-api.js", async () => {
const actual = await vi.importActual<typeof import("../runtime-api.js")>("../runtime-api.js");
return {
...actual,
createChannelPairingController: createChannelPairingControllerMock,
resolveAllowlistProviderRuntimeGroupPolicy: resolveAllowlistProviderRuntimeGroupPolicyMock,
resolveDefaultGroupPolicy: resolveDefaultGroupPolicyMock,
warnMissingProviderGroupPolicyFallbackOnce: warnMissingProviderGroupPolicyFallbackOnceMock,
};
});
vi.mock("./send.js", () => ({
sendMessageNextcloudTalk: sendMessageNextcloudTalkMock,
}));
vi.mock("./room-info.js", async () => {
const actual = await vi.importActual<typeof import("./room-info.js")>("./room-info.js");
return {
...actual,
resolveNextcloudTalkRoomKind: resolveNextcloudTalkRoomKindMock,
};
});
function installRuntime(params?: {
buildMentionRegexes?: () => RegExp[];
hasControlCommand?: (body: string) => boolean;
matchesMentionPatterns?: (body: string, regexes: RegExp[]) => boolean;
shouldHandleTextCommands?: () => boolean;
}) {
const runtime = {
channel: {
inbound: {
dispatchReply: vi.fn(async () => undefined),
},
pairing: {
readAllowFromStore: vi.fn(async () => []),
upsertPairingRequest: vi.fn(async () => ({ code: "123456", created: true })),
},
commands: {
shouldHandleTextCommands: params?.shouldHandleTextCommands ?? vi.fn(() => false),
},
text: {
hasControlCommand: params?.hasControlCommand ?? vi.fn(() => false),
},
mentions: {
buildMentionRegexes: params?.buildMentionRegexes ?? vi.fn(() => []),
matchesMentionPatterns: params?.matchesMentionPatterns ?? vi.fn(() => false),
},
},
};
setNextcloudTalkRuntime(runtime as unknown as PluginRuntime);
return runtime;
}
function createRuntimeEnv() {
return {
log: vi.fn(),
error: vi.fn(),
} as unknown as RuntimeEnv;
}
function requireFirstMockArg(mock: ReturnType<typeof vi.fn>, label: string): unknown {
const [call] = mock.mock.calls;
if (!call) {
throw new Error(`expected ${label}`);
}
return call[0];
}
function requireFirstSendMessageCall(): [unknown, unknown, unknown] {
const [call] = sendMessageNextcloudTalkMock.mock.calls;
if (!call) {
throw new Error("expected Nextcloud Talk send call");
}
return call as [unknown, unknown, unknown];
}
function createAccount(
overrides?: Partial<ResolvedNextcloudTalkAccount>,
): ResolvedNextcloudTalkAccount {
return {
accountId: "default",
enabled: true,
baseUrl: "https://cloud.example.com",
secret: "secret",
secretSource: "config",
config: {
dmPolicy: "pairing",
allowFrom: [],
groupPolicy: "allowlist",
groupAllowFrom: [],
},
...overrides,
};
}
function createMessage(
overrides?: Partial<NextcloudTalkInboundMessage>,
): NextcloudTalkInboundMessage {
return {
messageId: "msg-1",
roomToken: "room-1",
roomName: "Room 1",
senderId: "user-1",
senderName: "Alice",
text: "hello",
mediaType: "text/plain",
timestamp: Date.now(),
isGroupChat: false,
...overrides,
};
}
describe("nextcloud-talk inbound behavior", () => {
beforeEach(() => {
vi.clearAllMocks();
installRuntime();
resolveNextcloudTalkRoomKindMock.mockResolvedValue("direct");
resolveDefaultGroupPolicyMock.mockReturnValue("allowlist");
resolveAllowlistProviderRuntimeGroupPolicyMock.mockReturnValue({
groupPolicy: "allowlist",
providerMissingFallbackApplied: false,
});
warnMissingProviderGroupPolicyFallbackOnceMock.mockReturnValue(undefined);
});
it("issues a DM pairing challenge and sends the challenge text", async () => {
const issueChallenge = vi.fn(
async (params: { sendPairingReply: (text: string) => Promise<void> }) => {
await params.sendPairingReply("Pair with code 123456");
},
);
createChannelPairingControllerMock.mockReturnValue({
readStoreForDmPolicy: vi.fn(),
issueChallenge,
});
sendMessageNextcloudTalkMock.mockResolvedValue(undefined);
const statusSink = vi.fn();
await handleNextcloudTalkInbound({
message: createMessage({ timestamp: 1_736_380_800_000 }),
account: createAccount(),
config: { channels: { "nextcloud-talk": {} } } as CoreConfig,
runtime: createRuntimeEnv(),
statusSink,
});
const challengeParams = requireFirstMockArg(
issueChallenge,
"Nextcloud Talk pairing challenge",
) as {
meta?: { name?: string };
senderId?: string;
senderIdLine?: string;
};
expect(challengeParams.senderId).toBe("user-1");
expect(challengeParams.senderIdLine).toBe("Your Nextcloud user id: user-1");
expect(challengeParams.meta).toEqual({ name: "Alice" });
expect(sendMessageNextcloudTalkMock).toHaveBeenCalledTimes(1);
const sendArgs = requireFirstSendMessageCall();
expect(sendArgs[0]).toBe("room-1");
expect(sendArgs[1]).toBe("Pair with code 123456");
expect(sendArgs[2]).toEqual({
cfg: { channels: { "nextcloud-talk": {} } },
accountId: "default",
});
expect(statusSink).toHaveBeenCalledWith({ lastInboundAt: 1_736_380_800_000 });
const outboundStatus = statusSink.mock.calls
.map(([status]) => status as { lastOutboundAt?: unknown })
.find((status) => status.lastOutboundAt !== undefined);
expect(typeof outboundStatus?.lastOutboundAt).toBe("number");
expect(outboundStatus?.lastOutboundAt).toBeGreaterThanOrEqual(1_736_380_800_000);
expect(sendMessageNextcloudTalkMock).toHaveBeenCalledTimes(1);
});
it("drops unmentioned group traffic before dispatch", async () => {
installRuntime({
buildMentionRegexes: vi.fn(() => [/@openclaw/i]),
matchesMentionPatterns: vi.fn(() => false),
});
createChannelPairingControllerMock.mockReturnValue({
readStoreForDmPolicy: vi.fn(),
issueChallenge: vi.fn(),
});
resolveNextcloudTalkRoomKindMock.mockResolvedValue("group");
const runtime = createRuntimeEnv();
await handleNextcloudTalkInbound({
message: createMessage({
roomToken: "room-group",
roomName: "Ops",
isGroupChat: true,
}),
account: createAccount({
config: {
dmPolicy: "pairing",
allowFrom: [],
groupPolicy: "allowlist",
groupAllowFrom: ["user-1"],
},
}),
config: { channels: { "nextcloud-talk": {} } } as CoreConfig,
runtime,
});
expect(sendMessageNextcloudTalkMock).not.toHaveBeenCalled();
expect(runtime.log).toHaveBeenCalledWith("nextcloud-talk: drop room room-group (no mention)");
});
it("blocks unauthorized group text control commands even when room sender access allows chat", async () => {
const buildMentionRegexes = vi.fn(() => [/@openclaw/i]);
const coreRuntime = installRuntime({
buildMentionRegexes,
hasControlCommand: vi.fn(() => true),
shouldHandleTextCommands: vi.fn(() => true),
});
createChannelPairingControllerMock.mockReturnValue({
readStoreForDmPolicy: vi.fn(),
issueChallenge: vi.fn(),
});
resolveNextcloudTalkRoomKindMock.mockResolvedValue("group");
const runtime = createRuntimeEnv();
await handleNextcloudTalkInbound({
message: createMessage({
roomToken: "room-group",
roomName: "Ops",
isGroupChat: true,
text: "/openclaw reload",
}),
account: createAccount({
config: {
dmPolicy: "pairing",
allowFrom: [],
groupPolicy: "allowlist",
groupAllowFrom: [],
rooms: {
"room-group": {
allowFrom: ["user-1"],
requireMention: false,
},
},
},
}),
config: { channels: { "nextcloud-talk": {} } } as CoreConfig,
runtime,
});
expect(coreRuntime.channel.inbound.dispatchReply).not.toHaveBeenCalled();
expect(buildMentionRegexes).not.toHaveBeenCalled();
expect(runtime.log).toHaveBeenCalledWith(
"nextcloud-talk: drop control command (unauthorized) target=user-1",
);
});
it("passes the shared reply pipeline for dispatched replies", async () => {
const coreRuntime = createPluginRuntimeMock();
setNextcloudTalkRuntime(coreRuntime as unknown as PluginRuntime);
createChannelPairingControllerMock.mockReturnValue({
readStoreForDmPolicy: vi.fn(async () => []),
issueChallenge: vi.fn(),
});
await handleNextcloudTalkInbound({
message: createMessage(),
account: createAccount({
config: {
dmPolicy: "allowlist",
allowFrom: ["user-1"],
groupPolicy: "allowlist",
groupAllowFrom: [],
},
}),
config: { channels: { "nextcloud-talk": {} } } as CoreConfig,
runtime: createRuntimeEnv(),
});
const assembledRequest = requireFirstMockArg(
coreRuntime.channel.inbound.dispatchReply as ReturnType<typeof vi.fn>,
"Nextcloud Talk assembled request",
) as { replyPipeline?: unknown };
expect(assembledRequest.replyPipeline).toEqual({});
});
});