Repository navigation
feat(discord): add canvas-first Discord Activities support - #65205
thewilloftheshadow wants to merge 1 commit into
Conversation
🔒 Aisle Security AnalysisWe found 4 potential security issue(s) in this PR:
1. 🟠 Unauthenticated access to Canvas/A2UI endpoints when activity mode enabled without token
Description
Vulnerable code: // authorizeCanvasRequest() returns ok before bearer/capability auth
if (isActivityCanvasRequest && isCanvasActivityAccessAllowed(params.activity, req)) {
return { ok: true };
}
// isCanvasActivityAccessAllowed(): no token => allow
const configuredToken = activity.token?.trim();
if (!configuredToken) {
return true;
}RecommendationRequire a cryptographically strong secret (token) or a verifiable signed assertion for all activity-mode access; do not treat presence of query params as authorization. Options:
Example (fail-closed without token): export function isCanvasActivityAccessAllowed(activity: CanvasHostActivityConfig | undefined, req: IncomingMessage) {
if (!activity?.enabled) return false;
const configuredToken = activity.token?.trim();
if (!configuredToken) return false; // fail closed
if (activity.requireLaunchContext !== false && !hasDiscordActivityLaunchContext(req)) {
return false;
}
return resolveActivityToken(req) === configuredToken;
}Also ensure the A2UI activity WebSocket path is protected by the same robust auth mechanism. 2. 🟠 Remote third-party dynamic import in injected Canvas script enables supply-chain script execution
DescriptionThe Canvas HTML injection (
Vulnerable code: sdkModule = await import("https://cdn.jsdelivr.net/npm/@discord/embedded-app-sdk/+esm");
// fallback
sdkModule = await import("https://esm.sh/@discord/embedded-app-sdk");RecommendationAvoid runtime-loading executable code from third-party CDNs in production. Recommended fixes (pick one):
import { DiscordSDK } from "@discord/embedded-app-sdk";
// ... use DiscordSDK without remote import
Also ensure 3. 🟡 Unbounded A2UI activity broadcast and state retention enables memory/CPU denial of service
DescriptionThe A2UI activity hub broadcasts arbitrary JSONL/JSON messages to every connected WebSocket client and retains the last payload in memory without any size limits or backpressure handling.
Vulnerable code: // a2ui-activity.ts
broadcastPush: (jsonl: string) => {
lastJsonl = jsonl;
lastUpdatedAt = Date.now();
broadcast({ type: "a2ui.push", jsonl, updatedAt: lastUpdatedAt });
}
// nodes.ts
if (message && typeof message === "object") {
context.a2uiActivityHub.broadcastPush(JSON.stringify(message));
}RecommendationAdd explicit limits and backpressure handling:
Example size + backpressure guard: const MAX_ACTIVITY_BYTES = 256 * 1024;
function safeSend(ws: WebSocket, data: string) {
if (ws.readyState !== ws.OPEN) return;
if (ws.bufferedAmount > MAX_ACTIVITY_BYTES) {
ws.terminate();
return;
}
ws.send(data);
}
broadcastPush: (jsonl: string) => {
if (Buffer.byteLength(jsonl, 'utf8') > MAX_ACTIVITY_BYTES) return;
lastJsonl = jsonl;
lastUpdatedAt = Date.now();
const data = JSON.stringify({ type: 'a2ui.push', jsonl, updatedAt: lastUpdatedAt });
for (const ws of clients) safeSend(ws, data);
}Also apply similar checks in 4. 🟡 Activity token exposed over non-TLS WebSocket when page served via HTTP
DescriptionThe A2UI activity bridge in
Vulnerable code: const proto = window.location.protocol === "https:" ? "wss" : "ws";
const query = activityToken ? `?activityToken=${encodeURIComponent(activityToken)}` : "";
const wsUrl = `${proto}://${window.location.host}/__openclaw__/a2ui/ws${query}`;RecommendationRequire TLS for any authenticated activity bridge and avoid putting tokens in the URL.
if (window.location.protocol !== "https:") {
console.warn("A2UI activity bridge requires HTTPS/WSS");
return;
}
const wsUrl = `wss://${window.location.host}/__openclaw__/a2ui/ws`;
Analyzed PR: #65205 at commit Last updated on: 2026-04-12T06:54:20Z |
|
Found 1 test failure on Blacksmith runners: Failure
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 64ee279552
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| return DISCORD_ACTIVITY_LAUNCH_QUERY_KEYS.some((key) => { | ||
| const raw = url.searchParams.get(key); | ||
| return typeof raw === "string" && raw.trim().length > 0; | ||
| }); |
There was a problem hiding this comment.
Reject spoofed launch markers before granting activity auth bypass
hasDiscordActivityLaunchContext treats any non-empty instance_id, frame_id, or platform query param as trusted launch context, and authorizeCanvasRequest uses that result to allow unauthenticated canvas access when activity mode is enabled. In deployments without an activity.token (the documented optional default), an external caller can bypass gateway auth by appending one of these parameters to /__openclaw__/canvas or /__openclaw__/ws, so launch-context enforcement is trivially spoofable.
Useful? React with 👍 / 👎.
| } catch (error) { | ||
| state.error = error instanceof Error ? error.message : String(error); | ||
| state.ready = false; | ||
| state.sdk = undefined; | ||
| throw error; |
There was a problem hiding this comment.
Reset failed Discord SDK load promise to permit retries
When OpenClaw.discord.load() fails once (for example a transient CDN failure or ready() timeout), the rejected promise is kept in state._loadPromise and never cleared. Subsequent calls re-await the same rejected promise, so the helper cannot recover without a full page reload even if connectivity returns.
Useful? React with 👍 / 👎.
Greptile SummaryThis PR adds canvas-first Discord Activities support: an All P2 findings; the two substantive ones are the Confidence Score: 5/5Safe to merge; all findings are P2 style/hardening suggestions that do not affect correctness or security in a blocking way. The auth flow (launch-context cookies, activity token gating, Entry Point retention) is logically correct and well-tested. Both open findings are best-practice improvements (constant-time comparison, filtering empty prompt strings) rather than bugs. Test coverage across the key seams is solid. src/gateway/a2ui-activity.ts (token comparison) and src/agents/system-prompt.ts (empty strings in section builder).
|
| if (!configuredToken) { | ||
| return true; | ||
| } | ||
| return resolveActivityToken(req) === configuredToken; |
There was a problem hiding this comment.
Activity token compared with
=== instead of safeEqualSecret
isCanvasActivityAccessAllowed compares the activity token with ===, which is vulnerable to timing side-channels. safeEqualSecret is already imported and used in the surrounding gateway auth code for the bearer token — using it here too would keep the token-comparison surface consistent and safe.
| return resolveActivityToken(req) === configuredToken; | |
| return safeEqualSecret(resolveActivityToken(req) ?? "", configuredToken); |
(You'll also need to import safeEqualSecret into a2ui-activity.ts, or expose the comparison through the existing http-auth.ts call-site that already imports it.) The same plain === appears in the cookie-setting block in server-http.ts (queryActivityToken?.trim() === configuredActivityToken) and is worth fixing there too.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gateway/a2ui-activity.ts
Line: 154
Comment:
**Activity token compared with `===` instead of `safeEqualSecret`**
`isCanvasActivityAccessAllowed` compares the activity token with `===`, which is vulnerable to timing side-channels. `safeEqualSecret` is already imported and used in the surrounding gateway auth code for the bearer token — using it here too would keep the token-comparison surface consistent and safe.
```suggestion
return safeEqualSecret(resolveActivityToken(req) ?? "", configuredToken);
```
(You'll also need to import `safeEqualSecret` into `a2ui-activity.ts`, or expose the comparison through the existing `http-auth.ts` call-site that already imports it.) The same plain `===` appears in the cookie-setting block in `server-http.ts` (`queryActivityToken?.trim() === configuredActivityToken`) and is worth fixing there too.
How can I resolve this? If you propose a fix, please make it concise.| params.runtimeInfo.discordActivityTokenRequired | ||
| ? "- Activity token auth is enabled; direct opens without the configured token are rejected." | ||
| : "", | ||
| params.runtimeInfo.discordActivityRequireLaunchContext | ||
| ? "- Launch-context enforcement is enabled; direct opens outside Discord Activity launch context are rejected." | ||
| : "", | ||
| "", |
There was a problem hiding this comment.
Unconditional empty strings add spurious blank lines to the prompt
When discordActivityTokenRequired and/or discordActivityRequireLaunchContext are falsy, the array gets empty-string entries that, combined with the intentional trailing "", produce two or three consecutive blank lines in the assembled system prompt (extra wasted tokens). Filtering them out keeps the section clean:
| params.runtimeInfo.discordActivityTokenRequired | |
| ? "- Activity token auth is enabled; direct opens without the configured token are rejected." | |
| : "", | |
| params.runtimeInfo.discordActivityRequireLaunchContext | |
| ? "- Launch-context enforcement is enabled; direct opens outside Discord Activity launch context are rejected." | |
| : "", | |
| "", | |
| ...(params.runtimeInfo.discordActivityTokenRequired | |
| ? ["- Activity token auth is enabled; direct opens without the configured token are rejected."] | |
| : []), | |
| ...(params.runtimeInfo.discordActivityRequireLaunchContext | |
| ? ["- Launch-context enforcement is enabled; direct opens outside Discord Activity launch context are rejected."] | |
| : []), | |
| "", |
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/system-prompt.ts
Line: 367-373
Comment:
**Unconditional empty strings add spurious blank lines to the prompt**
When `discordActivityTokenRequired` and/or `discordActivityRequireLaunchContext` are falsy, the array gets empty-string entries that, combined with the intentional trailing `""`, produce two or three consecutive blank lines in the assembled system prompt (extra wasted tokens). Filtering them out keeps the section clean:
```suggestion
...(params.runtimeInfo.discordActivityTokenRequired
? ["- Activity token auth is enabled; direct opens without the configured token are rejected."]
: []),
...(params.runtimeInfo.discordActivityRequireLaunchContext
? ["- Launch-context enforcement is enabled; direct opens outside Discord Activity launch context are rejected."]
: []),
"",
```
How can I resolve this? If you propose a fix, please make it concise.64ee279 to
89b8977
Compare
|
Codex review: found issues before merge. Reviewed July 31, 2026, 7:14 AM ET / 11:14 UTC. ClawSweeper reviewWhat this changesThe branch adds Discord Activity launch buttons, a Canvas/A2UI Activity bridge and authorization path, Discord command-deploy handling, configuration, tests, and Discord Activities documentation. Merge readiness⛔ Blocked by patch quality or review findings - 19 items remain Keep this maintainer-authored, maintainer-labeled PR open for explicit owner review. Current main does not implement Discord Activity support, but the branch still bypasses the Gateway’s existing Canvas authentication using spoofable request markers, adds Discord-specific policy to core, loads executable SDK code from public CDNs, exposes tokens in URLs, and fans unbounded A2UI payloads out to WebSocket clients. Priority: P1 Review scores
Verification
How this fits togetherDiscord messages can trigger a Discord Activity that loads the Gateway-hosted Canvas page. The branch would authorize that embedded page separately from normal Gateway authentication and relay node-produced A2UI updates to connected Activity clients. flowchart LR
A[Discord message action] --> B[Discord Activity launch]
B --> C[Gateway Canvas route]
C --> D[Activity authorization]
D --> E[Embedded Canvas page]
F[Node A2UI update] --> G[Activity WebSocket hub]
G --> E
Decision needed
Why: The current branch changes the security boundary and core/plugin ownership model; source review cannot safely choose the permanent access model or approve a public-facing auth bypass without maintainer intent. Before merge
Findings
Agent review detailsSecurityNeeds attention: The diff adds a new Gateway authorization exception, URL-borne credential handling, remote executable SDK loading, and unbounded WebSocket fanout without sufficient boundary proof. PR surfaceSource +1039, Tests +406, Docs +233, Generated 0. Total +1678 across 41 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: First decide the owner boundary: add a narrow, plugin-owned Discord Activity descriptor/API only if core must recognize Activity access. Then require a credentialed, non-URL authorization mechanism for every Activity request, bundle or locally serve a pinned SDK, bound retained/broadcast payloads and slow clients, and prove the complete Discord launch path with redacted diagnostics before reconsidering merge. Do we have a high-confidence way to reproduce the issue? Yes, from source: enable Is this the best way to solve the issue? No: Discord-specific Activity policy, credentials, and launch handling should not be embedded as a generic core Canvas exception. A plugin-owned descriptor plus a credentialed, non-URL access contract is the narrower maintainable solution. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 22911713e511. LabelsLabel changes:
Label justifications:
EvidenceSecurity concerns:
What I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
Summary
Describe the problem and fix in 2–5 bullets:
If this PR fixes a plugin beta-release blocker, title it
fix(<plugin-id>): beta blocker - <summary>and link the matchingBeta blocker: <plugin-name> - <summary>issue labeledbeta-blocker. Contributors cannot label PRs, so the title is the PR-side signal for maintainers and automation.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
Root Cause (if applicable)
For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write
N/A. If the cause is unclear, writeUnknown.Regression Test Plan (if applicable)
For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write
N/A.extensions/discord/src/monitor/provider.test.tssrc/gateway/server.canvas-auth.test.tssrc/agents/system-prompt.test.tssrc/agents/system-prompt-params.test.tssrc/canvas-host/server.test.tsUser-visible / Behavior Changes
List user-visible changes (including defaults/config).
If none, write
None.messageaction supports higher-level Activity launch helper behavior for easier launch button creation.canvasHost.activity.requireLaunchContextis now treated as default-on (trueunless explicitlyfalse).window.OpenClaw.discord/window.openclawDiscordhelper APIs (lazy SDK load).Diagram (if applicable)
For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write
N/A.Security Impact (required)
Yes/No) NoYes/No) YesYes/No) YesYes/No) YesYes/No) NoYes, explain risk + mitigation:Repro + Verification
Environment
canvasHost.activity.enabled=true,canvasHost.activity.requireLaunchContext=true, Discord account configuredSteps
launch-activitybutton and observe canvas/auth behavior.Expected
Actual
Evidence
Attach at least one:
Human Verification (required)
What you personally verified (not just CI), and how:
Review Conversations
If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.
Compatibility / Migration
Yes/No) YesYes/No) YesYes/No) NoRisks and Mitigations
List only real risks for this PR. Add/remove entries as needed. If none, write
None.canvasHost.activity.requireLaunchContext=false.