The design language that makes your AI harness better at design.
JavaScript
Fix live-inject CSP meta patch escaping and revert (#1128)
Paul Bakaus5b8c8e56bf3b
diff --git a/crates/live/src/inject/tag_strategy.rs b/crates/live/src/inject/tag_strategy.rsindex 7f06860e2..4b4d2424c 100644--- a/crates/live/src/inject/tag_strategy.rs+++ b/crates/live/src/inject/tag_strategy.rs@@ -244,45 +244,246 @@ fn get_attr(attrs: &str, name: &str) -> Option<Attr> {best.map(|(_, a)| a)}-fn append_origin_to_directive(csp: &str, directive: &str, origin: &str) -> String {- let re = RegexBuilder::new(&format!("(^|;)(\\s*)({})\\s+([^;]*)", directive))- .case_insensitive(true)- .build()- .unwrap();- if let Some(m) = re.captures(csp) {- let tokens_str = m.get(4).map(|t| t.as_str()).unwrap_or("");- let tokens: Vec<&str> = tokens_str.trim().split_whitespace().collect();- // JS: `m[4].trim().split(/\s+/)`; an empty trimmed string yields ['']- let tokens: Vec<&str> = if tokens_str.trim().is_empty() {- vec![""]+/// Length of the HTML character reference at the start of `s` (which starts+/// with `&`), if one starts there. A numeric reference may omit its `;`, as+/// browsers read it; a named one counts only with its `;`.+fn reference_len(s: &str) -> Option<usize> {+ let b = s.as_bytes();+ if b.get(1) == Some(&b'#') {+ let hex = matches!(b.get(2), Some(b'x' | b'X'));+ let start = if hex { 3 } else { 2 };+ let mut i = start;+ while i < b.len()+ && (if hex {+ b[i].is_ascii_hexdigit()+ } else {+ b[i].is_ascii_digit()+ })+ {+ i += 1;+ }+ if i == start {+ return None;+ }+ if b.get(i) == Some(&b';') {+ i += 1;+ }+ Some(i)+ } else {+ let mut i = 1;+ while i < b.len() && b[i].is_ascii_alphanumeric() {+ i += 1;+ }+ if i == 1 || b.get(i) != Some(&b';') {+ return None;+ }+ Some(i + 1)+ }+}++/// The named references that decode to ASCII, the only characters a CSP is+/// made of. Any other `&name;` is kept as one opaque unit: it may be a real+/// reference (`©`) or literal text (`&bogus;`), and telling them apart+/// takes the full HTML table. Treating it as text inside a source means an+/// insertion never lands between its name and its `;`.+const ASCII_NAMED_REFERENCES: [(&str, char); 29] = [+ ("amp", '&'),+ ("quot", '"'),+ ("apos", '\''),+ ("lt", '<'),+ ("gt", '>'),+ ("semi", ';'),+ ("colon", ':'),+ ("comma", ','),+ ("period", '.'),+ ("sol", '/'),+ ("bsol", '\\'),+ ("Tab", '\t'),+ ("NewLine", '\n'),+ ("ast", '*'),+ ("plus", '+'),+ ("lowbar", '_'),+ ("equals", '='),+ ("quest", '?'),+ ("num", '#'),+ ("percnt", '%'),+ ("excl", '!'),+ ("commat", '@'),+ ("dollar", '$'),+ ("lpar", '('),+ ("rpar", ')'),+ ("lsqb", '['),+ ("rsqb", ']'),+ ("lcub", '{'),+ ("rcub", '}'),+];++/// `tail` starts with `&`. Returns the decoded char and the reference length+/// for numeric references and the names in `ASCII_NAMED_REFERENCES`.+fn decode_reference(tail: &str) -> Option<(char, usize)> {+ let len = reference_len(tail)?;+ let body = tail[1..len].trim_end_matches(';');+ let ch = if let Some(num) = body.strip_prefix('#') {+ let code = match num.strip_prefix(['x', 'X']) {+ Some(hex) => u32::from_str_radix(hex, 16).ok(),+ None => num.parse::<u32>().ok(),+ };+ code.filter(|c| *c != 0)+ .and_then(char::from_u32)+ .unwrap_or('\u{FFFD}')+ } else {+ ASCII_NAMED_REFERENCES+ .iter()+ .find(|(name, _)| *name == body)?+ .1+ };+ Some((ch, len))+}++/// One decoded character of a raw attribute value and the raw bytes it came+/// from (a single character, or a whole character reference).+struct Unit {+ ch: char,+ start: usize,+ end: usize,+ /// An `&name;` outside `ASCII_NAMED_REFERENCES`, read as its raw text.+ opaque: bool,+}++fn decode_units(raw: &str) -> Vec<Unit> {+ let mut out = Vec::with_capacity(raw.len());+ let mut i = 0;+ while i < raw.len() {+ let tail = &raw[i..];+ let (ch, len, opaque) = if tail.starts_with('&') {+ match decode_reference(tail) {+ Some((ch, len)) => (ch, len, false),+ None => match reference_len(tail) {+ Some(len) if tail.as_bytes()[1] != b'#' => ('\u{FFFD}', len, true),+ _ => ('&', 1, false),+ },+ }} else {- tokens+ let c = tail.chars().next().unwrap();+ (c, c.len_utf8(), false)};- if tokens.contains(&origin) {- return csp.to_string();+ out.push(Unit {+ ch,+ start: i,+ end: i + len,+ opaque,+ });+ i += len;+ }+ out+}++/// The value a browser hands the CSP parser, for the references+/// `decode_reference` knows; anything else passes through unchanged.+#[cfg(test)]+fn decode_html_attr_value(value: &str) -> String {+ let mut out = String::with_capacity(value.len());+ for u in decode_units(value) {+ if u.opaque {+ out.push_str(&value[u.start..u.end]);+ } else {+ out.push(u.ch);+ }+ }+ out+}++/// Encode a source for an attribute delimited by `quote`, so the quotes in+/// `'self'` and `'wasm-unsafe-eval'` cannot end a single-quoted value.+fn encode_html_attr_value(value: &str, quote: &str) -> String {+ let mut out = String::with_capacity(value.len());+ for c in value.chars() {+ match c {+ '&' => out.push_str("&"),+ '<' => out.push_str("<"),+ '>' => out.push_str(">"),+ '"' if quote == "\"" => out.push_str("""),+ '\'' if quote == "'" => out.push_str("'"),+ _ => out.push(c),}- let mut joined: Vec<&str> = tokens.clone();- joined.push(origin);- let replacement = format!(- "{}{}{} {}",- m.get(1).map(|x| x.as_str()).unwrap_or(""),- m.get(2).map(|x| x.as_str()).unwrap_or(""),- m.get(3).map(|x| x.as_str()).unwrap_or(""),- joined.join(" ")- );- let whole = m.get(0).unwrap();- return format!(- "{}{}{}",- &csp[..whole.start()],- replacement,- &csp[whole.end()..]- );}- let trimmed = csp.trim();- // JS: .replace(/;?\s*$/, '')- let trailing_re = Regex::new(r";?\s*$").unwrap();- let base = trailing_re.replacen(trimmed, 1, "").into_owned();- format!("{}; {} 'self' {}", base, directive, origin)+ out+}++/// Append `source` to `directive` in the raw attribute value `raw`, or add the+/// directive as `; <directive> 'self' <source>` when it is missing. Directive+/// names, separators and sources are read on the decoded value, the way the+/// browser reads them, but the edit is made on the raw text: the existing text+/// and its character references are copied through byte for byte, and only+/// the inserted text is encoded for `quote`. Whitespace is CSP's ASCII+/// whitespace, so a decoded ` ` does not separate a name from a source.+fn append_origin_to_directive(raw: &str, directive: &str, source: &str, quote: &str) -> String {+ let encoded = encode_html_attr_value(source, quote);+ let units = decode_units(raw);+ let name: Vec<char> = directive.chars().collect();+ for seg in units.split(|u| u.ch == ';') {+ let body: Vec<&Unit> = seg+ .iter()+ .skip_while(|u| u.ch.is_ascii_whitespace())+ .collect();+ let named = body.len() > name.len()+ && body+ .iter()+ .zip(&name)+ .all(|(u, c)| u.ch.eq_ignore_ascii_case(c))+ && body[name.len()].ch.is_ascii_whitespace();+ if !named {+ continue;+ }+ let rest: String = body[name.len()..]+ .iter()+ .map(|u| if u.opaque { '\u{FFFD}' } else { u.ch })+ .collect();+ if rest+ .split(|c: char| c.is_ascii_whitespace())+ .any(|t| t == source)+ {+ return raw.to_string();+ }+ // After the last source, or after the name when there is none.+ let at = body+ .iter()+ .rev()+ .find(|u| !u.ch.is_ascii_whitespace())+ .map(|u| u.end)+ .unwrap_or(raw.len());+ return format!("{} {}{}", &raw[..at], encoded, &raw[at..]);+ }+ // JS: csp.trim().replace(/;?\s*$/, ''), on decoded characters.+ let first = units.iter().position(|u| !u.ch.is_ascii_whitespace());+ let last = units.iter().rposition(|u| !u.ch.is_ascii_whitespace());+ let base = match (first, last) {+ (Some(f), Some(l)) => {+ let end = if units[l].ch == ';' {+ units[l].start+ } else {+ units[l].end+ };+ &raw[units[f].start..end.max(units[f].start)]+ }+ _ => "",+ };+ // A trailing `c` or `&` would take the new `;` as its terminator+ // and swallow the separator; a space ends the reference first.+ let tail = base.rfind('&').map(|i| &base[i + 1..]).unwrap_or(" ");+ let gap = if !tail.is_empty() && tail.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'#') {+ " "+ } else {+ ""+ };+ format!(+ "{}{}; {} {} {}",+ base,+ gap,+ directive,+ encode_html_attr_value("'self'", quote),+ encoded+ )}/// JS: patchCspMeta(content, port)@@ -301,25 +502,26 @@ pub fn patch_csp_meta(content: &str, port: i64) -> String {let Some(content_attr) = get_attr(attrs, "content") else {continue;};+ // The value is patched in place on its raw text (character references+ // kept, only the inserted sources encoded for the quote style), and+ // the marker keeps the raw original so revert restores its bytes.let original = content_attr.value.clone();+ let q = content_attr.quote.as_str();let mut patched = original.clone();- patched = append_origin_to_directive(&patched, "script-src", &origin);+ patched = append_origin_to_directive(&patched, "script-src", &origin, q);// The detector the overlay loads from that origin is a WebAssembly// module (WASM-BUNDLE.md in the detector repo); a script-src that names the origin// but not 'wasm-unsafe-eval' still refuses to compile it. Not in the// JS patchCspMeta: goldens live-inject-vite-csp-meta,// live-inject-csp-meta-no-connect-src and live-inject-next-jsx carry// the pre-wasm form (see tests/oracle/DELTAS.md in the public repo).- patched = append_origin_to_directive(&patched, "script-src", "'wasm-unsafe-eval'");- patched = append_origin_to_directive(&patched, "connect-src", &origin);- patched = append_origin_to_directive(&patched, "img-src", "blob:");+ patched = append_origin_to_directive(&patched, "script-src", "'wasm-unsafe-eval'", q);+ patched = append_origin_to_directive(&patched, "connect-src", &origin, q);+ patched = append_origin_to_directive(&patched, "img-src", "blob:", q);if patched == original {continue;}- let new_content_attr = format!(- "content={}{}{}",- content_attr.quote, patched, content_attr.quote- );+ let new_content_attr = format!("content={q}{patched}{q}");let marker = format!("{}=\"{}\"",CSP_MARKER_ATTR,@@ -360,28 +562,22 @@ pub fn revert_csp_meta(content: &str) -> String {content_attr.quote, original_value, content_attr.quote);let mut new_attrs = tag.attrs.replacen(&content_attr.full, &new_content_attr, 1);- // JS: new RegExp(`\\s*${origAttr.full}`) (unescaped; the value is- // base64 + quotes, which carry no regex metacharacters besides `+`- // and `/`... `+` IS a metachar; JS would treat `A+` as a quantifier).- // JS-PARITY: build the same regex the JS builds.- let re_src = format!("\\s*{}", orig_attr.full);- match Regex::new(&re_src) {- Ok(re) => {- new_attrs = re.replacen(&new_attrs, 1, "").into_owned();- }- Err(_) => {- // A base64 value like `A+B` compiles in JS as a quantifier;- // fall back to a literal removal when the Rust regex rejects it.- if let Some(pos) = new_attrs.find(&orig_attr.full) {- let before = &new_attrs[..pos];- let ws = before.len() - before.trim_end().len();- new_attrs = format!(- "{}{}",- &before[..before.len() - ws],- &new_attrs[pos + orig_attr.full.len()..]- );- }- }+ // Remove the marker literally. The JS built a regex from the raw+ // base64, where `+` acts as a quantifier, so a marker whose value held+ // a `+` was never matched and stayed behind. Patch writes the marker+ // as ` <marker>`: drop exactly that one space so the attributes come+ // back byte for byte.+ if let Some(pos) = new_attrs.find(&orig_attr.full) {+ let start = if new_attrs[..pos].ends_with(' ') {+ pos - 1+ } else {+ pos+ };+ new_attrs = format!(+ "{}{}",+ &new_attrs[..start],+ &new_attrs[pos + orig_attr.full.len()..]+ );}let new_tag = tag.full.replacen(tag.attrs.as_str(), &new_attrs, 1);result = format!("{}{}{}", &result[..tag.start], new_tag, &result[tag.end..]);@@ -423,4 +619,223 @@ mod tests {"{patched}");}++ /// The `content` value of the first CSP meta, decoded the way a browser+ /// reads it. Panics when the tag or the attribute cannot be found.+ fn browser_policy(html: &str) -> String {+ let tag = find_csp_meta_tags(html)+ .into_iter()+ .next()+ .expect("csp meta");+ let attr = get_attr(&tag.attrs, "content").expect("content attr");+ decode_html_attr_value(&attr.value)+ }++ fn marker_value(html: &str) -> String {+ let tag = find_csp_meta_tags(html)+ .into_iter()+ .next()+ .expect("csp meta");+ get_attr(&tag.attrs, CSP_MARKER_ATTR).expect("marker").value+ }++ #[test]+ fn single_quoted_content_escapes_inserted_quotes() {+ let html = "<meta http-equiv=\"Content-Security-Policy\" content='script-src https://example.com/a~' />";+ let patched = patch_csp_meta(html, 9797);+ assert!(+ patched.contains("content='script-src https://example.com/a~ http://localhost:9797 'wasm-unsafe-eval'; connect-src 'self' http://localhost:9797; img-src 'self' blob:'"),+ "{patched}"+ );+ assert_eq!(+ browser_policy(&patched),+ "script-src https://example.com/a~ http://localhost:9797 'wasm-unsafe-eval'; connect-src 'self' http://localhost:9797; img-src 'self' blob:"+ );+ assert_eq!(revert_csp_meta(&patched), html);+ }++ #[test]+ fn entity_encoded_semicolons_are_not_directive_separators() {+ let html = "<meta http-equiv=\"Content-Security-Policy\" content='script-src 'self' https://a.example; object-src 'none'' />";+ let patched = patch_csp_meta(html, 9797);+ assert_eq!(+ browser_policy(&patched),+ "script-src 'self' https://a.example http://localhost:9797 'wasm-unsafe-eval'; object-src 'none'; connect-src 'self' http://localhost:9797; img-src 'self' blob:"+ );+ assert_eq!(revert_csp_meta(&patched), html);+ }++ #[test]+ fn double_quoted_content_with_entities_round_trips() {+ let html = "<meta http-equiv='Content-Security-Policy' content=\"script-src 'self' https://a.example/?a=1&b="2"\">";+ let patched = patch_csp_meta(html, 8412);+ assert_eq!(+ browser_policy(&patched),+ "script-src 'self' https://a.example/?a=1&b=\"2\" http://localhost:8412 'wasm-unsafe-eval'; connect-src 'self' http://localhost:8412; img-src 'self' blob:"+ );+ // The existing text keeps its own references; only the inserted+ // sources are new, and raw `'` is fine inside double quotes.+ assert!(+ patched.contains("content=\"script-src 'self' https://a.example/?a=1&b="2" http://localhost:8412 'wasm-unsafe-eval';"),+ "{patched}"+ );+ assert_eq!(revert_csp_meta(&patched), html);+ }++ #[test]+ fn already_present_entity_encoded_source_is_not_duplicated() {+ let html = "<meta http-equiv=\"Content-Security-Policy\" content='script-src http://localhost:9797 'wasm-unsafe-eval'; connect-src http://localhost:9797; img-src blob:'>";+ assert_eq!(patch_csp_meta(html, 9797), html);+ }++ #[test]+ fn revert_removes_marker_whose_base64_holds_plus_or_slash() {+ for (html, needle) in [+ (+ "<meta http-equiv=\"Content-Security-Policy\" content=\"script-src https://example.com/a~\" />",+ '+',+ ),+ ("<meta http-equiv=\"Content-Security-Policy\" content=\"img-src ???\">", '/'),+ ] {+ let patched = patch_csp_meta(html, 9797);+ let marker = marker_value(&patched);+ assert!(marker.contains(needle), "{marker} lacks {needle}");+ let reverted = revert_csp_meta(&patched);+ assert!(!reverted.contains(CSP_MARKER_ATTR), "{reverted}");+ assert_eq!(reverted, html);+ }+ }++ #[test]+ fn decode_leaves_unknown_and_bare_ampersands_alone() {+ assert_eq!(+ decode_html_attr_value("a & b © &#xZZ; &#"),+ "a & b © &#xZZ; &#"+ );+ // Numeric references without `;`, and NUL as U+FFFD, as browsers read them.+ assert_eq!(decode_html_attr_value("src �"), "src \u{FFFD}");+ assert_eq!(+ decode_html_attr_value("''''"&<>"),+ "''''\"&<>"+ );+ }++ #[test]+ fn existing_references_are_copied_through_unchanged() {+ // `c` (no `;`) is `c` to a browser, and `>` must stay escaped so+ // the tag reader still finds the end of the tag after the patch.+ let html = "<meta http-equiv=\"Content-Security-Policy\" content=\"object-src 'none'; img-src https://example.com/a>b © x; default-src *\">";+ let patched = patch_csp_meta(html, 9797);+ assert!(patched.contains("object-src 'none'; img-src https://example.com/a>b © x blob:; default-src *; script-src 'self' http://localhost:9797 'wasm-unsafe-eval'; connect-src 'self' http://localhost:9797\""), "{patched}");+ assert!(patched.contains(CSP_MARKER_ATTR));+ assert_eq!(revert_csp_meta(&patched), html);+ // Re-inject after remove patches the same way again.+ assert_eq!(patch_csp_meta(&revert_csp_meta(&patched), 9797), patched);+ }++ #[test]+ fn trailing_reference_semicolon_is_not_stripped() {+ let html =+ "<meta http-equiv=\"Content-Security-Policy\" content='default-src 'none''>";+ let patched = patch_csp_meta(html, 9797);+ assert_eq!(+ browser_policy(&patched),+ "default-src 'none'; script-src 'self' http://localhost:9797 'wasm-unsafe-eval'; connect-src 'self' http://localhost:9797; img-src 'self' blob:"+ );+ }++ #[test]+ fn directive_names_and_boundaries_are_read_decoded() {+ for (csp, expect) in [+ (+ "script-src 'self'",+ "script-src 'self' http://localhost:9797 'wasm-unsafe-eval'; connect-src 'self' http://localhost:9797; img-src 'self' blob:",+ ),+ (+ "script-src 'self'",+ "script-src 'self' http://localhost:9797 'wasm-unsafe-eval'; connect-src 'self' http://localhost:9797; img-src 'self' blob:",+ ),+ (+ "img-src 'self'; script-src 'self'",+ "img-src 'self' blob:; script-src 'self' http://localhost:9797 'wasm-unsafe-eval'; connect-src 'self' http://localhost:9797",+ ),+ ] {+ let html = format!("<meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\">");+ let patched = patch_csp_meta(&html, 9797);+ assert!(patched.contains(&format!("content=\"{expect}\"")), "{patched}");+ assert_eq!(revert_csp_meta(&patched), html);+ }+ }++ #[test]+ fn trailing_unterminated_reference_keeps_the_new_separator() {+ for (csp, base) in [+ (+ "default-src https://a.example/c",+ "default-src https://a.example/c ",+ ),+ (+ "default-src https://a.example/?a&",+ "default-src https://a.example/?a& ",+ ),+ ] {+ let html = format!("<meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\">");+ let patched = patch_csp_meta(&html, 9797);+ assert!(+ patched.contains(&format!(+ "content=\"{base}; script-src 'self' http://localhost:9797 'wasm-unsafe-eval';"+ )),+ "{patched}"+ );+ assert_eq!(revert_csp_meta(&patched), html);+ }+ }++ #[test]+ fn only_ascii_whitespace_and_exact_names_match_a_directive() {+ // ` ` is not CSP whitespace and `‐` is U+2010, so neither+ // value names script-src; the patch adds a real one.+ for csp in [+ "default-src 'self'; script-src 'self'",+ "default-src 'self'; script‐src 'self'",+ ] {+ let html = format!("<meta http-equiv=\"Content-Security-Policy\" content=\"{csp}\">");+ let patched = patch_csp_meta(&html, 9797);+ assert!(+ patched.contains(&format!(+ "content=\"{csp}; script-src 'self' http://localhost:9797 'wasm-unsafe-eval';"+ )),+ "{patched}"+ );+ assert_eq!(revert_csp_meta(&patched), html);+ }+ }++ #[test]+ fn patch_then_revert_is_byte_identical() {+ let cases = [+ "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'self'; script-src 'self'; img-src 'self'\">",+ "<meta http-equiv=\"Content-Security-Policy\" content='script-src https://example.com/a~' />",+ "<meta http-equiv=\"Content-Security-Policy\" content='script-src 'self' https://a.example; object-src 'none'' />",+ "<meta http-equiv=\"Content-Security-Policy\" content=\"script-src https://example.com/a~\" />",+ "<meta\n http-equiv=\"Content-Security-Policy\"\n content='default-src 'self'; connect-src ws:;'\n/>",+ "<meta http-equiv=\"Content-Security-Policy\" content=\"img-src ???; script-src https://x.example/?q=a&r="s"\"\t>",+ "<meta http-equiv=\"Content-Security-Policy\" content=\"object-src 'none'; img-src https://e.example/a>b; default-src *\">",+ "<meta http-equiv='Content-Security-Policy' content='default-src 'none''><meta http-equiv=\"Content-Security-Policy\" content=\"script-src 'self'\">",+ ];+ for csp in cases {+ let html =+ format!("<!DOCTYPE html>\r\n<html><head>{csp}</head><body>\r\n</body></html>\r\n");+ let patched = patch_csp_meta(&html, 9797);+ assert_ne!(patched, html, "nothing patched: {csp}");+ assert!(!browser_policy(&patched).is_empty());+ assert_eq!(revert_csp_meta(&patched), html, "revert: {csp}");+ // The full inject/remove cycle a live session runs.+ let injected = patch_csp_meta(+ &insert_tag(&html, "html", Some("</body>"), None, 9797, Some("t"), ""),+ 9797,+ );+ assert_eq!(unpatch_tag_file(&injected), html, "unpatch: {csp}");+ }+ }}diff --git a/docs/CLI-CONTRACT.md b/docs/CLI-CONTRACT.mdindex 5926fe548..60e1ef523 100644--- a/docs/CLI-CONTRACT.md+++ b/docs/CLI-CONTRACT.md@@ -1615,7 +1615,7 @@ Source traits by target file extension (first registry entry claiming the ext; d````open/close` = `<!--`/`-->` for `html`, `{/*`/`*/}` for `jsx`. Line endings normalized to the file's dominant one. `insertBefore`: inserted at LAST occurrence of anchor. `insertAfter`: after FIRST occurrence, preserving an existing newline right after the anchor. Anchor missing → content unchanged → result `{file, error:'insertion_point_not_found', anchor}`. Removal regex handles both comment styles, indent-preserving. Repeat inject first removes any old block and reverts CSP.-CSP meta patch: for `<meta http-equiv="Content-Security-Policy" content="…">` (not already carrying `data-impeccable-csp-original`): append `http://localhost:PORT` to `script-src` and `connect-src` (add directive as `; <dir> 'self' <origin>` if absent), and `blob:` to `img-src`; store original content base64 in `data-impeccable-csp-original="…"`. Revert decodes and restores, drops the marker attr.+CSP meta patch: for `<meta http-equiv="Content-Security-Policy" content="…">` (not already carrying `data-impeccable-csp-original`): append `http://localhost:PORT` to `script-src` and `connect-src` (add directive as `; <dir> 'self' <origin>` if absent), and `blob:` to `img-src`; store the original raw attribute text base64 in `data-impeccable-csp-original="…"`. The content value is patched in place on its raw text: directive names, `;` separators and existing sources are read on the decoded value the way a browser reads it (numeric references with or without `;`, and the named references that decode to ASCII; any other `&name;` is one opaque unit), the existing text and its references are copied through byte for byte, and only the inserted text is encoded for the attribute's own quote style (`&`, `<`, `>`, and the delimiting quote as `"` or `'`), so the inserted `'self'` and `'wasm-unsafe-eval'` cannot end a single-quoted attribute. A source is appended after the directive's last source; a value that ends in an unterminated reference gets a space before the added `;`. Revert writes the stored raw text back in the same quote style and removes the marker attr and the one space before it literally, so patch then revert is byte-identical (the JS built a regex from the base64 and left the marker behind when it held `+`).**Adapters** (kind `adapter`): SvelteKit, Nuxt, TanStack Start; the config `files` entry is NOT patched.- SvelteKit `apply({cwd,port,token,config})`: writes `src/lib/impeccable/ImpeccableLiveRoot.svelte` (script: onMount creates `<impeccable-live-root id="impeccable-live-root">` host with `all:initial;display:block;position:fixed;top:0;left:0;width:0;height:0;overflow:visible;z-index:2147483000;pointer-events:none` !important, open shadow root + reset style, sets `window.__IMPECCABLE_LIVE_ADAPTER__='sveltekit'`, `__IMPECCABLE_LIVE_UI_ROOT__`, `__IMPECCABLE_LIVE_CHROME_MOUNT__={adapter,version:1,host,root}`, appends `<script async src=LIVE_URL data-impeccable-live-script="true">`, cleanup on destroy). Patches layout (created with default `<script>\n let { children } = $props();\n</script>\n\n{@render children?.()}\n` if missing): import line `import ImpeccableLiveRoot from '$lib/impeccable/ImpeccableLiveRoot.svelte?impeccable-live=<sha256(token)[:8]>';` inserted after the first `<script…>` (or a new script block prepended), replacing an older-revision import in place; block `<!-- impeccable-live-svelte-start -->\n<ImpeccableLiveRoot />\n<!-- impeccable-live-svelte-end -->\n` inserted before `{@render children()}`/`<slot />` else appended. Result `{file: layoutRel, adapter:'sveltekit', inserted, appHtmlUntouched:true, rootComponent}`. Remove: unpatch layout (block, import, empty `<script></script>`, collapse 3+ newlines), delete component, prune empty dirs up to `src`. Journal artifacts: created `src/lib/impeccable/ImpeccableLiveRoot.svelte` marker `impeccable-live-root` pruneTo `src`; patched layout `patch:'sveltekit-layout'` markers `[SVELTE_LAYOUT_MARKER_OPEN]`.diff --git a/tests/oracle/DELTAS.md b/tests/oracle/DELTAS.mdindex 12e275678..50bb928fa 100644--- a/tests/oracle/DELTAS.md+++ b/tests/oracle/DELTAS.md@@ -7200,3 +7200,19 @@ The per-edit pass now records each project root it writes a cache in under a per## Recorded 2026-10-22: a signed value in a stylesheet shorthand keeps its spaceThe static cascade reads a stylesheet declaration back through the css-tree generator, which drops the space before a signed number wherever re-tokenizing gives the same tokens: `margin: 0 0 0 -24px` came back as `0 0 0-24px`, so the box expansion saw three values and the left margin was never negative (`margin: 0 -8px 0 0` read `0-8px` as its top margin and lost the right one; `inset: 0 -1px` and `-1px +2px` merged the same way). A `style=""` attribute was read from its raw text and never had the gap. At the top level of a declaration value, a number, percentage or dimension after another one or after a function (`10% 0`, written `10%0`; `var(--x) 0`, written `var(--x)0`) now keeps its space; text inside a function stays as css-tree writes it. `cramped-padding-shell.html` gains `flag-shell-shorthand-pull`, the `flag-shell-negative-margin` case written as a shorthand. Re-recorded from the binary and reviewed by hand: `detect-fixture-json-cramped-padding-shell-html` and `detect-fixture-text-cramped-padding-shell-html` gain that one finding, and the seven directory, scope and no-advisory sweeps (`detect-dir-{json,text,quiet}-all-fixtures`, `detect-no-advisory-{json,text}`, `detect-scope-both`, `detect-scope-layout-text`) gain the same finding and its count, and nothing else in them moved: no other fixture's finding depended on the merged text.++## Recorded 2026-10-22: CSP meta revert restores the original bytes (issue #1125)++The JS `revertCspMeta` removed the `data-impeccable-csp-original` marker with a+regex built from `\s*` plus the raw marker text. The `\s*` also ate the newline+before the marker when the attributes ended on their own line, so the reverted+tag lost that line break, and a base64 value holding `+` never matched, so the+marker stayed behind. The engine now removes the marker and the one space the+patch put before it literally. The goldens of `live-inject-vite-csp-meta` and+`live-inject-next-jsx` were re-recorded from the engine after a line-level+review: the only change is that the reverted file keeps the newline before+`/>`, which makes it byte-identical to the file before inject. They are+ordinary goldens again, not accepted deltas. The new cases+`live-inject-csp-meta-quote-styles` and `live-inject-csp-meta-quote-styles-remove`+pin the in-place patch of the raw content value (references kept, inserted+sources encoded for the quote style) and the round trip.diff --git a/tests/oracle/cases/live-roots.mjs b/tests/oracle/cases/live-roots.mjsindex 81f9ed7ed..6ea0f6717 100644--- a/tests/oracle/cases/live-roots.mjs+++ b/tests/oracle/cases/live-roots.mjs@@ -14,6 +14,8 @@ const PORT_NORM = [['Stopped live server on port \\d+\\.', 'g', 'Stopped live server on port <PORT>.'],];+const CSP_QUOTE_STYLES_HTML = '<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv="Content-Security-Policy" content=\'script-src 'self' https://a.example; object-src 'none'\' />\n<meta http-equiv="Content-Security-Policy" content="script-src https://example.com/a~" />\n</head>\n<body>\n<h1>Hi</h1>\n</body>\n</html>\n';+export default [// --- live.mjs (boot) ---{ id: 'live-help', verb: 'live', workspace: 'live-html', args: ['--help'] },@@ -93,6 +95,9 @@ export default [setup: (ws) => write(ws, 'index.html', '<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv="Content-Security-Policy" content="default-src \'self\'; script-src \'self\'">\n</head>\n<body>\n<h1 class="hero-title">Hi</h1>\n</body>\n</html>\n'),args: ['--port', '8412', '--token', 't'],},+ // Issue #1125: a single-quoted content attribute with entity-encoded quotes, and a policy whose base64 marker holds `+`. The first case pins the patched file; the second pins that remove restores it byte for byte.+ { id: 'live-inject-csp-meta-quote-styles', verb: 'live-inject', workspace: 'live-html', files: [...F, 'index.html'], setup: (ws) => write(ws, 'index.html', CSP_QUOTE_STYLES_HTML), args: ['--port', '8412', '--token', 't'] },+ { id: 'live-inject-csp-meta-quote-styles-remove', verb: 'live-inject', workspace: 'live-html', files: [...F, 'index.html'], setup: (ws) => write(ws, 'index.html', CSP_QUOTE_STYLES_HTML), steps: [{ args: ['--port', '8412', '--token', 't'] }, { args: ['--remove'] }] },{ id: 'live-inject-next-jsx', verb: 'live-inject', workspace: 'live-next', files: [...F, 'app/**'], steps: [{ args: ['--port', '8412', '--token', 't'] }, { args: ['--remove'] }] },{ id: 'live-inject-astro-inline', verb: 'live-inject', workspace: 'live-astro', files: [...F, 'src/**'], steps: [{ args: ['--port', '8412', '--token', 't'] }, { args: ['--remove'] }] },{ id: 'live-inject-sveltekit-adapter', verb: 'live-inject', workspace: 'live-sveltekit', files: [...F, 'src/**'], steps: [{ args: ['--port', '8412', '--token', 't'] }, { args: ['--port', '8412', '--token', 't'] }, { args: ['--remove'] }, { args: ['--remove'] }] },diff --git a/tests/oracle/golden/live-inject-csp-meta-quote-styles-remove.json b/tests/oracle/golden/live-inject-csp-meta-quote-styles-remove.jsonnew file mode 100644index 000000000..3f2a530ff--- /dev/null+++ b/tests/oracle/golden/live-inject-csp-meta-quote-styles-remove.json@@ -0,0 +1,21 @@+{+ "steps": [+ {+ "stdout": "{\"ok\":true,\"port\":8412,\"gitIgnore\":{\"file\":\".gitignore\",\"mode\":\"gitignore\",\"changed\":true,\"patterns\":[\".impeccable/hook.cache.json\",\".impeccable/hook.pending.json\",\".impeccable/config.local.json\",\".impeccable/live/server.json\",\".impeccable/live/roots.json\",\".impeccable/live/app-root.json\",\".impeccable/live/inject-journal.json\",\".impeccable/live/sessions/\",\".impeccable/live/previews/\",\".impeccable/live/annotations/\",\".impeccable/live/artifacts/\",\".impeccable/live/accept-receipts/\",\".impeccable/live/locks/\",\".impeccable/live/cache/\",\".impeccable/live/manual-edit-apply-transaction.json\",\".impeccable/live/manual-edit-events.jsonl\",\".impeccable/live/manual-edit-evidence/\",\".impeccable/live/pending-manual-edits.json\",\".impeccable/live/deferred-svelte-component-accepts.json\",\".impeccable-live.json\",\".impeccable-live/\",\"app/.impeccable-live/\",\"src/.impeccable-live/\",\"node_modules/.impeccable-live/\",\"src/lib/impeccable/ImpeccableLiveRoot.svelte\",\"src/lib/impeccable/__runtime.js\",\"src/lib/impeccable/[0-9a-f]*/\",\"plugins/impeccable-live.client.ts\",\"app/plugins/impeccable-live.client.ts\",\"src/plugins/impeccable-live.client.ts\"]},\"results\":[{\"file\":\"index.html\",\"inserted\":true,\"cspPatched\":true},{\"file\":\"public/no-body.html\",\"error\":\"insertion_point_not_found\",\"anchor\":\"</body>\"},{\"file\":\"public/docs/guide.html\",\"inserted\":true,\"cspPatched\":false}]}\n",+ "stderr": "",+ "exit": 0,+ "signal": null+ },+ {+ "stdout": "{\"ok\":true,\"results\":[{\"file\":\"index.html\",\"removed\":true,\"cspReverted\":true},{\"file\":\"public/no-body.html\",\"removed\":false,\"note\":\"no tag present\"},{\"file\":\"public/docs/guide.html\",\"removed\":true,\"cspReverted\":false}]}\n",+ "stderr": "",+ "exit": 0,+ "signal": null+ }+ ],+ "files": {+ ".gitignore": "# impeccable-live-ignore-start\n.impeccable/hook.cache.json\n.impeccable/hook.pending.json\n.impeccable/config.local.json\n.impeccable/live/server.json\n.impeccable/live/roots.json\n.impeccable/live/app-root.json\n.impeccable/live/inject-journal.json\n.impeccable/live/sessions/\n.impeccable/live/previews/\n.impeccable/live/annotations/\n.impeccable/live/artifacts/\n.impeccable/live/accept-receipts/\n.impeccable/live/locks/\n.impeccable/live/cache/\n.impeccable/live/manual-edit-apply-transaction.json\n.impeccable/live/manual-edit-events.jsonl\n.impeccable/live/manual-edit-evidence/\n.impeccable/live/pending-manual-edits.json\n.impeccable/live/deferred-svelte-component-accepts.json\n.impeccable-live.json\n.impeccable-live/\napp/.impeccable-live/\nsrc/.impeccable-live/\nnode_modules/.impeccable-live/\nsrc/lib/impeccable/ImpeccableLiveRoot.svelte\nsrc/lib/impeccable/__runtime.js\nsrc/lib/impeccable/[0-9a-f]*/\nplugins/impeccable-live.client.ts\napp/plugins/impeccable-live.client.ts\nsrc/plugins/impeccable-live.client.ts\n# impeccable-live-ignore-end\n",+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",+ "index.html": "<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content='script-src 'self' https://a.example; object-src 'none'' />\n<meta http-equiv=\"Content-Security-Policy\" content=\"script-src https://example.com/a~\" />\n</head>\n<body>\n<h1>Hi</h1>\n</body>\n</html>\n"+ }+}diff --git a/tests/oracle/golden/live-inject-csp-meta-quote-styles.json b/tests/oracle/golden/live-inject-csp-meta-quote-styles.jsonnew file mode 100644index 000000000..474795a6b--- /dev/null+++ b/tests/oracle/golden/live-inject-csp-meta-quote-styles.json@@ -0,0 +1,12 @@+{+ "stdout": "{\"ok\":true,\"port\":8412,\"gitIgnore\":{\"file\":\".gitignore\",\"mode\":\"gitignore\",\"changed\":true,\"patterns\":[\".impeccable/hook.cache.json\",\".impeccable/hook.pending.json\",\".impeccable/config.local.json\",\".impeccable/live/server.json\",\".impeccable/live/roots.json\",\".impeccable/live/app-root.json\",\".impeccable/live/inject-journal.json\",\".impeccable/live/sessions/\",\".impeccable/live/previews/\",\".impeccable/live/annotations/\",\".impeccable/live/artifacts/\",\".impeccable/live/accept-receipts/\",\".impeccable/live/locks/\",\".impeccable/live/cache/\",\".impeccable/live/manual-edit-apply-transaction.json\",\".impeccable/live/manual-edit-events.jsonl\",\".impeccable/live/manual-edit-evidence/\",\".impeccable/live/pending-manual-edits.json\",\".impeccable/live/deferred-svelte-component-accepts.json\",\".impeccable-live.json\",\".impeccable-live/\",\"app/.impeccable-live/\",\"src/.impeccable-live/\",\"node_modules/.impeccable-live/\",\"src/lib/impeccable/ImpeccableLiveRoot.svelte\",\"src/lib/impeccable/__runtime.js\",\"src/lib/impeccable/[0-9a-f]*/\",\"plugins/impeccable-live.client.ts\",\"app/plugins/impeccable-live.client.ts\",\"src/plugins/impeccable-live.client.ts\"]},\"results\":[{\"file\":\"index.html\",\"inserted\":true,\"cspPatched\":true},{\"file\":\"public/no-body.html\",\"error\":\"insertion_point_not_found\",\"anchor\":\"</body>\"},{\"file\":\"public/docs/guide.html\",\"inserted\":true,\"cspPatched\":false}]}\n",+ "stderr": "",+ "exit": 0,+ "signal": null,+ "files": {+ ".gitignore": "# impeccable-live-ignore-start\n.impeccable/hook.cache.json\n.impeccable/hook.pending.json\n.impeccable/config.local.json\n.impeccable/live/server.json\n.impeccable/live/roots.json\n.impeccable/live/app-root.json\n.impeccable/live/inject-journal.json\n.impeccable/live/sessions/\n.impeccable/live/previews/\n.impeccable/live/annotations/\n.impeccable/live/artifacts/\n.impeccable/live/accept-receipts/\n.impeccable/live/locks/\n.impeccable/live/cache/\n.impeccable/live/manual-edit-apply-transaction.json\n.impeccable/live/manual-edit-events.jsonl\n.impeccable/live/manual-edit-evidence/\n.impeccable/live/pending-manual-edits.json\n.impeccable/live/deferred-svelte-component-accepts.json\n.impeccable-live.json\n.impeccable-live/\napp/.impeccable-live/\nsrc/.impeccable-live/\nnode_modules/.impeccable-live/\nsrc/lib/impeccable/ImpeccableLiveRoot.svelte\nsrc/lib/impeccable/__runtime.js\nsrc/lib/impeccable/[0-9a-f]*/\nplugins/impeccable-live.client.ts\napp/plugins/impeccable-live.client.ts\nsrc/plugins/impeccable-live.client.ts\n# impeccable-live-ignore-end\n",+ ".impeccable/live/config.json": "{\n \"files\": [\"index.html\", \"public/**/*.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",+ ".impeccable/live/inject-journal.json": "{\n \"version\": 1,\n \"appRoot\": \"<WS>\",\n \"framework\": \"static-html\",\n \"port\": 8412,\n \"pid\": <PID>,\n \"recordedAt\": \"<ISO>\",\n \"artifacts\": [\n {\n \"kind\": \"patched\",\n \"path\": \"index.html\",\n \"patch\": \"live-tag\",\n \"markers\": [\n \"impeccable-live-start\",\n \"data-impeccable-csp-original\"\n ]\n },\n {\n \"kind\": \"patched\",\n \"path\": \"public/docs/guide.html\",\n \"patch\": \"live-tag\",\n \"markers\": [\n \"impeccable-live-start\",\n \"data-impeccable-csp-original\"\n ]\n }\n ]\n}\n",+ "index.html": "<!DOCTYPE html>\n<html>\n<head>\n<meta http-equiv=\"Content-Security-Policy\" content='script-src 'self' https://a.example http://localhost:8412 'wasm-unsafe-eval'; object-src 'none'; connect-src 'self' http://localhost:8412; img-src 'self' blob:' data-impeccable-csp-original=\"c2NyaXB0LXNyYyAmIzM5O3NlbGYmIzM5OyBodHRwczovL2EuZXhhbXBsZTsgb2JqZWN0LXNyYyAmI3gyNztub25lJiN4Mjc7\" />\n<meta http-equiv=\"Content-Security-Policy\" content=\"script-src https://example.com/a~ http://localhost:8412 'wasm-unsafe-eval'; connect-src 'self' http://localhost:8412; img-src 'self' blob:\" data-impeccable-csp-original=\"c2NyaXB0LXNyYyBodHRwczovL2V4YW1wbGUuY29tL2F+\" />\n</head>\n<body>\n<h1>Hi</h1>\n<!-- impeccable-live-start -->\n<script src=\"http://localhost:8412/live.js?token=t\"></script>\n<!-- impeccable-live-end -->\n</body>\n</html>\n"+ }+}diff --git a/tests/oracle/golden/live-inject-next-jsx.json b/tests/oracle/golden/live-inject-next-jsx.jsonindex 3be7933dc..f090f238f 100644--- a/tests/oracle/golden/live-inject-next-jsx.json+++ b/tests/oracle/golden/live-inject-next-jsx.json@@ -16,7 +16,7 @@"files": {".gitignore": "# impeccable-live-ignore-start\n.impeccable/hook.cache.json\n.impeccable/hook.pending.json\n.impeccable/config.local.json\n.impeccable/live/server.json\n.impeccable/live/roots.json\n.impeccable/live/app-root.json\n.impeccable/live/inject-journal.json\n.impeccable/live/sessions/\n.impeccable/live/previews/\n.impeccable/live/annotations/\n.impeccable/live/artifacts/\n.impeccable/live/accept-receipts/\n.impeccable/live/locks/\n.impeccable/live/cache/\n.impeccable/live/manual-edit-apply-transaction.json\n.impeccable/live/manual-edit-events.jsonl\n.impeccable/live/manual-edit-evidence/\n.impeccable/live/pending-manual-edits.json\n.impeccable/live/deferred-svelte-component-accepts.json\n.impeccable-live.json\n.impeccable-live/\napp/.impeccable-live/\nsrc/.impeccable-live/\nnode_modules/.impeccable-live/\nsrc/lib/impeccable/ImpeccableLiveRoot.svelte\nsrc/lib/impeccable/__runtime.js\nsrc/lib/impeccable/[0-9a-f]*/\nplugins/impeccable-live.client.ts\napp/plugins/impeccable-live.client.ts\nsrc/plugins/impeccable-live.client.ts\n# impeccable-live-ignore-end\n",".impeccable/live/config.json": "{\n \"files\": [\"app/layout.tsx\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"jsx\"\n}\n",- "app/layout.tsx": "export const metadata = { title: 'Next Fixture' };\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <head>\n <meta\n httpEquiv=\"Content-Security-Policy\"\n content=\"default-src 'self'; script-src 'self' 'unsafe-inline'; connect-src 'self'\" />\n </head>\n <body>\n {children}\n </body>\n </html>\n );\n}\n",+ "app/layout.tsx": "export const metadata = { title: 'Next Fixture' };\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n return (\n <html lang=\"en\">\n <head>\n <meta\n httpEquiv=\"Content-Security-Policy\"\n content=\"default-src 'self'; script-src 'self' 'unsafe-inline'; connect-src 'self'\"\n />\n </head>\n <body>\n {children}\n </body>\n </html>\n );\n}\n","app/page.tsx": "export default function Page() {\n return (\n <main className=\"page\">\n <h1 className=\"hero-title\">Next Fixture</h1>\n <p className=\"hero-hook\">Minimal Next app-router page.</p>\n </main>\n );\n}\n"}}diff --git a/tests/oracle/golden/live-inject-vite-csp-meta.json b/tests/oracle/golden/live-inject-vite-csp-meta.jsonindex d6cca3a80..7dc1f920a 100644--- a/tests/oracle/golden/live-inject-vite-csp-meta.json+++ b/tests/oracle/golden/live-inject-vite-csp-meta.json@@ -16,6 +16,6 @@"files": {".gitignore": "# impeccable-live-ignore-start\n.impeccable/hook.cache.json\n.impeccable/hook.pending.json\n.impeccable/config.local.json\n.impeccable/live/server.json\n.impeccable/live/roots.json\n.impeccable/live/app-root.json\n.impeccable/live/inject-journal.json\n.impeccable/live/sessions/\n.impeccable/live/previews/\n.impeccable/live/annotations/\n.impeccable/live/artifacts/\n.impeccable/live/accept-receipts/\n.impeccable/live/locks/\n.impeccable/live/cache/\n.impeccable/live/manual-edit-apply-transaction.json\n.impeccable/live/manual-edit-events.jsonl\n.impeccable/live/manual-edit-evidence/\n.impeccable/live/pending-manual-edits.json\n.impeccable/live/deferred-svelte-component-accepts.json\n.impeccable-live.json\n.impeccable-live/\napp/.impeccable-live/\nsrc/.impeccable-live/\nnode_modules/.impeccable-live/\nsrc/lib/impeccable/ImpeccableLiveRoot.svelte\nsrc/lib/impeccable/__runtime.js\nsrc/lib/impeccable/[0-9a-f]*/\nplugins/impeccable-live.client.ts\napp/plugins/impeccable-live.client.ts\nsrc/plugins/impeccable-live.client.ts\n# impeccable-live-ignore-end\n",".impeccable/live/config.json": "{\n \"files\": [\"index.html\"],\n \"insertBefore\": \"</body>\",\n \"commentSyntax\": \"html\"\n}\n",- "index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta\n http-equiv=\"Content-Security-Policy\"\n content=\"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; img-src 'self' data:;\" />\n <title>CSP</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.jsx\"></script>\n </body>\n</html>\n"+ "index.html": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\" />\n <meta\n http-equiv=\"Content-Security-Policy\"\n content=\"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss:; img-src 'self' data:;\"\n />\n <title>CSP</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"module\" src=\"/src/main.jsx\"></script>\n </body>\n</html>\n"}}