diff --git a/package.json b/package.json index 0ce9cf0..3a3349a 100755 --- a/package.json +++ b/package.json @@ -19,11 +19,8 @@ }, "dependencies": { "create-react-class": "^15.7.0", - "is-retina": "^1.0.3", - "md5": "^2.3.0", "prop-types": "^15.8.1", "react": "^18.2.0", - "recompose": "^0.30.0", "validator": "^13.15.26" }, "devDependencies": { diff --git a/src/avatar-image.jsx b/src/avatar-image.jsx index 5ff6afe..1a82ef5 100755 --- a/src/avatar-image.jsx +++ b/src/avatar-image.jsx @@ -4,27 +4,165 @@ import {Utils, React} from 'mailspring-exports'; import PropTypes from 'prop-types'; import createReactClass from 'create-react-class'; -import md5 from 'md5'; import validator from 'validator'; -const isRetina = require('is-retina')(); -const a_table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D"; -const b_table = a_table.split(' ').map(function(s){ return parseInt(s,16) }); +// Simple LRU cache implementation with TTL support +class LRUCache { + constructor(maxSize, ttlMs = 3600000) { // Default TTL: 1 hour + this.maxSize = maxSize; + this.ttlMs = ttlMs; + this.cache = new Map(); + this.timestamps = new Map(); + } + + has(key) { + if (!this.cache.has(key)) return false; + + // Check if entry has expired + if (this.isExpired(key)) { + this.delete(key); + return false; + } + + return true; + } + + get(key) { + if (!this.cache.has(key)) return undefined; + + // Check expiration + if (this.isExpired(key)) { + this.delete(key); + return undefined; + } + + // Move to end (most recently used) + var value = this.cache.get(key); + var timestamp = this.timestamps.get(key); + this.cache.delete(key); + this.timestamps.delete(key); + this.cache.set(key, value); + this.timestamps.set(key, timestamp); + + return value; + } + + set(key, value) { + // Delete if exists to refresh position + if (this.cache.has(key)) { + this.cache.delete(key); + this.timestamps.delete(key); + } + + this.cache.set(key, value); + this.timestamps.set(key, Date.now()); + + // Evict oldest if over capacity + if (this.cache.size > this.maxSize) { + var oldest = this.cache.keys().next().value; + this.cache.delete(oldest); + this.timestamps.delete(oldest); + } + } + + delete(key) { + this.cache.delete(key); + this.timestamps.delete(key); + } + + isExpired(key) { + if (!this.timestamps.has(key)) return true; + var timestamp = this.timestamps.get(key); + return (Date.now() - timestamp) > this.ttlMs; + } + + clear() { + this.cache.clear(); + this.timestamps.clear(); + } + + // Cleanup expired entries + cleanup() { + var keysToDelete = []; + for (var key of this.cache.keys()) { + if (this.isExpired(key)) { + keysToDelete.push(key); + } + } + for (var i = 0; i < keysToDelete.length; i++) { + this.delete(keysToDelete[i]); + } + return keysToDelete.length; + } +} + +// LRU cache for favicons - stores base64 data URLs +const urlCache = new LRUCache(4096, 1209600000); // 2 weeks in ms + +// Periodic cleanup every 10 minutes +// Store interval ID to allow cleanup on module unload +var cleanupIntervalId = null; +if (typeof window !== 'undefined') { + cleanupIntervalId = setInterval(() => { + urlCache.cleanup(); + }, 600000); + + // Cleanup on window unload to prevent memory leaks + if (window.addEventListener) { + window.addEventListener('beforeunload', function() { + if (cleanupIntervalId !== null) { + clearInterval(cleanupIntervalId); + cleanupIntervalId = null; + } + }); + } +} const AvatarImage = createReactClass({ displayName: 'AvatarImage', - getProtocol: function() - { - if( typeof window === 'undefined' ) - return 'https:'; - - return window.location.protocol; - }, shouldComponentUpdate(nextProps, nextState) { return !Utils.isEqualReact(nextProps, this.props) || !Utils.isEqualReact(nextState, this.state); }, + propTypes: { + className: PropTypes.string, + fgColor: PropTypes.string, + color: PropTypes.string, + name: PropTypes.string, + value: PropTypes.string, + email: PropTypes.string, + round: PropTypes.bool, + size: PropTypes.number + }, + + getInitialState: function() { + return { + img_data: null, + value: null, + }; + }, + + componentDidMount: function() { + this.fetchAvatar(); + }, + + componentWillReceiveProps: function(newProps) { + if (newProps.img_data && newProps.img_data !== this.props.img_data) { + this.trySetState({ img_data: newProps.img_data }); + } else if (newProps.name && newProps.name !== this.props.name) { + this.trySetState({ value: this.getInitials(newProps.name) }); + } else if (newProps.value && newProps.value !== this.props.value) { + this.trySetState({ value: newProps.value }); + } + }, + + trySetState: function(hash) { + if (this.isMounted()) { + this.setState(hash); + } + }, + /** * Validate and sanitize domain extracted from email * @param {string} domain @@ -43,163 +181,281 @@ const AvatarImage = createReactClass({ }, /** - * Gravatar implementation - * @param {string} email MD5 hash or plain text email address - * @param {int} size - * @param {Function} cb - * @return {void} + * Extract domain from email, optionally getting root domain only */ - getGravatarURL: function(email, size, cb, tryNext ) - { - var base = 'gravatar.com/avatar/<%=id%>?s=<%=size%>&d=404'; - - // if email does not contain @ it's already an MD5 hash - if( email.indexOf('@') > -1 ) - email = md5(email); - - var prefix = this.getProtocol() === 'https:' ? 'https://secure.' : 'http://'; - size = isRetina ? size * 2 : size; - var url = prefix + this.parse(base, { id: email, size: size }); - this.get(url, function(data) { - cb(url); - }, tryNext) - }, - - getClearbitURL: function(email, size, cb, tryNext) - { - var base = "logo.clearbit.com/<%=domain%>"; - - var domain; - if( email.indexOf('@') > -1 ) { - domain = email.split('@')[1]; - domain = this.validateDomain(domain); - if (!domain) { - tryNext(); - return; + getDomain: function(email, useFullDomain) { + if (!email || typeof email !== 'string') return null; + if (email.indexOf('@') === -1) return null; + + var parts = email.split('@'); + // Reject malformed emails like "user@@domain" or "user@" or "@domain" + if (parts.length !== 2 || !parts[0] || !parts[1]) return null; + + var domain = parts[1].trim(); + if (!domain) return null; + + if (!useFullDomain) { + var domainParts = domain.split('.'); + if (domainParts.length > 2) { + domain = domainParts.slice(-2).join('.'); } } - var prefix = this.getProtocol() === 'https:' ? 'https://secure.' : 'http://'; - var url = prefix + this.parse(base, { domain: encodeURIComponent(domain) }); - this.get(url, function(data) { - cb(url); - }, tryNext); + return domain; }, - getTwentyIconsURL: function(email, size, cb, tryNext, useFullDomain) - { - var base = "twenty-icons.com/<%=domain%>"; - - var domain; - if( email.indexOf('@') > -1 ) { - domain = email.split('@')[1]; + /** + * Convert loaded image to base64 data URL using canvas + * @param {Image} img - The loaded image element + * @param {string} url - The original URL (for fallback) + * @return {string} Base64 data URL or original URL if CORS fails + */ + imageToDataUrl: function(img, url) { + // Security: Validate that we actually loaded an image + if (!img || !img.width || !img.height || img.width === 0 || img.height === 0) { + throw new Error('Invalid image: dimensions are zero or undefined'); + } + + // Security: Reasonable size limits to prevent memory exhaustion + var MAX_DIMENSION = 512; + if (img.width > MAX_DIMENSION || img.height > MAX_DIMENSION) { + // Image too large, use URL fallback instead of base64 + return url; + } + + try { + var canvas = document.createElement('canvas'); + canvas.width = img.width; + canvas.height = img.height; + var ctx = canvas.getContext('2d'); + ctx.drawImage(img, 0, 0); + var dataUrl = canvas.toDataURL('image/png'); - // Validate domain first - domain = this.validateDomain(domain); - if (!domain) { - tryNext(); - return; + // Security: Validate that toDataURL returned a proper data URL + if (!dataUrl || !dataUrl.startsWith('data:image/')) { + throw new Error('Invalid data URL generated'); } - // If useFullDomain is false, get root domain by removing subdomains - // Example: mail.adflex.vn -> adflex.vn - if( !useFullDomain ) { - var parts = domain.split('.'); - if( parts.length > 2 ) { - // Take the last 2 parts (domain + TLD) - domain = parts.slice(-2).join('.'); - } - } + return dataUrl; + } catch (e) { + // CORS error or other canvas issues - use URL directly + return url; } - var prefix = this.getProtocol() === 'https:' ? 'https://' : 'http://'; - var url = prefix + this.parse(base, { domain: encodeURIComponent(domain) }); - this.get(url, function(data) { - cb(url); - }, tryNext); }, /** - * Facebook implementation - * @param {string|int} id - * @param {int} size - * @param {Function} cb - * @return {void} + * Load favicon, convert to base64 data URL, and cache the result + * This avoids network requests on re-renders */ - getFacebookURL: function( id, size, cb, tryNext ) - { - var base = 'graph.facebook.com/<%=id%>/picture?width=<%=size%>'; - var url = this.getProtocol() + '//' + this.parse(base, {id: id, size: size}); - this.get(url, function(data) { - cb(url); - }, tryNext) + loadFavicon: function(url) { + // Security: Validate URL format before processing + if (!url || typeof url !== 'string') { + return Promise.reject(new Error('Invalid URL provided')); + } + + // Security: Only allow HTTPS URLs to prevent mixed content and MITM attacks + if (!url.startsWith('https://')) { + return Promise.reject(new Error('Only HTTPS URLs are allowed')); + } + + // Return cached result if available + if (urlCache.has(url)) { + var cached = urlCache.get(url); + // If it's a string (resolved data URL), return it + if (typeof cached === 'string') { + return Promise.resolve(cached); + } + // If it's a promise, return a new independent promise + // This prevents shared promise failures from affecting all callers + return new Promise((resolve, reject) => { + cached.then(resolve, reject); + }); + } + + // Create the promise that will load and convert the image + var self = this; + var promise = new Promise((resolve, reject) => { + var img = new Image(); + img.crossOrigin = 'anonymous'; + + img.onload = () => { + try { + // Convert to base64 data URL (or fallback to URL on CORS error) + var dataUrl = self.imageToDataUrl(img, url); + + // Security: Validate result before caching + if (!dataUrl || typeof dataUrl !== 'string') { + throw new Error('imageToDataUrl returned invalid data'); + } + + // Security: Ensure it's either a data URL or the original HTTPS URL + if (!dataUrl.startsWith('data:image/') && !dataUrl.startsWith('https://')) { + throw new Error('Invalid data URL format'); + } + + // Cache the result for future use + urlCache.set(url, dataUrl); + resolve(dataUrl); + } catch (e) { + // Don't cache errors + reject(e); + } + }; + + img.onerror = () => { + // Don't cache failures - remove from cache to allow retry + if (urlCache.has(url)) { + var cached = urlCache.get(url); + // Only delete if it's still our promise (not replaced by another call) + if (cached === promise) { + urlCache.delete(url); + } + } + reject(new Error('Failed to load favicon: ' + url)); + }; + + img.src = url; + }); + + // Cache the promise temporarily until it resolves + urlCache.set(url, promise); + + return promise; }, /** - * Google+ implementation - * @param {int} id - * @param {int} size - * @param {Function} cb - * @return {void} + * Try to fetch avatar from TwentyIcons */ - getGoogleURL: function( id, size, cb, tryNext ) - { - var base = 'picasaweb.google.com/data/entry/api/user/<%=id%>?alt=json'; - var url = this.getProtocol() + '//' + this.parse(base, {id: id}); - this.get(url, function(data) { - var src = data.entry.gphoto$thumbnail.$t.replace('s64', 's' + size); // replace with the correct size - cb(src); - }, tryNext); + fetchAvatar: async function() { + if (!this.props.email) { + this.setFallback(); + return; + } + + var fullDomain = this.validateDomain(this.getDomain(this.props.email, true)); + var rootDomain = this.validateDomain(this.getDomain(this.props.email, false)); + + // Encode domains for URL safety (defense in depth) + var encodedFullDomain = fullDomain ? encodeURIComponent(fullDomain) : null; + var encodedRootDomain = rootDomain ? encodeURIComponent(rootDomain) : null; + + // Try full domain first if it has subdomains + if (encodedFullDomain && fullDomain !== rootDomain) { + try { + var img_data = await this.loadFavicon('https://twenty-icons.com/' + encodedFullDomain); + this.trySetState({ img_data: img_data }); + return; + } catch (e) { + // Fall through to try root domain + } + } + + // Try root domain + if (encodedRootDomain) { + try { + var img_data = await this.loadFavicon('https://twenty-icons.com/' + encodedRootDomain); + this.trySetState({ img_data: img_data }); + return; + } catch (e) { + // Fall through to vemetric fallback + } + } + + // Try vemetric with full domain first if it has subdomains + // default= forces vemetric to return 404 if no favicon found + if (encodedFullDomain && fullDomain !== rootDomain) { + try { + var img_data = await this.loadFavicon('https://favicon.vemetric.com/' + encodedFullDomain + '?default='); + this.trySetState({ img_data: img_data }); + return; + } catch (e) { + // Fall through to try root domain + } + } + + // Try vemetric with root domain + // default= forces vemetric to return 404 if no favicon found + if (encodedRootDomain) { + try { + var img_data = await this.loadFavicon('https://favicon.vemetric.com/' + encodedRootDomain + '?default='); + this.trySetState({ img_data: img_data }); + return; + } catch (e) { + // Fall through to favicon0 fallback + } + } + + // Try favicon0 with full domain first if it has subdomains + if (encodedFullDomain && fullDomain !== rootDomain) { + try { + var img_data = await this.loadFavicon('https://cdn.favicon0.com/' + encodedFullDomain + '/favicon.png'); + this.trySetState({ img_data: img_data }); + return; + } catch (e) { + // Fall through to try root domain + } + } + + // Try favicon0 with root domain + if (encodedRootDomain) { + try { + var img_data = await this.loadFavicon('https://cdn.favicon0.com/' + encodedRootDomain + '/favicon.png'); + this.trySetState({ img_data: img_data }); + return; + } catch (e) { + // Fall through to initials + } + } + + this.setFallback(); }, - /** - * Skype implementation - * @param {string} id - * @param {int} size - * @param {Function} cb - * @return {void} - */ - getSkypeURL: function( id, size, cb, tryNext ) - { - var base = 'api.skype.com/users/<%=id%>/profile/avatar'; - var url = this.getProtocol() + '//' + this.parse(base, {id: id}); - this.get(url, function(data) { - cb(url); - }, tryNext) + setFallback: function() { + if (this.props.name) { + this.trySetState({ value: this.getInitials(this.props.name) }); + } else if (this.props.value) { + this.trySetState({ value: this.props.value }); + } }, /** - * Replace variables in a string - * @param {string} value String that will be parsed - * @param {Object} variables Key value object - * @return {string} + * Validate and sanitize color value to prevent CSS injection + * @param {string} color - Color value to validate + * @return {string|null} Valid hex color or null */ - parse: function( value, variables ) - { - for(var variable in variables) - { - value = value.replace('<%=' + variable + '%>', variables[variable]); + validateColor: function(color) { + if (!color || typeof color !== 'string') return null; + + // Only allow hex colors (#RGB or #RRGGBB) + var hexPattern = /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/; + if (!hexPattern.test(color)) { + return null; } - return value; + + return color; }, /** - * Implementatiopn of PHP crc32 function - * @param str - * @return {number} + * Validate and sanitize size value to prevent CSS injection + * @param {number} size - Size value to validate + * @return {number} Valid size (clamped to safe range) */ - crc32 (str) { - var crc = -1; - for (var i= 0, iTop=str.length; i>> 8 ) ^ b_table[( crc ^ str.charCodeAt( i ) ) & 0xFF]; + validateSize: function(size) { + // Ensure it's a number + var numSize = parseInt(size, 10); + if (isNaN(numSize) || numSize <= 0) { + return 32; // Default size } - return (crc ^ (-1)) >>> 0; + + // Clamp to reasonable range (prevent DOS via huge sizes) + var MIN_SIZE = 16; + var MAX_SIZE = 512; + return Math.max(MIN_SIZE, Math.min(MAX_SIZE, numSize)); }, /** - * Return a random color - * @return {string} + * Return a deterministic color based on email */ - rndColor: function() - { + rndColor: function() { var colors = [ '#d73d32', '#7e3794', @@ -212,256 +468,85 @@ const AvatarImage = createReactClass({ '#430C05', '#955149' ]; - var crc32Value = this.crc32(this.props.email) - var index = (crc32Value % colors.length) + 1; - // var index = Math.floor(Math.random()*colors.length); - return colors[ index ]; + var hash = 0; + var str = this.props.email || ''; + for (var i = 0; i < str.length; i++) { + hash = ((hash << 5) - hash) + str.charCodeAt(i); + hash = hash & hash; + } + return colors[Math.abs(hash) % colors.length]; }, /** * Convert a name into initials - * @param {string} name - * @return {string} */ - getInitials: function( name ) - { + getInitials: function(name) { var parts = name.split(' '); var initials = ''; - for(var i=0 ; i < parts.length ; i++) - { - if (i > 3) break; + for (var i = 0; i < parts.length && i < 4; i++) { initials += parts[i].substr(0, 1).toUpperCase(); } return initials; }, - /** - * Do an ajax request to fetch remote data - * @param {string} url - * @param {Function} cb - * @return {void} - */ - get: function(url, successCb, errorCb) { - var request = new XMLHttpRequest(); - request.onreadystatechange = () => { - if (request.readyState === 4) { - if (request.status === 200) { - var data = request.responseText; - if (this.isJsonString(data)) { - data = JSON.parse(data); - } - successCb(data); - } else { - errorCb(request.status); - } - } - }; - request.open('GET', url, true); - request.send(); - }, - - isJsonString: function(str) { - try { - JSON.parse(str); - } catch (e) { - return false; - } - return true; - }, - - /** - * Set the src attribute of the image element use to display the avatar - * @param {string} src - */ - setSrc: function( src ) - { - if( src === null ) - return; - - this.trySetState({ src: src }); - }, - - propTypes: { - className: PropTypes.string, - fgColor: PropTypes.string, - color: PropTypes.string, - name: PropTypes.string, - value: PropTypes.string, - email: PropTypes.string, - facebookId: PropTypes.string, - googleId: PropTypes.string, - skypeID: PropTypes.string, - round: PropTypes.bool, - size: PropTypes.number - }, - getInitialState: function() { - return { - src: null, - value: null, - triedFacebook: false, - triedGoogle: false, - triedSkype: false, - triedGravatar: false, - triedClearbit: false, - triedTwentyIcons: false, - triedTwentyIconsFullDomain: false, - }; - }, - // componentWillMount: function() { - // this.fetch(); - // }, - componentDidMount: function() { - this.fetch(); - }, - componentWillReceiveProps: function(newProps) { - /** - * This component ignores changes in `this.props.src`, `this.props.name`, and - * `this.props.value`. This lifecycle method will allow users to change the avatars name or - * value. - */ - if (newProps.src && newProps.src !== this.props.src) { - this.trySetState({ src: newProps.src }); - } else if (newProps.name && newProps.name !== this.props.name) { - this.trySetState({ value: this.getInitials(newProps.name) }); - } else if (newProps.value && newProps.value !== this.props.value) { - this.trySetState({ value: newProps.value }); - } - }, - - trySetState: function(hash){ - if(this.isMounted()) { //bad antipattern - this.setState(hash); - } + handleImageError: function() { + this.trySetState({ img_data: null }); + this.setFallback(); }, - fetch: function( e ) { - var url = null; - var self = this; - var tryNext = function() { - self.fetch(); - }; - - // If fetch was triggered by img onError - // then set state src back to null so getVisual will - // automatically switch to drawn avatar if there is no other social ID available to try - if( e && e.type === "error" ) { - this.state.src = null; - } - - if( this.state.triedClearbit === false && ! this.state.url && this.props.email ) { - this.state.triedClearbit = true; - this.getClearbitURL( this.props.email, this.props.size, this.setSrc, tryNext); - return; - } - - if( this.state.triedGravatar === false && ! this.state.url && this.props.email) { - this.state.triedGravatar = true; - this.getGravatarURL( this.props.email, this.props.size, this.setSrc, tryNext ); - return; - } - - if( this.state.triedFacebook === false && ! this.state.url && this.props.facebookId) { - this.state.triedFacebook = true; - this.getFacebookURL( this.props.facebookId , this.props.size, this.setSrc, tryNext ); - return; - } - - if( this.state.triedGoogle === false && ! this.state.url && this.props.googleId) { - this.state.triedGoogle = true; - this.getGoogleURL( this.props.googleId , this.props.size, this.setSrc, tryNext ); - return; - } - - if( this.state.triedSkype === false && ! this.state.url && this.props.skypeId) { - this.state.triedSkype = true; - this.getSkypeURL( this.props.skypeId , this.props.size, this.setSrc, tryNext ); - return; - } - - if( this.state.triedTwentyIcons === false && ! this.state.url && this.props.email) { - // Check if domain has subdomains (more than 2 parts) - var emailDomain = this.props.email.indexOf('@') > -1 ? this.props.email.split('@')[1] : null; - var hasSubdomain = emailDomain && emailDomain.split('.').length > 2; - - if( hasSubdomain && this.state.triedTwentyIconsFullDomain === false ) { - // Try full domain first (e.g., mail.adflex.vn) - this.state.triedTwentyIconsFullDomain = true; - this.getTwentyIconsURL( this.props.email, this.props.size, this.setSrc, tryNext, true ); - return; - } else { - // Try root domain (e.g., adflex.vn) or if no subdomain, try the domain as is - this.state.triedTwentyIcons = true; - this.getTwentyIconsURL( this.props.email, this.props.size, this.setSrc, tryNext, false ); - return; - } - } - - if( this.state.src ) - return; - - if( this.props.name ) - this.trySetState({ value: this.getInitials( this.props.name ) }); - - if( !this.props.name && this.props.value ) - this.trySetState({ value: this.props.value }); - - if( url === null && this.props.src) { - this.setSrc( this.parse(this.props.src, {size: this.props.size}) ); - return; - } - }, getVisual: function() { - + // Security: Validate all user-provided style values + var safeSize = this.validateSize(this.props.size); + var safeBgColor = this.validateColor(this.props.color) || this.rndColor(); + var safeFgColor = this.validateColor(this.props.fgColor) || '#FFF'; + var imageStyle = { maxWidth: '100%', - width: this.props.size, - height: this.props.size, + width: safeSize, + height: safeSize, borderRadius: (this.props.round ? 500 : 0), objectFit: 'cover' }; var initialsStyle = { - background: this.props.color || this.rndColor(), - width: this.props.size, - height: this.props.size, - font: Math.floor(this.props.size/3) + 'px/100px', - color: this.props.fgColor, + background: safeBgColor, + width: safeSize, + height: safeSize, + font: Math.floor(safeSize / 3) + 'px/100px', + color: safeFgColor, textAlign: 'center', textTransform: 'uppercase', - lineHeight: (this.props.size + Math.floor(this.props.size/10)) + 'px', + lineHeight: (safeSize + Math.floor(safeSize / 10)) + 'px', borderRadius: (this.props.round ? 500 : 0) }; - if(this.state.src) { + if (this.state.img_data) { return ( - /* jshint ignore:start */ - - /* jshint ignore:end */ + ); } else { return ( - /* jshint ignore:start */ -
{ this.state.value }
- /* jshint ignore:end */ +
{this.state.value}
); } }, + render: function() { + // Security: Validate size to prevent CSS injection + var safeSize = this.validateSize(this.props.size); + var hostStyle = { display: 'inline-block', - width: this.props.size, - height: this.props.size, + width: safeSize, + height: safeSize, borderRadius: (this.props.round ? 500 : 0), objectFit: 'cover' }; - var visual = this.getVisual(); return ( - /* jshint ignore:start */ -
- { visual } +
+ {this.getVisual()}
- /* jshint ignore:end */ ); } }); @@ -472,9 +557,6 @@ AvatarImage.defaultProps = { name: null, value: null, email: null, - facebookId: null, - skypeId: null, - googleId: null, round: false, size: 32 }; diff --git a/yarn.lock b/yarn.lock index 694d2d7..1330d9c 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2,51 +2,18 @@ # yarn lockfile v1 -"@babel/runtime@^7.0.0": - version "7.19.4" - resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.19.4.tgz#a42f814502ee467d55b38dd1c256f53a7b885c78" - integrity sha512-EXpLCrk55f+cYqmHsSR+yD/0gAIMxxA9QK9lnQWzhMCvt+YmoBN7Zx94s++Kv0+unHk39vxNO8t+CMA2WSS3wA== - dependencies: - regenerator-runtime "^0.13.4" - "@types/prop-types@*": - version "15.7.3" - resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.3.tgz#2ab0d5da2e5815f94b0b9d4b95d1e5f243ab2ca7" - integrity sha512-KfRL3PuHmqQLOG+2tGpRO26Ctg+Cq1E01D2DMriKEATHgWLfeNDmq9e29Q9WIky0dQ3NPkd1mzYH8Lm936Z9qw== + version "15.7.15" + resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.15.tgz#e6e5a86d602beaca71ce5163fadf5f95d70931c7" + integrity sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw== "@types/react@^18.0.21": - version "18.0.21" - resolved "https://registry.yarnpkg.com/@types/react/-/react-18.0.21.tgz#b8209e9626bb00a34c76f55482697edd2b43cc67" - integrity sha512-7QUCOxvFgnD5Jk8ZKlUAhVcRj7GuJRjnjjiY/IUBWKgOlnvDvTMLD4RTF7NPyVmbRhNrbomZiOepg7M/2Kj1mA== + version "18.3.27" + resolved "https://registry.yarnpkg.com/@types/react/-/react-18.3.27.tgz#74a3b590ea183983dc65a474dc17553ae1415c34" + integrity sha512-cisd7gxkzjBKU2GgdYrTdtQx1SORymWyaAFhaxQPK9bYO9ot3Y5OikQRvY0VYQtvwjeQnizCINJAenh/V7MK2w== dependencies: "@types/prop-types" "*" - "@types/scheduler" "*" - csstype "^3.0.2" - -"@types/scheduler@*": - version "0.16.2" - resolved "https://registry.yarnpkg.com/@types/scheduler/-/scheduler-0.16.2.tgz#1a62f89525723dde24ba1b01b092bf5df8ad4d39" - integrity sha512-hppQEBDmlwhFAXKJX2KnWLYu5yMfi91yazPb2l+lbJiwW+wdo1gNeRA+3RgNSO39WYX2euey41KEwnqesU2Jew== - -asap@~2.0.3: - version "2.0.6" - resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46" - integrity sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY= - -change-emitter@^0.1.2: - version "0.1.6" - resolved "https://registry.yarnpkg.com/change-emitter/-/change-emitter-0.1.6.tgz#e8b2fe3d7f1ab7d69a32199aff91ea6931409515" - integrity sha512-YXzt1cQ4a2jqazhcuSWEOc1K2q8g9H6eWNsyZgi640LDzRWVQ2eDe+Y/kVdftH+vYdPF2rgDb3dLdpxE1jvAxw== - -charenc@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/charenc/-/charenc-0.0.2.tgz#c0a1d2f3a7092e03774bfa83f14c0fc5790a8667" - integrity sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA== - -core-js@^1.0.0: - version "1.2.7" - resolved "https://registry.yarnpkg.com/core-js/-/core-js-1.2.7.tgz#652294c14651db28fa93bd2d5ff2983a4f08c636" - integrity sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY= + csstype "^3.2.2" create-react-class@^15.7.0: version "15.7.0" @@ -56,111 +23,27 @@ create-react-class@^15.7.0: loose-envify "^1.3.1" object-assign "^4.1.1" -crypt@0.0.2: - version "0.0.2" - resolved "https://registry.yarnpkg.com/crypt/-/crypt-0.0.2.tgz#88d7ff7ec0dfb86f713dc87bbb42d044d3e6c41b" - integrity sha512-mCxBlsHFYh9C+HVpiEacem8FEBnMXgU9gy4zmNC+SXAZNB/1idgp/aulFJ4FgCi7GPEVbfyng092GqL2k2rmow== - -csstype@^3.0.2: - version "3.1.1" - resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.1.1.tgz#841b532c45c758ee546a11d5bd7b7b473c8c30b9" - integrity sha512-DJR/VvkAvSZW9bTouZue2sSxDwdTN92uHjqeKVm+0dAqdfNykRzQ95tay8aXMBAAPpUiq4Qcug2L7neoRh2Egw== - -encoding@^0.1.11: - version "0.1.12" - resolved "https://registry.yarnpkg.com/encoding/-/encoding-0.1.12.tgz#538b66f3ee62cd1ab51ec323829d1f9480c74beb" - integrity sha1-U4tm8+5izRq1HsMjgp0flIDHS+s= - dependencies: - iconv-lite "~0.4.13" - -fbjs@^0.8.1: - version "0.8.18" - resolved "https://registry.yarnpkg.com/fbjs/-/fbjs-0.8.18.tgz#9835e0addb9aca2eff53295cd79ca1cfc7c9662a" - integrity sha512-EQaWFK+fEPSoibjNy8IxUtaFOMXcWsY0JaVrQoZR9zC8N2Ygf9iDITPWjUTVIax95b6I742JFLqASHfsag/vKA== - dependencies: - core-js "^1.0.0" - isomorphic-fetch "^2.1.1" - loose-envify "^1.0.0" - object-assign "^4.1.0" - promise "^7.1.1" - setimmediate "^1.0.5" - ua-parser-js "^0.7.30" - -hoist-non-react-statics@^2.3.1: - version "2.5.5" - resolved "https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz#c5903cf409c0dfd908f388e619d86b9c1174cb47" - integrity sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw== - -iconv-lite@~0.4.13: - version "0.4.24" - resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b" - integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA== - dependencies: - safer-buffer ">= 2.1.2 < 3" - -is-buffer@~1.1.6: - version "1.1.6" - resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-1.1.6.tgz#efaa2ea9daa0d7ab2ea13a97b2b8ad51fefbe8be" - integrity sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w== - -is-retina@^1.0.3: - version "1.0.3" - resolved "https://registry.yarnpkg.com/is-retina/-/is-retina-1.0.3.tgz#d7401b286bea2ae37f62477588de504d0b8647e3" - integrity sha1-10AbKGvqKuN/Ykd1iN5QTQuGR+M= - -is-stream@^1.0.1: - version "1.1.0" - resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-1.1.0.tgz#12d4a3dd4e68e0b79ceb8dbc84173ae80d91ca44" - integrity sha1-EtSj3U5o4Lec6428hBc66A2RykQ= - -isomorphic-fetch@^2.1.1: - version "2.2.1" - resolved "https://registry.yarnpkg.com/isomorphic-fetch/-/isomorphic-fetch-2.2.1.tgz#611ae1acf14f5e81f729507472819fe9733558a9" - integrity sha1-YRrhrPFPXoH3KVB0coGf6XM1WKk= - dependencies: - node-fetch "^1.0.1" - whatwg-fetch ">=0.10.0" +csstype@^3.2.2: + version "3.2.3" + resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.2.3.tgz#ec48c0f3e993e50648c86da559e2610995cf989a" + integrity sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ== "js-tokens@^3.0.0 || ^4.0.0": version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== -loose-envify@^1.0.0, loose-envify@^1.1.0, loose-envify@^1.3.1, loose-envify@^1.4.0: +loose-envify@^1.1.0, loose-envify@^1.3.1, loose-envify@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== dependencies: js-tokens "^3.0.0 || ^4.0.0" -md5@^2.3.0: - version "2.3.0" - resolved "https://registry.yarnpkg.com/md5/-/md5-2.3.0.tgz#c3da9a6aae3a30b46b7b0c349b87b110dc3bda4f" - integrity sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g== - dependencies: - charenc "0.0.2" - crypt "0.0.2" - is-buffer "~1.1.6" - -node-fetch@^1.0.1: - version "1.7.3" - resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-1.7.3.tgz#980f6f72d85211a5347c6b2bc18c5b84c3eb47ef" - integrity sha512-NhZ4CsKx7cYm2vSrBAr2PvFOe6sWDf0UYLRqA6svUYg7+/TSfVAu49jYC4BvQ4Sms9SZgdqGBgroqfDhJdTyKQ== - dependencies: - encoding "^0.1.11" - is-stream "^1.0.1" - -object-assign@^4.1.0, object-assign@^4.1.1: +object-assign@^4.1.1: version "4.1.1" resolved "https://registry.yarnpkg.com/object-assign/-/object-assign-4.1.1.tgz#2109adc7965887cfc05cbbd442cac8bfbb360863" - integrity sha1-IQmtx5ZYh8/AXLvUQsrIv7s2CGM= - -promise@^7.1.1: - version "7.3.1" - resolved "https://registry.yarnpkg.com/promise/-/promise-7.3.1.tgz#064b72602b18f90f29192b8b1bc418ffd1ebd3bf" - integrity sha512-nolQXZ/4L+bP/UGlkfaIujX9BKxGwmQ9OT4mOt5yvy8iK1h3wqTEJCijzGANTCCl9nWjY41juyAn2K3Q1hLLTg== - dependencies: - asap "~2.0.3" + integrity sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg== prop-types@^15.8.1: version "15.8.1" @@ -176,66 +59,19 @@ react-is@^16.13.1: resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4" integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ== -react-lifecycles-compat@^3.0.2: - version "3.0.4" - resolved "https://registry.yarnpkg.com/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz#4f1a273afdfc8f3488a8c516bfda78f872352362" - integrity sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA== - react@^18.2.0: - version "18.2.0" - resolved "https://registry.yarnpkg.com/react/-/react-18.2.0.tgz#555bd98592883255fa00de14f1151a917b5d77d5" - integrity sha512-/3IjMdb2L9QbBdWiW5e3P2/npwMBaU9mHCSCUzNln0ZCYbcfTsGbTJrU/kGemdH2IWmB2ioZ+zkxtmq6g09fGQ== + version "18.3.1" + resolved "https://registry.yarnpkg.com/react/-/react-18.3.1.tgz#49ab892009c53933625bd16b2533fc754cab2891" + integrity sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ== dependencies: loose-envify "^1.1.0" -recompose@^0.30.0: - version "0.30.0" - resolved "https://registry.yarnpkg.com/recompose/-/recompose-0.30.0.tgz#82773641b3927e8c7d24a0d87d65aeeba18aabd0" - integrity sha512-ZTrzzUDa9AqUIhRk4KmVFihH0rapdCSMFXjhHbNrjAWxBuUD/guYlyysMnuHjlZC/KRiOKRtB4jf96yYSkKE8w== - dependencies: - "@babel/runtime" "^7.0.0" - change-emitter "^0.1.2" - fbjs "^0.8.1" - hoist-non-react-statics "^2.3.1" - react-lifecycles-compat "^3.0.2" - symbol-observable "^1.0.4" - -regenerator-runtime@^0.13.4: - version "0.13.10" - resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.10.tgz#ed07b19616bcbec5da6274ebc75ae95634bfc2ee" - integrity sha512-KepLsg4dU12hryUO7bp/axHAKvwGOCV0sGloQtpagJ12ai+ojVDqkeGSiRX1zlq+kjIMZ1t7gpze+26QqtdGqw== - -"safer-buffer@>= 2.1.2 < 3": - version "2.1.2" - resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" - integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== - -setimmediate@^1.0.5: - version "1.0.5" - resolved "https://registry.yarnpkg.com/setimmediate/-/setimmediate-1.0.5.tgz#290cbb232e306942d7d7ea9b83732ab7856f8285" - integrity sha1-KQy7Iy4waULX1+qbg3Mqt4VvgoU= - -symbol-observable@^1.0.4: - version "1.2.0" - resolved "https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804" - integrity sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ== - typescript@^4.8.4: - version "4.8.4" - resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.8.4.tgz#c464abca159669597be5f96b8943500b238e60e6" - integrity sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ== - -ua-parser-js@^0.7.30: - version "0.7.31" - resolved "https://registry.yarnpkg.com/ua-parser-js/-/ua-parser-js-0.7.31.tgz#649a656b191dffab4f21d5e053e27ca17cbff5c6" - integrity sha512-qLK/Xe9E2uzmYI3qLeOmI0tEOt+TBBQyUIAh4aAgU05FVYzeZrKUdkAZfBNVGRaHVgV0TDkdEngJSw/SyQchkQ== + version "4.9.5" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.5.tgz#095979f9bcc0d09da324d58d03ce8f8374cbe65a" + integrity sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g== validator@^13.15.26: version "13.15.26" resolved "https://registry.yarnpkg.com/validator/-/validator-13.15.26.tgz#36c3deeab30e97806a658728a155c66fcaa5b944" integrity sha512-spH26xU080ydGggxRyR1Yhcbgx+j3y5jbNXk/8L+iRvdIEQ4uTRH2Sgf2dokud6Q4oAtsbNvJ1Ft+9xmm6IZcA== - -whatwg-fetch@>=0.10.0: - version "3.0.0" - resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.0.0.tgz#fc804e458cc460009b1a2b966bc8817d2578aefb" - integrity sha512-9GSJUgz1D4MfyKU7KRqwOjXCXTqWdFNvEr7eUBYchQiVc744mqK/MzXPNR2WsPkmkOa4ywfg8C2n8h+13Bey1Q==