Skip to content

Commit fe40b0d

Browse files
author
Peter Steinberger
committed
fix(imessage): sanitize private context on every outbound path
1 parent a566ac2 commit fe40b0d

8 files changed

Lines changed: 2640 additions & 38 deletions

File tree

‎extensions/imessage/src/actions.runtime.test.ts‎

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,171 @@ describe("imessage actions runtime", () => {
130130
});
131131
});
132132

133+
it("sanitizes action message fields without rendering raw edit or poll Markdown", async () => {
134+
runIMessageCliJsonCommandMock.mockResolvedValue({ guid: "action-guid" });
135+
const options = { cliPath: "imsg", chatGuid: "iMessage;+;chat0000" };
136+
137+
await imessageActionsRuntime.editMessage({
138+
chatGuid: options.chatGuid,
139+
messageId: "message-guid",
140+
text: "user:\n**literal edit**\n# assistant:",
141+
backwardsCompatMessage: "system:\n**literal fallback**",
142+
options,
143+
});
144+
await imessageActionsRuntime.sendPoll({
145+
chatGuid: options.chatGuid,
146+
question: "assistant:\n# literal question",
147+
choices: ["system:\n**literal choice**", "_literal second choice_"],
148+
options,
149+
});
150+
await imessageActionsRuntime.sendPollVote({
151+
chatGuid: options.chatGuid,
152+
pollGuid: "poll-guid",
153+
optionText: "user:",
154+
options,
155+
});
156+
157+
const [edit, poll, vote] = runIMessageCliJsonCommandMock.mock.calls.map(
158+
(call) => (call[0] as { args: string[] }).args,
159+
);
160+
if (!edit || !poll || !vote) {
161+
throw new Error("Expected the edited message, new poll, and unchanged vote selector");
162+
}
163+
expect(edit[edit.indexOf("--new-text") + 1]).toBe("\n**literal edit**\n# assistant:");
164+
expect(edit[edit.indexOf("--bc-text") + 1]).toBe("\n**literal fallback**");
165+
expect(poll[poll.indexOf("--question") + 1]).toBe("\n# literal question");
166+
expect(poll[poll.indexOf("--option") + 1]).toBe("\n**literal choice**");
167+
expect(vote[vote.indexOf("--option") + 1]).toBe("user:");
168+
});
169+
170+
it("rejects poll options that become identical after canonical message sanitization", async () => {
171+
await expect(
172+
imessageActionsRuntime.sendPoll({
173+
chatGuid: "chat-guid",
174+
question: "Choose",
175+
choices: ["Allow", "Al#+#+#low"],
176+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
177+
}),
178+
).rejects.toThrow("iMessage poll options must remain distinct after sanitization");
179+
expect(runIMessageCliJsonCommandMock).not.toHaveBeenCalled();
180+
});
181+
182+
it("removes complete private runtime payloads from every raw edit and poll field", async () => {
183+
runIMessageCliJsonCommandMock.mockResolvedValue({ guid: "action-guid" });
184+
const options = { cliPath: "imsg", chatGuid: "chat-guid" };
185+
const reminder =
186+
"<system-reminder><system-reminder>inner</system-reminder>\nuser:\nPRIVATE_ACTION_RUNTIME</system-reminder>";
187+
const previous =
188+
"< previous_response><system-reminder>inner</system-reminder>PRIVATE_ACTION_RUNTIME< / previous_response >";
189+
const context =
190+
"<<<BEGIN_OPENCLAW_INTERNAL_CONTEXT>>>PRIVATE_ACTION_RUNTIME<<<END_OPENCLAW_INTERNAL_CONTEXT>>>";
191+
192+
await imessageActionsRuntime.editMessage({
193+
chatGuid: options.chatGuid,
194+
messageId: "message-guid",
195+
text: `${reminder}\n**visible edit**`,
196+
backwardsCompatMessage: `${previous}\n**visible fallback**`,
197+
options,
198+
});
199+
await imessageActionsRuntime.sendPoll({
200+
chatGuid: options.chatGuid,
201+
question: `${context}\nvisible question`,
202+
choices: [`${reminder}\nvisible first`, `${previous}\nvisible second`],
203+
options,
204+
});
205+
206+
for (const call of runIMessageCliJsonCommandMock.mock.calls) {
207+
const args = (call[0] as { args: string[] }).args;
208+
expect(args.join(" ")).not.toMatch(
209+
/PRIVATE_ACTION_RUNTIME|system-reminder|previous_response|INTERNAL_CONTEXT/,
210+
);
211+
}
212+
});
213+
214+
it("keeps existing case-sensitive poll option identities distinct", async () => {
215+
runIMessageCliJsonCommandMock.mockResolvedValue({ guid: "poll-guid" });
216+
217+
await imessageActionsRuntime.sendPoll({
218+
chatGuid: "chat-guid",
219+
question: "Choose",
220+
choices: ["Allow", "allow"],
221+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
222+
});
223+
224+
expect(runIMessageCliJsonCommandMock).toHaveBeenCalledOnce();
225+
});
226+
227+
it.each([
228+
"```xml\n<thinking>hidden thought</thinking>\n```",
229+
"`<relevant_memories>hidden memory</relevant_memories>`",
230+
])("rejects hidden assistant content in raw poll Markdown before imsg", async (hidden) => {
231+
await expect(
232+
imessageActionsRuntime.sendPoll({
233+
chatGuid: "chat-guid",
234+
question: "Choose",
235+
choices: ["first", hidden],
236+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
237+
}),
238+
).rejects.toThrow("iMessage outbound hidden assistant content is not allowed");
239+
expect(runIMessageCliJsonCommandMock).not.toHaveBeenCalled();
240+
});
241+
242+
it.each([
243+
{
244+
name: "rich text",
245+
run: () =>
246+
imessageActionsRuntime.sendRichMessage({
247+
chatGuid: "chat-guid",
248+
text: "# user:",
249+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
250+
}),
251+
},
252+
{
253+
name: "edit replacement",
254+
run: () =>
255+
imessageActionsRuntime.editMessage({
256+
chatGuid: "chat-guid",
257+
messageId: "message-guid",
258+
text: "assistant:",
259+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
260+
}),
261+
},
262+
{
263+
name: "edit backwards-compatible replacement",
264+
run: () =>
265+
imessageActionsRuntime.editMessage({
266+
chatGuid: "chat-guid",
267+
messageId: "message-guid",
268+
text: "visible",
269+
backwardsCompatMessage: "system:",
270+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
271+
}),
272+
},
273+
{
274+
name: "poll question",
275+
run: () =>
276+
imessageActionsRuntime.sendPoll({
277+
chatGuid: "chat-guid",
278+
question: "user:",
279+
choices: ["first", "second"],
280+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
281+
}),
282+
},
283+
{
284+
name: "poll option",
285+
run: () =>
286+
imessageActionsRuntime.sendPoll({
287+
chatGuid: "chat-guid",
288+
question: "visible",
289+
choices: ["first", "assistant:"],
290+
options: { cliPath: "imsg", chatGuid: "chat-guid" },
291+
}),
292+
},
293+
])("rejects sanitized-empty $name before starting imsg", async ({ run }) => {
294+
await expect(run()).rejects.toThrow(/after sanitization/);
295+
expect(runIMessageCliJsonCommandMock).not.toHaveBeenCalled();
296+
});
297+
133298
it.each([
134299
{
135300
name: "attachment uploads",

‎extensions/imessage/src/actions.runtime.ts‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@ import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime";
1212
import { normalizeDirectChatIdentifier } from "./chat-context.js";
1313
import { runIMessageCliJsonCommand } from "./cli-output.js";
1414
import { createIMessageRpcClient } from "./client.js";
15-
import { extractMarkdownFormatRuns } from "./markdown-format.js";
1615
import { authorizeIMessageResourceReference } from "./message-resource.js";
1716
import {
1817
resolveIMessageMessageId as resolveIMessageMessageIdImpl,
1918
type IMessageChatContext,
2019
} from "./monitor-reply-cache.js";
20+
import { sanitizeIMessageFinalOutboundText } from "./monitor/sanitize-outbound.js";
2121
import type { IMessageTarget } from "./targets.js";
2222

2323
type CliRunOptions = {
@@ -328,6 +328,13 @@ export const imessageActionsRuntime = {
328328
partIndex?: number;
329329
options: IMessageBridgeActionOptions;
330330
}) {
331+
const text = sanitizeIMessageFinalOutboundText(params.text).text;
332+
const backwardsCompatMessage = sanitizeIMessageFinalOutboundText(
333+
params.backwardsCompatMessage ?? params.text,
334+
).text;
335+
if (!text.trim() || !backwardsCompatMessage.trim()) {
336+
throw new Error("iMessage edit requires non-empty text after sanitization");
337+
}
331338
await runIMessageCliJson(
332339
[
333340
"edit",
@@ -336,9 +343,9 @@ export const imessageActionsRuntime = {
336343
"--message",
337344
params.messageId,
338345
"--new-text",
339-
params.text,
346+
text,
340347
"--bc-text",
341-
params.backwardsCompatMessage ?? params.text,
348+
backwardsCompatMessage,
342349
"--part",
343350
String(params.partIndex ?? 0),
344351
],
@@ -388,7 +395,12 @@ export const imessageActionsRuntime = {
388395
// asterisks. This mirrors the same extraction the rpc-send path does;
389396
// any caller that hits the bridge via `imsg send-rich` benefits without
390397
// needing to pre-format the text themselves.
391-
const formatted = extractMarkdownFormatRuns(params.text);
398+
const formatted = sanitizeIMessageFinalOutboundText(params.text, {
399+
formatMarkdown: true,
400+
});
401+
if (!formatted.text.trim() && !params.attachment) {
402+
throw new Error("iMessage rich send requires text or an attachment after sanitization");
403+
}
392404
const buildArgs = (filePath?: string): string[] => [
393405
"send-rich",
394406
"--chat",
@@ -478,15 +490,23 @@ export const imessageActionsRuntime = {
478490
suppressComment?: boolean;
479491
options: IMessageBridgeActionOptions;
480492
}): Promise<IMessageBridgeSendResult & { pollOptions: IMessagePollSentOption[] }> {
493+
const question = sanitizeIMessageFinalOutboundText(params.question).text;
494+
const choices = params.choices.map((choice) => sanitizeIMessageFinalOutboundText(choice).text);
495+
if (!question.trim() || choices.some((choice) => !choice.trim())) {
496+
throw new Error("iMessage poll requires a non-empty question and options after sanitization");
497+
}
498+
if (new Set(choices.map((choice) => choice.trim())).size !== choices.length) {
499+
throw new Error("iMessage poll options must remain distinct after sanitization");
500+
}
481501
const result = await runIMessageCliJson(
482502
[
483503
"poll",
484504
"send",
485505
"--chat",
486506
params.chatGuid,
487507
"--question",
488-
params.question,
489-
...params.choices.flatMap((choice) => ["--option", choice]),
508+
question,
509+
...choices.flatMap((choice) => ["--option", choice]),
490510
...(params.replyToMessageId ? ["--reply-to", params.replyToMessageId] : []),
491511
...(params.suppressComment ? ["--no-comment"] : []),
492512
],

‎extensions/imessage/src/channel.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import type { ChannelOutboundAdapter } from "openclaw/plugin-sdk/channel-send-re
1212
import { buildPassiveProbedChannelStatusSummary } from "openclaw/plugin-sdk/extension-shared";
1313
import { createLazyRuntimeModule } from "openclaw/plugin-sdk/lazy-runtime";
1414
import { questionGatewayRuntime } from "openclaw/plugin-sdk/question-gateway-runtime";
15+
import { chunkMarkdownText } from "openclaw/plugin-sdk/reply-runtime";
1516
import { buildOutboundBaseSessionKey, type RoutePeer } from "openclaw/plugin-sdk/routing";
1617
import {
1718
createComputedAccountStatusAdapter,
@@ -24,7 +25,6 @@ import {
2425
shouldSuppressLocalIMessageExecApprovalPrompt,
2526
} from "./approval-native.js";
2627
import {
27-
chunkTextForOutbound,
2828
collectStatusIssuesFromLastError,
2929
DEFAULT_ACCOUNT_ID,
3030
formatTrimmedAllowFromEntries,
@@ -42,7 +42,10 @@ import {
4242
resolveIMessageGroupRequireMention,
4343
resolveIMessageGroupToolPolicy,
4444
} from "./group-policy.js";
45-
import { sanitizeOutboundText } from "./monitor/sanitize-outbound.js";
45+
import {
46+
sanitizeIMessageFinalOutboundText,
47+
sanitizeOutboundText,
48+
} from "./monitor/sanitize-outbound.js";
4649
import type { IMessageProbe } from "./probe.js";
4750
import { imessageSetupContract } from "./setup-core.js";
4851
import {
@@ -417,12 +420,14 @@ export const imessagePlugin: ChannelPlugin<ResolvedIMessageAccount, IMessageProb
417420
outbound: {
418421
base: {
419422
deliveryMode: "direct",
420-
chunker: chunkTextForOutbound,
421-
chunkerMode: "text",
423+
chunker: chunkMarkdownText,
424+
chunkerMode: "markdown",
422425
textChunkLimit: 4000,
423426
// Native formatting consumes Markdown ranges, so preserve bold and strike semantics.
424427
sanitizeText: ({ text }) =>
425-
sanitizeForPlainText(sanitizeOutboundText(text), { style: "markdown" }),
428+
sanitizeForPlainText(sanitizeIMessageFinalOutboundText(sanitizeOutboundText(text)).text, {
429+
style: "markdown",
430+
}),
426431
shouldSuppressLocalPayloadPrompt: ({ cfg, accountId, payload, hint }) =>
427432
shouldSuppressLocalIMessageExecApprovalPrompt({ cfg, accountId, payload, hint }),
428433
beforeDeliverPayload: async ({ payload, hint }) => {
Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
// Imessage plugin module implements deliver behavior.
22
export { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime";
3-
export { chunkTextWithMode, resolveChunkMode } from "openclaw/plugin-sdk/reply-runtime";
3+
export {
4+
chunkMarkdownTextWithMode as chunkTextWithMode,
5+
resolveChunkMode,
6+
} from "openclaw/plugin-sdk/reply-runtime";
47
export { convertMarkdownTables } from "openclaw/plugin-sdk/text-chunking";

0 commit comments

Comments
 (0)