TLS-Lens/popup/popup.js

1289 lines
40 KiB
JavaScript
Executable file

/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
"use strict";
// Release date of the current version (year, monthIndex, day) — built as a
// local date so the day does not shift across time zones.
const RELEASE_DATE = new Date(2026, 10, 1);
// The record currently on screen, kept so the copy actions in the settings
// menu can build their output without querying the background again.
var currentData = null;
var currentUrl = "";
var currentWarnings = [];
var currentStatus = "neutral";
/* ============================ i18n plumbing ============================ */
// Replaces the text of every element carrying a data-i18n key, plus the
// attribute variants for titles, tooltips and labels.
function applyI18n() {
document.documentElement.lang = I18N.lang;
document.querySelectorAll("[data-i18n]").forEach(function(el) {
el.textContent = I18N.t(el.getAttribute("data-i18n"));
});
document.querySelectorAll("[data-i18n-title]").forEach(function(el) {
el.title = I18N.t(el.getAttribute("data-i18n-title"));
});
// The custom tooltip reads dataset.tip, not the native title attribute
document.querySelectorAll("[data-i18n-tip]").forEach(function(el) {
el.dataset.tip = I18N.t(el.getAttribute("data-i18n-tip"));
});
document.querySelectorAll("[data-i18n-aria-label]").forEach(function(el) {
el.setAttribute("aria-label", I18N.t(el.getAttribute("data-i18n-aria-label")));
});
}
/* ============================ DOM helpers ============================= */
// A field may appear more than once (the common name shows up in both the
// overview and the certificate tab), so always address all of them.
function fill(field, value) {
fillRaw(field, value === null || value === undefined || value === ""
? I18N.t("not_available")
: String(value));
}
// Writes exactly what it is given, including an empty string. Counters and
// hints must stay blank rather than fall back to "N/A".
function fillRaw(field, text) {
document.querySelectorAll('[data-field="' + field + '"]').forEach(function(el) {
el.textContent = text;
});
}
function fillAll(map) {
Object.keys(map).forEach(function(field) {
fill(field, map[field]);
});
}
function field(name) {
return document.querySelector('[data-field="' + name + '"]');
}
function setView(view) {
document.body.dataset.view = view;
}
function setStatus(status) {
document.body.dataset.status = status;
}
// Link fields fall back to a muted "not specified" when the certificate
// carries no URL.
function fillLink(name, url) {
var el = field(name);
if (!el) return;
if (url) {
el.textContent = url;
el.href = url;
el.classList.remove("muted");
} else {
el.textContent = I18N.t("aia_not_specified");
el.removeAttribute("href");
el.classList.add("muted");
}
}
/* ======================= Formatting and derivation ===================== */
function formatDate(date) {
return date.toLocaleDateString(I18N.dateLocale(), {
year: "numeric",
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit"
});
}
function formatTime(date) {
return date.toLocaleTimeString(I18N.dateLocale(), {
hour: "2-digit",
minute: "2-digit"
});
}
// Complete days until the certificate expires — truncated towards zero, so
// neither direction is ever overstated: 0 on the final day, negative once it
// has expired.
function daysUntil(date) {
return Math.trunc((date.getTime() - Date.now()) / 86400000);
}
// Firefox reports "TLSv1" for TLS 1.0, which would read as a bare "TLS 1".
const PROTOCOL_NUMBERS = {
"TLSv1": "1.0", "TLSv1.1": "1.1", "TLSv1.2": "1.2", "TLSv1.3": "1.3"
};
function formatProtocol(version) {
if (!version) {
return null;
}
return PROTOCOL_NUMBERS[version]
? "TLS " + PROTOCOL_NUMBERS[version]
: version.replace("TLSv", "TLS ");
}
// Remaining lifetime for the tile. Expired certificates get the short word
// rather than a full sentence — the tile is a single ellipsised line.
function remainingText(days) {
if (days < 0) {
return I18N.t("warn_expired_title");
}
if (days === 0) {
return I18N.t("remaining_today");
}
return I18N.tn("remaining", days);
}
// "TLS_AES_128_GCM_SHA256" -> "AES-128-GCM · SHA-256". TLS 1.2 names carry
// the key exchange before "_WITH_", which says nothing about the cipher.
function shortCipher(suite) {
if (!suite) {
return null;
}
var rest = suite.replace(/^TLS_/, "");
var withIndex = rest.indexOf("_WITH_");
if (withIndex !== -1) {
rest = rest.substring(withIndex + "_WITH_".length);
}
var parts = rest.split("_");
var hash = null;
if (parts.length > 1 && /^(SHA|MD)\d*$/.test(parts[parts.length - 1])) {
hash = parts.pop();
}
var cipher = parts.join("-");
if (!hash) {
return cipher;
}
return cipher + " · " + hash.replace(/^SHA(\d+)$/, "SHA-$1");
}
// Share of the lifetime still left, for the progress bar. Clamped so a
// not-yet-valid or long-expired certificate cannot overflow the track.
function validityFraction(start, end) {
var from = new Date(start).getTime();
var to = new Date(end).getTime();
if (!isFinite(from) || !isFinite(to) || to <= from) {
return 0;
}
var share = ((to - Date.now()) / (to - from)) * 100;
return Math.max(0, Math.min(100, Math.round(share)));
}
// getSecurityInfo() only reports Extended Validation. Organisation
// validation is inferred from an organisation in the subject — the usual
// distinction, though a heuristic rather than a certified fact.
function validationLevel(certData, securityInfo) {
if (securityInfo.isExtendedValidation) {
return I18N.t("validation_ev");
}
if (certData.subject && certData.subject.O) {
return I18N.t("validation_ov");
}
return I18N.t("validation_dv");
}
function issuerHintText(certData, country) {
var cn = certData.issuer.CN;
if (!cn) {
return null;
}
if (country) {
return I18N.t("issuer_hint", { cn: cn, country: country.code.toUpperCase() });
}
return I18N.t("issuer_hint_no_country", { cn: cn });
}
// True when the certificate itself is the problem, regardless of what
// securityInfo.state claims: Firefox reports "secure" for accepted security
// exceptions while these flags still describe the actual situation.
function hasCertificateProblem(certData, securityInfo) {
return Boolean((certData && certData.isNotValidAtThisTime)
|| securityInfo.isNotValidAtThisTime
|| securityInfo.isDomainMismatch
|| securityInfo.isUntrusted);
}
// One short phrase for the header. The issuer and the remaining lifetime
// have their own tiles now, so the sentence no longer repeats them.
function summaryText(certData, securityInfo) {
if (securityInfo.isDomainMismatch) {
return I18N.t("summary_mismatch");
}
if (securityInfo.isUntrusted) {
return I18N.t("summary_untrusted");
}
if ((certData && certData.isNotValidAtThisTime) || securityInfo.isNotValidAtThisTime) {
return I18N.t("summary_expired");
}
if (securityInfo.state === "broken") {
return I18N.t("summary_broken");
}
if (securityInfo.state === "weak") {
return I18N.t("summary_weak");
}
return I18N.t("summary_secure");
}
/* ============================== Warnings ============================== */
// Substrings that mark a cipher suite as outdated. Modern suites (AES-GCM,
// CHACHA20-POLY1305) contain none of them. CBC is included deliberately:
// Firefox only negotiates it with servers that offer nothing better.
const WEAK_CIPHER_MARKERS = ["RC4", "3DES", "_DES", "NULL", "MD5", "EXPORT", "CBC"];
// Everything worth flagging in plain language, as {title, text, severity}.
// Returns an empty array for a well-configured site, which keeps the warning
// list out of the popup entirely.
function collectWarnings(certData, securityInfo, techInfo, days) {
var warnings = [];
function add(key, severity, params) {
warnings.push({
title: I18N.t(key + "_title"),
text: I18N.t(key, params),
severity: severity
});
}
var version = securityInfo.protocolVersion || "";
if (version === "TLSv1" || version === "TLSv1.1" || version === "SSLv3") {
add("warn_old_tls", "warn", { version: formatProtocol(version) });
}
var cipher = (securityInfo.cipherSuite || "").toUpperCase();
var isWeakCipher = cipher !== "" && WEAK_CIPHER_MARKERS.some(function(marker) {
return cipher.indexOf(marker) !== -1;
});
if (isWeakCipher) {
add("warn_weak_cipher", "warn");
}
if (techInfo) {
if (techInfo.signatureHash === "sha1") {
add("warn_sha1", "error");
} else if (techInfo.signatureHash === "md5") {
add("warn_md5", "error");
}
if (techInfo.keyAlgorithm === "rsa" && techInfo.keySize && techInfo.keySize < 2048) {
add("warn_small_key", "error", { bits: techInfo.keySize });
}
}
var ct = securityInfo.certificateTransparencyStatus;
if (ct === "policy_not_enough_scts" || ct === "policy_not_diverse_scts") {
add("warn_ct", "warn");
}
var expired = (certData && certData.isNotValidAtThisTime) || securityInfo.isNotValidAtThisTime;
if (expired) {
// The tile only has room for the word "expired", so the exact number of
// days lives here, where there is space for a sentence.
warnings.push({
title: I18N.t("warn_expired_title"),
text: days < 0 ? I18N.tn("warn_expired_since", Math.abs(days))
: I18N.t("warn_expired"),
severity: "error"
});
} else if (days !== null) {
// days is null when Firefox withheld the certificate — there is no
// expiry date to warn about then.
if (days === 0) {
add("warn_expires_today", "warn");
} else if (days > 0 && days <= 14) {
warnings.push({
title: I18N.t("warn_expiring_title"),
text: I18N.tn("warn_expiring", days),
severity: "warn"
});
}
}
return warnings;
}
/* ===================== Key, signature, usage, country ================== */
// Algorithm display names. These are identifiers rather than prose, so they
// are the same in every language.
const KEY_ALG_NAMES = { rsa: "RSA", ec: "ECDSA", ed25519: "Ed25519", ed448: "Ed448" };
const SIG_KEY_NAMES = {
rsa: "RSA", rsapss: "RSASSA-PSS", ecdsa: "ECDSA",
ed25519: "Ed25519", ed448: "Ed448"
};
const HASH_NAMES = {
md5: "MD5", sha1: "SHA-1", sha224: "SHA-224",
sha256: "SHA-256", sha384: "SHA-384", sha512: "SHA-512"
};
function formatPublicKey(techInfo) {
if (!techInfo || !techInfo.keyAlgorithm) {
return null;
}
var name = KEY_ALG_NAMES[techInfo.keyAlgorithm] || techInfo.keyAlgorithm;
if (techInfo.curve) {
return I18N.t("key_curve", { alg: name, curve: techInfo.curve });
}
if (techInfo.keySize) {
return I18N.t("key_bits", { alg: name, bits: techInfo.keySize });
}
return name;
}
function formatSignature(techInfo) {
if (!techInfo) {
return null;
}
var key = SIG_KEY_NAMES[techInfo.signatureKey];
var hash = HASH_NAMES[techInfo.signatureHash];
if (key && hash) {
return I18N.t("sig_with", { hash: hash, key: key });
}
return key || techInfo.signatureOid || null;
}
// Translates the parser's usage slugs. Unknown purposes arrive as raw OIDs
// and are passed through unchanged.
function usageNames(slugs, prefix) {
if (!slugs || slugs.length === 0) {
return [];
}
return slugs.map(function(slug) {
var key = prefix + slug;
var text = I18N.t(key);
return text === key ? slug : text;
});
}
// Country of the issuing CA, taken from the C= field of its distinguished
// name. Falls back up the chain when the issuing intermediate omits it —
// the root then speaks for the chain. Returns null when nobody states one.
function issuerCountry(certData, chainInfo) {
if (certData.issuer.C) {
return { code: certData.issuer.C, source: "direct" };
}
// Index 0 is the server certificate itself, so start at the first issuer.
var chain = chainInfo || [];
for (var i = 1; i < chain.length; i++) {
if (chain[i].subject && chain[i].subject.C) {
return {
code: chain[i].subject.C,
source: chain[i].isBuiltInRoot ? "root" : "chain"
};
}
}
return null;
}
// Country names come from the browser, so there is no table of our own to
// maintain and no extra translations: Intl resolves them against the
// language chosen in the settings menu.
function countryName(code) {
var name;
try {
name = new Intl.DisplayNames([I18N.lang], { type: "region" }).of(code);
} catch (e) {
// Not a well-formed region code ("D", "DEU", "")
return null;
}
// Unknown but well-formed codes come back unchanged — that is a code, not
// a name, and the caller formats it differently.
return name && name.toUpperCase() !== code.toUpperCase() ? name : null;
}
// "DE" -> the regional indicator pair that renders as a flag. Firefox ships
// its own emoji font on every platform, so this shows up on Windows too.
function countryFlag(code) {
if (!/^[A-Za-z]{2}$/.test(code)) {
return null;
}
var upper = code.toUpperCase();
return String.fromCodePoint(
0x1F1E6 + upper.charCodeAt(0) - 65,
0x1F1E6 + upper.charCodeAt(1) - 65
);
}
function formatCountry(code) {
if (!code) {
return null;
}
var upper = code.toUpperCase();
var name = countryName(code);
var flag = countryFlag(code);
var text = name
? I18N.t("country_value", { flag: flag || "", name: name, code: upper })
: I18N.t("country_value_code_only", { flag: flag || "", code: upper });
// Without a flag the template leaves a leading space behind
return text.trim();
}
// Where a fallback country came from. Empty for "direct" — the issuer
// stated it itself and there is nothing to qualify.
function countrySourceNote(source) {
if (source === "direct") {
return "";
}
var key = "country_source_" + source;
var text = I18N.t(key);
return text === key ? "" : text;
}
// Translates an error code reported by background.js. Unknown codes still
// produce something readable instead of a blank message.
function backendErrorMessage(code, detail) {
var key = "error_" + code;
var message = I18N.t(key);
if (message === key) {
return I18N.t("error_unknown", { detail: detail || code });
}
return detail ? message + " (" + detail + ")" : message;
}
/* =============================== Renderers ============================= */
// Icons live as <template> elements in popup.html and are cloned here, so
// this file never assembles markup from strings.
function icon(id) {
var template = document.getElementById(id);
return template ? template.content.cloneNode(true) : document.createDocumentFragment();
}
function renderWarnings(warnings) {
var list = field("warnings");
var dot = field("warningsDot");
if (!list) return;
if (!warnings || warnings.length === 0) {
list.hidden = true;
if (dot) dot.hidden = true;
return;
}
warnings.forEach(function(warning) {
var item = document.createElement("li");
item.className = "alert alert--" + (warning.severity === "error" ? "error" : "warn");
item.appendChild(icon(warning.severity === "error"
? "icon-alert-error" : "icon-alert-warn"));
var body = document.createElement("div");
body.className = "alert__body";
var title = document.createElement("span");
title.className = "alert__title";
title.textContent = warning.title;
body.appendChild(title);
var text = document.createElement("span");
text.className = "alert__text";
text.textContent = warning.text;
body.appendChild(text);
item.appendChild(body);
list.appendChild(item);
});
list.hidden = false;
if (dot) dot.hidden = false;
}
// Beyond this depth the indent would eat the panel. Real chains are three
// or four long; the cap only matters for pathological ones.
const MAX_CHAIN_INDENT = 5;
// The chain arrives leaf first. Rendered as a tree it reads top down: the
// trusted root, then each step indented under the one that vouches for it,
// the website last. Every node has exactly one child, so the indent alone
// carries the relationship.
function renderChain(chainInfo) {
var list = field("chain");
if (!list) return 0;
var chain = (chainInfo || []).slice(0, 20).reverse();
chain.forEach(function(cert, index) {
var isLeaf = index === chain.length - 1;
var isRoot = !isLeaf && index === 0;
var role = isLeaf ? "leaf" : (isRoot ? "root" : "intermediate");
var item = document.createElement("li");
item.className = "chain__item";
item.style.setProperty("--depth", Math.min(index, MAX_CHAIN_INDENT));
var iconEl = document.createElement("span");
iconEl.className = "chain__icon chain__icon--" + role;
iconEl.appendChild(icon("icon-chain-" + role));
item.appendChild(iconEl);
var body = document.createElement("div");
body.className = "chain__body";
var name = document.createElement("span");
name.className = "chain__name";
name.textContent = cert.subject.CN || cert.subject.O || I18N.t("not_available");
body.appendChild(name);
var meta = document.createElement("span");
meta.className = "chain__meta";
if (isLeaf) {
meta.textContent = I18N.t("chain_leaf", {
date: currentData && currentData.certData
? formatDate(new Date(currentData.certData.validityEnd))
: I18N.t("not_available")
});
} else if (isRoot) {
meta.textContent = cert.isBuiltInRoot
? I18N.t("chain_root_trusted")
: I18N.t("chain_root");
} else if (cert.subject.O) {
meta.textContent = I18N.t("chain_intermediate_of", { name: cert.subject.O });
} else {
meta.textContent = I18N.t("chain_intermediate");
}
body.appendChild(meta);
item.appendChild(body);
list.appendChild(item);
});
return chain.length;
}
// How many names are shown before the list folds. Nine plus the toggle
// make ten rows, which keeps the control visible without scrolling.
// Everything beyond is rendered but hidden, so expanding costs no re-render.
const SAN_PREVIEW = 9;
function renderSan(sanInfo) {
var list = field("sanList");
if (!list) return 0;
var entries = [];
if (sanInfo && !sanInfo.errorCode) {
(sanInfo.dnsNames || []).forEach(function(name) {
entries.push({ value: name, type: null });
});
(sanInfo.ipAddresses || []).forEach(function(ip) {
entries.push({ value: ip, type: I18N.t("san_type_ip") });
});
}
var hidden = [];
entries.forEach(function(entry, index) {
var item = document.createElement("li");
// Only IP entries are marked: an address is otherwise indistinguishable
// from a hostname.
if (entry.type) {
var type = document.createElement("span");
type.className = "san__type";
type.textContent = entry.type;
item.appendChild(type);
}
var value = document.createElement("span");
value.textContent = entry.value;
item.appendChild(value);
if (index >= SAN_PREVIEW) {
item.hidden = true;
hidden.push(item);
}
list.appendChild(item);
});
if (hidden.length > 0) {
list.appendChild(buildSanToggle(hidden));
}
return entries.length;
}
// Folds the remainder of the list in and out. Kept as a real button so it
// is reachable by keyboard and announces its state.
function buildSanToggle(hiddenItems) {
var row = document.createElement("li");
row.className = "san__more-row";
var button = document.createElement("button");
button.type = "button";
button.className = "san__more";
button.setAttribute("aria-expanded", "false");
button.textContent = I18N.tn("san_show_more", hiddenItems.length);
button.addEventListener("click", function() {
var expand = button.getAttribute("aria-expanded") !== "true";
hiddenItems.forEach(function(item) { item.hidden = !expand; });
button.setAttribute("aria-expanded", String(expand));
button.textContent = expand
? I18N.t("san_show_less")
: I18N.tn("san_show_more", hiddenItems.length);
});
row.appendChild(button);
return row;
}
function renderTags(name, names) {
var container = field(name);
if (!container) return;
if (!names || names.length === 0) {
container.textContent = I18N.t("not_available");
return;
}
names.forEach(function(text) {
var tag = document.createElement("span");
tag.className = "tag";
tag.textContent = text;
container.appendChild(tag);
});
}
// The check rows use a tick, a dash or a warning tint depending on the value.
function setCheck(id, variant) {
var el = document.getElementById(id);
if (el) {
el.className = "check check--" + variant;
}
}
/* ================================= init ================================ */
async function init() {
fill("fetchedAt", I18N.t("fetched_at", { time: formatTime(new Date()) }));
fill("summary", I18N.t("summary_loading"));
fill("statusLabel", I18N.t("status_loading"));
try {
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
if (!tabs || tabs.length === 0) {
showErrorState(I18N.t("err_no_active_tab"));
return;
}
const activeTab = tabs[0];
currentUrl = activeTab.url || "";
fill("host", hostnameOf(currentUrl) || currentUrl);
if (!currentUrl.startsWith("http") || isRestrictedDomain(currentUrl)) {
setView("blocked");
setStatus("neutral");
fill("summary", I18N.t("summary_blocked"));
fill("statusLabel", I18N.t("status_blocked"));
return;
}
const data = await browser.runtime.sendMessage({
type: "getCertInfo",
tabId: activeTab.id,
url: currentUrl
});
if (!data) {
showErrorState(I18N.t("err_no_cert_data"));
return;
}
if (data.errorCode === "insecure_http") {
setView("http");
setStatus("error");
fill("summary", I18N.t("summary_http"));
fill("statusLabel", I18N.t("status_insecure"));
return;
}
if (data.errorCode) {
showErrorState(backendErrorMessage(data.errorCode, data.errorDetail));
return;
}
if (!data.certData && !data.securityInfo) {
showErrorState(I18N.t("err_cert_unreadable"));
return;
}
renderReady(data);
} catch (err) {
showErrorState(I18N.t("err_unexpected", { message: err.message }));
}
}
function hostnameOf(url) {
try {
return new URL(url).hostname;
} catch (e) {
return null;
}
}
function showErrorState(message) {
setView("error");
setStatus("neutral");
fill("summary", I18N.t("summary_error"));
fill("statusLabel", I18N.t("status_unknown"));
fill("errorMessage", message);
}
function renderReady(data) {
setView("ready");
const certData = data.certData;
const securityInfo = data.securityInfo || {};
const techInfo = data.techInfo || null;
currentData = data;
// Firefox withholds certificate details for accepted security exceptions
if (!certData) {
document.body.dataset.limited = "true";
fill("limitedReason", limitedReason(securityInfo));
}
const endDate = certData ? new Date(certData.validityEnd) : null;
const days = endDate ? daysUntil(endDate) : null;
currentWarnings = collectWarnings(certData, securityInfo, techInfo, days);
// Header
currentStatus = statusOf(certData, securityInfo, currentWarnings);
setStatus(currentStatus);
fill("summary", summaryText(certData, securityInfo));
fill("statusLabel", I18N.t("status_" + currentStatus));
if (securityInfo.isExtendedValidation) {
document.body.dataset.ev = "true";
}
// Overview
renderWarnings(currentWarnings);
fillAll({
tlsVersion: formatProtocol(securityInfo.protocolVersion),
cipherShort: shortCipher(securityInfo.cipherSuite),
cipherSuite: securityInfo.cipherSuite,
daysLeft: days === null ? null : remainingText(days),
notAfterShort: endDate ? I18N.t("not_after_short", { date: formatDate(endDate) }) : null,
subjectCN: certData ? certData.subject.CN : null,
issuerOrg: certData ? certData.issuer.O : null,
issuerCN: certData ? certData.issuer.CN : null
});
const ctStatus = securityInfo.certificateTransparencyStatus;
const ctLabels = {
"not_applicable": "ct_not_applicable",
"policy_compliant": "ct_policy_compliant",
"policy_not_enough_scts": "ct_not_enough_scts",
"policy_not_diverse_scts": "ct_not_diverse_scts"
};
fill("ctStatus", ctLabels[ctStatus] ? I18N.t(ctLabels[ctStatus]) : ctStatus);
setCheck("ct-check", ctStatus === "policy_compliant" ? "ok"
: (ctStatus === "policy_not_enough_scts" || ctStatus === "policy_not_diverse_scts") ? "warn"
: "neutral");
fill("ocsp", securityInfo.usedOcsp ? I18N.t("yes") : I18N.t("no"));
setCheck("ocsp-check", securityInfo.usedOcsp ? "ok" : "neutral");
if (!certData) {
["tab-cert", "tab-chain", "tab-san", "tab-tech"].forEach(hideTab);
return;
}
// Certificate tab
const bar = field("validityPercent");
if (bar) {
bar.style.width = validityFraction(certData.validityStart, certData.validityEnd) + "%";
}
fillAll({
notBefore: certData.validityStart ? formatDate(new Date(certData.validityStart)) : null,
notAfter: formatDate(endDate),
validationLevel: validationLevel(certData, securityInfo)
});
const country = issuerCountry(certData, data.chainInfo);
fill("issuerCountry", country ? formatCountry(country.code) : null);
const note = country ? countrySourceNote(country.source) : "";
fillRaw("issuerCountryHint", note);
const countryHint = field("issuerCountryHint");
if (countryHint) {
countryHint.hidden = note === "";
}
fill("issuerHint", issuerHintText(certData, country));
const aiaInfo = data.aiaInfo && !data.aiaInfo.errorCode ? data.aiaInfo : {};
fillLink("aiaIssuer", aiaInfo.caIssuersUrl);
fillLink("aiaOcsp", aiaInfo.ocspUrl);
// Chain and SAN
const chainCount = renderChain(data.chainInfo);
const sanCount = renderSan(data.sanInfo);
fillRaw("chainCount", chainCount > 0 ? "(" + chainCount + ")" : "");
fillRaw("sanCount", sanCount > 0 ? "(" + sanCount + ")" : "");
if (chainCount === 0) hideTab("tab-chain");
if (sanCount === 0) hideTab("tab-san");
// Technical details
renderTags("keyUsage", usageNames(techInfo && techInfo.keyUsage, "ku_"));
renderTags("extKeyUsage", usageNames(techInfo && techInfo.extKeyUsage, "eku_"));
fillAll({
serial: certData.serialNumber,
sigAlg: formatSignature(techInfo),
publicKey: formatPublicKey(techInfo),
fpSha256: techInfo ? techInfo.fingerprintSha256 : null
});
// The copy actions need a rendered certificate to work from
document.getElementById("act-copy-report").disabled = false;
document.getElementById("act-copy-pem").disabled =
!(data.chainInfo && data.chainInfo.length > 0 && data.chainInfo[0].pem);
}
function statusOf(certData, securityInfo, warnings) {
if (hasCertificateProblem(certData, securityInfo) || securityInfo.state === "broken") {
return "error";
}
// A finding of severity "error" outranks Firefox's own "weak" verdict —
// a SHA-1 signature is not merely a weak connection.
if (warnings.some(function(w) { return w.severity === "error"; })) {
return "error";
}
if (securityInfo.state === "weak" || warnings.length > 0) {
return "warn";
}
return "ok";
}
function limitedReason(securityInfo) {
var reasons = [];
if (securityInfo.isNotValidAtThisTime) reasons.push(I18N.t("reason_expired"));
if (securityInfo.isDomainMismatch) reasons.push(I18N.t("reason_domain_mismatch"));
if (securityInfo.isUntrusted) reasons.push(I18N.t("reason_untrusted"));
if (securityInfo.errorMessage) reasons.push(securityInfo.errorMessage);
return reasons.length > 0 ? reasons.join("; ") : I18N.t("limited_reason_generic");
}
function hideTab(id) {
var tab = document.getElementById(id);
if (tab) {
tab.hidden = true;
}
}
function isRestrictedDomain(url) {
try {
var hostname = new URL(url).hostname;
var restricted = [
"addons.mozilla.org",
"discovery.addons.mozilla.org",
"accounts.firefox.com",
"support.mozilla.org",
"install.mozilla.org",
"testpilot.firefox.com",
"content.cdn.mozilla.net",
"input.mozilla.org",
"services.addons.mozilla.org"
];
return restricted.some(function(domain) {
return hostname === domain || hostname.endsWith("." + domain);
});
} catch (e) {
return false;
}
}
/* ============================= UI behaviour ============================ */
function wireTabs() {
var tabs = Array.prototype.slice.call(document.querySelectorAll('[role="tab"]'));
function select(tab) {
tabs.forEach(function(t) {
var active = t === tab;
t.setAttribute("aria-selected", String(active));
t.tabIndex = active ? 0 : -1;
document.getElementById(t.getAttribute("aria-controls")).hidden = !active;
});
tab.focus();
}
function step(from, direction) {
var visible = tabs.filter(function(t) { return !t.hidden; });
var index = visible.indexOf(from);
return visible[(index + direction + visible.length) % visible.length];
}
tabs.forEach(function(tab) {
tab.addEventListener("click", function() { select(tab); });
tab.addEventListener("keydown", function(e) {
if (e.key === "ArrowRight") select(step(tab, 1));
if (e.key === "ArrowLeft") select(step(tab, -1));
});
});
}
function wireMenu() {
var menuBtn = document.getElementById("btn-menu");
var menu = document.getElementById("menu");
function setOpen(open) {
menu.hidden = !open;
menuBtn.setAttribute("aria-expanded", String(open));
if (open) {
var first = menu.querySelector('[aria-checked="true"], [role="menuitem"]');
if (first) first.focus();
}
}
menuBtn.addEventListener("click", function(e) {
e.stopPropagation();
setOpen(menu.hidden);
});
document.addEventListener("click", function(e) {
if (!menu.contains(e.target)) setOpen(false);
});
menu.addEventListener("keydown", function(e) {
if (e.key === "Escape") { setOpen(false); menuBtn.focus(); }
});
function markGroup(group, value) {
group.querySelectorAll('[role="menuitemradio"]').forEach(function(b) {
b.setAttribute("aria-checked", String(b.dataset.value === value));
});
}
var langGroup = menu.querySelector('[data-setting="language"]');
var themeGroup = menu.querySelector('[data-setting="theme"]');
markGroup(langGroup, I18N.setting);
markGroup(themeGroup, THEME.setting);
langGroup.addEventListener("click", async function(e) {
var btn = e.target.closest('[role="menuitemradio"]');
if (!btn) return;
await I18N.setSetting(btn.dataset.value);
markGroup(langGroup, btn.dataset.value);
// Re-render in place rather than reload: a reload would tear down the
// popup and take the open menu with it.
await rerender();
});
// The theme only swaps CSS variables, so it applies without a reload.
themeGroup.addEventListener("click", function(e) {
var btn = e.target.closest('[role="menuitemradio"]');
if (!btn) return;
THEME.set(btn.dataset.value);
markGroup(themeGroup, btn.dataset.value);
});
}
// The tooltip is positioned fixed and flipped above the term when it would
// otherwise leave the popup.
function wireTooltips() {
var tip = document.getElementById("tooltip");
var active = null;
function show(el) {
if (!el.dataset.tip) return;
active = el;
tip.textContent = el.dataset.tip;
tip.hidden = false;
var r = el.getBoundingClientRect();
var t = tip.getBoundingClientRect();
var margin = 8;
var left = Math.min(Math.max(margin, r.left), window.innerWidth - t.width - margin);
var top = r.bottom + 6;
if (top + t.height > window.innerHeight - margin) {
top = r.top - t.height - 6;
}
tip.style.left = left + "px";
tip.style.top = top + "px";
el.setAttribute("aria-describedby", "tooltip");
}
function hide() {
tip.hidden = true;
if (active) {
active.removeAttribute("aria-describedby");
active = null;
}
}
document.querySelectorAll("[data-i18n-tip]").forEach(function(el) {
el.addEventListener("mouseenter", function() { show(el); });
el.addEventListener("mouseleave", hide);
el.addEventListener("focus", function() { show(el); });
el.addEventListener("blur", hide);
});
document.addEventListener("keydown", function(e) {
if (e.key === "Escape") hide();
});
document.querySelector(".content").addEventListener("scroll", hide);
}
// Certificate data is only observable while the request is in flight, so a tab
// that was already open when the extension started has no cached data. Reloading
// the tab is the only way to capture it — there is no API to read it afterwards.
function wireRefresh() {
document.querySelectorAll('[data-action="refresh"]').forEach(function(btn) {
btn.addEventListener("click", function() {
btn.disabled = true;
setView("loading");
browser.tabs.query({ active: true, currentWindow: true }).then(function(tabs) {
if (!tabs || tabs.length === 0) {
throw new Error("no active tab");
}
var tabId = tabs[0].id;
var finished = false;
function finish() {
if (finished) return;
finished = true;
browser.tabs.onUpdated.removeListener(onUpdated);
// Rebuild the popup from scratch: the render path appends rows and
// binds listeners, so it cannot run twice in the same document.
location.reload();
}
function onUpdated(id, changeInfo) {
if (id === tabId && changeInfo.status === "complete") {
finish();
}
}
browser.tabs.onUpdated.addListener(onUpdated);
// Safety net for pages that never report "complete"
setTimeout(finish, 8000);
return browser.tabs.reload(tabId);
}).catch(function(err) {
console.warn("TLS Lens: Could not reload tab:", err);
location.reload();
});
});
});
}
// The release date is locale-dependent, so this re-runs on a language change.
function fillAboutDialog() {
fill("version", browser.runtime.getManifest().version);
fill("releaseDate", RELEASE_DATE.toLocaleDateString(I18N.dateLocale(), {
year: "numeric", month: "long", day: "numeric"
}));
}
// Everything the render path appends or toggles, back to its initial state.
// Without this a second render would duplicate chain entries, SAN rows,
// warnings and usage tags.
function resetRenderState() {
["warnings", "chain", "sanList", "keyUsage", "extKeyUsage"].forEach(function(name) {
var el = field(name);
if (el) el.replaceChildren();
});
var warnings = field("warnings");
if (warnings) warnings.hidden = true;
var dot = field("warningsDot");
if (dot) dot.hidden = true;
var countryHint = field("issuerCountryHint");
if (countryHint) countryHint.hidden = false;
document.querySelectorAll('[role="tab"]').forEach(function(tab) {
tab.hidden = false;
});
document.body.dataset.ev = "false";
document.body.dataset.limited = "false";
document.getElementById("act-copy-report").disabled = true;
document.getElementById("act-copy-pem").disabled = true;
currentData = null;
currentWarnings = [];
currentStatus = "neutral";
}
// Rebuilds the whole view in the newly chosen language.
async function rerender() {
applyI18n();
fillAboutDialog();
resetRenderState();
await init();
}
function wireAbout() {
var overlay = document.getElementById("about-overlay");
var openBtn = document.getElementById("act-about");
var closeBtn = document.getElementById("about-close");
openBtn.addEventListener("click", function() {
document.getElementById("menu").hidden = true;
document.getElementById("btn-menu").setAttribute("aria-expanded", "false");
overlay.hidden = false;
closeBtn.focus();
});
closeBtn.addEventListener("click", function() { overlay.hidden = true; });
overlay.addEventListener("click", function(e) {
if (e.target === overlay) overlay.hidden = true;
});
document.addEventListener("keydown", function(e) {
if (e.key === "Escape") overlay.hidden = true;
});
}
/* =============================== Export ================================ */
// Readable plain-text summary of everything on screen, for support tickets
// and documentation. Uses the labels of the currently selected language.
function buildReport() {
if (!currentData || !currentData.certData) {
return null;
}
const certData = currentData.certData;
const securityInfo = currentData.securityInfo || {};
const techInfo = currentData.techInfo || null;
const endDate = new Date(certData.validityEnd);
const days = daysUntil(endDate);
const lines = [I18N.t("report_title"), ""];
function line(labelKey, value) {
if (value) {
lines.push(I18N.t(labelKey) + ": " + value);
}
}
line("report_address", currentUrl);
line("label_status", I18N.t("status_" + currentStatus)
+ " — " + summaryText(certData, securityInfo));
if (currentWarnings.length > 0) {
lines.push("", I18N.t("report_warnings") + ":");
currentWarnings.forEach(function(w) {
lines.push(" ! " + w.title + " — " + w.text);
});
}
lines.push("");
line("label_tls_version", formatProtocol(securityInfo.protocolVersion));
line("label_cipher_suite", securityInfo.cipherSuite);
line("label_ocsp_query", securityInfo.usedOcsp ? I18N.t("yes") : I18N.t("no"));
line("label_validation_level", validationLevel(certData, securityInfo));
lines.push("");
line("label_cn", certData.subject.CN);
line("label_issuer_o", certData.issuer.O);
line("label_issuer_cn", certData.issuer.CN);
const reportCountry = issuerCountry(certData, currentData.chainInfo);
if (reportCountry) {
const note = countrySourceNote(reportCountry.source);
line("label_issuer_country",
formatCountry(reportCountry.code) + (note ? " (" + note + ")" : ""));
}
if (certData.validityStart) {
line("label_validity_start", formatDate(new Date(certData.validityStart)));
}
line("label_validity_end", formatDate(endDate));
line("label_remaining", remainingText(days));
if (techInfo) {
lines.push("");
line("label_fingerprint", techInfo.fingerprintSha256);
line("label_serial", certData.serialNumber);
line("label_public_key", formatPublicKey(techInfo));
line("label_signature", formatSignature(techInfo));
}
const sanInfo = currentData.sanInfo;
if (sanInfo && !sanInfo.errorCode) {
const sanCount = (sanInfo.dnsNames || []).length + (sanInfo.ipAddresses || []).length;
if (sanCount > 0) {
line("report_san_count", String(sanCount));
}
}
const chainInfo = currentData.chainInfo;
if (chainInfo && chainInfo.length > 0) {
line("report_chain", chainInfo.map(function(cert) {
return cert.subject.CN || I18N.t("not_available");
}).join(" -> "));
}
return lines.join("\n");
}
// The full chain, leaf first — the form `openssl x509` and most server
// configurations expect.
function buildPem() {
if (!currentData || !currentData.chainInfo) {
return null;
}
const pems = currentData.chainInfo.map(function(cert) {
return cert.pem;
}).filter(Boolean);
return pems.length > 0 ? pems.join("\n") : null;
}
function wireCopy() {
// The menu stays open on click, so the confirmation is actually visible.
function copy(button, labelKey, text) {
var label = button.querySelector("span");
function feedback(ok) {
label.textContent = I18N.t(ok ? "menu_copied" : "menu_copy_failed");
setTimeout(function() {
label.textContent = I18N.t(labelKey);
}, 1500);
}
if (!text) {
feedback(false);
return;
}
navigator.clipboard.writeText(text).then(function() {
feedback(true);
}).catch(function(err) {
console.warn("TLS Lens: Could not copy to clipboard:", err);
feedback(false);
});
}
var reportBtn = document.getElementById("act-copy-report");
var pemBtn = document.getElementById("act-copy-pem");
reportBtn.addEventListener("click", function() {
copy(reportBtn, "menu_copy_report", buildReport());
});
pemBtn.addEventListener("click", function() {
copy(pemBtn, "menu_copy_pem", buildPem());
});
}
/* ============================== Bootstrap ============================== */
document.addEventListener("DOMContentLoaded", async function() {
// Must finish before anything is rendered, otherwise the wrong language
// flashes up briefly. The theme is already applied by theme.js in <head>.
await I18N.init();
applyI18n();
fillAboutDialog();
wireTabs();
wireMenu();
wireTooltips();
wireRefresh();
wireAbout();
wireCopy();
init();
});