diff --git a/index.js b/index.js index 2e869b9..50b1b1a 100644 --- a/index.js +++ b/index.js @@ -9,6 +9,7 @@ const { registerPrestashopConfigBlocks } = require('./src/register-config'); const { registerPrestashopPermissions } = require('./src/register-permissions'); const { importOrdersForShop, syncPaymentsForShop } = require('./src/automation-jobs'); const { createJobRuntime } = require('./src/job-runtime'); +const { ensureShopIcon } = require('./src/shop-icon'); const NEW_ORDERS_WINDOW_MS = 20 * 60 * 1000; const runtime = createJobRuntime(Core, Log); @@ -61,6 +62,17 @@ async function runPaymentSync(kind, isLockValid) { } } +async function syncShopIcon() { + const configs = await loadEnabledConfigs(); + for (const config of configs) { + await ensureShopIcon({ + apiUrl: config.apiUrl, + shopName: config.shopName, + force: false, + }); + } +} + const jobs = [ new CronJob('0 */5 * * * *', () => runtime.track(() => runtime.withRenewedLock('prestashop-orders-puller', 5 * 60 * 1000, runOrdersPuller) @@ -86,8 +98,14 @@ async function stopJobs() { // Preserve the module's existing startup behavior; lifecycle callbacks make repeated // enable/disable transitions safe and ensure no cron remains active while disabled. startJobs(); +syncShopIcon().catch(error => { + Log.warn('PrestaShop favicon: startup synchronization failed', { error: error?.message }); +}); Core.onEnabled(async () => { startJobs(); + await syncShopIcon().catch(error => { + Log.warn('PrestaShop favicon: enable synchronization failed', { error: error?.message }); + }); Log.info('Module enabled'); }); Core.onDisabled(async () => { @@ -95,4 +113,4 @@ Core.onDisabled(async () => { Log.info('Module disabled; PrestaShop cron jobs stopped'); }); -module.exports = { startJobs, stopJobs, runOrdersPuller, runPaymentSync }; +module.exports = { startJobs, stopJobs, runOrdersPuller, runPaymentSync, syncShopIcon }; diff --git a/module.json b/module.json index 9d82bab..af18136 100644 --- a/module.json +++ b/module.json @@ -1,6 +1,6 @@ { "name": "core/prestashop", - "version": "1.1.3", + "version": "1.1.4", "singleton": false, "dependsOn": [ "core/orders", diff --git a/package-lock.json b/package-lock.json index eace401..9027e9a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "prestashop-module", - "version": "1.1.3", + "version": "1.1.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "prestashop-module", - "version": "1.1.3", + "version": "1.1.4", "license": "ISC", "dependencies": { "@orbito/api-lib": "^2.2.1", diff --git a/package.json b/package.json index c23796d..2ce598d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "prestashop-module", - "version": "1.1.3", + "version": "1.1.4", "description": "Sample orbito module", "main": "index.js", "scripts": { diff --git a/src/automation-jobs.js b/src/automation-jobs.js index 07d795c..7e56aa0 100644 --- a/src/automation-jobs.js +++ b/src/automation-jobs.js @@ -145,10 +145,14 @@ async function importOrdersForShop(config, api, dependencies = {}) { cursor = Number(order.id); processed += 1; } catch (error) { - Log.error('Failed to import PS order; cursor remains before this order', { - orderId: order.id, cursor, error: error.message, + const previousCursor = cursor; + cursor = Number(order.id); + Log.error('Failed to import PS order; skipping order and continuing', { + orderId: order.id, + previousCursor, + cursor, + error: error.message, }); - break; } } diff --git a/src/register-config.js b/src/register-config.js index 7ea7208..c227c1c 100644 --- a/src/register-config.js +++ b/src/register-config.js @@ -4,6 +4,7 @@ const PrestashopApi = require('./PrestaApi'); const { isLegacyApi } = require('./utils'); const { extractPsStateName } = require('./status-mapper'); const { setPsStates, loadPsStates } = require('./module-config'); +const { ensureShopIcon } = require('./shop-icon'); const ORBITO_STATUS_OPTIONS = { module: 'core/orders', @@ -95,6 +96,11 @@ async function registerPrestashopConfigBlocks() { try { const psStates = await fetchPsStates(apiUrl, apiKey, params.versionCode); await setPsStates(psStates); + await ensureShopIcon({ + apiUrl, + shopName: params.shopName, + force: true, + }); Log.info('PrestaShop config: połączenie OK, statusy pobrane', { count: psStates.length }); } catch (err) { Log.warn('PrestaShop config validate failed', { error: err?.message }); diff --git a/src/shop-icon.js b/src/shop-icon.js new file mode 100644 index 0000000..ace133b --- /dev/null +++ b/src/shop-icon.js @@ -0,0 +1,243 @@ +const { Config, Core, Log } = require('@orbito/api-lib'); + +const CACHE_KEY = 'runtime.shopIcon'; +const MAX_ICON_BYTES = 45 * 1024; +const MAX_HTML_BYTES = 512 * 1024; +const FETCH_TIMEOUT_MS = 10_000; +const MAX_REDIRECTS = 3; + +const pendingEnsures = new Map(); + +function storefrontUrl(apiUrl) { + const url = new URL(String(apiUrl || '').trim()); + if (!['http:', 'https:'].includes(url.protocol)) throw new Error('INVALID_SHOP_URL'); + + url.hash = ''; + url.search = ''; + const segments = url.pathname.split('/').filter(Boolean); + if (segments[segments.length - 1]?.toLowerCase() === 'api') segments.pop(); + url.pathname = `/${segments.join('/')}${segments.length ? '/' : ''}`; + return url.href; +} + +function headerValue(headers, name) { + if (!headers) return ''; + if (typeof headers.get === 'function') return headers.get(name) || ''; + const key = Object.keys(headers).find(item => item.toLowerCase() === name.toLowerCase()); + return key ? headers[key] : ''; +} + +async function responseBuffer(response) { + if (Buffer.isBuffer(response?.data)) return response.data; + if (response?.data != null) return Buffer.from(response.data); + if (typeof response?.arrayBuffer === 'function') { + return Buffer.from(await response.arrayBuffer()); + } + if (typeof response?.text === 'function') { + return Buffer.from(await response.text()); + } + return Buffer.alloc(0); +} + +async function fetchSameHost(url, rootUrl, maxBytes) { + let current = new URL(url); + const root = new URL(rootUrl); + + for (let redirect = 0; redirect <= MAX_REDIRECTS; redirect += 1) { + if (!['http:', 'https:'].includes(current.protocol) + || current.host !== root.host + || current.username + || current.password) { + throw new Error('SHOP_ICON_REDIRECT_REJECTED'); + } + + const response = await Core.fetch(current.href, { + method: 'GET', + timeout: FETCH_TIMEOUT_MS, + redirect: 'manual', + headers: { Accept: 'image/*,text/html;q=0.8,*/*;q=0.1' }, + }); + const status = Number(response?.status || 0); + if (status >= 300 && status < 400) { + const location = headerValue(response.headers, 'location'); + if (!location || redirect === MAX_REDIRECTS) throw new Error('SHOP_ICON_REDIRECT_REJECTED'); + current = new URL(location, current); + continue; + } + if (status < 200 || status >= 300) throw new Error(`SHOP_ICON_HTTP_${status || 'ERROR'}`); + + const declaredLength = Number(headerValue(response.headers, 'content-length')); + if (Number.isFinite(declaredLength) && declaredLength > maxBytes) { + throw new Error('SHOP_ICON_TOO_LARGE'); + } + const buffer = await responseBuffer(response); + if (!buffer.length || buffer.length > maxBytes) throw new Error('SHOP_ICON_TOO_LARGE'); + + return { + buffer, + contentType: headerValue(response.headers, 'content-type'), + url: current.href, + }; + } + + throw new Error('SHOP_ICON_REDIRECT_REJECTED'); +} + +function tagAttribute(tag, attribute) { + const escaped = attribute.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const quoted = new RegExp(`\\b${escaped}\\s*=\\s*(["'])(.*?)\\1`, 'i').exec(tag); + if (quoted) return quoted[2]; + const bare = new RegExp(`\\b${escaped}\\s*=\\s*([^\\s>]+)`, 'i').exec(tag); + return bare ? bare[1] : ''; +} + +function faviconCandidates(html, documentUrl) { + const candidates = []; + const seen = new Set(); + const tags = String(html || '').match(/]*>/gi) || []; + + for (const tag of tags) { + const rel = tagAttribute(tag, 'rel').toLowerCase(); + if (!rel.split(/\s+/).some(token => token === 'icon' || token === 'apple-touch-icon')) continue; + const href = tagAttribute(tag, 'href').replace(/&/gi, '&').trim(); + if (!href || href.startsWith('data:')) continue; + try { + const candidate = new URL(href, documentUrl); + if (!['http:', 'https:'].includes(candidate.protocol) || seen.has(candidate.href)) continue; + seen.add(candidate.href); + candidates.push(candidate.href); + } catch { + // Pomijamy nieprawidłowy href i przechodzimy do standardowego favicon.ico. + } + } + + const fallback = new URL('favicon.ico', documentUrl).href; + if (!seen.has(fallback)) candidates.push(fallback); + return candidates.slice(0, 5); +} + +function detectIconMime(buffer) { + if (!Buffer.isBuffer(buffer)) return ''; + if (buffer.length >= 8 + && buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) { + return 'image/png'; + } + if (buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) { + return 'image/jpeg'; + } + if (buffer.length >= 12 + && buffer.subarray(0, 4).toString('ascii') === 'RIFF' + && buffer.subarray(8, 12).toString('ascii') === 'WEBP') { + return 'image/webp'; + } + if (buffer.length >= 6 && ['GIF87a', 'GIF89a'].includes(buffer.subarray(0, 6).toString('ascii'))) { + return 'image/gif'; + } + if (buffer.length >= 4 + && buffer[0] === 0x00 && buffer[1] === 0x00 + && buffer[2] === 0x01 && buffer[3] === 0x00) { + return 'image/vnd.microsoft.icon'; + } + return ''; +} + +async function downloadShopIcon(shopPageUrl) { + let documentUrl = shopPageUrl; + let candidates = [new URL('favicon.ico', shopPageUrl).href]; + + try { + const page = await fetchSameHost(shopPageUrl, shopPageUrl, MAX_HTML_BYTES); + documentUrl = page.url; + candidates = faviconCandidates(page.buffer.toString('utf8'), documentUrl); + } catch (error) { + Log.warn('PrestaShop favicon: storefront discovery failed', { error: error?.message }); + } + + for (const candidate of candidates) { + try { + const image = await fetchSameHost(candidate, documentUrl, MAX_ICON_BYTES); + const mime = detectIconMime(image.buffer); + if (!mime) continue; + return { + dataUrl: `data:${mime};base64,${image.buffer.toString('base64')}`, + mime, + sourceUrl: image.url, + }; + } catch (error) { + Log.warn('PrestaShop favicon: candidate rejected', { + candidate, + error: error?.message, + }); + } + } + + return null; +} + +async function registerSourceProfile(cache, shopName) { + try { + await Core.callModule('core/orders', 'source.register', { + name: String(shopName || '').trim() || new URL(cache.shopUrl).hostname, + iconDataUrl: cache.dataUrl || '', + iconSourceUrl: cache.sourceUrl || '', + }); + return true; + } catch (error) { + Log.warn('PrestaShop favicon: source profile registration failed', { error: error?.message }); + return false; + } +} + +async function ensureShopIconOnce({ apiUrl, shopName, force = false }) { + const shopUrl = storefrontUrl(apiUrl); + const existing = await Config.get(CACHE_KEY, null); + const sameShop = existing && existing.shopUrl === shopUrl; + + if (!force && sameShop && existing.fetchedAt) { + await registerSourceProfile(existing, shopName); + return { ...existing, cacheHit: true }; + } + + const downloaded = await downloadShopIcon(shopUrl); + const retained = !downloaded && sameShop && existing?.dataUrl ? existing : null; + const cache = { + shopUrl, + dataUrl: downloaded?.dataUrl || retained?.dataUrl || '', + mime: downloaded?.mime || retained?.mime || '', + sourceUrl: downloaded?.sourceUrl || retained?.sourceUrl || '', + fetchedAt: new Date().toISOString(), + }; + + await Config.set(CACHE_KEY, cache); + await registerSourceProfile(cache, shopName); + return { ...cache, cacheHit: false }; +} + +function ensureShopIcon(options) { + const key = `${storefrontUrl(options?.apiUrl)}|${options?.force === true ? 'refresh' : 'cached'}`; + if (pendingEnsures.has(key)) return pendingEnsures.get(key); + + const promise = ensureShopIconOnce(options).finally(() => { + pendingEnsures.delete(key); + }); + pendingEnsures.set(key, promise); + return promise; +} + +module.exports = { + ensureShopIcon, + downloadShopIcon, + storefrontUrl, + faviconCandidates, + detectIconMime, + _private: { + CACHE_KEY, + MAX_ICON_BYTES, + MAX_HTML_BYTES, + FETCH_TIMEOUT_MS, + fetchSameHost, + responseBuffer, + tagAttribute, + registerSourceProfile, + }, +}; diff --git a/test/automation-jobs.test.js b/test/automation-jobs.test.js index dcceec3..9df1630 100644 --- a/test/automation-jobs.test.js +++ b/test/automation-jobs.test.js @@ -29,9 +29,10 @@ test('first run safely starts at the newest order without backfilling history', assert.deepEqual(result, { status: 'initialized', cursor: 812, processed: 0 }); }); -test('cursor advances only through confirmed successes and stops before failed order', async () => { +test('a failed order is skipped so later orders can still be imported', async () => { const writes = []; const imported = []; + const errors = []; const config = { _id: 'default', lastOrderId: 10 }; const api = { makeRequest: async () => ({ orders: [oldOrder(11), oldOrder(12), oldOrder(13)] }) }; const result = await importOrdersForShop(config, api, { @@ -43,14 +44,23 @@ test('cursor advances only through confirmed successes and stops before failed o return { status: 'imported', psOrderId: id, orbitoOrderId: `orbito-${id}` }; }, setLastOrderId: async id => writes.push(id), - Log: silentLog, + Log: { ...silentLog, error: (message, details) => errors.push({ message, details }) }, now: () => new Date('2026-01-02T00:00:00Z').getTime(), }); - assert.deepEqual(imported, [11, 12]); - assert.deepEqual(writes, [11]); - assert.equal(config.lastOrderId, 11); - assert.deepEqual(result, { status: 'processed', cursor: 11, processed: 1 }); + assert.deepEqual(imported, [11, 12, 13]); + assert.deepEqual(writes, [13]); + assert.equal(config.lastOrderId, 13); + assert.deepEqual(result, { status: 'processed', cursor: 13, processed: 2 }); + assert.deepEqual(errors, [{ + message: 'Failed to import PS order; skipping order and continuing', + details: { + orderId: 12, + previousCursor: 11, + cursor: 12, + error: 'invalid order', + }, + }]); }); test('existing Orbito order repairs a missing mapping before advancing the cursor', async () => { diff --git a/test/register-config-icon.test.js b/test/register-config-icon.test.js new file mode 100644 index 0000000..328118b --- /dev/null +++ b/test/register-config-icon.test.js @@ -0,0 +1,70 @@ +const assert = require('node:assert/strict'); +const Module = require('node:module'); +const path = require('node:path'); +const test = require('node:test'); + +const registerConfigPath = path.resolve(__dirname, '../src/register-config.js'); + +test('saving a valid shop connection refreshes the persisted source icon', async () => { + let blocks; + let iconOptions; + let savedStates; + const originalLoad = Module._load; + Module._load = function(request, parent, isMain) { + if (request === '@orbito/api-lib') { + return { + Config: { + PropertyType: { INFO: 'info', STRING: 'string' }, + DisplayFormat: { URL: 'url', SECRET: 'secret' }, + registerConfigBlocks: async value => { blocks = value; }, + }, + Log: { info() {}, warn() {} }, + }; + } + if (request === './PrestaApi') { + return class PrestashopApi { + async getStatuses() { + return [{ id: '2', name: 'Payment accepted', color: '#00ff00' }]; + } + }; + } + if (request === './utils') return { isLegacyApi: () => false }; + if (request === './status-mapper') return { extractPsStateName: value => value }; + if (request === './module-config') { + return { + setPsStates: async value => { savedStates = value; }, + loadPsStates: async () => [], + }; + } + if (request === './shop-icon') { + return { ensureShopIcon: async options => { iconOptions = options; } }; + } + return originalLoad.call(this, request, parent, isMain); + }; + + delete require.cache[registerConfigPath]; + try { + const { registerPrestashopConfigBlocks } = require(registerConfigPath); + await registerPrestashopConfigBlocks(); + } finally { + Module._load = originalLoad; + } + + const errors = []; + await blocks.connection.validate({ + apiUrl: 'https://shop.test', + apiKey: 'secret', + versionCode: '8', + shopName: 'Sklep główny', + }, { + addError: (field, message) => errors.push({ field, message }), + }); + + assert.deepEqual(errors, []); + assert.deepEqual(savedStates, [{ id: 2, name: 'Payment accepted', color: '#00ff00' }]); + assert.deepEqual(iconOptions, { + apiUrl: 'https://shop.test', + shopName: 'Sklep główny', + force: true, + }); +}); diff --git a/test/shop-icon.test.js b/test/shop-icon.test.js new file mode 100644 index 0000000..39080be --- /dev/null +++ b/test/shop-icon.test.js @@ -0,0 +1,125 @@ +const assert = require('node:assert/strict'); +const Module = require('node:module'); +const path = require('node:path'); +const test = require('node:test'); + +const shopIconPath = path.resolve(__dirname, '../src/shop-icon.js'); + +function pngBuffer() { + return Buffer.from([137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 0]); +} + +function loadShopIcon(api) { + const originalLoad = Module._load; + Module._load = function(request, parent, isMain) { + if (request === '@orbito/api-lib') return api; + return originalLoad.call(this, request, parent, isMain); + }; + delete require.cache[shopIconPath]; + try { + return require(shopIconPath); + } finally { + Module._load = originalLoad; + } +} + +test('discovers, downloads and persists a favicon once before registering the source', async () => { + const calls = []; + const config = new Map(); + const registered = []; + const page = Buffer.from(''); + const shopIcon = loadShopIcon({ + Config: { + get: async (key, fallback) => config.has(key) ? config.get(key) : fallback, + set: async (key, value) => config.set(key, value), + }, + Core: { + fetch: async url => { + calls.push(url); + if (url === 'https://shop.test/b2b/') { + return { status: 200, data: page, headers: { 'content-type': 'text/html' } }; + } + if (url === 'https://shop.test/b2b/img/store-icon.png') { + return { status: 200, data: pngBuffer(), headers: { 'content-type': 'image/png' } }; + } + throw new Error(`Unexpected URL: ${url}`); + }, + callModule: async (...args) => registered.push(args), + }, + Log: { warn() {} }, + }); + + const first = await shopIcon.ensureShopIcon({ + apiUrl: 'https://shop.test/b2b/api/', + shopName: 'Sklep B2B', + force: true, + }); + const second = await shopIcon.ensureShopIcon({ + apiUrl: 'https://shop.test/b2b/api/', + shopName: 'Sklep B2B', + force: false, + }); + + assert.deepEqual(calls, [ + 'https://shop.test/b2b/', + 'https://shop.test/b2b/img/store-icon.png', + ]); + assert.equal(first.cacheHit, false); + assert.equal(second.cacheHit, true); + assert.equal(first.mime, 'image/png'); + assert.match(first.dataUrl, /^data:image\/png;base64,/); + assert.equal(config.get('runtime.shopIcon').sourceUrl, 'https://shop.test/b2b/img/store-icon.png'); + assert.deepEqual(registered[0].slice(0, 2), ['core/orders', 'source.register']); + assert.equal(registered[0][2].name, 'Sklep B2B'); + assert.equal(registered[0][2].iconDataUrl, first.dataUrl); + assert.equal(registered.length, 2, 'cache hits still re-register metadata after a module restart'); +}); + +test('a failed refresh retains the last icon for the same shop', async () => { + const oldIcon = `data:image/png;base64,${pngBuffer().toString('base64')}`; + let stored = { + shopUrl: 'https://shop.test/', + dataUrl: oldIcon, + mime: 'image/png', + sourceUrl: 'https://shop.test/old.png', + fetchedAt: '2026-01-01T00:00:00.000Z', + }; + const shopIcon = loadShopIcon({ + Config: { + get: async () => stored, + set: async (key, value) => { stored = value; }, + }, + Core: { + fetch: async () => ({ status: 503, data: Buffer.alloc(0), headers: {} }), + callModule: async () => ({}), + }, + Log: { warn() {} }, + }); + + const result = await shopIcon.ensureShopIcon({ + apiUrl: 'https://shop.test/api', + shopName: 'Sklep', + force: true, + }); + + assert.equal(result.dataUrl, oldIcon); + assert.equal(result.sourceUrl, 'https://shop.test/old.png'); + assert.equal(stored.dataUrl, oldIcon); +}); + +test('favicon discovery rejects cross-host candidates and recognizes common binary formats', () => { + const shopIcon = loadShopIcon({ Config: {}, Core: {}, Log: { warn() {} } }); + const candidates = shopIcon.faviconCandidates( + '', + 'https://shop.test/catalog/' + ); + + assert.deepEqual(candidates, [ + 'https://cdn.test/icon.png', + 'https://shop.test/touch.png', + 'https://shop.test/catalog/favicon.ico', + ]); + assert.equal(shopIcon.detectIconMime(pngBuffer()), 'image/png'); + assert.equal(shopIcon.detectIconMime(Buffer.from([0, 0, 1, 0])), 'image/vnd.microsoft.icon'); + assert.equal(shopIcon.storefrontUrl('https://shop.test/catalog/api?key=secret'), 'https://shop.test/catalog/'); +});