Skip to main content

stackdeck_mcp_writes/
json.rs

1use std::collections::BTreeMap;
2
3use crate::error::{ErrorCode, WriteSafetyError};
4use crate::sha256::sha256_hex;
5
6pub(crate) const MAX_SAFE_INTEGER: i64 = (1 << 53) - 1;
7const MAX_DEPTH: usize = 128;
8
9/// Minimal JSON value representation with zero external dependencies.
10/// `BTreeMap<String, JsonValue>` preserves ascending Unicode code-point order
11/// because Rust `String` ordering compares UTF-8 bytes, which matches code-point order.
12#[derive(Debug, Clone, PartialEq)]
13pub enum JsonValue {
14    Null,
15    Bool(bool),
16    Int(i64),
17    Float(f64),
18    String(String),
19    Array(Vec<JsonValue>),
20    Object(BTreeMap<String, JsonValue>),
21}
22
23impl JsonValue {
24    pub fn as_object(&self) -> Option<&BTreeMap<String, JsonValue>> {
25        match self {
26            JsonValue::Object(map) => Some(map),
27            _ => None,
28        }
29    }
30
31    pub fn as_array(&self) -> Option<&[JsonValue]> {
32        match self {
33            JsonValue::Array(items) => Some(items),
34            _ => None,
35        }
36    }
37
38    pub fn as_str(&self) -> Option<&str> {
39        match self {
40            JsonValue::String(s) => Some(s.as_str()),
41            _ => None,
42        }
43    }
44
45    pub fn as_bool(&self) -> Option<bool> {
46        match self {
47            JsonValue::Bool(b) => Some(*b),
48            _ => None,
49        }
50    }
51
52    pub fn as_i64(&self) -> Option<i64> {
53        match self {
54            JsonValue::Int(n) => Some(*n),
55            _ => None,
56        }
57    }
58}
59
60fn write_escaped_string(s: &str, out: &mut String) {
61    out.push('"');
62    for ch in s.chars() {
63        match ch {
64            '"' => out.push_str("\\\""),
65            '\\' => out.push_str("\\\\"),
66            '\u{08}' => out.push_str("\\b"),
67            '\u{0C}' => out.push_str("\\f"),
68            '\n' => out.push_str("\\n"),
69            '\r' => out.push_str("\\r"),
70            '\t' => out.push_str("\\t"),
71            c if (c as u32) < 0x20 => {
72                use std::fmt::Write as _;
73                let _ = write!(out, "\\u{:04x}", c as u32);
74            }
75            c => out.push(c),
76        }
77    }
78    out.push('"');
79}
80
81fn exact_midpoint(value: f64, odd_decimal: u64, power: i32) -> bool {
82    let bits = value.to_bits();
83    let biased_exponent = ((bits >> 52) & 0x7ff) as i32;
84    let fraction = bits & ((1 << 52) - 1);
85    let (significand, exponent) = if biased_exponent == 0 {
86        (fraction, -1074)
87    } else {
88        (fraction | (1 << 52), biased_exponent - 1075)
89    };
90    let trailing = significand.trailing_zeros();
91    // A midpoint is odd_decimal * 5^power * 2^(power - 1).
92    // Strip powers of two first, then compare the remaining odd factors.
93    if exponent + trailing as i32 != power - 1 {
94        return false;
95    }
96    let odd_binary = significand >> trailing;
97    let Some(five) = 5_u64.checked_pow(power.unsigned_abs()) else {
98        return false;
99    };
100    if power >= 0 {
101        odd_decimal.checked_mul(five) == Some(odd_binary)
102    } else {
103        odd_binary.checked_mul(five) == Some(odd_decimal)
104    }
105}
106
107fn write_float(value: f64, out: &mut String) {
108    use std::fmt::Write as _;
109    if value == 0.0 {
110        out.push('0');
111        return;
112    }
113    if value.is_sign_negative() {
114        out.push('-');
115    }
116    let value = value.abs();
117    let scientific = format!("{value:e}");
118    let (mantissa, exponent) = scientific.split_once('e').expect("scientific notation");
119    let exponent = exponent.parse::<i32>().expect("decimal exponent");
120    let mut digits = mantissa.replace('.', "");
121    let coefficient = digits.parse::<u64>().expect("shortest binary64 significand");
122    let power = exponent + 1 - digits.len() as i32;
123    // Rust's formatter can choose the larger decimal at an exact tie.
124    // ECMAScript chooses the decimal with an even significand.
125    if coefficient % 2 != 0 {
126        if exact_midpoint(value, 2 * coefficient - 1, power) {
127            digits = (coefficient - 1).to_string();
128        } else if exact_midpoint(value, 2 * coefficient + 1, power) {
129            digits = (coefficient + 1).to_string();
130        }
131    }
132    let point = power + digits.len() as i32;
133    let digits = digits.trim_end_matches('0');
134    if (1..=21).contains(&point) {
135        let point = point as usize;
136        if point >= digits.len() {
137            out.push_str(digits);
138            out.push_str(&"0".repeat(point - digits.len()));
139        } else {
140            out.push_str(&digits[..point]);
141            out.push('.');
142            out.push_str(&digits[point..]);
143        }
144    } else if (-5..=0).contains(&point) {
145        out.push_str("0.");
146        out.push_str(&"0".repeat((-point) as usize));
147        out.push_str(digits);
148    } else {
149        out.push_str(&digits[..1]);
150        if digits.len() > 1 {
151            out.push('.');
152            out.push_str(&digits[1..]);
153        }
154        write!(out, "e{:+}", point - 1).expect("write to String");
155    }
156}
157
158fn write_canonical(value: &JsonValue, out: &mut String, depth: usize) -> Result<(), WriteSafetyError> {
159    if depth >= MAX_DEPTH && matches!(value, JsonValue::Array(_) | JsonValue::Object(_)) {
160        return Err(WriteSafetyError::new(ErrorCode::Validation, "JSON nested too deeply."));
161    }
162    match value {
163        JsonValue::Null => out.push_str("null"),
164        JsonValue::Bool(true) => out.push_str("true"),
165        JsonValue::Bool(false) => out.push_str("false"),
166        JsonValue::Int(n) => {
167            if !(-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(n) {
168                return Err(WriteSafetyError::new(ErrorCode::Validation, "JSON integer is outside the safe range."));
169            }
170            out.push_str(&n.to_string());
171        }
172        JsonValue::Float(f) => {
173            if !f.is_finite() {
174                return Err(WriteSafetyError::new(
175                    ErrorCode::Validation,
176                    "Write input must contain only finite JSON numbers.",
177                ));
178            }
179            write_float(*f, out);
180        }
181        JsonValue::String(s) => write_escaped_string(s, out),
182        JsonValue::Array(items) => {
183            out.push('[');
184            for (idx, item) in items.iter().enumerate() {
185                if idx > 0 {
186                    out.push(',');
187                }
188                write_canonical(item, out, depth + 1)?;
189            }
190            out.push(']');
191        }
192        JsonValue::Object(map) => {
193            out.push('{');
194            for (idx, (k, v)) in map.iter().enumerate() {
195                if idx > 0 {
196                    out.push(',');
197                }
198                write_escaped_string(k, out);
199                out.push(':');
200                write_canonical(v, out, depth + 1)?;
201            }
202            out.push('}');
203        }
204    }
205    Ok(())
206}
207
208/// Serialize any `JsonValue` to deterministic canonical JSON matching SPEC.md section 3.
209pub fn canonical_json(value: &JsonValue) -> Result<String, WriteSafetyError> {
210    let mut out = String::new();
211    write_canonical(value, &mut out, 0)?;
212    Ok(out)
213}
214
215/// Build the canonical binding envelope JSON for `(operation, scope, input)`.
216pub fn canonical_binding_json(
217    operation: &str,
218    scope: &str,
219    input: &JsonValue,
220) -> Result<String, WriteSafetyError> {
221    let mut out = String::from("{\"input\":");
222    write_canonical(input, &mut out, 0)?;
223    out.push_str(",\"operation\":");
224    write_escaped_string(operation, &mut out);
225    out.push_str(",\"scope\":");
226    write_escaped_string(scope, &mut out);
227    out.push_str(",\"version\":1}");
228    Ok(out)
229}
230
231/// Compute the 64-character lowercase SHA-256 hex digest of the canonical write binding.
232pub fn canonical_hash(
233    operation: &str,
234    scope: &str,
235    input: &JsonValue,
236) -> Result<String, WriteSafetyError> {
237    let payload = canonical_binding_json(operation, scope, input)?;
238    Ok(sha256_hex(payload.as_bytes()))
239}
240
241struct Parser<'a> {
242    text: &'a str,
243    pos: usize,
244}
245
246impl<'a> Parser<'a> {
247    fn skip_ws(&mut self) {
248        while self.pos < self.text.len() {
249            match self.text.as_bytes()[self.pos] {
250                b' ' | b'\t' | b'\r' | b'\n' => self.pos += 1,
251                _ => break,
252            }
253        }
254    }
255
256    fn peek(&self) -> Option<u8> {
257        self.text.as_bytes().get(self.pos).copied()
258    }
259
260    fn parse_value(&mut self, depth: usize) -> Result<JsonValue, WriteSafetyError> {
261        self.skip_ws();
262        match self.peek() {
263            Some(b'[' | b'{') if depth >= MAX_DEPTH => {
264                Err(WriteSafetyError::new(ErrorCode::Validation, "JSON nested too deeply."))
265            }
266            Some(b'n') => self.parse_literal(b"null", JsonValue::Null),
267            Some(b't') => self.parse_literal(b"true", JsonValue::Bool(true)),
268            Some(b'f') => self.parse_literal(b"false", JsonValue::Bool(false)),
269            Some(b'"') => self.parse_string().map(JsonValue::String),
270            Some(b'[') => self.parse_array(depth),
271            Some(b'{') => self.parse_object(depth),
272            Some(b'-') | Some(b'0'..=b'9') => self.parse_number(),
273            _ => Err(WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON value.")),
274        }
275    }
276
277    fn parse_literal(&mut self, expected: &[u8], value: JsonValue) -> Result<JsonValue, WriteSafetyError> {
278        if self.text.as_bytes()[self.pos..].starts_with(expected) {
279            self.pos += expected.len();
280            Ok(value)
281        } else {
282            Err(WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON literal."))
283        }
284    }
285
286    fn parse_hex4(&mut self) -> Result<u16, WriteSafetyError> {
287        let hex = self.text.get(self.pos..self.pos + 4)
288            .filter(|hex| hex.bytes().all(|byte| byte.is_ascii_hexdigit()))
289            .ok_or_else(|| WriteSafetyError::new(ErrorCode::Validation, "Invalid unicode escape."))?;
290        let val = u16::from_str_radix(hex, 16).expect("four hex digits");
291        self.pos += 4;
292        Ok(val)
293    }
294
295    fn parse_string(&mut self) -> Result<String, WriteSafetyError> {
296        self.pos += 1; // opening quote
297        let mut out = String::new();
298        while let Some(b) = self.peek() {
299            if b == b'"' {
300                self.pos += 1;
301                return Ok(out);
302            }
303            if b == b'\\' {
304                self.pos += 1;
305                let esc = self
306                    .peek()
307                    .ok_or_else(|| WriteSafetyError::new(ErrorCode::Validation, "Unterminated escape."))?;
308                self.pos += 1;
309                match esc {
310                    b'"' => out.push('"'),
311                    b'\\' => out.push('\\'),
312                    b'/' => out.push('/'),
313                    b'b' => out.push('\u{08}'),
314                    b'f' => out.push('\u{0C}'),
315                    b'n' => out.push('\n'),
316                    b'r' => out.push('\r'),
317                    b't' => out.push('\t'),
318                    b'u' => {
319                        let code = self.parse_hex4()?;
320                        if (0xD800..=0xDBFF).contains(&code) {
321                            if !self.text.as_bytes()[self.pos..].starts_with(b"\\u") {
322                                return Err(WriteSafetyError::new(
323                                    ErrorCode::Validation,
324                                    "Unpaired high surrogate.",
325                                ));
326                            }
327                            self.pos += 2;
328                            let low = self.parse_hex4()?;
329                            if !(0xDC00..=0xDFFF).contains(&low) {
330                                return Err(WriteSafetyError::new(
331                                    ErrorCode::Validation,
332                                    "Invalid low surrogate.",
333                                ));
334                            }
335                            let cp = 0x10000 + (((code as u32 - 0xD800) << 10) | (low as u32 - 0xDC00));
336                            let ch = char::from_u32(cp).ok_or_else(|| {
337                                WriteSafetyError::new(ErrorCode::Validation, "Invalid unicode scalar.")
338                            })?;
339                            out.push(ch);
340                        } else {
341                            let ch = char::from_u32(code as u32).ok_or_else(|| {
342                                WriteSafetyError::new(ErrorCode::Validation, "Invalid unicode scalar.")
343                            })?;
344                            out.push(ch);
345                        }
346                    }
347                    _ => return Err(WriteSafetyError::new(ErrorCode::Validation, "Unknown JSON escape.")),
348                }
349            } else {
350                if b < 0x20 {
351                    return Err(WriteSafetyError::new(ErrorCode::Validation, "Unescaped control character."));
352                }
353                let ch = self.text[self.pos..]
354                    .chars()
355                    .next()
356                    .ok_or_else(|| WriteSafetyError::new(ErrorCode::Validation, "Unterminated string."))?;
357                out.push(ch);
358                self.pos += ch.len_utf8();
359            }
360        }
361        Err(WriteSafetyError::new(ErrorCode::Validation, "Unterminated JSON string."))
362    }
363
364    fn parse_number(&mut self) -> Result<JsonValue, WriteSafetyError> {
365        let invalid = || WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON number.");
366        let start = self.pos;
367        if self.peek() == Some(b'-') {
368            self.pos += 1;
369        }
370        match self.peek() {
371            Some(b'0') => {
372                self.pos += 1;
373                if self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
374                    return Err(invalid());
375                }
376            }
377            Some(b'1'..=b'9') => self.consume_digits(),
378            _ => return Err(invalid()),
379        }
380        let mut is_float = false;
381        if self.peek() == Some(b'.') {
382            is_float = true;
383            self.pos += 1;
384            if !self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
385                return Err(invalid());
386            }
387            self.consume_digits();
388        }
389        if matches!(self.peek(), Some(b'e' | b'E')) {
390            is_float = true;
391            self.pos += 1;
392            if matches!(self.peek(), Some(b'+' | b'-')) {
393                self.pos += 1;
394            }
395            if !self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
396                return Err(invalid());
397            }
398            self.consume_digits();
399        }
400        let slice = &self.text[start..self.pos];
401        if !is_float {
402            if let Some(integer) = slice.parse::<i64>().ok()
403                .filter(|n| (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(n))
404            {
405                return Ok(JsonValue::Int(integer));
406            }
407        }
408        let f = slice
409            .parse::<f64>()
410            .map_err(|_| WriteSafetyError::new(ErrorCode::Validation, "Invalid JSON number."))?;
411        if !f.is_finite() {
412            return Err(WriteSafetyError::new(ErrorCode::Validation, "Non-finite JSON number."));
413        }
414        Ok(JsonValue::Float(f))
415    }
416
417    fn consume_digits(&mut self) {
418        while self.peek().is_some_and(|byte| byte.is_ascii_digit()) {
419            self.pos += 1;
420        }
421    }
422
423    fn parse_array(&mut self, depth: usize) -> Result<JsonValue, WriteSafetyError> {
424        self.pos += 1; // '['
425        let mut items = Vec::new();
426        self.skip_ws();
427        if self.peek() == Some(b']') {
428            self.pos += 1;
429            return Ok(JsonValue::Array(items));
430        }
431        loop {
432            items.push(self.parse_value(depth + 1)?);
433            self.skip_ws();
434            match self.peek() {
435                Some(b',') => self.pos += 1,
436                Some(b']') => {
437                    self.pos += 1;
438                    return Ok(JsonValue::Array(items));
439                }
440                _ => return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected ',' or ']'.")),
441            }
442        }
443    }
444
445    fn parse_object(&mut self, depth: usize) -> Result<JsonValue, WriteSafetyError> {
446        self.pos += 1; // '{'
447        let mut map = BTreeMap::new();
448        self.skip_ws();
449        if self.peek() == Some(b'}') {
450            self.pos += 1;
451            return Ok(JsonValue::Object(map));
452        }
453        loop {
454            self.skip_ws();
455            if self.peek() != Some(b'"') {
456                return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected object key string."));
457            }
458            let key = self.parse_string()?;
459            self.skip_ws();
460            if self.peek() != Some(b':') {
461                return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected ':' after key."));
462            }
463            self.pos += 1;
464            let value = self.parse_value(depth + 1)?;
465            map.insert(key, value);
466            self.skip_ws();
467            match self.peek() {
468                Some(b',') => self.pos += 1,
469                Some(b'}') => {
470                    self.pos += 1;
471                    return Ok(JsonValue::Object(map));
472                }
473                _ => return Err(WriteSafetyError::new(ErrorCode::Validation, "Expected ',' or '}'.")),
474            }
475        }
476    }
477}
478
479/// Parse a JSON string into a `JsonValue`.
480pub fn parse_json(text: &str) -> Result<JsonValue, WriteSafetyError> {
481    let mut parser = Parser {
482        text,
483        pos: 0,
484    };
485    let value = parser.parse_value(0)?;
486    parser.skip_ws();
487    if parser.pos != parser.text.len() {
488        return Err(WriteSafetyError::new(ErrorCode::Validation, "Trailing characters after JSON."));
489    }
490    Ok(value)
491}