mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-01 00:42:49 +08:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2d9115782 | ||
|
|
54a580dc39 | ||
|
|
abecd4e14d | ||
|
|
d054c9bba4 | ||
|
|
deff678cfa | ||
|
|
512366bc94 | ||
|
|
5f9950a96b | ||
|
|
8c0d0a3d1d |
No files matched your search
+52
-5
@@ -63,6 +63,27 @@ async fn ft_pace(limit: &AtomicU64, bytes: usize, started: std::time::Instant) {
|
||||
tokio::time::sleep(rest).await;
|
||||
}
|
||||
}
|
||||
/// Upload bodies held at once (waiting for the server or being sent, which
|
||||
/// ftlimit can stretch to days). Without a cap a client could park any
|
||||
/// amount of memory in the connector.
|
||||
const MAX_UPLOADS_HELD: u64 = 2 * MAX_UPLOAD_BYTES;
|
||||
static UPLOADS_HELD: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
/// A share of MAX_UPLOADS_HELD, given back when dropped.
|
||||
struct HeldUpload(u64);
|
||||
impl Drop for HeldUpload {
|
||||
fn drop(&mut self) {
|
||||
UPLOADS_HELD.fetch_sub(self.0, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
fn hold_upload(size: u64) -> Option<HeldUpload> {
|
||||
UPLOADS_HELD
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |held| (held + size <= MAX_UPLOADS_HELD).then_some(held + size))
|
||||
.ok()
|
||||
.map(|_| HeldUpload(size))
|
||||
}
|
||||
const UPLOADS_BUSY: &str = "Upload refused: too many uploads in progress, try again when they are done";
|
||||
|
||||
/// Half-received chunked uploads per connection - each can hold up to
|
||||
/// MAX_UPLOAD_BYTES until it completes.
|
||||
const MAX_PARTIAL_UPLOADS: usize = 4;
|
||||
@@ -1201,7 +1222,7 @@ async fn run(args: Args) -> Result<()> {
|
||||
// (StreamItem::FileDownload/FileUpload below); these just remember which
|
||||
// request that stream belongs to.
|
||||
let mut pending_downloads: HashMap<u16, (u64, String)> = HashMap::new();
|
||||
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>)> = HashMap::new();
|
||||
let mut pending_uploads: HashMap<u16, (u64, String, Vec<u8>, HeldUpload)> = HashMap::new();
|
||||
// Chunked uploads still arriving from the browser: (cid, path) -> (total size, bytes so far).
|
||||
let mut partial_uploads: HashMap<(u64, String), (u64, Vec<u8>)> = HashMap::new();
|
||||
// Set by "permissionlist" while waiting to emit the full permission
|
||||
@@ -2333,9 +2354,19 @@ async fn run(args: Args) -> Result<()> {
|
||||
) {
|
||||
(Ok(cid), Ok(bytes)) => {
|
||||
let size = bytes.len() as u64;
|
||||
let held = if size > MAX_UPLOAD_BYTES { None } else { hold_upload(size) };
|
||||
let Some(held) = held else {
|
||||
let message = if size > MAX_UPLOAD_BYTES {
|
||||
format!("Upload refused: {path} is larger than {} KiB", MAX_UPLOAD_BYTES >> 10)
|
||||
} else {
|
||||
UPLOADS_BUSY.into()
|
||||
};
|
||||
emit(&Event::TransferError { message, cid, path: path.to_string() });
|
||||
continue;
|
||||
};
|
||||
match con.upload_file(ChannelId(cid), path, None, size, true, false) {
|
||||
Ok(handle) => {
|
||||
pending_uploads.insert(handle.0, (cid, path.to_string(), bytes));
|
||||
pending_uploads.insert(handle.0, (cid, path.to_string(), bytes, held));
|
||||
}
|
||||
Err(e) => emit(&Event::TransferError {
|
||||
message: format!("Upload failed: {e}"),
|
||||
@@ -2349,9 +2380,13 @@ async fn run(args: Args) -> Result<()> {
|
||||
} else if let Some(rest) = l.strip_prefix("ftuploadchunk ") {
|
||||
match take_upload_chunk(&mut partial_uploads, rest) {
|
||||
Ok(Some((cid, path, bytes))) => {
|
||||
let Some(held) = hold_upload(bytes.len() as u64) else {
|
||||
emit(&Event::TransferError { message: UPLOADS_BUSY.into(), cid, path });
|
||||
continue;
|
||||
};
|
||||
match con.upload_file(ChannelId(cid), &path, None, bytes.len() as u64, true, false) {
|
||||
Ok(handle) => {
|
||||
pending_uploads.insert(handle.0, (cid, path, bytes));
|
||||
pending_uploads.insert(handle.0, (cid, path, bytes, held));
|
||||
}
|
||||
Err(e) => emit(&Event::TransferError { message: format!("Upload failed: {e}"), cid, path }),
|
||||
}
|
||||
@@ -3244,10 +3279,11 @@ async fn run(args: Args) -> Result<()> {
|
||||
}
|
||||
}
|
||||
Some(Ok(StreamItem::FileUpload(handle, result))) => {
|
||||
if let Some((cid, path, data)) = pending_uploads.remove(&handle.0) {
|
||||
if let Some((cid, path, data, held)) = pending_uploads.remove(&handle.0) {
|
||||
let seek = result.seek_position as usize;
|
||||
let mut stream = result.stream;
|
||||
tokio::spawn(async move {
|
||||
let _held = held;
|
||||
let slice = if seek < data.len() { &data[seek..] } else { &[][..] };
|
||||
for piece in slice.chunks(TRANSFER_CHUNK_BYTES) {
|
||||
let started = std::time::Instant::now();
|
||||
@@ -3264,7 +3300,7 @@ async fn run(args: Args) -> Result<()> {
|
||||
Some(Ok(StreamItem::FiletransferFailed(handle, e))) => {
|
||||
let failed = pending_downloads
|
||||
.remove(&handle.0)
|
||||
.or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, _)| (cid, path)));
|
||||
.or_else(|| pending_uploads.remove(&handle.0).map(|(cid, path, ..)| (cid, path)));
|
||||
if let Some((cid, path)) = failed {
|
||||
emit(&Event::TransferError { message: format!("File transfer failed: {e}"), cid, path });
|
||||
}
|
||||
@@ -3331,6 +3367,17 @@ async fn run(args: Args) -> Result<()> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn held_uploads_are_capped_and_released() {
|
||||
let a = hold_upload(MAX_UPLOAD_BYTES).unwrap();
|
||||
let b = hold_upload(MAX_UPLOAD_BYTES).unwrap();
|
||||
assert!(hold_upload(1).is_none());
|
||||
drop(a);
|
||||
assert!(hold_upload(MAX_UPLOAD_BYTES).is_some());
|
||||
drop(b);
|
||||
assert_eq!(UPLOADS_HELD.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
fn chunk(offset: u64, total: u64, data: &[u8]) -> String {
|
||||
format!("7\t{offset}\t{total}\t/a b.txt\t{}", base64::engine::general_purpose::STANDARD.encode(data))
|
||||
}
|
||||
|
||||
@@ -31,6 +31,10 @@ const KEEPALIVE_EVERY: Duration = Duration::from_secs(3);
|
||||
const RESEND_AFTER: Duration = Duration::from_secs(1);
|
||||
const MAX_RESENDS: u16 = 10;
|
||||
const SERVER_TIMEOUT: Duration = Duration::from_secs(20);
|
||||
// Caps what a (hostile) server can make us buffer: packets ahead of the next
|
||||
// expected one, and the size of one reassembled fragmented message.
|
||||
const REORDER_WINDOW: u32 = 256;
|
||||
const MAX_FRAGMENTS_BYTES: usize = 1 << 20;
|
||||
/// Speex narrowband: 20 ms frames of 160 samples at 8 kHz, 5 per voice packet.
|
||||
const SPEEX_FRAME: usize = 160;
|
||||
const FRAMES_PER_PACKET: usize = 5;
|
||||
@@ -675,6 +679,10 @@ impl Ts2 {
|
||||
match u16_at(b, 0) {
|
||||
0xbef0 if b.len() >= 24 => {
|
||||
let seq = u32_at(b, 12);
|
||||
// Too far ahead: no ack, so a real server resends it later.
|
||||
if seq >= self.next_in && seq - self.next_in >= REORDER_WINDOW {
|
||||
return Ok(true);
|
||||
}
|
||||
let mut ack = Vec::with_capacity(16);
|
||||
ack.extend_from_slice(&0xbef1u16.to_le_bytes());
|
||||
ack.extend_from_slice(&0u16.to_le_bytes());
|
||||
@@ -695,6 +703,9 @@ impl Ts2 {
|
||||
if self.fragments.is_empty() {
|
||||
self.fragment_type = typ;
|
||||
}
|
||||
if self.fragments.len() + p.len() - 24 > MAX_FRAGMENTS_BYTES {
|
||||
bail!("The TeamSpeak 2 server sent an oversized message");
|
||||
}
|
||||
self.fragments.extend_from_slice(&p[24..]);
|
||||
if fragment != 0 {
|
||||
continue;
|
||||
@@ -922,6 +933,40 @@ which this gateway does not connect to. (Self-hosting admin? Set ALLOW_PRIVATE_T
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
// A hostile server can't make the connector buffer without bound.
|
||||
#[tokio::test]
|
||||
async fn reorder_and_fragment_buffers_are_capped() {
|
||||
let peer = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let sock = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
sock.connect(peer.local_addr().unwrap()).await.unwrap();
|
||||
let mut ts = Ts2 {
|
||||
sock, session: 0, client_id: 0, conn_counter: 0, seq: 0, outbox: VecDeque::new(), in_flight: None,
|
||||
next_in: 1, early: BTreeMap::new(), fragments: Vec::new(), fragment_type: 0, channels: BTreeMap::new(),
|
||||
players: BTreeMap::new(), lists_done: false, speakers: HashMap::new(), talking: HashSet::new(),
|
||||
encoder: None, voice_counter: 0, voice_conversation: 0, last_audio_in: None, codec_warned: false,
|
||||
};
|
||||
let packet = |seq: u32, fragment: u16, body: usize| {
|
||||
let mut p = vec![0u8; 24 + body];
|
||||
p[0..2].copy_from_slice(&0xbef0u16.to_le_bytes());
|
||||
p[12..16].copy_from_slice(&seq.to_le_bytes());
|
||||
p[18..20].copy_from_slice(&fragment.to_le_bytes());
|
||||
p
|
||||
};
|
||||
for seq in 2..2000 {
|
||||
ts.on_datagram(&packet(seq, 0, 100)).await.unwrap();
|
||||
}
|
||||
assert!(ts.early.len() < REORDER_WINDOW as usize);
|
||||
ts.early.clear();
|
||||
let mut result = Ok(true);
|
||||
for _ in 0..100 {
|
||||
result = ts.on_datagram(&packet(ts.next_in, 1, 60_000)).await;
|
||||
if result.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(result.is_err() && ts.fragments.len() <= MAX_FRAGMENTS_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crc_matches_zlib() {
|
||||
assert_eq!(crc32(b"123456789"), 0xCBF4_3926);
|
||||
|
||||
@@ -11,11 +11,10 @@ import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import type { TLSSocket } from "node:tls";
|
||||
import { createHash, createHmac, randomBytes, scrypt, timingSafeEqual } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { rename, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import qrcode from "qrcode-generator";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
import { describeSettings, updateSettings, validate } from "./config.js";
|
||||
|
||||
const ADMIN_USER = process.env.ADMIN_USER ?? "";
|
||||
@@ -36,9 +35,7 @@ try {
|
||||
}
|
||||
const totpSecret = () => auth.totpSecret ?? ENV_TOTP;
|
||||
async function saveAuth(next: typeof auth) {
|
||||
const tmp = `${AUTH_FILE}.${process.pid}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
|
||||
await rename(tmp, AUTH_FILE);
|
||||
await writeFileAtomic(AUTH_FILE, JSON.stringify(next, null, 2), 0o600);
|
||||
auth = next;
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
// Deliberately absent: CONNECTOR_BIN (would be code execution), ALLOW_PRIVATE_TARGETS (opens the
|
||||
// operator's LAN), and the admin credentials themselves.
|
||||
import { readFileSync } from "node:fs";
|
||||
import { rename, writeFile } from "node:fs/promises";
|
||||
import { writeFileAtomic } from "./net.js";
|
||||
import path from "node:path";
|
||||
|
||||
export type SettingKind = "number" | "bool" | "list" | "text" | "secret";
|
||||
@@ -116,9 +116,7 @@ export async function updateSettings(changes: Record<string, string | null>): Pr
|
||||
if (value === null) delete next[key];
|
||||
else next[key] = value;
|
||||
}
|
||||
const tmp = `${CONFIG_FILE}.${process.pid}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(next, null, 2), { mode: 0o600 });
|
||||
await rename(tmp, CONFIG_FILE);
|
||||
await writeFileAtomic(CONFIG_FILE, JSON.stringify(next, null, 2), 0o600);
|
||||
overrides = next;
|
||||
apply();
|
||||
}
|
||||
|
||||
+30
-16
@@ -50,8 +50,10 @@ const allowedServers = () =>
|
||||
// as-is. Deliberately not full URL parsing - `host` here is never a URL.
|
||||
function stripPort(host: string): string {
|
||||
if (host.startsWith("[")) {
|
||||
const end = host.indexOf("]");
|
||||
return end === -1 ? host : host.slice(1, end);
|
||||
// Only "[v6]" or "[v6]:port"; anything after "]" would otherwise be
|
||||
// ignored here but still reach the connector ("[allowed]evil.tld").
|
||||
const m = /^\[([^\]]*)\](?::\d+)?$/.exec(host);
|
||||
return m ? m[1] : host;
|
||||
}
|
||||
const i = host.lastIndexOf(":");
|
||||
return i !== -1 && /^\d+$/.test(host.slice(i + 1)) ? host.slice(0, i) : host;
|
||||
@@ -708,6 +710,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
|
||||
// One browser WebSocket ↔ one Rust connector. Multi-join in the UI opens
|
||||
// multiple /ws connections in parallel (one per server tab).
|
||||
let connection: Ts3Connection | undefined;
|
||||
// Message handlers are async and run concurrently, so a connect can still be
|
||||
// awaiting when a newer connect or the close arrives. Only the newest
|
||||
// connect on an open socket may spawn a connector, else one leaks.
|
||||
let closed = false;
|
||||
let connectGen = 0;
|
||||
|
||||
// Full: accept and say so, since a browser can't read why an upgrade was refused.
|
||||
if (maxConnections() > 0 && wss.clients.size > maxConnections()) {
|
||||
@@ -791,17 +798,16 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
|
||||
}
|
||||
socket.send(JSON.stringify({ type: "turnstilePass", pass: issuePass(ip) }));
|
||||
}
|
||||
// Replacing a connection on the same socket: tear down the previous
|
||||
// connector so we don't leak processes.
|
||||
if (connection) {
|
||||
try {
|
||||
await connection.disconnect();
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
liveConnections.delete(connection);
|
||||
connection = undefined;
|
||||
// Replacing a connection on the same socket: take the previous one
|
||||
// out before awaiting its teardown, so no other handler sees it.
|
||||
const gen = ++connectGen;
|
||||
const prev = connection;
|
||||
connection = undefined;
|
||||
if (prev) {
|
||||
liveConnections.delete(prev);
|
||||
await prev.disconnect().catch(() => {});
|
||||
}
|
||||
if (closed || gen !== connectGen) break;
|
||||
const options: Ts3ConnectOptions = {
|
||||
host: msg.host,
|
||||
nickname: msg.nickname,
|
||||
@@ -1095,9 +1101,13 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
|
||||
break;
|
||||
}
|
||||
case "disconnect": {
|
||||
await connection?.disconnect(msg.message ?? "");
|
||||
if (connection) liveConnections.delete(connection);
|
||||
// Same as above: detach first, a connect may arrive while this awaits.
|
||||
const current = connection;
|
||||
connection = undefined;
|
||||
if (current) {
|
||||
liveConnections.delete(current);
|
||||
await current.disconnect(msg.message ?? "");
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
@@ -1113,7 +1123,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => {
|
||||
if (remaining > 0) connectionsPerIp.set(ip, remaining);
|
||||
else connectionsPerIp.delete(ip);
|
||||
heartbeats.delete(socket);
|
||||
if (connection) liveConnections.delete(connection);
|
||||
connection?.disconnect();
|
||||
closed = true;
|
||||
if (connection) {
|
||||
liveConnections.delete(connection);
|
||||
void connection.disconnect().catch(() => {});
|
||||
connection = undefined;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
import { rename, writeFile } from "node:fs/promises";
|
||||
|
||||
// Behind a reverse proxy / tunnel every request arrives from the proxy's own
|
||||
// address, so per-IP limits would lump all users into one bucket. Only set
|
||||
@@ -38,3 +39,21 @@ export function createRateLimiter(limit: number | (() => number), windowMs: numb
|
||||
return recent.length > (typeof limit === "function" ? limit() : limit);
|
||||
};
|
||||
}
|
||||
|
||||
/** Write-then-rename, one write at a time per file. Concurrent requests used
|
||||
* to share one `.tmp` path: one rename won, the others failed with ENOENT,
|
||||
* and overlapping writes could leave a mangled file. Queued, the last caller's
|
||||
* data always lands last. */
|
||||
const writeQueues = new Map<string, Promise<void>>();
|
||||
export function writeFileAtomic(file: string, data: string, mode?: number): Promise<void> {
|
||||
const run = async () => {
|
||||
const tmp = `${file}.tmp`;
|
||||
await writeFile(tmp, data, { encoding: "utf-8", mode });
|
||||
await rename(tmp, file);
|
||||
};
|
||||
const done = (writeQueues.get(file) ?? Promise.resolve()).then(run);
|
||||
const tail = done.catch(() => {});
|
||||
writeQueues.set(file, tail);
|
||||
void tail.then(() => { if (writeQueues.get(file) === tail) writeQueues.delete(file); });
|
||||
return done;
|
||||
}
|
||||
+3
-4
@@ -13,7 +13,8 @@
|
||||
//
|
||||
// Like store.ts, this file has zero private modifications.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { writeFileAtomic } from "./net.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { isAdminRequest, latestPublicTheme } from "./store.js";
|
||||
|
||||
@@ -43,9 +44,7 @@ async function load(): Promise<TextItem[]> {
|
||||
}
|
||||
|
||||
async function save(items: TextItem[]) {
|
||||
const tmp = `${NEWS_DATA_FILE}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(items), "utf-8");
|
||||
await rename(tmp, NEWS_DATA_FILE!);
|
||||
await writeFileAtomic(NEWS_DATA_FILE!, JSON.stringify(items));
|
||||
cache = items;
|
||||
}
|
||||
|
||||
|
||||
+3
-5
@@ -4,8 +4,8 @@
|
||||
// row per instance id: version, first and last seen. No IP addresses, no
|
||||
// request log. The admin view returns counts only.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
import { isAdminRequest } from "./store.js";
|
||||
|
||||
const PING_DATA_FILE = process.env.PING_DATA_FILE;
|
||||
@@ -36,9 +36,7 @@ async function save(instances: Record<string, Instance>) {
|
||||
// Instances silent for 90 days are gone for good.
|
||||
const cutoff = Date.now() - 90 * DAY_MS;
|
||||
for (const [id, i] of Object.entries(instances)) if (Date.parse(i.lastSeen) < cutoff) delete instances[id];
|
||||
const tmp = `${PING_DATA_FILE}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(instances), "utf-8");
|
||||
await rename(tmp, PING_DATA_FILE!);
|
||||
await writeFileAtomic(PING_DATA_FILE!, JSON.stringify(instances));
|
||||
}
|
||||
|
||||
function json(res: ServerResponse, status: number, body: unknown) {
|
||||
|
||||
+14
-12
@@ -11,10 +11,10 @@
|
||||
// touched. It has zero private modifications, so the overlay just copies it
|
||||
// verbatim; only index.ts's small SQLite-persistence sections need patching.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { timingSafeEqual, randomUUID } from "node:crypto";
|
||||
import path from "node:path";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
|
||||
const storeAllowedOrigin = () => process.env.STORE_ALLOWED_ORIGIN || "*";
|
||||
// Plain JSON file (whole-array read-modify-write, not JSON-lines like
|
||||
@@ -75,9 +75,10 @@ interface StoreTheme {
|
||||
|
||||
// Undo what a plain pattern check would miss: comments splitting a keyword
|
||||
// (u/**/rl), CSS escapes (\75 rl( is url(), and case.
|
||||
function normalizeCss(css: string): string {
|
||||
return css
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
// Comment stripping isn't string-aware ("/*" inside content:"..."), so the
|
||||
// checks run on both variants: with and without comments removed.
|
||||
function normalizeCss(css: string, stripComments: boolean): string {
|
||||
return (stripComments ? css.replace(/\/\*[\s\S]*?\*\//g, "") : css)
|
||||
.replace(/\\([0-9a-f]{1,6})\s?/gi, (_, hex: string) => {
|
||||
const cp = parseInt(hex, 16);
|
||||
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : "\ufffd";
|
||||
@@ -94,7 +95,7 @@ const FORBIDDEN_CSS = [
|
||||
/@import/,
|
||||
/@font-face/,
|
||||
/@namespace/,
|
||||
/(?:^|[^a-z-])(?:image-set|image|cross-fade|element|src|expression)\s*\(/,
|
||||
/(?:^|[^a-z])(?:-[a-z]+-)?(?:image-set|image|cross-fade|element|src|expression)\s*\(/,
|
||||
/-moz-binding/,
|
||||
/behavior\s*:/,
|
||||
/javascript:/,
|
||||
@@ -102,7 +103,10 @@ const FORBIDDEN_CSS = [
|
||||
];
|
||||
|
||||
export function isSafeThemeCss(css: string): boolean {
|
||||
const normalized = normalizeCss(css);
|
||||
return isSafeNormalized(normalizeCss(css, true)) && isSafeNormalized(normalizeCss(css, false));
|
||||
}
|
||||
|
||||
function isSafeNormalized(normalized: string): boolean {
|
||||
if (FORBIDDEN_CSS.some((re) => re.test(normalized))) return false;
|
||||
for (const match of normalized.matchAll(/url\s*\(\s*(["']?)\s*([^"')\s]*)/g)) {
|
||||
if (!/^data:image\/(?:png|jpeg|gif|webp|svg\+xml)[;,]/.test(match[2])) return false;
|
||||
@@ -130,9 +134,7 @@ async function saveStoreThemes(themes: StoreTheme[]): Promise<void> {
|
||||
storeCache = themes;
|
||||
// Write-then-rename: a crash mid-write must not leave a truncated file,
|
||||
// which loadStoreThemes() would read as "no themes" and then overwrite.
|
||||
const tmp = `${STORE_DATA_FILE}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(themes), "utf-8");
|
||||
await rename(tmp, STORE_DATA_FILE);
|
||||
await writeFileAtomic(STORE_DATA_FILE, JSON.stringify(themes));
|
||||
}
|
||||
|
||||
export function isAdminRequest(req: IncomingMessage): boolean {
|
||||
@@ -372,8 +374,8 @@ async function handleStoreSubmit(req: IncomingMessage, res: ServerResponse) {
|
||||
|
||||
const themes = await loadStoreThemes();
|
||||
// Re-uploading an installed store theme unchanged would just duplicate it.
|
||||
const cssKey = normalizeCss(css).replace(/\s+/g, "");
|
||||
if (themes.some((t) => normalizeCss(t.css).replace(/\s+/g, "") === cssKey)) {
|
||||
const cssKey = normalizeCss(css, true).replace(/\s+/g, "");
|
||||
if (themes.some((t) => normalizeCss(t.css, true).replace(/\s+/g, "") === cssKey)) {
|
||||
res.writeHead(409, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify({ error: "duplicate" }));
|
||||
return;
|
||||
|
||||
+3
-5
@@ -8,9 +8,9 @@
|
||||
// One JSON file per account in SYNC_DATA_DIR. Only served by sync-server.ts.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { mkdir, readdir, readFile, rm } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { clientIp, createRateLimiter } from "./net.js";
|
||||
import { clientIp, createRateLimiter, writeFileAtomic } from "./net.js";
|
||||
|
||||
const SYNC_DATA_DIR = process.env.SYNC_DATA_DIR;
|
||||
const SYNC_ALLOWED_ORIGIN = process.env.SYNC_ALLOWED_ORIGIN ?? "*";
|
||||
@@ -76,9 +76,7 @@ async function load(id: string): Promise<Account | null> {
|
||||
}
|
||||
|
||||
async function save(id: string, account: Account) {
|
||||
const tmp = `${file(id)}.tmp`;
|
||||
await writeFile(tmp, JSON.stringify(account), "utf-8");
|
||||
await rename(tmp, file(id));
|
||||
await writeFileAtomic(file(id), JSON.stringify(account));
|
||||
}
|
||||
|
||||
// Writes to one account run one after another, so the version check can't race.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
// Concurrent saves to one file used to share a .tmp path: all but one rename
|
||||
// failed with ENOENT (seen live from a parallel /api/ping probe).
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { writeFileAtomic } from "../dist/net.js";
|
||||
|
||||
test("parallel writes to one file all succeed, last one wins", async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "ws3-atomic-"));
|
||||
try {
|
||||
const file = path.join(dir, "data.json");
|
||||
await Promise.all(Array.from({ length: 50 }, (_, i) => writeFileAtomic(file, JSON.stringify({ i, pad: "x".repeat(i * 500) }))));
|
||||
assert.equal(JSON.parse(readFileSync(file, "utf-8")).i, 49);
|
||||
assert.deepEqual(readdirSync(dir), ["data.json"]);
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// Theme CSS from the Design Store must never load anything external.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { isSafeThemeCss } from "../dist/store.js";
|
||||
|
||||
test("theme CSS filter", () => {
|
||||
const evil = "url(https://attacker.example/t.png)";
|
||||
for (const css of [
|
||||
`body{background:${evil}}`,
|
||||
`body{background:\\75rl(https://attacker.example/t.png)}`,
|
||||
`body{background:image-set("https://attacker.example/t.png" 1x)}`,
|
||||
`a{content:"/*"}body{background:${evil}}b{content:"*/"}`,
|
||||
`a{--x:\\/*}body{background:${evil}}b{--y:*/}`,
|
||||
`body{background:-webkit-image-set("https://attacker.example/t.png" 1x)}`,
|
||||
]) assert.equal(isSafeThemeCss(css), false, css);
|
||||
for (const css of [
|
||||
":root{--bg:#123}body{color:red}a:hover{opacity:.5}",
|
||||
"body{background:url(data:image/png;base64,AAAA)}",
|
||||
"/* a comment */ body{color:red}",
|
||||
]) assert.equal(isSafeThemeCss(css), true, css);
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
// Connect/close races on one WebSocket must not leave connector processes
|
||||
// behind. Uses a fake connector that records its PID and lives until its
|
||||
// stdin closes (like the real one), against the built gateway.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { spawn } from "node:child_process";
|
||||
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { createServer } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
const INDEX = path.resolve(import.meta.dirname, "../dist/index.js");
|
||||
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } };
|
||||
const freePort = () => new Promise((ok) => {
|
||||
const s = createServer().listen(0, () => { const p = s.address().port; s.close(() => ok(p)); });
|
||||
});
|
||||
|
||||
test("no connector outlives its WebSocket", { timeout: 60_000 }, async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "ws3-orphans-"));
|
||||
const pids = path.join(dir, "pids");
|
||||
const fake = path.join(dir, "fake-connector.sh");
|
||||
writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\nsleep 1\n`);
|
||||
chmodSync(fake, 0o755);
|
||||
const port = await freePort();
|
||||
const gw = spawn(process.execPath, [INDEX], {
|
||||
cwd: dir,
|
||||
env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake },
|
||||
stdio: "ignore",
|
||||
});
|
||||
const recorded = () => (existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).map(Number) : []);
|
||||
try {
|
||||
for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } }
|
||||
const connect = JSON.stringify({ type: "connect", host: "example.invalid", nickname: "dummy" });
|
||||
const open = async () => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; });
|
||||
return ws;
|
||||
};
|
||||
|
||||
// connect, connect while the first connector shuts down, close
|
||||
let ws = await open();
|
||||
ws.send(connect); await wait(300);
|
||||
ws.send(connect); await wait(100);
|
||||
ws.close();
|
||||
// connect, then two connects back to back, close later
|
||||
ws = await open();
|
||||
ws.send(connect); await wait(300);
|
||||
ws.send(connect); ws.send(connect);
|
||||
await wait(4000);
|
||||
ws.close();
|
||||
|
||||
await wait(4000);
|
||||
assert.ok(recorded().length >= 2, "fake connector was spawned");
|
||||
assert.deepEqual(recorded().filter(alive), [], "connector processes left behind");
|
||||
} finally {
|
||||
for (const pid of recorded()) if (alive(pid)) process.kill(pid, "SIGKILL");
|
||||
await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); });
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("ALLOWED_SERVERS can't be bypassed with a bracketed prefix", { timeout: 30_000 }, async () => {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), "ws3-allow-"));
|
||||
const pids = path.join(dir, "pids");
|
||||
const fake = path.join(dir, "fake-connector.sh");
|
||||
writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\n`);
|
||||
chmodSync(fake, 0o755);
|
||||
const port = await freePort();
|
||||
const gw = spawn(process.execPath, [INDEX], {
|
||||
cwd: dir,
|
||||
env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake, ALLOWED_SERVERS: "ts.example.com" },
|
||||
stdio: "ignore",
|
||||
});
|
||||
try {
|
||||
for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } }
|
||||
const reply = async (host) => {
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`);
|
||||
const msgs = [];
|
||||
ws.onmessage = (e) => msgs.push(JSON.parse(e.data));
|
||||
await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; });
|
||||
ws.send(JSON.stringify({ type: "connect", host, nickname: "dummy" }));
|
||||
await wait(500);
|
||||
ws.close();
|
||||
return msgs.find((m) => m.type === "error")?.message ?? "";
|
||||
};
|
||||
for (const host of ["[ts.example.com]evil.tld", "[ts.example.com]evil.tld:9987", "evil.tld"]) {
|
||||
assert.match(await reply(host), /not allowed/, host);
|
||||
}
|
||||
assert.doesNotMatch(await reply("ts.example.com:9987"), /not allowed/);
|
||||
assert.equal(existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).length : 0, 1, "only the allowed host spawned a connector");
|
||||
} finally {
|
||||
await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); });
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user