-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
482 lines (414 loc) · 19.3 KB
/
Copy pathscript.js
File metadata and controls
482 lines (414 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
const state = {
rating: 3,
url: 'https://cyberthing.trustmark',
regId: 'AU-CT-2026-0000',
expiryYears: 5,
expiryDate: '',
productName: 'Smart Home Device',
testDate: new Date().toISOString().split('T')[0],
iotClouds: ['Google Home', 'Apple Home', 'Amazon Alexa', 'HomeAssistant'],
remoteAccess: 'Yes',
appType: 'Proprietary',
comments: '',
themeColor: '#2a64ad',
showTestingInfo: false,
showIP: false,
ipAddress: ''
};
// DOM Elements
const labelForm = document.getElementById('labelForm');
const viewExampleBtn = document.getElementById('viewExampleBtn');
const closeModal = document.getElementById('closeModal');
const modalBackdrop = document.getElementById('modalBackdrop');
const downloadSvgBtn = document.getElementById('downloadSvg');
const downloadPngBtn = document.getElementById('downloadPng');
const statusMessage = document.getElementById('statusMessage');
const labelWrapper = document.getElementById('labelWrapper');
const modalProductName = document.getElementById('modalProductName');
const modalManufacturer = document.getElementById('modalManufacturer');
const modalTrustmark = document.getElementById('modalTrustmark');
/**
* Security: Escape HTML special characters to prevent XSS.
*/
function escapeHTML(str) {
if (typeof str !== 'string') return '';
return str.replace(/[&<>"']/g, m => ({
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
}[m]));
}
/**
* Security: Validate and normalize state values.
*/
function validateState(key, value) {
switch (key) {
case 'rating':
const r = parseInt(value);
return (isNaN(r) || r < 0 || r > 3) ? 3 : r;
case 'expiryYears':
const y = parseInt(value);
return [1, 3, 5, 7].includes(y) ? y : 5;
case 'themeColor':
return /^#[0-9A-F]{6}$/i.test(value) ? value : '#2a64ad';
case 'url':
case 'productName':
case 'appType':
case 'comments':
return String(value).substring(0, 80); // Stricter limit
case 'regId':
return String(value).substring(0, 100); // Safe length limit
case 'testDate':
return /^\d{4}-\d{2}-\d{2}$/.test(value) ? value : new Date().toISOString().split('T')[0];
case 'iotClouds':
const clouds = Array.isArray(value) ? value : (typeof value === 'string' ? value.split(',') : []);
return clouds.filter(v => typeof v === 'string' && v.length > 0).map(v => v.substring(0, 30));
case 'remoteAccess':
return ['Yes', 'No'].includes(value) ? value : 'Yes';
case 'showTestingInfo':
case 'showIP':
return value === 'true' || value === true;
case 'ipAddress':
return String(value).substring(0, 45);
default:
return value;
}
}
// Initialize
loadStateFromURL();
calculateDateFromYears();
fetchVisitorCount();
initPills();
updateLabel();
// Event Listeners
labelForm.addEventListener('input', (e) => {
const { id, value, type, checked } = e.target;
if (type === 'checkbox') {
state[id] = checked;
if (id === 'showIP') {
const container = document.getElementById('ipInputContainer');
if (container) container.style.display = checked ? 'block' : 'none';
}
} else if (id === 'expiryYears') {
state.expiryYears = parseInt(value);
calculateDateFromYears();
} else {
state[id] = id === 'rating' ? parseInt(value) : value;
}
updateURL();
updateLabel();
});
viewExampleBtn.addEventListener('click', () => {
showVerificationExample();
});
closeModal.addEventListener('click', () => {
modalBackdrop.classList.remove('active');
});
modalBackdrop.addEventListener('click', (e) => {
if (e.target === modalBackdrop) modalBackdrop.classList.remove('active');
});
function initPills() {
const pills = document.querySelectorAll('.pill');
pills.forEach(pill => {
pill.addEventListener('click', () => {
const val = pill.getAttribute('data-value');
if (state.iotClouds.includes(val)) {
state.iotClouds = state.iotClouds.filter(c => c !== val);
pill.classList.remove('active');
} else {
state.iotClouds.push(val);
pill.classList.add('active');
}
updateURL();
updateLabel();
});
});
}
async function fetchVisitorCount() {
try {
const response = await fetch('https://api.counterapi.dev/v1/cttm-generator/visitor-count/up');
const data = await response.json();
const count = String(data.count).padStart(4, '0');
state.regId = `AU-CR-2026-${count}`;
updateLabel();
} catch (err) {
state.regId = `AU-CR-2026-0001`; // Fallback
updateLabel();
}
}
function calculateDateFromYears() {
const now = new Date();
const expiry = new Date(now.setFullYear(now.getFullYear() + state.expiryYears));
state.expiryDate = expiry.toISOString().split('T')[0];
}
function syncForm() {
Object.keys(state).forEach(key => {
const input = document.getElementById(key);
if (input) input.value = state[key];
});
// Sync pills
document.querySelectorAll('.pill').forEach(pill => {
const val = pill.getAttribute('data-value');
if (state.iotClouds.includes(val)) pill.classList.add('active');
else pill.classList.remove('active');
});
// Checkboxes and conditional visibility
document.getElementById('showTestingInfo').checked = state.showTestingInfo;
document.getElementById('showIP').checked = state.showIP;
document.getElementById('ipAddress').value = state.ipAddress;
document.getElementById('ipInputContainer').style.display = state.showIP ? 'block' : 'none';
}
function updateURL() {
const params = new URLSearchParams({
...state,
iotClouds: state.iotClouds.join(',')
});
params.set('utm_source', 'qr');
window.history.replaceState({}, '', `${window.location.pathname}?${params.toString()}`);
}
function loadStateFromURL() {
const params = new URLSearchParams(window.location.search);
params.forEach((value, key) => {
if (state.hasOwnProperty(key)) {
state[key] = validateState(key, value);
}
});
syncForm();
}
function showStatus(msg, type = 'success') {
statusMessage.textContent = msg;
statusMessage.className = `status-msg ${type} visible`;
setTimeout(() => statusMessage.className = 'status-msg', 3000);
}
downloadSvgBtn.addEventListener('click', () => {
const svgElement = labelWrapper.querySelector('svg');
if (!svgElement) return;
// Ensure the SVG has the correct XML namespace
const svgData = new XMLSerializer().serializeToString(svgElement);
const blob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
downloadURI(URL.createObjectURL(blob), 'security-label.svg');
showStatus('SVG Downloaded!');
});
downloadPngBtn.addEventListener('click', () => {
const svgElement = labelWrapper.querySelector('svg');
if (!svgElement) return;
const svgData = new XMLSerializer().serializeToString(svgElement);
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const img = new Image();
// Get dynamic dimensions
const width = parseInt(svgElement.getAttribute('width')) || 500;
const height = parseInt(svgElement.getAttribute('height')) || 850;
const scale = 3; // Higher quality
canvas.width = width * scale;
canvas.height = height * scale;
const svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(svgBlob);
img.onload = () => {
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Use the native width/height to ensure proper scaling
ctx.drawImage(img, 0, 0, width * scale, height * scale);
const pngUrl = canvas.toDataURL('image/png');
downloadURI(pngUrl, 'security-label.png');
URL.revokeObjectURL(url);
showStatus('PNG Generated & Downloaded!');
};
img.onerror = () => {
showStatus('Error generating PNG. Try SVG instead.', 'error');
URL.revokeObjectURL(url);
};
img.src = url;
});
function downloadURI(uri, name) {
const link = document.createElement('a');
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
function shareViaEmail() {
const productName = state.productName || 'this device';
const subject = encodeURIComponent(`Cyber Security Trustmark: ${productName}`);
const body = encodeURIComponent(`Check out the Cyber Security Trustmark for this product here:\n\n${window.location.href}`);
window.location.href = `mailto:?subject=${subject}&body=${body}`;
}
function shareViaSMS() {
const body = encodeURIComponent(`Check out this Cyber Security Trustmark: ${window.location.href}`);
window.location.href = `sms:?&body=${body}`;
}
function updateLabel() {
const svg = generateSVG();
labelWrapper.innerHTML = svg;
// Note: Modal trustmark update disabled to use static sample PNG instead of dynamic SVG Blob
// This prevents broken image issues in some browser environments
}
function showVerificationExample() {
modalBackdrop.classList.add('active');
// Set dynamic info
modalProductName.innerText = state.productName || 'CyberThing Hub 2000';
modalManufacturer.innerText = state.url || 'CyberThing Labs GmbH';
const tD = new Date(state.testDate);
const months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const formattedDate = !isNaN(tD.getTime()) ? `${months[tD.getMonth()]} ${tD.getDate()}, ${tD.getFullYear()}` : 'April 11, 2026';
document.getElementById('modalTestDate').innerText = formattedDate;
const statsStartDateElem = document.querySelector('.stats-start-date');
if (statsStartDateElem) statsStartDateElem.innerText = formattedDate;
// Pre-scroll to top of modal if needed
document.querySelector('.modal-content').scrollTop = 0;
}
function getQRCodePath() {
const qr = qrcode(0, 'L');
qr.addData(window.location.href);
qr.make();
const count = qr.getModuleCount();
const size = 145; // Further increased from 125
const cell = size / count;
let path = '';
for (let r = 0; r < count; r++) {
for (let c = 0; c < count; c++) {
if (qr.isDark(r, c)) path += `M${c * cell} ${r * cell} h${cell} v${cell} h-${cell} z `;
}
}
return path;
}
function getColor(rating, themeColor) {
if (rating === 3) return themeColor;
if (rating === 2) return '#f59e0b'; // Gold
if (rating === 1) return '#f97316'; // Orange
return '#dc2626'; // Red
}
function generateSVG() {
const { rating, url, regId, expiryDate, productName, testDate, iotClouds, remoteAccess, appType, comments, themeColor } = state;
// Rating Color vs Base Color logic
const ratingColor = getColor(rating, themeColor);
// If rating is 0, everything is red. Otherwise, everything but stars/icon uses themeColor.
const baseColor = (rating === 0) ? '#dc2626' : themeColor;
const d = new Date(expiryDate);
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const formattedDate = !isNaN(d.getTime()) ? `${d.getDate()}-${months[d.getMonth()]}-${d.getFullYear()}` : 'N/A';
const tD = new Date(testDate);
const formattedTestDate = !isNaN(tD.getTime()) ? `${tD.getDate()}-${months[tD.getMonth()]}-${tD.getFullYear()}` : 'N/A';
const stars = Array.from({ length: 3 }, (_, i) => {
const fill = i < rating ? ratingColor : 'none';
const stroke = (rating === 3) ? '#f59e0b' : ratingColor;
const y = i * 45;
return `<path d="M15 ${y} l5 11 l12 2 l-9 8 l2 12 l-10 -6 l-10 6 l2 -12 l-9 -8 l12 -2 z" stroke="${stroke}" stroke-width="2" fill="${fill}" />`;
}).join('');
const desc = rating >= 3 ? "Device works on local network only. No diagnostics." :
rating === 2 ? "Data encrypted in transit and on servers." :
rating === 1 ? "Data encrypted in transit. Provider access enabled." :
"Non-compliant. Significant vulnerabilities present.";
// Stale Test Logic
const testDateObj = new Date(testDate);
const today = new Date();
const ageInYears = (today - testDateObj) / (1000 * 60 * 60 * 24 * 365.25);
const isStale = !isNaN(ageInYears) && (ageInYears > 1 || ageInYears > expiryYears);
let staleWarningHtml = '';
if (isStale) {
const yearsStr = ageInYears >= 2 ? `${Math.floor(ageInYears)} years` : `1 year`;
staleWarningHtml = `
<g transform="translate(40, 452)">
<rect x="0" y="0" width="420" height="22" rx="4" fill="#fef2f2" stroke="#ef4444" stroke-width="1" />
<text x="210" y="15" font-family="Inter" font-size="10" font-weight="800" fill="#b91c1c" text-anchor="middle">⚠️ TEST CONDUCTED ${yearsStr.toUpperCase()} AGO - MAY BE INVALID</text>
</g>
`;
}
const cloudsText = Array.isArray(iotClouds) && iotClouds.length > 0
? (iotClouds.length > 2
? `${iotClouds.slice(0, 2).map(c => escapeHTML(c)).join(', ')} (+${iotClouds.length - 2} more...)`
: iotClouds.map(c => escapeHTML(c)).join(', '))
: '';
const lines = [
`Product: ${escapeHTML(productName)}`,
`Test Date: ${escapeHTML(formattedTestDate)}`,
`Clouds: ${cloudsText}`,
`Remote: ${escapeHTML(remoteAccess)} | App: ${escapeHTML(appType)}`,
];
if (state.showTestingInfo) {
lines.push(`Testing Body: CyberThing Authority (Independent)`);
lines.push(`Methodology: CT-CS-001 (Level 3 Assessment)`);
}
if (state.showIP && state.ipAddress) {
lines.push(`Device IP: ${escapeHTML(state.ipAddress)}`);
}
if (comments) {
lines.push(`Notes: ${escapeHTML(comments)}`);
}
const lineSpacing = lines.length > 5 ? 18 : 22;
const compLinesHtml = lines.map((line, i) => {
const truncated = line.length > 65 ? line.substring(0, 62) + '...' : line;
return `<text x="20" y="${60 + (i * lineSpacing)}" font-family="Inter" font-size="13" fill="#334155">${truncated}</text>`;
}).join('');
const qrPath = getQRCodePath();
// Dynamic Box Height logic
const boxHeight = 60 + (lines.length * lineSpacing) + 25;
const footerY = boxHeight - 14;
const footerLineY = boxHeight - 28;
// Dynamic SVG height logic
const complianceY = 480;
const padding = 20;
const svgHeight = complianceY + boxHeight + padding;
const innerBorderHeight = svgHeight - 20;
return `
<svg width="500" height="${svgHeight}" viewBox="0 0 500 ${svgHeight}" xmlns="http://www.w3.org/2000/svg">
<defs>
<style type="text/css">
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=Outfit:wght@400;600;700;900&display=swap');
text { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
.title { font-family: 'Outfit', sans-serif; }
</style>
</defs>
<rect x="0" y="0" width="500" height="${svgHeight}" fill="white" />
<rect x="10" y="10" width="480" height="${innerBorderHeight}" rx="10" fill="white" stroke="#e2e8f0" stroke-width="1" />
<text x="40" y="60" class="title" font-size="28" font-weight="700" fill="${escapeHTML(baseColor)}">CyberThing</text>
<text x="40" y="95" class="title" font-size="28" font-weight="700" fill="${escapeHTML(baseColor)}">Trustmark</text>
<g transform="translate(40, 140)">
<path d="M0 20 C0 20 0 0 75 0 C150 0 150 20 150 20 C150 100 75 160 75 160 C75 160 0 100 0 20Z" fill="${escapeHTML(baseColor)}" opacity="${rating === 0 ? 1 : 0.9}" />
${rating >= 2 ? `
<rect x="55" y="65" width="40" height="30" rx="4" fill="white" />
<path d="M60 65 V55 C60 45 90 45 90 55 V65" stroke="white" stroke-width="5" fill="none" />
<circle cx="75" cy="80" r="4" fill="${escapeHTML(ratingColor)}" />
` : `
<path d="M75 15 L120 95 H30 Z" fill="white" opacity="0.9" />
<text x="75" y="82" font-family="Outfit" font-size="60" font-weight="900" text-anchor="middle" fill="${escapeHTML(ratingColor)}">!</text>
`}
</g>
<g transform="translate(230, 140)">
<text x="-25" y="145" font-family="Inter" font-size="11" font-weight="700" fill="${escapeHTML(baseColor)}" transform="rotate(-90 -25 145)" opacity="0.8">Cyber Security Rating</text>
<line x1="0" y1="0" x2="0" y2="145" stroke="${escapeHTML(baseColor)}" stroke-dasharray="2 2" opacity="0.3" />
<g transform="translate(10, 5)">
${stars}
</g>
</g>
<g transform="translate(320, 140)">
<path d="${qrPath}" fill="${escapeHTML(baseColor)}" />
<rect x="-2" y="-2" width="149" height="149" stroke="${escapeHTML(baseColor)}" stroke-width="1" fill="none" opacity="0.2" />
</g>
<g transform="translate(40, 340)">
<line x1="0" y1="0" x2="420" y2="0" stroke="${escapeHTML(baseColor)}" stroke-dasharray="4 4" opacity="0.5" />
<text x="0" y="35" font-family="Inter" font-size="16" font-weight="700" fill="${escapeHTML(baseColor)}">${escapeHTML(url)}</text>
<text x="245" y="35" font-family="Inter" font-size="14" font-weight="600" fill="${escapeHTML(baseColor)}">Reg ID: ${escapeHTML(regId)}</text>
<line x1="0" y1="60" x2="420" y2="60" stroke="${escapeHTML(baseColor)}" stroke-dasharray="4 4" opacity="0.5" />
<g transform="translate(0, 92)">
<text x="0" y="0" font-family="Inter" font-size="14" fill="${escapeHTML(baseColor)}" font-weight="500">Security updates until: ${escapeHTML(formattedDate)}</text>
</g>
<line x1="0" y1="110" x2="420" y2="110" stroke="${escapeHTML(baseColor)}" stroke-dasharray="4 4" opacity="0.5" />
</g>
${staleWarningHtml}
<g transform="translate(40, ${complianceY})">
<rect x="0" y="0" width="420" height="${boxHeight}" rx="8" fill="none" stroke="${escapeHTML(baseColor)}" stroke-dasharray="2 2" />
<text x="20" y="30" font-family="Inter" font-size="14" font-weight="800" fill="${escapeHTML(baseColor)}" text-transform="uppercase">Compliance Information</text>
${compLinesHtml}
<!-- Rating Footer -->
<line x1="10" y1="${footerLineY}" x2="410" y2="${footerLineY}" stroke="${rating === 3 ? '#f59e0b' : escapeHTML(baseColor)}" stroke-dasharray="2 2" opacity="${rating === 3 ? 0.6 : 0.3}" />
<circle cx="25" cy="${footerY}" r="8" fill="${escapeHTML(ratingColor)}" />
<text x="25" y="${footerY + 5}" font-family="Outfit" font-size="12" font-weight="900" text-anchor="middle" fill="white">i</text>
<text x="45" y="${footerY + 5}" font-family="Inter" font-size="12" font-weight="700" fill="${escapeHTML(ratingColor)}">${escapeHTML(desc)}</text>
</g>
</svg>
`;
}