Skip to content

Commit e16134f

Browse files
Hyperlinking ChartJS Bubbles and the Class Relationship column (#17)
* Hyperlinking ChartJS Bubbles and the Class Relationship column Hyperlinking ChartJS Bubbles and the Class & Package Relationship columns * Document initBubbleChart parameters and behavior with JSDoc * Applied CodeRabbit suggestions: Update mustache partial rendering and link validation for class-relationships source links. * Applied CodeRabbit suggestion: Add tooltip for hover effect only if URL is an HTTP or HTTPS URL * Applied CodeRabbit suggestions * Fix CodeRabbit issues in PR #17 --------- Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
1 parent dd35ad5 commit e16134f

7 files changed

Lines changed: 301 additions & 9 deletions

File tree

‎assets/refactor-first-report.mustache‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@
469469
<tbody>
470470
{{#classRelationshipsToRemove.relationships}}
471471
<tr>
472-
<td class="rf-text-left">{{renderedLabel}}</td>
472+
<td class="rf-text-left">{{{safeRenderedLabel}}}</td>
473473
<td class="rf-text-right">{{priority}}</td>
474474
<td class="rf-text-right">{{cycleCount}}</td>
475475
<td class="rf-text-right">{{effortRank}}</td>
@@ -579,7 +579,7 @@
579579
<tbody>
580580
{{#packageRelationshipsToRemove.relationships}}
581581
<tr>
582-
<td class="rf-text-left">{{{renderedLabel}}}</td>
582+
<td class="rf-text-left">{{{safeRenderedLabel}}}</td>
583583
<td class="rf-text-right">{{priority}}</td>
584584
<td class="rf-text-right">{{cycleCount}}</td>
585585
<td class="rf-text-right">{{effortRank}}</td>

‎lib/renderer.js‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,27 @@ function registerLinkSafetyHook() {
5050
linkSafetyHookRegistered = true;
5151
}
5252

53+
/**
54+
* Copies a relationship with label markup limited to source links and markers.
55+
* The report-wide sanitizer permits template styles, so labels need their own
56+
* allow-list before interpolation. Never trust a precomputed value from JSON.
57+
*
58+
* @param {object} relationship - Raw relationship data.
59+
* @returns {object} Relationship with a restricted HTML label.
60+
*/
61+
function prepareRelationship(relationship) {
62+
registerLinkSafetyHook();
63+
return {
64+
...relationship,
65+
safeRenderedLabel: DOMPurify.sanitize(relationship.renderedLabel ?? '', {
66+
ALLOWED_TAGS: ['a', 'strong'],
67+
ALLOWED_ATTR: ['href', 'target', 'rel'],
68+
ALLOW_DATA_ATTR: false,
69+
ALLOW_ARIA_ATTR: false
70+
})
71+
};
72+
}
73+
5374
// ---------------------------------------------------------------------------
5475
// Enhanced tables: filter -> sort -> paginate pipeline feeding the template
5576
// (plan Phase 3). prepareReportData returns a shallow-copied report object
@@ -170,7 +191,7 @@ export function prepareReportData(data, tableStates = {}, config = TABLE_CONFIG)
170191
descriptor, data.classRelationshipsToRemove.relationships, stateOf(descriptor.id), config);
171192
result.classRelationshipsToRemove = {
172193
...data.classRelationshipsToRemove,
173-
relationships: rows,
194+
relationships: rows.map(prepareRelationship),
174195
tableUi: ui
175196
};
176197
}
@@ -181,7 +202,7 @@ export function prepareReportData(data, tableStates = {}, config = TABLE_CONFIG)
181202
descriptor, data.packageRelationshipsToRemove.relationships, stateOf(descriptor.id), config);
182203
result.packageRelationshipsToRemove = {
183204
...data.packageRelationshipsToRemove,
184-
relationships: rows,
205+
relationships: rows.map(prepareRelationship),
185206
tableUi: ui
186207
};
187208
}

‎lib/report-view.js‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,39 @@ export function bindThemeChartRedraw() {
508508
}
509509
}
510510

511+
/**
512+
* Validates an untrusted URL from the report payload before it reaches
513+
* window.open: only absolute http:/https: URLs pass, so injected schemes
514+
* (javascript:, data:, file:, …) and malformed values are rejected.
515+
*
516+
* @param {*} value - Candidate URL from the fetched report data.
517+
* @returns {boolean} True when value parses to an http: or https: URL.
518+
*/
519+
export function isHttpUrl(value) {
520+
if (typeof value !== 'string') return false;
521+
let parsed;
522+
try {
523+
parsed = new URL(value);
524+
} catch {
525+
return false;
526+
}
527+
return parsed.protocol === 'http:' || parsed.protocol === 'https:';
528+
}
529+
530+
/**
531+
* Creates a disharmony bubble chart, replacing any chart on the canvas and
532+
* registering it for theme redraws. Clicking a bubble with a URL opens its
533+
* source in a new tab with noopener. Warns and returns if Chart.js is unavailable.
534+
*
535+
* @param {HTMLCanvasElement} canvas - Canvas on which to render the chart.
536+
* @param {string} title - Dataset label displayed in the legend.
537+
* @param {object} chartData - Report chart data with optional bubbles and axis labels.
538+
* @param {Array<object>} [chartData.bubbles] - Bubble coordinates, radius, colors,
539+
* label, priority, and optional source URL.
540+
* @param {string} [chartData.xaxisLabel] - Overrides the effort axis label.
541+
* @param {string} [chartData.yaxisLabel] - Overrides the relative churn axis label.
542+
* @returns {void}
543+
*/
511544
export function initBubbleChart(canvas, title, chartData) {
512545
const ChartLib = window.Chart;
513546
if (!ChartLib) {
@@ -532,6 +565,41 @@ export function initBubbleChart(canvas, title, chartData) {
532565
options: {
533566
responsive: true,
534567
maintainAspectRatio: false,
568+
// Clicking a bubble opens the source file the report links it
569+
// to (disharmonies[].chart.bubbles[].url) in a new tab, with
570+
// noopener so the opened page can't reach back into this one.
571+
onClick: (event, elements, chart) => {
572+
const hit = elements && elements[0];
573+
if (!hit || !chart || !chart.data || !chart.data.datasets) return;
574+
const point = chart.data.datasets[hit.datasetIndex];
575+
const url = point && point.data && point.data[hit.index] && point.data[hit.index].raw
576+
? point.data[hit.index].raw.url
577+
: null;
578+
// The url comes from the fetched report payload, which is
579+
// untrusted: only parsed http(s) URLs may reach
580+
// window.open, so a malicious javascript:/data: value
581+
// can't execute when the bubble is clicked.
582+
if (isHttpUrl(url) && typeof window !== 'undefined' && typeof window.open === 'function') {
583+
window.open(url, '_blank', 'noopener');
584+
}
585+
},
586+
// Pointer affordance while the cursor is over a bubble — only
587+
// when the hovered bubble carries a URL the click handler would
588+
// actually open (isHttpUrl), so the hover hint can never
589+
// promise a navigation the click refuses to perform.
590+
onHover: (event, elements, chart) => {
591+
if (!event || !event.native || !event.native.target) return;
592+
const hit = elements && elements[0];
593+
const dataset = hit && chart && chart.data && chart.data.datasets
594+
? chart.data.datasets[hit.datasetIndex]
595+
: null;
596+
const raw = dataset && dataset.data && dataset.data[hit.index]
597+
? dataset.data[hit.index].raw
598+
: null;
599+
event.native.target.style.cursor = hit && isHttpUrl(raw ? raw.url : null)
600+
? 'pointer'
601+
: 'default';
602+
},
535603
plugins: {
536604
legend: {
537605
display: true,
@@ -565,12 +633,18 @@ export function initBubbleChart(canvas, title, chartData) {
565633
callbacks: {
566634
label: context => {
567635
const raw = context.raw.raw;
568-
return [
636+
const lines = [
569637
`File: ${raw.label}`,
570638
`Priority: ${raw.priority}`,
571639
`Effort Rank: ${raw.x}`,
572640
`Change Proneness Rank: ${raw.y}`
573641
];
642+
// Same gate as the click handler: the prompt
643+
// only appears when the url is actually
644+
// openable (isHttpUrl), never for scheme-
645+
// injected or malformed values.
646+
if (isHttpUrl(raw.url)) lines.push('Click to open source file');
647+
return lines;
574648
}
575649
}
576650
}

‎public/assets/refactor-first-report.mustache‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@
469469
<tbody>
470470
{{#classRelationshipsToRemove.relationships}}
471471
<tr>
472-
<td class="rf-text-left">{{renderedLabel}}</td>
472+
<td class="rf-text-left">{{{safeRenderedLabel}}}</td>
473473
<td class="rf-text-right">{{priority}}</td>
474474
<td class="rf-text-right">{{cycleCount}}</td>
475475
<td class="rf-text-right">{{effortRank}}</td>
@@ -579,7 +579,7 @@
579579
<tbody>
580580
{{#packageRelationshipsToRemove.relationships}}
581581
<tr>
582-
<td class="rf-text-left">{{{renderedLabel}}}</td>
582+
<td class="rf-text-left">{{{safeRenderedLabel}}}</td>
583583
<td class="rf-text-right">{{priority}}</td>
584584
<td class="rf-text-right">{{cycleCount}}</td>
585585
<td class="rf-text-right">{{effortRank}}</td>

‎tests/integration/report-view.test.jsx‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -160,10 +160,16 @@ describe('ReportView', () => {
160160
expect(container.querySelector('[role="alert"]')).not.toBeNull();
161161
});
162162

163-
test('escapes renderedLabel in class relationships', async () => {
163+
test('hyperlinks the Class Relationship column like the Package Relationships table', async () => {
164164
respondJsonFor(sampleJson);
165165
const { container } = await renderReport();
166-
expect(container.innerHTML).toContain('&lt;a href=https://github.com/junit-team/junit4');
166+
const table = container.querySelector('table[data-rf-table="class-relationships"]');
167+
expect(table).not.toBeNull();
168+
const link = table.querySelector('tbody a[href^="https://github.com/junit-team/junit4"]');
169+
expect(link).not.toBeNull();
170+
expect(link.getAttribute('target')).toBe('_blank');
171+
expect(link.getAttribute('rel')).toContain('noopener');
172+
expect(container.innerHTML).not.toContain('<a href=https://github.com/junit-team/junit4');
167173
expect(container.querySelector('.rf-report')).not.toBeNull();
168174
});
169175

‎tests/unit/renderer.test.js‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -184,6 +184,82 @@ describe('templating safety (repository-provided templates are untrusted)', () =
184184
});
185185
});
186186

187+
// ---------------------------------------------------------------------------
188+
// Source-link cell output: both report templates render the class-
189+
// relationships cell inline; the rendering layer owns
190+
// the link-safety behavior around it. These guards pin the rendered output
191+
// so template or renderer changes cannot silently drop or weaken the
192+
// source links.
193+
// ---------------------------------------------------------------------------
194+
195+
describe('source-link cell rendering (owned by the report rendering layer)', () => {
196+
const junitFixture = JSON.parse(
197+
readFileSync(path.join(import.meta.dir, '../fixtures/junit4-report.json'), 'utf8')
198+
);
199+
200+
for (const templatePath of ['assets', 'public/assets']) {
201+
it(`restricts relationship labels to links and markers in ${templatePath}`, () => {
202+
const template = readFileSync(
203+
path.join(import.meta.dir, `../../${templatePath}/refactor-first-report.mustache`), 'utf8'
204+
);
205+
const renderedLabel =
206+
'<style>body { display: none }</style>' +
207+
'<a href="https://example.com/source" target="_blank" rel="opener" ' +
208+
'style="display:none" class="close-btn" id="app" onclick="alert(1)" ' +
209+
'data-rf-sort="class-relationships" aria-hidden="true">Source</a>' +
210+
'<strong style="display:none">*</strong> &#8594; Target : 1' +
211+
'<img src="https://example.com/tracker"><button>Injected</button>' +
212+
'<a href="javascript:alert(1)">Unsafe</a>';
213+
const data = structuredClone(junitFixture);
214+
for (const key of ['classRelationshipsToRemove', 'packageRelationshipsToRemove']) {
215+
data[key].relationships = [
216+
{ ...data[key].relationships[0], renderedLabel,
217+
safeRenderedLabel: '<style>body { color: red }</style>' },
218+
{ priority: 2, renderedLabel: null, safeRenderedLabel: '<strong>Forged</strong>' }
219+
];
220+
}
221+
const original = structuredClone(data);
222+
const html = renderTemplate(template, prepareReportData(data));
223+
const doc = new JSDOM(html).window.document;
224+
expect(data).toEqual(original);
225+
expect(html).not.toContain('body {');
226+
for (const table of ['class-relationships', 'package-relationships']) {
227+
const cells = doc.querySelectorAll(`table[data-rf-table="${table}"] tbody tr td:first-child`);
228+
const cell = cells[0];
229+
expect(cell.textContent).toContain('Source* → Target : 1');
230+
expect(cell.querySelector('strong')?.textContent).toBe('*');
231+
expect(cell.querySelector('a')?.getAttribute('href')).toBe('https://example.com/source');
232+
expect(cell.querySelector('a')?.getAttribute('target')).toBe('_blank');
233+
expect(cell.querySelector('a')?.getAttribute('rel')).toBe('noopener noreferrer');
234+
expect(cell.querySelector('a:last-child')?.hasAttribute('href')).toBe(false);
235+
for (const element of cell.querySelectorAll('*')) {
236+
expect(['A', 'STRONG']).toContain(element.tagName);
237+
for (const attribute of element.attributes) {
238+
expect(['href', 'target', 'rel']).toContain(attribute.name);
239+
}
240+
}
241+
expect(cells[1].textContent).toBe('');
242+
}
243+
});
244+
}
245+
246+
it('renders the class-relationships source-link cell with a hardened anchor', () => {
247+
const template = readFileSync(
248+
path.join(import.meta.dir, '../../assets/refactor-first-report.mustache'), 'utf8'
249+
);
250+
const html = renderTemplate(template, prepareReportData(junitFixture));
251+
const doc = new JSDOM(html).window.document;
252+
const cell = doc.querySelector(
253+
'table[data-rf-table="class-relationships"] tbody td.rf-text-left'
254+
);
255+
expect(cell).not.toBeNull();
256+
const link = cell.querySelector('a[target="_blank"]');
257+
expect(link).not.toBeNull();
258+
expect(link.getAttribute('href')).toContain('https://github.com/junit-team/junit4/blob/');
259+
expect(link.getAttribute('rel')).toBe('noopener noreferrer');
260+
});
261+
});
262+
187263
// ---------------------------------------------------------------------------
188264
// prepareReportData: filter -> sort -> paginate pipeline feeding the report
189265
// template with paginated rows and tableUi metadata (plan Phase 3).

0 commit comments

Comments
 (0)