wishforge-ide/apps/ide/policy/plugin-dap-guard.cjs
eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
Adds prettier 3.9.8 (exact) with a shared config (single quotes,
120 columns, trailing commas), .prettierignore, .editorconfig and the
`format` / `format:check` scripts, then formats all TypeScript,
JavaScript, CSS, JSON and YAML sources.

Purely mechanical: no behaviour change. Typecheck passes, the vitest
suite and the 74 IDE node tests produce the same results as before
(socket-binding tests still cannot run inside this sandbox).
Previously the longest source line was ~3000 characters; reviewing the
following semantic changes now produces readable diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:32:43 +08:00

221 lines
7.7 KiB
JavaScript

'use strict';
const {
Uint8ArrayReadBuffer,
Uint8ArrayWriteBuffer,
} = require('@theia/core/lib/common/message-rpc/uint8-array-message-buffer');
const {
MsgPackMessageDecoder,
MsgPackMessageEncoder,
} = require('@theia/core/lib/common/message-rpc/rpc-message-encoder');
const MAX_BATCH_MESSAGES = 10_000;
const MAX_BATCH_BYTES = 64 * 1024 * 1024;
const MAX_MESSAGE_BYTES = 16 * 1024 * 1024;
// filterPluginRpc is invoked once per batch. Keep synthetic DAP response sequence
// numbers increasing across batches for the lifetime of this backend process.
let pluginDapResponseSequence = 0;
function rejected(code) {
return Object.assign(new Error(code), { code });
}
// Theia's ReadBuffer intentionally trusts frame lengths. Validate every boundary
// first: a Uint8Array may be a view into a larger websocket backing buffer.
function readLength(bytes, cursor, maximum) {
let value = 0;
for (let shift = 0; shift <= 28; shift += 7) {
if (cursor.offset >= bytes.byteLength) throw rejected('MALFORMED_PLUGIN_RPC');
const byte = bytes[cursor.offset++];
value += (byte & 127) * 2 ** shift;
if (value > maximum) throw rejected('RPC_BATCH_LIMIT');
if (byte < 128) return value;
}
throw rejected('MALFORMED_PLUGIN_RPC');
}
function decodeBatch(payload) {
if (!(payload instanceof Uint8Array)) throw rejected('MALFORMED_PLUGIN_RPC');
if (payload.byteLength > MAX_BATCH_BYTES) throw rejected('RPC_BATCH_LIMIT');
const cursor = { offset: 0 };
const count = readLength(payload, cursor, MAX_BATCH_MESSAGES);
const messages = [];
const decoder = new MsgPackMessageDecoder();
for (let index = 0; index < count; index++) {
const length = readLength(payload, cursor, MAX_MESSAGE_BYTES);
if (length === 0 || length > payload.byteLength - cursor.offset) throw rejected('MALFORMED_PLUGIN_RPC');
const bytes = payload.slice(cursor.offset, cursor.offset + length);
cursor.offset += length;
const inner = { offset: 0 };
const encodedLength = readLength(bytes, inner, MAX_MESSAGE_BYTES);
if (encodedLength !== bytes.byteLength - inner.offset) throw rejected('MALFORMED_PLUGIN_RPC');
let message;
try {
message = decoder.parse(new Uint8ArrayReadBuffer(bytes));
} catch {
throw rejected('UNDECODABLE_PLUGIN_RPC');
}
if (!message || ![1, 2, 3, 4, 5].includes(message.type)) throw rejected('MALFORMED_PLUGIN_RPC');
if ((message.type !== 2 || message.id !== undefined) && (!Number.isSafeInteger(message.id) || message.id < 0))
throw rejected('MALFORMED_PLUGIN_RPC');
if (
(message.type === 1 || message.type === 2) &&
(typeof message.method !== 'string' || !Array.isArray(message.args))
)
throw rejected('MALFORMED_PLUGIN_RPC');
messages.push({ bytes, message });
}
if (cursor.offset !== payload.byteLength) throw rejected('MALFORMED_PLUGIN_RPC');
return messages;
}
function encodeBatch(messages) {
if (messages.length === 0) return null;
const writer = new Uint8ArrayWriteBuffer();
writer.writeLength(messages.length);
for (const message of messages) writer.writeBytes(message);
const encoded = writer.getCurrentContents();
writer.dispose();
return encoded;
}
function gated(message) {
if (message.type !== 1 && message.type !== 2) return false;
return (
(message.args[0] === 'DebugExt' && ['$createDebugSession', '$terminateDebugSession'].includes(message.method)) ||
(message.args[0] === 'ConnectionExt' && ['$sendMessage', '$deleteConnection'].includes(message.method))
);
}
function assertSynchronously(assertControl) {
const result = assertControl();
// The backend guard must make its authorization decision before forwarding.
if (result === false || (result && typeof result.then === 'function')) throw rejected('DEBUG_CONTROL_REQUIRED');
}
function dapRequest(value) {
if (typeof value !== 'string') return null;
let request;
try {
request = JSON.parse(value);
} catch {
return null;
}
if (
!request ||
Array.isArray(request) ||
request.type !== 'request' ||
!Number.isSafeInteger(request.seq) ||
request.seq < 0 ||
typeof request.command !== 'string' ||
!request.command
)
return null;
return request;
}
function pluginDapDenial(message, encoder) {
if (message.args[0] !== 'ConnectionExt' || message.method !== '$sendMessage') return null;
const sessionId = message.args[1];
if (typeof sessionId !== 'string' || !sessionId || sessionId.length > 1024) return null;
const request = dapRequest(message.args[2]);
if (!request) return null;
const response = {
seq: ++pluginDapResponseSequence,
type: 'response',
request_seq: request.seq,
command: request.command,
success: false,
message: 'WishForge debug controller lease required',
};
const writer = new Uint8ArrayWriteBuffer();
// PluginChannel.send discards its RPC promise. ReplyErr alone leaves the DAP
// request pending, so deliver a real DAP failure through the frontend channel.
encoder.notification(writer, '$sendMessage', ['ConnectionMain', sessionId, JSON.stringify(response)]);
const bytes = writer.getCurrentContents();
writer.dispose();
return bytes;
}
/** Filter a real Theia BatchingChannel frame without forwarding any undecoded bytes. */
function filterPluginRpc(payload, assertControl) {
if (typeof assertControl !== 'function') throw rejected('DEBUG_GUARD_REQUIRED');
const messages = decodeBatch(payload);
const forwarded = [];
const replies = [];
const encoder = new MsgPackMessageEncoder();
let denied = 0;
for (const { bytes, message } of messages) {
if (gated(message)) {
try {
assertSynchronously(assertControl);
} catch {
denied++;
if (message.type === 1) {
const writer = new Uint8ArrayWriteBuffer();
encoder.replyErr(writer, message.id, rejected('DEBUG_CONTROL_REQUIRED'));
replies.push(writer.getCurrentContents());
writer.dispose();
}
const dapReply = pluginDapDenial(message, encoder);
if (dapReply) replies.push(dapReply);
continue;
}
}
forwarded.push(bytes);
}
return { forwarded: encodeBatch(forwarded), replies: encodeBatch(replies), denied };
}
/** Wrap the native ForwardingDebugChannel; authorization is checked per incoming DAP message. */
function guardDebugChannel(raw, assertControl) {
if (typeof assertControl !== 'function') throw rejected('DEBUG_GUARD_REQUIRED');
let responseSequence = 0;
return {
send: message => raw.send(message),
onClose: callback => raw.onClose(callback),
onError: callback => raw.onError(callback),
close: () => raw.close(),
onMessage: callback =>
raw.onMessage(message => {
try {
assertSynchronously(assertControl);
} catch {
let request;
try {
request = JSON.parse(message);
} catch {
raw.close();
return;
}
if (
!request ||
request.type !== 'request' ||
!Number.isSafeInteger(request.seq) ||
request.seq < 0 ||
typeof request.command !== 'string' ||
!request.command
) {
raw.close();
return;
}
raw.send(
JSON.stringify({
seq: ++responseSequence,
type: 'response',
request_seq: request.seq,
command: request.command,
success: false,
message: 'WishForge debug controller lease required',
}),
);
return;
}
// Adapter callback errors are not authorization failures and must not be swallowed.
callback(message);
}),
};
}
module.exports = { filterPluginRpc, guardDebugChannel, MAX_BATCH_MESSAGES, MAX_BATCH_BYTES, MAX_MESSAGE_BYTES };