278 lines
14 KiB
JavaScript
278 lines
14 KiB
JavaScript
'use strict';
|
|
const { createAdminValidators } = require('./admin-validate');
|
|
|
|
/**
|
|
* Allowlist + argument-shape validation for renderer → core requests.
|
|
* The renderer may only call these bridge commands; `shutdown`, `audio_frame` and `audio_end`
|
|
* are main-owned (audio has its own binary IPC channel). Unknown keys are rejected like the core does.
|
|
*/
|
|
|
|
class ValidationError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.code = 'bad_request';
|
|
}
|
|
}
|
|
|
|
const CONTROL_CHARS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
|
|
|
|
const str = (min, max, { multiline = false, maxBytes } = {}) => (value, key) => {
|
|
if (typeof value !== 'string') throw new ValidationError(`${key}: expected a string`);
|
|
if (value.length < min || value.length > max) throw new ValidationError(`${key}: invalid length`);
|
|
if (maxBytes !== undefined && Buffer.byteLength(value, 'utf8') > maxBytes) throw new ValidationError(`${key}: too long`);
|
|
if (multiline ? CONTROL_CHARS.test(value) : /[\u0000-\u001f\u007f]/.test(value)) {
|
|
throw new ValidationError(`${key}: control characters are not allowed`);
|
|
}
|
|
return value;
|
|
};
|
|
|
|
const posInt = (value, key) => {
|
|
if (!Number.isSafeInteger(value) || value < 0) throw new ValidationError(`${key}: expected a non-negative integer`);
|
|
return value;
|
|
};
|
|
|
|
const bool = (value, key) => {
|
|
if (typeof value !== 'boolean') throw new ValidationError(`${key}: expected true/false`);
|
|
return value;
|
|
};
|
|
|
|
const oneOf = (...allowed) => (value, key) => {
|
|
if (!allowed.includes(value)) throw new ValidationError(`${key}: value not allowed`);
|
|
return value;
|
|
};
|
|
|
|
const optional = (check) => {
|
|
const wrapped = (value, key) => check(value, key);
|
|
wrapped.optional = true;
|
|
return wrapped;
|
|
};
|
|
|
|
function isPlainObject(value) {
|
|
return value !== null && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype;
|
|
}
|
|
|
|
function shape(spec) {
|
|
return (args) => {
|
|
if (args === undefined || args === null) args = {};
|
|
if (!isPlainObject(args)) throw new ValidationError('args: expected an object');
|
|
for (const key of Object.keys(args)) {
|
|
if (!Object.prototype.hasOwnProperty.call(spec, key)) throw new ValidationError(`${key}: unknown argument`);
|
|
}
|
|
const out = {};
|
|
for (const [key, check] of Object.entries(spec)) {
|
|
const value = args[key];
|
|
if (value === undefined) {
|
|
if (!check.optional) throw new ValidationError(`${key}: required argument`);
|
|
continue;
|
|
}
|
|
out[key] = check(value, key);
|
|
}
|
|
return out;
|
|
};
|
|
}
|
|
|
|
const streamId = str(1, 256);
|
|
const SIGNAL_COMMANDS = new Set(['answer', 'iceCandidate', 'reconnectOffer']);
|
|
|
|
function signalJson(value) {
|
|
if (!isPlainObject(value)) throw new ValidationError('json: expected an object');
|
|
const keys = Object.keys(value);
|
|
if (keys.length !== 2 || !keys.includes('cmd') || !keys.includes('args')) throw new ValidationError('json: expected exactly the fields cmd and args');
|
|
if (!SIGNAL_COMMANDS.has(value.cmd)) throw new ValidationError('json.cmd: signalling command not allowed');
|
|
const args = value.args;
|
|
if (!isPlainObject(args)) throw new ValidationError('json.args: expected an object');
|
|
if (value.cmd === 'answer') {
|
|
shape({ answer: str(1, 60000, { multiline: true }) })(args);
|
|
} else if (value.cmd === 'reconnectOffer') {
|
|
shape({ offer: str(1, 60000, { multiline: true }) })(args);
|
|
} else {
|
|
shape({
|
|
mLine: posInt,
|
|
mid: str(0, 64),
|
|
sdp: str(0, 2048),
|
|
})(args);
|
|
}
|
|
const serialized = JSON.stringify(value);
|
|
if (Buffer.byteLength(serialized, 'utf8') > 60 * 1024) throw new ValidationError('json: larger than 60 KiB');
|
|
return JSON.parse(serialized);
|
|
}
|
|
|
|
const boundedInt = (min, max) => (value, key) => {
|
|
if (!Number.isSafeInteger(value) || value < min || value > max) throw new ValidationError(`${key}: integer out of range`);
|
|
return value;
|
|
};
|
|
const modifierDb = (value, key) => {
|
|
if (typeof value !== 'number' || !Number.isFinite(value) || value < -200 || value > 10 || !Number.isInteger(value * 2)) throw new ValidationError(`${key}: expected dB -200..10 in 0.5 steps`);
|
|
return value;
|
|
};
|
|
/** Server-side file path: absolute within the channel's file area ("/…"), no control characters. */
|
|
const filePath = (value, key) => {
|
|
str(1, 512)(value, key);
|
|
if (!value.startsWith('/')) throw new ValidationError(`${key}: expected a path starting with /`);
|
|
return value;
|
|
};
|
|
const channelPassword = str(0, 255);
|
|
const clientTarget = { client_id: boundedInt(1, 65535), uid: str(1, 128) };
|
|
const menuActionArgs = {
|
|
poke: { message: str(1, 1024, { maxBytes: 1024 }) },
|
|
connection_info: {}, commander: { enabled: bool },
|
|
move_to_own_channel: { password: optional(str(0, 1024, { maxBytes: 1024 })) },
|
|
delete_avatar: {},
|
|
server_group: { group_id: boundedInt(1, Number.MAX_SAFE_INTEGER), enabled: bool },
|
|
channel_group: { group_id: boundedInt(1, Number.MAX_SAFE_INTEGER), channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER) },
|
|
client_permissions: {}, channel_permissions: { channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER) },
|
|
set_client_permission: { permission_id: boundedInt(1, 0xffffffff), value: (v,k) => v === null ? null : boundedInt(-2147483648,2147483647)(v,k), skip: bool },
|
|
set_channel_permission: { channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER), permission_id: boundedInt(1,0xffffffff), value: (v,k) => v === null ? null : boundedInt(-2147483648,2147483647)(v,k) },
|
|
kick_channel: { reason: str(0,1024,{ maxBytes:1024 }) },
|
|
kick_server: { reason: str(0,1024,{ maxBytes:1024 }) },
|
|
ban: { reason: str(0,1024,{ maxBytes:1024 }), duration: boundedInt(0,0xffffffff) },
|
|
volume: { db: modifierDb, muted: bool },
|
|
avatar: { data: (v,k) => {
|
|
str(1,174764)(v,k);
|
|
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(v)) throw new ValidationError('avatar: invalid base64');
|
|
const bytes=Buffer.from(v,'base64');
|
|
if (bytes.length > 128*1024 || !(bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.subarray(0,3).equals(Buffer.from([255,216,255])))) throw new ValidationError('avatar: expected PNG/JPEG <=128 KiB');
|
|
return v;
|
|
} },
|
|
};
|
|
function clientAction(args) {
|
|
if (!isPlainObject(args) || !Object.prototype.hasOwnProperty.call(menuActionArgs,args.action)) throw new ValidationError('action: unknown client action');
|
|
return shape({ ...clientTarget, generation: boundedInt(1,Number.MAX_SAFE_INTEGER), action: oneOf(args.action), ...menuActionArgs[args.action] })(args);
|
|
}
|
|
|
|
const streamMetadata = {
|
|
name: str(1, 200), type: oneOf(1, 2, 3), accessibility: oneOf(1, 2, 3), mode: oneOf(1),
|
|
bitrate: boundedInt(100, 100000), viewer_limit: boundedInt(0, 65535), audio: bool,
|
|
};
|
|
|
|
const boundedArray = (max, item) => (value, key) => {
|
|
if (!Array.isArray(value) || value.length > max) throw new ValidationError(`${key}: expected at most ${max} items`);
|
|
return value.map((v, i) => item(v, `${key}[${i}]`));
|
|
};
|
|
function whisperTarget(value, key) {
|
|
if (!isPlainObject(value)) throw new ValidationError(`${key}: expected an object`);
|
|
switch (value.kind) {
|
|
case 'list': return shape({ kind: oneOf('list'), entries: boundedArray(1024, shape({ type: boundedInt(0, 255), uuid: str(0, 256), name: str(0, 8192, { maxBytes: 8192 }) })) })(value);
|
|
case 'group': return shape({ kind: oneOf('group'), group_type: boundedInt(0, 3), target_mode: boundedInt(0, 6), group_id: str(0, 20), server_uuid: str(0, 256) })(value);
|
|
case 'ids': return shape({ kind: oneOf('ids'), clients: boundedArray(255, shape({ id: boundedInt(1, 65535), uid: (u, k) => u === null ? null : str(1, 128)(u, k) })), channel_ids: boundedArray(255, boundedInt(1, Number.MAX_SAFE_INTEGER)) })(value);
|
|
default: throw new ValidationError(`${key}.kind: expected list, group or ids`);
|
|
}
|
|
}
|
|
|
|
const COMMANDS = {
|
|
...createAdminValidators({ shape, bool, boundedInt, optional, oneOf, isPlainObject, ValidationError }),
|
|
whisper_start: shape({ epoch: boundedInt(1, 0xffffffff), target: whisperTarget }),
|
|
whisper_stop: shape({ epoch: boundedInt(1, 0xffffffff) }),
|
|
set_whisper_receive: shape({ mode: oneOf('allow_all', 'deny_all') }),
|
|
profile_get: shape({}),
|
|
profile_create: shape({ nickname: str(1, 64) }),
|
|
rename: shape({ nickname: str(1, 64) }),
|
|
connect: shape({
|
|
address: str(1, 255),
|
|
server_password: optional(str(0, 255)),
|
|
channel: optional(str(1, 512)),
|
|
channel_password: optional(str(0, 255)),
|
|
identity_id: optional((v, k) => { if (typeof v !== 'string' || !/^[A-Za-z0-9+/]{27}=$/.test(v)) throw new ValidationError(`${k}: invalid identity UID`); return v; }),
|
|
// Per-connection override (bookmark nickname); same bound as rename, the core enforces 3-30 trimmed chars.
|
|
nickname: optional(str(1, 64)),
|
|
}),
|
|
disconnect: shape({ message: optional(str(0, 80)) }),
|
|
join_channel: shape({ channel_id: posInt, password: optional(str(0, 255)) }),
|
|
send_text: (args) => {
|
|
const out = shape({
|
|
target: oneOf('channel', 'server', 'client'),
|
|
client_id: optional(posInt),
|
|
expected_client_uid: optional(str(1, 128)),
|
|
message: str(1, 8192, { multiline: true, maxBytes: 8192 }),
|
|
})(args);
|
|
if ((out.target === 'client') !== (out.client_id !== undefined)) {
|
|
throw new ValidationError('client_id: required for private messages only');
|
|
}
|
|
if ((out.target === 'client') !== (out.expected_client_uid !== undefined)) throw new ValidationError('expected_client_uid: required for private messages only');
|
|
return out;
|
|
},
|
|
set_audio: shape({ input_muted: optional(bool), output_muted: optional(bool) }),
|
|
set_transmit: (args) => {
|
|
const out = shape({ mode: oneOf('direct', 'vad'), detector: optional(oneOf('automatic', 'volume_gate', 'hybrid')), sensitivity: optional(oneOf('high', 'normal', 'low')), level_db: optional(boundedInt(-50, 50)) })(args);
|
|
if (out.mode === 'direct' && (out.detector !== undefined || out.sensitivity !== undefined || out.level_db !== undefined)) throw new ValidationError('set_transmit: detector, sensitivity and level_db apply to vad only');
|
|
return out;
|
|
},
|
|
set_playback_dsp: shape({ agc: bool }),
|
|
stream_list: shape({ client_id: optional(posInt) }),
|
|
stream_join: shape({ stream_id: streamId, client_id: posInt, message: optional(str(0, 200)) }),
|
|
stream_signal: shape({ stream_id: streamId, client_id: posInt, json: signalJson }),
|
|
stream_leave: shape({ stream_id: streamId, client_id: posInt }),
|
|
stream_setup: shape(streamMetadata),
|
|
stream_update: shape({ stream_id: streamId, ...streamMetadata }),
|
|
stream_stop: shape({ stream_id: streamId }),
|
|
stream_respond: (args) => {
|
|
const out = shape({ stream_id: streamId, client_id: boundedInt(1, 65535), decision: bool,
|
|
offer: str(0, 60000, { multiline: true, maxBytes: 60000 }), message: str(0, 200) })(args);
|
|
if (out.decision !== (out.offer.length > 0)) throw new ValidationError('offer: required only for acceptance');
|
|
return out;
|
|
},
|
|
stream_remove: shape({ stream_id: streamId, client_id: boundedInt(1, 65535) }),
|
|
fetch_icon: shape({
|
|
icon_id: (v, k) => {
|
|
if (!Number.isSafeInteger(v) || v <= 0 || v > 0xffffffff) throw new ValidationError(`${k}: expected an icon id`);
|
|
return v;
|
|
},
|
|
}),
|
|
fetch_avatar: shape({ client_id: posInt }),
|
|
fetch_banner: shape({ channel_id: posInt }),
|
|
fetch_server_banner: shape({}),
|
|
client_context: shape(clientTarget),
|
|
client_action: clientAction,
|
|
// Local recording (core/src/recording_session.rs). The folder must be the one chosen in the main-owned
|
|
// folder dialog (recording-main.js); the renderer cannot name another directory.
|
|
recording_start: (args, context) => shape({
|
|
directory: (v, key) => {
|
|
const approved = context.approvedRecordingDirectory?.() ?? null;
|
|
if (typeof v !== 'string' || approved === null || v !== approved) throw new ValidationError(`${key}: folder was not chosen in the folder dialog`);
|
|
return v;
|
|
},
|
|
mode: oneOf(1, 2, 3),
|
|
label: optional(str(19, 19)),
|
|
})(args),
|
|
recording_stop: shape({}),
|
|
recording_pause: shape({}),
|
|
recording_resume: shape({}),
|
|
recording_status: shape({}),
|
|
recording_info: shape({}),
|
|
recording_waveform: shape({ track_id: posInt, from_bucket: posInt }),
|
|
// Server file browser (legacy file transfer). file_download/file_upload carry host paths and are main-only
|
|
// (files-main.js), so they are deliberately absent here.
|
|
file_list: shape({ channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER), path: filePath, channel_password: optional(channelPassword) }),
|
|
file_mkdir: shape({ channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER), path: filePath, channel_password: optional(channelPassword) }),
|
|
file_rename: shape({
|
|
channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER), from: filePath, to: filePath, channel_password: optional(channelPassword),
|
|
target_channel_id: optional(boundedInt(1, Number.MAX_SAFE_INTEGER)), target_channel_password: optional(channelPassword),
|
|
}),
|
|
file_delete: shape({
|
|
channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER),
|
|
paths: (v, key) => {
|
|
if (!Array.isArray(v) || v.length < 1 || v.length > 100) throw new ValidationError(`${key}: expected 1-100 paths`);
|
|
return v.map((p, i) => filePath(p, `${key}[${i}]`));
|
|
},
|
|
channel_password: optional(channelPassword),
|
|
}),
|
|
file_cancel: shape({ transfer_id: boundedInt(1, 0xffffffff) }),
|
|
file_transfers: shape({}),
|
|
file_fetch_image: shape({ channel_id: boundedInt(1, Number.MAX_SAFE_INTEGER), path: filePath }),
|
|
};
|
|
|
|
/**
|
|
* Returns sanitized args or throws ValidationError. `context` supplies main-owned facts some commands are
|
|
* checked against (approvedRecordingDirectory()).
|
|
*/
|
|
function validateRequest(cmd, args, context = {}) {
|
|
if (typeof cmd !== 'string' || !Object.prototype.hasOwnProperty.call(COMMANDS, cmd)) {
|
|
const err = new ValidationError('Command not allowed');
|
|
err.code = 'unknown_command';
|
|
throw err;
|
|
}
|
|
return COMMANDS[cmd](args, context);
|
|
}
|
|
|
|
module.exports = { validateRequest, ValidationError, RENDERER_COMMANDS: Object.keys(COMMANDS) };
|