Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01JkYTqsvYu6AYr9yQ3Q4Nt6
270 lines
20 KiB
JavaScript
270 lines
20 KiB
JavaScript
// Checks a Chrome extension (Manifest V3) before loading or publishing it: bin/jumphp chrome:check <folder> [--json]
|
|
// node check.cjs <folder> [--json] -> a readable report (or the JSON one), var/chrome-check.json, exit 1 on errors
|
|
// What it checks: manifest.json (required keys, MV3 rules, version, lengths the Chrome Web Store enforces), every file
|
|
// it references (and the scripts / styles / images of its pages), the icons (PNG, their real size), the permissions
|
|
// (unknown, broad, declared but unused, used but not declared), and the translations (_locales: every key used is in
|
|
// every locale, the same keys everywhere).
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { shippedFiles, readJson, resolveMessage } = require('./common.cjs');
|
|
|
|
const PERMISSIONS = {
|
|
// permission: the chrome.* namespace that needs it (null: no namespace of its own)
|
|
activeTab: null, alarms: 'alarms', background: null, bookmarks: 'bookmarks', browsingData: 'browsingData',
|
|
certificateProvider: 'certificateProvider', clipboardRead: null, clipboardWrite: null, contentSettings: 'contentSettings',
|
|
contextMenus: 'contextMenus', cookies: 'cookies', debugger: 'debugger', declarativeContent: 'declarativeContent',
|
|
declarativeNetRequest: 'declarativeNetRequest', declarativeNetRequestWithHostAccess: null, declarativeNetRequestFeedback: null,
|
|
desktopCapture: 'desktopCapture', documentScan: 'documentScan', downloads: 'downloads', 'downloads.open': null, 'downloads.ui': null,
|
|
enterprise: null, 'enterprise.deviceAttributes': null, 'enterprise.hardwarePlatform': null, 'enterprise.networkingAttributes': null,
|
|
'enterprise.platformKeys': null, favicon: null, fileBrowserHandler: 'fileBrowserHandler', fileSystemProvider: 'fileSystemProvider',
|
|
fontSettings: 'fontSettings', gcm: 'gcm', geolocation: null, history: 'history', identity: 'identity', 'identity.email': null,
|
|
idle: 'idle', loginState: 'loginState', management: 'management', nativeMessaging: null, notifications: 'notifications',
|
|
offscreen: 'offscreen', pageCapture: 'pageCapture', platformKeys: 'platformKeys', power: 'power', printerProvider: 'printerProvider',
|
|
printing: 'printing', printingMetrics: 'printingMetrics', privacy: 'privacy', processes: 'processes', proxy: 'proxy',
|
|
readingList: 'readingList', runtime: null, scripting: 'scripting', search: 'search', sessions: 'sessions', sidePanel: 'sidePanel',
|
|
storage: 'storage', 'system.cpu': null, 'system.display': null, 'system.memory': null, 'system.storage': null,
|
|
tabCapture: 'tabCapture', tabGroups: 'tabGroups', tabs: null, topSites: 'topSites', tts: 'tts', ttsEngine: 'ttsEngine',
|
|
unlimitedStorage: null, userScripts: 'userScripts', vpnProvider: 'vpnProvider', wallpaper: 'wallpaper', webAuthenticationProxy: null,
|
|
webNavigation: 'webNavigation', webRequest: 'webRequest', webRequestBlocking: null,
|
|
};
|
|
// permissions that make the install dialog scary and the Web Store review longer: say why in the listing
|
|
const SENSITIVE = new Set(['tabs', 'history', 'bookmarks', 'cookies', 'webRequest', 'webNavigation', 'debugger', 'management', 'nativeMessaging',
|
|
'downloads', 'topSites', 'privacy', 'proxy', 'clipboardRead', 'geolocation', 'pageCapture', 'tabCapture', 'desktopCapture', 'browsingData',
|
|
'contentSettings', 'userScripts', 'declarativeNetRequestFeedback', 'sessions', 'readingList']);
|
|
const BROAD_HOSTS = /^(<all_urls>|\*:\/\/\*\/\*|https?:\/\/\*\/\*|\*:\/\/\*\/|https?:\/\/\*\/)$/;
|
|
const MV2_ONLY = { browser_action: 'use "action"', page_action: 'use "action"', chrome_settings_overrides_v2: null };
|
|
|
|
function check(root) {
|
|
const errors = [], warnings = [], info = [];
|
|
const err = (code, message) => errors.push({ code, message });
|
|
const warn = (code, message) => warnings.push({ code, message });
|
|
const exists = (rel) => typeof rel === 'string' && fs.existsSync(path.join(root, rel.replace(/^\//, '').split('?')[0].split('#')[0]));
|
|
|
|
const manifestFile = path.join(root, 'manifest.json');
|
|
if (!fs.existsSync(manifestFile)) {
|
|
err('manifest.missing', 'manifest.json is missing at the root of the folder');
|
|
return { ok: false, errors, warnings, info };
|
|
}
|
|
let m;
|
|
try {
|
|
m = readJson(manifestFile);
|
|
} catch (e) {
|
|
err('manifest.json', `manifest.json is not valid JSON: ${e.message}`);
|
|
return { ok: false, errors, warnings, info };
|
|
}
|
|
|
|
// ---- translations
|
|
const localesDir = path.join(root, '_locales');
|
|
const locales = {};
|
|
if (fs.existsSync(localesDir)) {
|
|
for (const lang of fs.readdirSync(localesDir)) {
|
|
const file = path.join(localesDir, lang, 'messages.json');
|
|
if (!fs.existsSync(file)) { warn('i18n.locale', `_locales/${lang} has no messages.json`); continue; }
|
|
try { locales[lang] = readJson(file); } catch (e) { err('i18n.json', `_locales/${lang}/messages.json is not valid JSON: ${e.message}`); }
|
|
}
|
|
}
|
|
const langs = Object.keys(locales);
|
|
const defaultMessages = locales[m.default_locale] || {};
|
|
if (langs.length && !m.default_locale) err('i18n.default_locale', '_locales exists: manifest.json needs "default_locale"');
|
|
if (m.default_locale && !locales[m.default_locale]) err('i18n.default_locale', `default_locale "${m.default_locale}" has no _locales/${m.default_locale}/messages.json`);
|
|
const R = (v) => resolveMessage(v, defaultMessages);
|
|
|
|
// ---- required keys, MV3
|
|
if (m.manifest_version !== 3) err('mv3.version', `manifest_version is ${JSON.stringify(m.manifest_version)}: the Chrome Web Store only takes Manifest V3 (3)`);
|
|
for (const key of ['name', 'version']) if (!m[key]) err('manifest.required', `"${key}" is required`);
|
|
if (!m.description) warn('manifest.description', '"description" is missing: the Chrome Web Store needs one (132 characters at most)');
|
|
const name = R(m.name || '');
|
|
if (name.length > 75) err('manifest.name', `the name is ${name.length} characters long: 75 at most`);
|
|
if (m.short_name && R(m.short_name).length > 12) warn('manifest.short_name', `short_name "${R(m.short_name)}" is longer than 12 characters: it may be cut`);
|
|
const description = R(m.description || '');
|
|
if (description.length > 132) err('manifest.description', `the description is ${description.length} characters long: 132 at most`);
|
|
if (m.version && !/^(0|[1-9]\d{0,4})(\.(0|[1-9]\d{0,4})){0,3}$/.test(m.version) || String(m.version || '').split('.').some((n) => Number(n) > 65535)) {
|
|
err('manifest.version', `version "${m.version}": 1 to 4 numbers (0-65535) separated by dots, no leading zero (put "1.0 beta" in version_name)`);
|
|
}
|
|
for (const [key, hint] of Object.entries(MV2_ONLY)) if (key in m) err('mv3.removed', `"${key}" does not exist in Manifest V3${hint ? `: ${hint}` : ''}`);
|
|
if (m.background) {
|
|
if (m.background.scripts || m.background.page) err('mv3.background', 'background.scripts / background.page are Manifest V2: use background.service_worker (one file, "type": "module" to import others)');
|
|
if ('persistent' in m.background) err('mv3.background', 'background.persistent does not exist in Manifest V3 (the service worker stops when idle)');
|
|
if (m.background.service_worker && !exists(m.background.service_worker)) err('file.missing', `background.service_worker: ${m.background.service_worker} does not exist`);
|
|
}
|
|
if (typeof m.content_security_policy === 'string') err('mv3.csp', 'content_security_policy must be an object in Manifest V3: {"extension_pages": "..."}');
|
|
const csp = m.content_security_policy?.extension_pages || '';
|
|
if (/unsafe-eval|https?:\/\/|unsafe-inline/.test(csp)) err('mv3.csp', `content_security_policy.extension_pages "${csp}": Manifest V3 forbids remote code, eval and inline scripts`);
|
|
if (Array.isArray(m.web_accessible_resources) && m.web_accessible_resources.some((w) => typeof w === 'string')) {
|
|
err('mv3.web_accessible_resources', 'web_accessible_resources must be a list of objects in Manifest V3: [{"resources": [...], "matches": [...]}]');
|
|
}
|
|
|
|
// ---- permissions
|
|
const permissions = Array.isArray(m.permissions) ? m.permissions : [];
|
|
const hosts = [...(m.host_permissions || []), ...(m.optional_host_permissions || [])];
|
|
for (const p of permissions) {
|
|
if (/[:/*<]/.test(p)) err('mv3.host_permissions', `"${p}" is a host: put it in "host_permissions" (Manifest V3)`);
|
|
else if (!(p in PERMISSIONS)) err('permissions.unknown', `unknown permission "${p}"`);
|
|
else if (SENSITIVE.has(p)) warn('permissions.sensitive', `"${p}" shows a warning when installing and lengthens the review: keep it only if needed and justify it in the listing`);
|
|
}
|
|
for (const p of [...(m.permissions || []), ...(m.optional_permissions || [])]) {
|
|
if (p === 'webRequestBlocking') err('mv3.webRequestBlocking', 'webRequestBlocking is not available to Manifest V3 extensions: use declarativeNetRequest');
|
|
}
|
|
for (const h of hosts) if (BROAD_HOSTS.test(h)) warn('permissions.broad', `host permission "${h}" = every site: prefer "activeTab" or the sites you need`);
|
|
for (const cs of m.content_scripts || []) {
|
|
for (const h of cs.matches || []) if (BROAD_HOSTS.test(h)) warn('permissions.broad', `content script on "${h}" = every site: list the sites you need`);
|
|
}
|
|
if (permissions.includes('tabs') && permissions.includes('activeTab')) info.push({ code: 'permissions.tabs', message: '"tabs" and "activeTab": activeTab is often enough (the tab the user clicked on)' });
|
|
|
|
// ---- files referenced by the manifest
|
|
const refs = [];
|
|
const add = (where, file) => { if (typeof file === 'string' && file) refs.push([where, file]); };
|
|
for (const [size, file] of Object.entries(m.icons || {})) add(`icons.${size}`, file);
|
|
if (m.action) {
|
|
add('action.default_popup', m.action.default_popup);
|
|
if (typeof m.action.default_icon === 'string') add('action.default_icon', m.action.default_icon);
|
|
else for (const [s, f] of Object.entries(m.action.default_icon || {})) add(`action.default_icon.${s}`, f);
|
|
}
|
|
add('options_page', m.options_page);
|
|
add('options_ui.page', m.options_ui?.page);
|
|
if (m.options_page && m.options_ui) warn('manifest.options', 'both options_page and options_ui: keep one');
|
|
add('side_panel.default_path', m.side_panel?.default_path);
|
|
add('devtools_page', m.devtools_page);
|
|
for (const [k, f] of Object.entries(m.chrome_url_overrides || {})) add(`chrome_url_overrides.${k}`, f);
|
|
(m.content_scripts || []).forEach((cs, i) => {
|
|
if (!Array.isArray(cs.matches) || !cs.matches.length) err('content_scripts.matches', `content_scripts[${i}] has no "matches"`);
|
|
for (const f of cs.js || []) add(`content_scripts[${i}].js`, f);
|
|
for (const f of cs.css || []) add(`content_scripts[${i}].css`, f);
|
|
});
|
|
(m.web_accessible_resources || []).forEach((w, i) => {
|
|
if (typeof w !== 'object') return;
|
|
if (!w.matches && !w.extension_ids) err('mv3.web_accessible_resources', `web_accessible_resources[${i}] needs "matches" (or "extension_ids")`);
|
|
for (const f of w.resources || []) if (!/[*]/.test(f)) add(`web_accessible_resources[${i}]`, f);
|
|
});
|
|
for (const r of m.declarative_net_request?.rule_resources || []) add('declarative_net_request.rule_resources', r.path);
|
|
for (const p of m.sandbox?.pages || []) add('sandbox.pages', p);
|
|
for (const [where, file] of refs) {
|
|
if (/^https?:/.test(file)) err('file.remote', `${where}: ${file} is remote: everything must be inside the package`);
|
|
else if (!exists(file)) err('file.missing', `${where}: ${file} does not exist`);
|
|
}
|
|
|
|
// ---- icons
|
|
const pngSize = (rel) => {
|
|
const buf = fs.readFileSync(path.join(root, rel));
|
|
if (buf.length < 24 || buf.toString('latin1', 1, 4) !== 'PNG') return null;
|
|
return [buf.readUInt32BE(16), buf.readUInt32BE(20)];
|
|
};
|
|
const iconChecks = Object.entries(m.icons || {}).map(([s, f]) => [`icons.${s}`, s, f]);
|
|
if (m.action && typeof m.action.default_icon === 'object') for (const [s, f] of Object.entries(m.action.default_icon)) iconChecks.push([`action.default_icon.${s}`, s, f]);
|
|
for (const [where, size, file] of iconChecks) {
|
|
if (!exists(file)) continue;
|
|
const dims = /\.png$/i.test(file) ? pngSize(file) : null;
|
|
if (!dims) { warn('icons.format', `${where}: ${file} is not a PNG (Chrome wants PNG icons)`); continue; }
|
|
if (dims[0] !== dims[1] || String(dims[0]) !== String(size)) warn('icons.size', `${where}: ${file} is ${dims[0]}x${dims[1]}, expected ${size}x${size}`);
|
|
}
|
|
for (const s of ['16', '48', '128']) {
|
|
if (!m.icons?.[s]) (s === '128' ? warn : (c, msg) => info.push({ code: c, message: msg }))('icons.missing', `no ${s}x${s} icon in "icons"${s === '128' ? ' (the Chrome Web Store and the install dialog use it)' : ''}`);
|
|
}
|
|
|
|
// ---- the code: pages, scripts, i18n keys used, chrome.* namespaces used
|
|
const files = shippedFiles(root);
|
|
const usedKeys = new Map(); // key -> where
|
|
const useKey = (key, where) => { if (!usedKeys.has(key)) usedKeys.set(key, where); };
|
|
JSON.stringify(m).replace(/__MSG_(\w+)__/g, (_, k) => useKey(k, 'manifest.json'));
|
|
const namespaces = new Map();
|
|
for (const rel of files) {
|
|
const abs = path.join(root, rel);
|
|
if (/\.html?$/i.test(rel)) {
|
|
const html = fs.readFileSync(abs, 'utf8');
|
|
for (const mm of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {
|
|
const src = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(mm[1]);
|
|
if (!src && mm[2].trim() && !/type\s*=\s*["'](application\/(ld\+)?json|text\/template)["']/i.test(mm[1])) err('mv3.inline-script', `${rel}: an inline <script>: the extension's content security policy blocks it, put it in a .js file`);
|
|
if (src && /^(https?:)?\/\//.test(src[1])) err('mv3.remote-code', `${rel}: <script src="${src[1]}"> loads remote code (forbidden in Manifest V3): ship the file in the package`);
|
|
}
|
|
if (/\son[a-z]+\s*=\s*["']/i.test(html.replace(/<script[\s\S]*?<\/script>/gi, ''))) warn('mv3.inline-handler', `${rel}: an inline event handler (onclick="..."): blocked by the content security policy, use addEventListener`);
|
|
for (const mm of html.matchAll(/\b(?:src|href)\s*=\s*["']([^"'#?]+)/gi)) {
|
|
const ref = mm[1];
|
|
if (/^([a-z]+:|\/\/|#|mailto:)/i.test(ref) || ref.includes('{{')) continue;
|
|
const target = ref.startsWith('/') ? ref.slice(1) : path.posix.normalize(path.posix.join(path.posix.dirname(rel), ref));
|
|
if (!fs.existsSync(path.join(root, target))) err('file.missing', `${rel}: ${ref} does not exist`);
|
|
}
|
|
for (const mm of html.matchAll(/data-i18n\s*=\s*["'](\w+)["']/g)) useKey(mm[1], rel);
|
|
for (const mm of html.matchAll(/data-i18n-attr\s*=\s*["']([^"']+)["']/g)) for (const pair of mm[1].split(',')) { const k = pair.split(':')[1]?.trim(); if (k) useKey(k, rel); }
|
|
JSON.stringify(html).replace(/__MSG_(\w+)__/g, (_, k) => useKey(k, rel));
|
|
} else if (/\.m?js$/i.test(rel)) {
|
|
const js = fs.readFileSync(abs, 'utf8');
|
|
for (const mm of js.matchAll(/(?:getMessage|\bt)\(\s*["'](\w+)["']/g)) useKey(mm[1], rel);
|
|
for (const mm of js.matchAll(/\bchrome\.(\w+)(?:\.(\w+))?/g)) {
|
|
const ns = mm[1] === 'system' || mm[1] === 'enterprise' ? `${mm[1]}.${mm[2]}` : mm[1];
|
|
if (!namespaces.has(ns)) namespaces.set(ns, rel);
|
|
}
|
|
if (/\beval\s*\(|\bnew\s+Function\s*\(/.test(js)) warn('mv3.eval', `${rel}: eval() / new Function(): refused by Manifest V3's content security policy`);
|
|
if (/import\s*\(\s*["']https?:|importScripts\(\s*["']https?:/.test(js)) err('mv3.remote-code', `${rel}: imports remote code (forbidden in Manifest V3)`);
|
|
for (const mm of js.matchAll(/(?:^|\n)\s*import\s+(?:[^'"]*?from\s+)?["'](\.{1,2}\/[^"']+)["']/g)) {
|
|
const target = path.posix.normalize(path.posix.join(path.posix.dirname(rel), mm[1]));
|
|
if (!fs.existsSync(path.join(root, target))) err('file.missing', `${rel}: import ${mm[1]} does not exist`);
|
|
}
|
|
if (/chrome\.runtime\.connectNative|chrome\.runtime\.sendNativeMessage/.test(js) && !permissions.includes('nativeMessaging')) err('permissions.missing', `${rel} uses native messaging without the "nativeMessaging" permission`);
|
|
}
|
|
}
|
|
const withoutPermission = new Map(Object.entries(PERMISSIONS).filter(([, ns]) => ns).map(([p, ns]) => [ns, p]));
|
|
for (const [ns, where] of namespaces) {
|
|
const needed = withoutPermission.get(ns);
|
|
if (needed && !permissions.includes(needed) && !(m.optional_permissions || []).includes(needed)) {
|
|
err('permissions.missing', `${where} uses chrome.${ns}: add "${needed}" to "permissions"`);
|
|
}
|
|
}
|
|
for (const p of permissions) {
|
|
const ns = PERMISSIONS[p];
|
|
if (ns && !namespaces.has(ns)) warn('permissions.unused', `"${p}" is declared but chrome.${ns} is never used: remove it (fewer permissions, faster review)`);
|
|
}
|
|
|
|
// ---- translations: every key used exists in every locale, the same keys everywhere
|
|
if (langs.length) {
|
|
const keysOf = (lang) => new Set(Object.keys(locales[lang]).map((k) => k.toLowerCase()));
|
|
const all = new Set(langs.flatMap((l) => [...keysOf(l)]));
|
|
for (const lang of langs) {
|
|
const keys = keysOf(lang);
|
|
for (const [key, where] of usedKeys) if (!keys.has(key.toLowerCase())) (lang === m.default_locale ? err : warn)('i18n.missing', `_locales/${lang}: no message "${key}" (used in ${where})`);
|
|
const missing = [...all].filter((k) => !keys.has(k));
|
|
if (missing.length) warn('i18n.incomplete', `_locales/${lang} lacks ${missing.length} key(s) the other locales have: ${missing.slice(0, 8).join(', ')}${missing.length > 8 ? '…' : ''}`);
|
|
for (const [key, value] of Object.entries(locales[lang])) {
|
|
if (!/^[A-Za-z0-9_@]+$/.test(key)) err('i18n.key', `_locales/${lang}: the key "${key}" may only hold A-Z a-z 0-9 _ @`);
|
|
if (typeof value?.message !== 'string') { err('i18n.message', `_locales/${lang}: "${key}" has no "message" text`); continue; }
|
|
for (const ph of value.message.matchAll(/\$([A-Za-z0-9_@]+)\$/g)) {
|
|
const defined = Object.keys(value.placeholders || {}).map((k) => k.toLowerCase());
|
|
if (!defined.includes(ph[1].toLowerCase())) err('i18n.placeholder', `_locales/${lang}: "${key}" uses $${ph[1]}$ without "placeholders"`);
|
|
}
|
|
if (value.message.includes('{{')) warn('i18n.placeholder-text', `_locales/${lang}: "${key}" still holds a template placeholder: ${value.message}`);
|
|
}
|
|
}
|
|
} else if (usedKeys.size) {
|
|
err('i18n.missing', `${[...usedKeys.values()][0]} uses translated messages (__MSG_…__ / getMessage) but there is no _locales folder`);
|
|
}
|
|
|
|
const size = files.reduce((n, f) => n + fs.statSync(path.join(root, f)).size, 0);
|
|
info.push({ code: 'package', message: `${files.length} file(s) shipped, ${(size / 1024).toFixed(1)} KB (tests, scripts, var, dist, *.md and dev files left out)` });
|
|
if (langs.length) info.push({ code: 'i18n', message: `locales: ${langs.join(', ')} (default ${m.default_locale}); ${usedKeys.size} message key(s) used` });
|
|
return { ok: errors.length === 0, name, version: m.version || null, description, manifest_version: m.manifest_version, permissions, host_permissions: hosts, errors, warnings, info };
|
|
}
|
|
|
|
module.exports = { check };
|
|
|
|
if (require.main === module) {
|
|
const args = process.argv.slice(2);
|
|
const json = args.includes('--json');
|
|
const root = path.resolve(args.find((a) => !a.startsWith('--')) || '.');
|
|
const report = check(root);
|
|
try {
|
|
fs.mkdirSync(path.join(root, 'var'), { recursive: true });
|
|
fs.writeFileSync(path.join(root, 'var', 'chrome-check.json'), JSON.stringify(report, null, 2) + '\n');
|
|
} catch { /* read-only folder: the report is printed anyway */ }
|
|
if (json) {
|
|
process.stdout.write(JSON.stringify(report, null, 2) + '\n');
|
|
} else {
|
|
const c = (code, s) => (process.stdout.isTTY ? `\x1b[${code}m${s}\x1b[0m` : s);
|
|
console.log(`${report.name || '?'} ${report.version || ''} (Manifest V${report.manifest_version ?? '?'})`);
|
|
for (const e of report.errors) console.log(c('31', ` error ${e.message}`) + c('2', ` [${e.code}]`));
|
|
for (const w of report.warnings) console.log(c('33', ` warning ${w.message}`) + c('2', ` [${w.code}]`));
|
|
for (const i of report.info) console.log(c('2', ` info ${i.message}`));
|
|
console.log(report.ok ? c('32', `OK: ${report.warnings.length} warning(s)`) : c('31', `${report.errors.length} error(s), ${report.warnings.length} warning(s)`));
|
|
console.log('report: var/chrome-check.json');
|
|
}
|
|
process.exit(report.ok ? 0 : 1);
|
|
}
|