Skip to content

Commit d5e89de

Browse files
authored
fix(synology-chat): deliver attachments without forwarding source URLs [AI] (#119941)
* fix(synology-chat): host outbound attachments * fix(synology-chat): isolate hosted media routes * fix(synology-chat): harden hosted media limits * fix(synology-chat): inspect hosted media content * fix(synology-chat): reject ambiguous media routes * fix(synology-chat): retain indeterminate media capabilities * fix(synology-chat): mask public callback URLs * fix(synology-chat): align callback sensitivity metadata * fix(synology-chat): reserve media capability query keys * fix(synology-chat): release rejected staged media * fix(synology-chat): preserve ambiguous media handoffs * fix(synology-chat): scan complete active media preamble * fix(synology-chat): report validated attachment readiness * fix(synology-chat): bound public media capability probes * fix(synology-chat): bound hosted media responses * test(synology-chat): model response headers read-only * fix(synology-chat): bound hosted media reads * fix(synology-chat): bound hosted media delivery * fix(synology-chat): retain media through active serves * fix(plugin-sdk): lease hosted media readers atomically * fix(synology-chat): close hosted media review gaps * test(synology-chat): clean up hosted media state * fix(system-agent): canonicalize sensitive config paths * fix(system-agent): honor runtime config sensitivity hints * fix(config): inherit sensitive metadata * fix(synology-chat): close latest review findings * test(system-agent): keep config recovery checks lint-clean * fix(system-agent): redact structured config secrets * fix(synology-chat): harden active-content sniffing * fix(security): close hosted media review gaps * fix(security): close remaining hosted media review findings * fix(system-agent): narrow dynamic owner ids safely * fix(system-agent): narrow dynamic channel ids safely * test(channels): isolate hosted media proofs * fix(security): close config and hosted media review gaps * test(plugin-sdk): split outbound media retention coverage * test(plugin-sdk): isolate capacity store fixtures * test(system-agent): assert config secrecy invariant
1 parent 1b98bc3 commit d5e89de

57 files changed

Lines changed: 5479 additions & 474 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎docs/channels/synology-chat.md‎

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ title: "Synology Chat"
88

99
Synology Chat connects to OpenClaw through a webhook pair: a Synology Chat outgoing webhook posts inbound direct messages to the Gateway, and replies go back through a Synology Chat incoming webhook.
1010

11-
Status: official plugin, installed separately. Direct messages only; text and URL-based file sends are supported.
11+
Status: official plugin, installed separately. Direct messages only; text and hosted file sends are supported.
1212

1313
## Install
1414

@@ -33,9 +33,10 @@ Details: [Plugins](/tools/plugin)
3333
3. Point the outgoing webhook URL to your OpenClaw Gateway:
3434
- `https://gateway-host/webhook/synology` by default.
3535
- Or your custom `channels.synology-chat.webhookPath`.
36+
- Record that exact externally reachable HTTPS URL as `channels.synology-chat.webhookUrl` so the NAS can retrieve hosted attachments.
3637
4. Finish setup in OpenClaw. Synology Chat appears in the same channel setup list in both flows:
3738
- Guided: `openclaw onboard` or `openclaw channels add`
38-
- Direct: `openclaw channels add --channel synology-chat --token <token> --url <incoming-webhook-url>`
39+
- Direct: `openclaw channels add --channel synology-chat --token <token> --url <incoming-webhook-url> --webhook-url <public-outgoing-webhook-url>`
3940
5. Restart the Gateway and send a DM to the Synology Chat bot.
4041

4142
Webhook auth details:
@@ -65,6 +66,7 @@ Minimal config:
6566
enabled: true,
6667
token: "synology-outgoing-token",
6768
incomingUrl: "https://nas.example.com/webapi/entry.cgi?api=SYNO.Chat.External&method=incoming&version=2&token=...",
69+
webhookUrl: "https://gateway.example.com/webhook/synology",
6870
webhookPath: "/webhook/synology",
6971
dmPolicy: "allowlist",
7072
allowedUserIds: ["123456"],
@@ -111,12 +113,22 @@ openclaw message send --channel synology-chat --target synology-chat:123456 --me
111113
openclaw message send --channel synology-chat --target synology:123456 --message "Short prefix"
112114
```
113115

114-
Outbound text is chunked at 2000 characters. Media sends are supported by URL-based file delivery: the NAS downloads and attaches the file (max 32 MB). Outbound file URLs must use `http` or `https`, and private or otherwise blocked network targets are rejected before OpenClaw forwards the URL to the NAS webhook.
116+
Outbound text is chunked at 2000 characters, and ordinary links remain intact. Keep **Hide URL previews in conversations and channels** enabled in Synology Chat Admin Console on a supported Chat Server release.
117+
118+
For attachments, OpenClaw loads the source under its guarded outbound-media policy, freezes the resulting bytes in bounded plugin-scoped SQLite state, and gives Synology a short-lived opaque HTTPS capability on the configured webhook route. The NAS receives only this OpenClaw-hosted URL, never the original remote or local media reference. Capabilities are account- and route-scoped, reusable for delayed `GET` or `HEAD` requests during their ten-minute lifetime, and expire automatically. Files are limited to 32 MB. Each account can serve at most four attachment responses concurrently and 128 MB per minute; stalled responses are closed after two minutes. Byte-range responses are not advertised.
119+
120+
`webhookUrl` and `webhookPath` have different roles:
121+
122+
- `webhookUrl` is the exact externally reachable HTTPS callback configured in Synology Chat. OpenClaw uses its public origin, path, and existing query string when creating attachment capabilities.
123+
- `webhookPath` is the internal Gateway route. A reverse proxy may map the public URL to this route, but should expose only this plugin path, not the general Gateway HTTP surface.
124+
- `incomingUrl` points in the opposite direction: OpenClaw uses it to post replies to the NAS.
125+
126+
OpenClaw never derives the public URL from `Host` or `X-Forwarded-*` headers and never falls back to forwarding the original source URL. If `webhookUrl` is missing or invalid, inbound messages and outbound text continue to work, while attachment sends fail with an actionable setup error.
115127

116128
## Multi-account
117129

118130
Multiple Synology Chat accounts are supported under `channels.synology-chat.accounts`.
119-
Each account can override token, incoming URL, webhook path, DM policy, and limits.
131+
Each account can override token, incoming URL, public webhook URL, webhook path, DM policy, and limits.
120132
Direct-message sessions are isolated per account and user, so the same numeric `user_id`
121133
on two different Synology accounts does not share transcript state.
122134
Give each enabled account a distinct `webhookPath`. OpenClaw rejects duplicate exact paths
@@ -134,10 +146,12 @@ but duplicate exact paths are still rejected fail-closed. Prefer explicit per-ac
134146
default: {
135147
token: "token-a",
136148
incomingUrl: "https://nas-a.example.com/...token=...",
149+
webhookUrl: "https://gateway.example.com/webhook/synology",
137150
},
138151
alerts: {
139152
token: "token-b",
140153
incomingUrl: "https://nas-b.example.com/...token=...",
154+
webhookUrl: "https://gateway.example.com/webhook/synology-alerts",
141155
webhookPath: "/webhook/synology-alerts",
142156
dmPolicy: "allowlist",
143157
allowedUserIds: ["987654"],
@@ -158,6 +172,8 @@ but duplicate exact paths are still rejected fail-closed. Prefer explicit per-ac
158172
- Prefer `dmPolicy: "allowlist"` for production.
159173
- Keep `dangerouslyAllowNameMatching` off unless you explicitly need legacy username-based reply delivery.
160174
- Keep `dangerouslyAllowInheritedWebhookPath` off unless you explicitly accept shared-path routing risk in a multi-account setup.
175+
- Reverse-proxy access logs can capture attachment capability tokens. Disable query-string logging or redact `__openclaw_synology_media_token_*` parameters, and keep application logs free of full capability URLs.
176+
- Hosted attachments use `Content-Disposition: attachment`, `X-Content-Type-Options: nosniff`, and `Cache-Control: no-store`. Files declared or named as HTML, SVG, or XML are rejected. Frozen bytes that begin as a UTF-8, UTF-16, or UTF-32 markup document after an optional encoding marker, whitespace, and comments are also rejected; literal tags later in passive text or source files do not make those files active documents.
161177

162178
## Troubleshooting
163179

@@ -175,6 +191,10 @@ but duplicate exact paths are still rejected fail-closed. Prefer explicit per-ac
175191
- `dmPolicy="allowlist"` is enabled but no users are configured
176192
- `User not authorized`:
177193
- the sender's numeric `user_id` is not in `allowedUserIds`
194+
- `Synology Chat attachments require webhookUrl`:
195+
- set the account's exact externally reachable HTTPS outgoing-webhook callback URL
196+
- confirm the reverse proxy maps only that public route to `webhookPath`
197+
- text and inbound messaging remain available while attachment setup is incomplete
178198

179199
## Related
180200

‎docs/plugins/sdk-channel-plugins.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,9 @@ the shared outbound loader. Hosted media capacity defaults to
296296
`overflowPolicy: "evict-oldest"` for compatibility. Use `"reject-new"` when
297297
issued URLs must remain valid until expiry, and configure both backing keyed
298298
stores with `"reject-new"` so independent writers cannot evict live rows.
299+
Use `validateBeforePersist` to inspect the guarded loader's exact bytes and
300+
metadata when a transport must reject a payload class. Treat its buffer as
301+
read-only and throw to reject before capability creation or any store write.
299302
Authenticate bearer requests with `readMetadata(...)` before calling `read(...)`
300303
so invalid tokens and `HEAD` requests do not hydrate stored media chunks.
301304

‎extensions/googlechat/src/google-auth.runtime.test.ts‎

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,17 @@ function mockCallArg(mock: ReturnType<typeof vi.fn>, callIndex = 0, argIndex = 0
7474
return call[argIndex];
7575
}
7676

77+
function stubIsolatedProcessEnv(patch: NodeJS.ProcessEnv): void {
78+
const isolatedProcess = Object.create(process) as NodeJS.Process;
79+
Object.defineProperty(isolatedProcess, "env", {
80+
configurable: true,
81+
value: { ...process.env, ...patch },
82+
});
83+
// Test files share the host process environment. Replace only this file's
84+
// global view so proxy-policy coverage cannot redirect sibling transports.
85+
vi.stubGlobal("process", isolatedProcess);
86+
}
87+
7788
type GoogleAuthFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
7889

7990
async function createGoogleAuthTransportFetch(): Promise<GoogleAuthFetch> {
@@ -216,8 +227,10 @@ describe("googlechat google auth runtime", () => {
216227
response: new Response("ok", { status: 200 }),
217228
release,
218229
});
219-
vi.stubEnv("HTTPS_PROXY", "http://env-proxy.example:8080");
220-
vi.stubEnv("https_proxy", "http://lower-proxy.example:8080");
230+
stubIsolatedProcessEnv({
231+
HTTPS_PROXY: "http://env-proxy.example:8080",
232+
https_proxy: "http://lower-proxy.example:8080",
233+
});
221234

222235
const guardedFetch = await createGoogleAuthTransportFetch();
223236
const response = await guardedFetch("https://oauth2.googleapis.com/token", {

‎extensions/synology-chat/package.json‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,21 @@
4949
{
5050
"key": "url",
5151
"kind": "string",
52+
"sensitive": true,
5253
"cli": {
5354
"flags": "--url <url>",
5455
"description": "Synology Chat webhook URL"
5556
}
5657
},
58+
{
59+
"key": "webhookUrl",
60+
"kind": "string",
61+
"sensitive": true,
62+
"cli": {
63+
"flags": "--webhook-url <url>",
64+
"description": "Public HTTPS Synology Chat callback URL used for attachments"
65+
}
66+
},
5767
{
5868
"key": "webhookPath",
5969
"kind": "string",

‎extensions/synology-chat/src/accounts.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,12 @@ export function resolveAccount(
133133
enabled: merged.enabled ?? true,
134134
token: merged.token ?? envToken,
135135
incomingUrl: merged.incomingUrl ?? envIncomingUrl,
136+
// The public callback is an exact per-route mapping. A named account with
137+
// its own webhookPath must not silently publish capabilities on the base route.
138+
webhookUrl:
139+
normalizeOptionalString(
140+
id === DEFAULT_ACCOUNT_ID ? merged.webhookUrl : rawAccount.webhookUrl,
141+
) ?? "",
136142
nasHost: merged.nasHost ?? envNasHost,
137143
webhookPath: merged.webhookPath ?? "/webhook/synology",
138144
webhookPathSource,

‎extensions/synology-chat/src/channel.integration.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
setSynologyRuntimeConfigForTest,
1212
synologyIngressStartMock,
1313
synologyIngressStopMock,
14+
tryHandleSynologyHostedMediaRequestMock,
1415
} from "./channel.test-mocks.js";
1516
import { makeFormBody, makeReq, makeRes } from "./test-http-utils.js";
1617

@@ -54,6 +55,8 @@ describe("Synology channel wiring integration", () => {
5455
resolveAgentRouteMock.mockClear();
5556
synologyIngressStartMock.mockClear();
5657
synologyIngressStopMock.mockClear();
58+
tryHandleSynologyHostedMediaRequestMock.mockClear();
59+
tryHandleSynologyHostedMediaRequestMock.mockResolvedValue(false);
5760
setSynologyRuntimeConfigForTest({});
5861
});
5962

@@ -112,6 +115,46 @@ describe("Synology channel wiring integration", () => {
112115
await started;
113116
});
114117

118+
it("dispatches hosted GET and HEAD capabilities before the inbound webhook parser", async () => {
119+
const abortController = new AbortController();
120+
const cfg = {
121+
channels: {
122+
"synology-chat": {
123+
enabled: true,
124+
token: "valid-token",
125+
incomingUrl: "https://nas.example.com/incoming",
126+
webhookUrl: "https://gateway.example.com/webhook/synology",
127+
webhookPath: "/webhook/synology",
128+
dmPolicy: "allowlist",
129+
allowedUserIds: ["123"],
130+
},
131+
},
132+
};
133+
const started = synologyChatPlugin.gateway.startAccount(
134+
makeStartContext(cfg, "default", abortController.signal),
135+
);
136+
const [registered] = requireMockCall(
137+
registerPluginHttpRouteMock,
138+
0,
139+
"Synology hosted media route",
140+
);
141+
tryHandleSynologyHostedMediaRequestMock.mockResolvedValue(true);
142+
143+
for (const method of ["GET", "HEAD"]) {
144+
await registered.handler(
145+
makeReq(method, "", {
146+
url: "/webhook/synology?__openclaw_synology_media_token_id=token",
147+
}),
148+
makeRes(),
149+
);
150+
}
151+
152+
expect(tryHandleSynologyHostedMediaRequestMock).toHaveBeenCalledTimes(2);
153+
expect(dispatchReplyWithBufferedBlockDispatcher).not.toHaveBeenCalled();
154+
abortController.abort();
155+
await started;
156+
});
157+
115158
it("stops ingress and rejects startup when the webhook route cannot bind", async () => {
116159
const abortController = new AbortController();
117160
const statusSink = vi.fn();

‎extensions/synology-chat/src/channel.test-mocks.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ export const registerPluginHttpRouteMock: Mock<typeof registerPluginHttpRoute> =
99
);
1010
export const synologyIngressStartMock = vi.fn();
1111
export const synologyIngressStopMock = vi.fn(async () => undefined);
12+
export const tryHandleSynologyHostedMediaRequestMock = vi.fn(async () => false);
1213

1314
export const dispatchReplyWithBufferedBlockDispatcher: Mock<
1415
(_params: unknown) => Promise<{ counts: Record<string, number> }>
@@ -148,10 +149,22 @@ vi.mock("openclaw/plugin-sdk/webhook-ingress", async () => {
148149
vi.mock("./client.js", () => ({
149150
SYNOLOGY_CHAT_TEXT_CHUNK_LIMIT: 2_000,
150151
sendMessage: vi.fn().mockResolvedValue(true),
151-
sendFileUrl: vi.fn().mockResolvedValue(true),
152+
sendHostedFileUrl: vi.fn().mockResolvedValue({ status: "accepted" }),
152153
resolveLegacyWebhookNameToChatUserId: vi.fn().mockResolvedValue(undefined),
153154
}));
154155

156+
vi.mock("./outbound-media.js", async () => {
157+
const actual = await vi.importActual<typeof import("./outbound-media.js")>("./outbound-media.js");
158+
return {
159+
...actual,
160+
prepareSynologyHostedMedia: vi.fn(async () => ({
161+
url: "https://gateway.example.com/webhook/synology?__openclaw_synology_media_token_test=value",
162+
cleanup: vi.fn(async () => undefined),
163+
})),
164+
tryHandleSynologyHostedMediaRequest: tryHandleSynologyHostedMediaRequestMock,
165+
};
166+
});
167+
155168
vi.mock("./webhook-ingress.js", async () => {
156169
const actual =
157170
await vi.importActual<typeof import("./webhook-ingress.js")>("./webhook-ingress.js");

0 commit comments

Comments
 (0)