hemsby commited on
Commit
e3bd00e
·
1 Parent(s): ec8df18

fix: harden HTML output and interaction edge cases

Browse files

- Escape user inputs and attribute names in HTML (XSS prevention)
- Secure JSON in script blocks against </script> injection
- Add JS esc() helper for all innerHTML insertions
- Hoist focus state to module scope so profile close clears it
- Fix driver code extraction to break on non-string values
- Remove dead numpy import from parse_excel
- Clarify auto-detected classification counts in UI

Files changed (3) hide show
  1. app.py +2 -1
  2. build_network.py +80 -52
  3. parse_excel.py +1 -2
app.py CHANGED
@@ -97,7 +97,8 @@ if uploaded_file is not None:
97
  territories_str = ", ".join(rewards_factors[:6])
98
  if len(rewards_factors) > 6:
99
  territories_str += f", +{len(rewards_factors) - 6} more"
100
- st.caption(f"Reward territories: {territories_str}")
 
101
 
102
  except Exception as e:
103
  st.error(f"❌ Error loading file: {str(e)}")
 
97
  territories_str = ", ".join(rewards_factors[:6])
98
  if len(rewards_factors) > 6:
99
  territories_str += f", +{len(rewards_factors) - 6} more"
100
+ st.caption(f"Detected reward territories: {territories_str}")
101
+ st.caption("(Counts based on auto-detected row; final classification at generation)")
102
 
103
  except Exception as e:
104
  st.error(f"❌ Error loading file: {str(e)}")
build_network.py CHANGED
@@ -1,11 +1,17 @@
1
  """Generate interactive HTML network visualization from parsed correlation data."""
2
 
 
3
  import json
4
  import textwrap
5
  import numpy as np
6
  from config import COLORS
7
 
8
 
 
 
 
 
 
9
  def generate_network_html(network_data, threshold, max_l1_nodes,
10
  client_name, country_name, brand_name, category_name,
11
  show_category_index=True):
@@ -241,11 +247,25 @@ def _build_html_template(*, chart_title, client_name, country_name, brand_name,
241
  corr_count, avg_corr, max_corr):
242
  """Build the standalone HTML string. Separated for readability."""
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  return f"""<!DOCTYPE html>
245
  <html lang="en">
246
  <head>
247
  <meta charset="utf-8">
248
- <title>{chart_title} — Association Network</title>
249
  <link type="text/css" href="https://unpkg.com/vis-network@9.1.9/dist/dist/vis-network.min.css" rel="stylesheet" />
250
  <script src="https://unpkg.com/vis-network@9.1.9/dist/vis-network.min.js"></script>
251
  <style>
@@ -350,15 +370,60 @@ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans
350
  .bar-val {{ font-size: 11px; font-weight: 600; color: #888; min-width: 30px; text-align: right; flex-shrink: 0; }}
351
  </style>
352
  <script>
353
- var allNetworkNodes = {json.dumps(all_nodes)};
354
- var allNetworkEdges = {json.dumps(all_edges)};
355
- var driverList = {json.dumps(driver_list)};
356
- var nonrewardsSet = new Set({json.dumps(nonrewards_list)});
357
  var network = null;
358
  var nodesDS = null;
359
  var edgesDS = null;
360
  var currentSort = 'index'; // 'index' or 'name'
361
  var selectedIdx = 0;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362
 
363
  function destroy() {{ if (network !== null) {{ network.destroy(); network = null; }} }}
364
 
@@ -397,52 +462,11 @@ function draw(id) {{
397
  document.getElementById('edgeCount').textContent = data.edges.length;
398
 
399
  // Store original node styling for restore
400
- var origNodes = {{}};
401
  nodesDS.forEach(function(n) {{
402
  origNodes[n.id] = {{ color: n.color, font: n.font, borderWidth: n.borderWidth }};
403
  }});
404
- var clickedNode = null;
405
-
406
- var FADED = {{
407
- color: {{ background: '#f5f5f5', border: '#e0e0e0',
408
- highlight: {{ background: '#f5f5f5', border: '#e0e0e0' }},
409
- hover: {{ background: '#f5f5f5', border: '#e0e0e0' }} }},
410
- font: {{ color: '#ccc' }},
411
- borderWidth: 1
412
- }};
413
-
414
- function applyFocus(nodeId) {{
415
- var connected = network.getConnectedNodes(nodeId);
416
- var connEdges = network.getConnectedEdges(nodeId);
417
- var nUp = [];
418
- nodesDS.forEach(function(n) {{
419
- if (n.id !== nodeId && connected.indexOf(n.id) === -1) {{
420
- nUp.push({{ id: n.id, color: FADED.color, font: FADED.font, borderWidth: FADED.borderWidth }});
421
- }}
422
- }});
423
- nodesDS.update(nUp);
424
- var eUp = [];
425
- edgesDS.forEach(function(e) {{
426
- if (connEdges.indexOf(e.id) === -1) {{
427
- eUp.push({{ id: e.id, hidden: true }});
428
- }}
429
- }});
430
- edgesDS.update(eUp);
431
- }}
432
-
433
- function clearFocus() {{
434
- var nUp = [];
435
- nodesDS.forEach(function(n) {{
436
- var o = origNodes[n.id];
437
- if (o) nUp.push({{ id: n.id, color: o.color, font: o.font, borderWidth: o.borderWidth }});
438
- }});
439
- nodesDS.update(nUp);
440
- var eUp = [];
441
- edgesDS.forEach(function(e) {{
442
- eUp.push({{ id: e.id, hidden: false }});
443
- }});
444
- edgesDS.update(eUp);
445
- }}
446
 
447
  network.on('hoverNode', function(params) {{
448
  if (clickedNode) return;
@@ -503,7 +527,7 @@ function showProfile(nodeId) {{
503
  var pct = Math.round((b.value / maxVal) * 100);
504
  var cls = nonrewardsSet.has(b.name) ? 'nonreward' : 'reward';
505
  html += '<div class="bar-row">'
506
- + '<span class="bar-label" title="' + b.name + '">' + b.name + '</span>'
507
  + '<div class="bar-track"><div class="bar-fill ' + cls + '" style="width:' + pct + '%"></div></div>'
508
  + '<span class="bar-val">' + b.value.toFixed(1) + '</span>'
509
  + '</div>';
@@ -514,13 +538,17 @@ function showProfile(nodeId) {{
514
 
515
  function closeProfile() {{
516
  document.getElementById('profilePanel').classList.remove('open');
 
 
 
 
517
  }}
518
 
519
  function saveScreenshot() {{
520
  var canvas = document.getElementById('mynetwork').getElementsByTagName('canvas')[0];
521
  if (!canvas) return;
522
  var link = document.createElement('a');
523
- link.download = '{chart_title}_network.png';
524
  link.href = canvas.toDataURL('image/png');
525
  link.click();
526
  }}
@@ -552,7 +580,7 @@ function renderSidebar() {{
552
  var sel = d.index === selectedIdx ? ' selected' : '';
553
  html += '<div class="attr-row' + sel + '" data-index="' + d.index + '" onclick="draw(' + d.index + ')">'
554
  + '<div class="attr-dot ' + cls + '"></div>'
555
- + '<span class="attr-name">' + d.name + '</span>'
556
  + '<span class="attr-idx">' + d.catIdx + '</span>'
557
  + '</div>';
558
  }});
@@ -595,7 +623,7 @@ document.addEventListener('DOMContentLoaded', function() {{
595
  <svg class="decode-logo" viewBox="0 0 160 21" xmlns="http://www.w3.org/2000/svg"><path d="M0,0.69 L0,19.5 L10.2,19.5 C15.83,19.5 19.72,16.02 19.72,9.81 C19.72,2.8 14.52,0.69 10.2,0.69 L0,0.69 Z M3.78,4.47 L10.2,4.47 C13.14,4.47 15.94,5.59 15.94,10.02 C15.94,13.84 13.51,15.72 10.2,15.72 L3.78,15.72 L3.78,4.47 Z M28.69,0.69 L28.69,19.5 L45.82,19.5 L45.82,15.72 L32.46,15.72 L32.46,11.66 L41.98,11.66 L41.98,7.88 L32.46,7.88 L32.46,4.47 L45.39,4.47 L45.39,0.69 L28.69,0.69 Z M73.57,3.67 C71.57,2.25 68.92,0.11 64.05,0.11 C58.82,0.11 52.72,3.45 52.72,10.1 C52.72,16.63 57.95,20.08 64.27,20.08 C67.18,20.08 71.24,19.1 73.89,17.14 L72.19,13.65 C70.63,14.85 67.65,16.31 64.31,16.31 C58.9,16.31 56.5,13 56.5,10.21 C56.5,7.16 59.22,3.89 63.87,3.89 C67.54,3.89 70.12,5.96 71.35,6.97 L73.57,3.67 Z M92.96,20.08 C100.33,20.08 104.5,15.36 104.5,10.1 C104.5,4.79 100.4,0.11 92.96,0.11 C85.55,0.11 81.41,4.83 81.41,10.1 C81.41,15.36 85.59,20.08 92.96,20.08 Z M92.96,16.31 C88.27,16.31 85.19,13.36 85.19,10.1 C85.19,6.86 88.27,3.89 92.96,3.89 C97.64,3.89 100.73,6.83 100.73,10.1 C100.73,13.36 97.64,16.31 92.96,16.31 Z M113.94,0.69 L113.94,19.5 L124.15,19.5 C129.78,19.5 133.66,16.02 133.66,9.81 C133.66,2.8 128.47,0.69 124.15,0.69 L113.94,0.69 Z M117.72,4.47 L124.15,4.47 C127.09,4.47 129.88,5.59 129.88,10.02 C129.88,13.84 127.45,15.72 124.15,15.72 L117.72,15.72 L117.72,4.47 Z M142.63,0.69 L142.63,19.5 L159.77,19.5 L159.77,15.72 L146.41,15.72 L146.41,11.66 L155.93,11.66 L155.93,7.88 L146.41,7.88 L146.41,4.47 L159.33,4.47 L159.33,0.69 L142.63,0.69 Z" fill="#283273"/></svg>
596
  </div>
597
  <div class="header-center">
598
- <h1>{client_name} &middot; {brand_name} &middot; {country_name} &middot; {category_name}</h1>
599
  <div class="subtitle">Association Network</div>
600
  </div>
601
  <div class="legend-bar">
 
1
  """Generate interactive HTML network visualization from parsed correlation data."""
2
 
3
+ import html
4
  import json
5
  import textwrap
6
  import numpy as np
7
  from config import COLORS
8
 
9
 
10
+ def _safe_json(obj):
11
+ """JSON-encode and escape </script> sequences for safe embedding in HTML."""
12
+ return json.dumps(obj).replace('</','<\\/')
13
+
14
+
15
  def generate_network_html(network_data, threshold, max_l1_nodes,
16
  client_name, country_name, brand_name, category_name,
17
  show_category_index=True):
 
247
  corr_count, avg_corr, max_corr):
248
  """Build the standalone HTML string. Separated for readability."""
249
 
250
+ # Escape all user-supplied strings for safe HTML embedding
251
+ h = html.escape
252
+ safe_title = h(chart_title)
253
+ safe_client = h(client_name)
254
+ safe_brand = h(brand_name)
255
+ safe_country = h(country_name)
256
+ safe_category = h(category_name)
257
+
258
+ # JSON data for script block (escape </script> sequences)
259
+ nodes_json = _safe_json(all_nodes)
260
+ edges_json = _safe_json(all_edges)
261
+ drivers_json = _safe_json(driver_list)
262
+ nonrewards_json = _safe_json(nonrewards_list)
263
+
264
  return f"""<!DOCTYPE html>
265
  <html lang="en">
266
  <head>
267
  <meta charset="utf-8">
268
+ <title>{safe_title} — Association Network</title>
269
  <link type="text/css" href="https://unpkg.com/vis-network@9.1.9/dist/dist/vis-network.min.css" rel="stylesheet" />
270
  <script src="https://unpkg.com/vis-network@9.1.9/dist/vis-network.min.js"></script>
271
  <style>
 
370
  .bar-val {{ font-size: 11px; font-weight: 600; color: #888; min-width: 30px; text-align: right; flex-shrink: 0; }}
371
  </style>
372
  <script>
373
+ var allNetworkNodes = {nodes_json};
374
+ var allNetworkEdges = {edges_json};
375
+ var driverList = {drivers_json};
376
+ var nonrewardsSet = new Set({nonrewards_json});
377
  var network = null;
378
  var nodesDS = null;
379
  var edgesDS = null;
380
  var currentSort = 'index'; // 'index' or 'name'
381
  var selectedIdx = 0;
382
+ var origNodes = {{}};
383
+ var clickedNode = null;
384
+
385
+ var FADED = {{
386
+ color: {{ background: '#f5f5f5', border: '#e0e0e0',
387
+ highlight: {{ background: '#f5f5f5', border: '#e0e0e0' }},
388
+ hover: {{ background: '#f5f5f5', border: '#e0e0e0' }} }},
389
+ font: {{ color: '#ccc' }},
390
+ borderWidth: 1
391
+ }};
392
+
393
+ function esc(s) {{ return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }}
394
+
395
+ function applyFocus(nodeId) {{
396
+ var connected = network.getConnectedNodes(nodeId);
397
+ var connEdges = network.getConnectedEdges(nodeId);
398
+ var nUp = [];
399
+ nodesDS.forEach(function(n) {{
400
+ if (n.id !== nodeId && connected.indexOf(n.id) === -1) {{
401
+ nUp.push({{ id: n.id, color: FADED.color, font: FADED.font, borderWidth: FADED.borderWidth }});
402
+ }}
403
+ }});
404
+ nodesDS.update(nUp);
405
+ var eUp = [];
406
+ edgesDS.forEach(function(e) {{
407
+ if (connEdges.indexOf(e.id) === -1) {{
408
+ eUp.push({{ id: e.id, hidden: true }});
409
+ }}
410
+ }});
411
+ edgesDS.update(eUp);
412
+ }}
413
+
414
+ function clearFocus() {{
415
+ var nUp = [];
416
+ nodesDS.forEach(function(n) {{
417
+ var o = origNodes[n.id];
418
+ if (o) nUp.push({{ id: n.id, color: o.color, font: o.font, borderWidth: o.borderWidth }});
419
+ }});
420
+ nodesDS.update(nUp);
421
+ var eUp = [];
422
+ edgesDS.forEach(function(e) {{
423
+ eUp.push({{ id: e.id, hidden: false }});
424
+ }});
425
+ edgesDS.update(eUp);
426
+ }}
427
 
428
  function destroy() {{ if (network !== null) {{ network.destroy(); network = null; }} }}
429
 
 
462
  document.getElementById('edgeCount').textContent = data.edges.length;
463
 
464
  // Store original node styling for restore
465
+ origNodes = {{}};
466
  nodesDS.forEach(function(n) {{
467
  origNodes[n.id] = {{ color: n.color, font: n.font, borderWidth: n.borderWidth }};
468
  }});
469
+ clickedNode = null;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
 
471
  network.on('hoverNode', function(params) {{
472
  if (clickedNode) return;
 
527
  var pct = Math.round((b.value / maxVal) * 100);
528
  var cls = nonrewardsSet.has(b.name) ? 'nonreward' : 'reward';
529
  html += '<div class="bar-row">'
530
+ + '<span class="bar-label" title="' + esc(b.name) + '">' + esc(b.name) + '</span>'
531
  + '<div class="bar-track"><div class="bar-fill ' + cls + '" style="width:' + pct + '%"></div></div>'
532
  + '<span class="bar-val">' + b.value.toFixed(1) + '</span>'
533
  + '</div>';
 
538
 
539
  function closeProfile() {{
540
  document.getElementById('profilePanel').classList.remove('open');
541
+ if (clickedNode) {{
542
+ clickedNode = null;
543
+ clearFocus();
544
+ }}
545
  }}
546
 
547
  function saveScreenshot() {{
548
  var canvas = document.getElementById('mynetwork').getElementsByTagName('canvas')[0];
549
  if (!canvas) return;
550
  var link = document.createElement('a');
551
+ link.download = '{safe_title}_network.png';
552
  link.href = canvas.toDataURL('image/png');
553
  link.click();
554
  }}
 
580
  var sel = d.index === selectedIdx ? ' selected' : '';
581
  html += '<div class="attr-row' + sel + '" data-index="' + d.index + '" onclick="draw(' + d.index + ')">'
582
  + '<div class="attr-dot ' + cls + '"></div>'
583
+ + '<span class="attr-name">' + esc(d.name) + '</span>'
584
  + '<span class="attr-idx">' + d.catIdx + '</span>'
585
  + '</div>';
586
  }});
 
623
  <svg class="decode-logo" viewBox="0 0 160 21" xmlns="http://www.w3.org/2000/svg"><path d="M0,0.69 L0,19.5 L10.2,19.5 C15.83,19.5 19.72,16.02 19.72,9.81 C19.72,2.8 14.52,0.69 10.2,0.69 L0,0.69 Z M3.78,4.47 L10.2,4.47 C13.14,4.47 15.94,5.59 15.94,10.02 C15.94,13.84 13.51,15.72 10.2,15.72 L3.78,15.72 L3.78,4.47 Z M28.69,0.69 L28.69,19.5 L45.82,19.5 L45.82,15.72 L32.46,15.72 L32.46,11.66 L41.98,11.66 L41.98,7.88 L32.46,7.88 L32.46,4.47 L45.39,4.47 L45.39,0.69 L28.69,0.69 Z M73.57,3.67 C71.57,2.25 68.92,0.11 64.05,0.11 C58.82,0.11 52.72,3.45 52.72,10.1 C52.72,16.63 57.95,20.08 64.27,20.08 C67.18,20.08 71.24,19.1 73.89,17.14 L72.19,13.65 C70.63,14.85 67.65,16.31 64.31,16.31 C58.9,16.31 56.5,13 56.5,10.21 C56.5,7.16 59.22,3.89 63.87,3.89 C67.54,3.89 70.12,5.96 71.35,6.97 L73.57,3.67 Z M92.96,20.08 C100.33,20.08 104.5,15.36 104.5,10.1 C104.5,4.79 100.4,0.11 92.96,0.11 C85.55,0.11 81.41,4.83 81.41,10.1 C81.41,15.36 85.59,20.08 92.96,20.08 Z M92.96,16.31 C88.27,16.31 85.19,13.36 85.19,10.1 C85.19,6.86 88.27,3.89 92.96,3.89 C97.64,3.89 100.73,6.83 100.73,10.1 C100.73,13.36 97.64,16.31 92.96,16.31 Z M113.94,0.69 L113.94,19.5 L124.15,19.5 C129.78,19.5 133.66,16.02 133.66,9.81 C133.66,2.8 128.47,0.69 124.15,0.69 L113.94,0.69 Z M117.72,4.47 L124.15,4.47 C127.09,4.47 129.88,5.59 129.88,10.02 C129.88,13.84 127.45,15.72 124.15,15.72 L117.72,15.72 L117.72,4.47 Z M142.63,0.69 L142.63,19.5 L159.77,19.5 L159.77,15.72 L146.41,15.72 L146.41,11.66 L155.93,11.66 L155.93,7.88 L146.41,7.88 L146.41,4.47 L159.33,4.47 L159.33,0.69 L142.63,0.69 Z" fill="#283273"/></svg>
624
  </div>
625
  <div class="header-center">
626
+ <h1>{safe_client} &middot; {safe_brand} &middot; {safe_country} &middot; {safe_category}</h1>
627
  <div class="subtitle">Association Network</div>
628
  </div>
629
  <div class="legend-bar">
parse_excel.py CHANGED
@@ -172,7 +172,7 @@ def extract_network_data(df, data_start_row, corr_col_start, rewards_factors):
172
  driver_code = df.iloc[4, col_idx]
173
  if pd.notna(driver_code) and isinstance(driver_code, str) and driver_code.strip():
174
  driver_codes.append(str(driver_code))
175
- elif pd.isna(driver_code) or driver_code == '':
176
  break
177
 
178
  # Get attributes from rows
@@ -212,7 +212,6 @@ def extract_network_data(df, data_start_row, corr_col_start, rewards_factors):
212
  driver_names = [code_to_name.get(code, code) for code in driver_codes]
213
 
214
  # Build correlation matrix
215
- import numpy as np
216
  corr_data = []
217
  for row_idx in range(data_start_idx, data_start_idx + len(attribute_names)):
218
  row_data = []
 
172
  driver_code = df.iloc[4, col_idx]
173
  if pd.notna(driver_code) and isinstance(driver_code, str) and driver_code.strip():
174
  driver_codes.append(str(driver_code))
175
+ else:
176
  break
177
 
178
  # Get attributes from rows
 
212
  driver_names = [code_to_name.get(code, code) for code in driver_codes]
213
 
214
  # Build correlation matrix
 
215
  corr_data = []
216
  for row_idx in range(data_start_idx, data_start_idx + len(attribute_names)):
217
  row_data = []