commit fcc2125e49c7429ac04ac157b71289c569f2901b Author: Mateusz Gruszczyński Date: Thu Nov 19 12:45:00 2026 +0100 first commit diff --git a/README.md b/README.md new file mode 100644 index 0000000..142c477 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# HTTP Headers — Compact v1.2.2 + +Rozszerzenie Chrome/Chromium (Manifest V3), pokazujące nagłówki aktualnie otwartej karty. +Nie trzeba wpisywać adresu URL. Rozszerzenie nie modyfikuje ruchu sieciowego. + +## Instalacja i aktualizacja + +1. Rozpakuj archiwum ZIP. +2. Otwórz `chrome://extensions`, włącz **Tryb dewelopera**. +3. Kliknij **Załaduj rozpakowane** i wskaż folder `HTTP-Headers-Complete` (z plikiem `manifest.json`). +4. Otwórz stronę HTTP/HTTPS, odśwież ją i kliknij ikonę rozszerzenia. + +Jeśli aktualizujesz poprzednią wersję: zastąp pliki w *dotychczasowym folderze rozszerzenia*, +a następnie kliknij **Odśwież** na `chrome://extensions`. Jeśli wskażesz inny folder, Chrome +może potraktować go jako nowe rozszerzenie. + +## Zachowanie + +- Po otwarciu automatycznie pokazuje żądanie **Dokument strony** (`main_frame`), nie CSS/JS/obrazy. +- W rozwijanym polu **Pozostałe zasoby** można wybrać konkretne żądanie (CSS, JS, obraz, fetch/XHR itd.). +- Zakładki **Odpowiedź** i **Żądanie** rozdzielają typ nagłówków. +- Niewielkie odstępy: wiersz tabeli ma ok. 20 px. Popup ma **stałą wysokość 520 px**, a przy większej liczbie nagłówków przewija się wyłącznie tabela (bez zmiany wysokości całego okna). +- Długie wartości są zwinięte do jednej linii. Kliknięcie wartości rozwija ją, a przycisk **Kopiuj** kopiuje pełne wartości. +- Powtarzające się nagłówki są pokazywane osobno (np. dwa `Vary`). +- Aktualizacje innych zasobów w tle nie przebudowują widoku dokumentu; zachowywana jest pozycja przewijania tabeli. +- Przy dużej liczbie zasobów wpis dokumentu jest chroniony przed usunięciem z historii. + +## Prywatność + +Rozszerzenie niczego nie wysyła poza przeglądarkę. W tymczasowym `chrome.storage.session` +zachowuje do 75 wpisów żądań na kartę; zapisane nagłówki mogą zawierać poufne `Cookie` +i tokeny uwierzytelniające. Nie udostępniaj ich bez anonimizacji. + +## Testy + +```bash +node tests/test-background.js +node tests/test-popup-layout.js +``` + +Bez zewnętrznych bibliotek i bez kompilacji. Chrome może nie ujawniać pewnych nagłówków (np. pseudo-nagłówków HTTP/2). diff --git a/background.js b/background.js new file mode 100644 index 0000000..6902654 --- /dev/null +++ b/background.js @@ -0,0 +1,201 @@ +'use strict'; + +// Manifest V3: chrome.webRequest pozwala ODCZYTYWAĆ odpowiedzi; niczego nie zmieniamy. +// Nagłówki przechowujemy jako tablicę, NIE jako mapę {nazwa: wartość}. +// Dwa pola "Vary" pozostają dwoma osobnymi rekordami. +const FILTER = { urls: ['http://*/*', 'https://*/*'] }; +const MAX_REQUESTS_PER_TAB = 75; +const MAX_VALUE_LENGTH = 16384; +const MAX_URL_LENGTH = 4096; +const pendingByTab = new Map(); + +function storageKey(tabId) { + return `headers_tab_${tabId}`; +} + +function newState() { + return { nextSeq: 1, navigationAt: 0, entries: [] }; +} + +function safeString(value, limit = MAX_VALUE_LENGTH) { + const string = String(value ?? ''); + return string.length > limit ? `${string.slice(0, limit)} … [wartość ucięta]` : string; +} + +function copyHeaders(headers) { + if (!Array.isArray(headers)) return []; + return headers.map(header => { + let value; + if (typeof header.value === 'string') { + value = safeString(header.value); + } else if (Array.isArray(header.binaryValue)) { + value = 'hex: ' + header.binaryValue.map(byte => byte.toString(16).padStart(2, '0')).join(' '); + value = safeString(value); + } else { + value = ''; + } + return { name: safeString(header.name, 256), value }; + }); +} + +// Kolejka per karta zapobiega utracie zdarzeń przy równoczesnym odczycie/zapisie +// asynchronicznego chrome.storage.session. Nie synchronizujemy danych do chmury. +function updateTab(tabId, change) { + if (!Number.isInteger(tabId) || tabId < 0) return; + const key = storageKey(tabId); + const previous = pendingByTab.get(tabId) || Promise.resolve(); + const pending = previous.catch(() => {}).then(async () => { + const saved = await chrome.storage.session.get(key); + const state = saved[key] || newState(); + change(state); + // Chronimy wpis dokumentu strony: przy dużej liczbie obrazów, skryptów + // i żądań XHR nie może wypaść z historii przed otwarciem popupu. + while (state.entries.length > MAX_REQUESTS_PER_TAB) { + let removable = state.entries.length - 1; + for (let i = state.entries.length - 1; i >= 0; i--) { + if (state.entries[i].type !== 'main_frame') { + removable = i; + break; + } + } + state.entries.splice(removable, 1); + } + await chrome.storage.session.set({ [key]: state }); + }); + pendingByTab.set(tabId, pending); + pending.finally(() => { + if (pendingByTab.get(tabId) === pending) pendingByTab.delete(tabId); + }).catch(() => {}); + return pending; +} + +function currentEntry(state, details) { + return state.entries.find(entry => + entry.requestId === details.requestId && + entry.phase !== 'redirected' && + entry.phase !== 'completed' && + entry.phase !== 'error' + ); +} + +function createEntry(state, details) { + const entry = { + id: String(state.nextSeq++), + requestId: details.requestId, + method: details.method || 'GET', + url: safeString(details.url, MAX_URL_LENGTH), + type: details.type || 'other', + frameId: details.frameId ?? -1, + timeStamp: details.timeStamp || Date.now(), + requestHeaders: [], + responseHeaders: [], + statusCode: null, + statusLine: '', + phase: 'pending', + redirectUrl: '', + error: '' + }; + state.entries.unshift(entry); + return entry; +} + +function entryForEvent(state, details) { + return currentEntry(state, details) || createEntry(state, details); +} + +function acceptEvent(state, details) { + // Odrzuć spóźnione zdarzenia poprzedniej strony po rozpoczęciu nowej nawigacji. + return !state.navigationAt || details.timeStamp >= state.navigationAt; +} + +chrome.webRequest.onBeforeRequest.addListener(details => { + updateTab(details.tabId, state => { + const previousHop = currentEntry(state, details); + if (details.type === 'main_frame' && !previousHop && + !state.entries.some(entry => entry.requestId === details.requestId && entry.phase === 'redirected')) { + state.entries = []; + state.navigationAt = details.timeStamp; + } + if (!acceptEvent(state, details)) return; + // Nowe wywołanie oznacza nową próbę / etap przekierowania. + createEntry(state, details); + }); +}, FILTER); + +// onSendHeaders, a nie onBeforeSendHeaders: najbliższy ostatecznemu zestaw +// nagłówków wysyłanych przez Chrome; extraHeaders ujawnia m.in. Cookie. +chrome.webRequest.onSendHeaders.addListener(details => { + updateTab(details.tabId, state => { + if (!acceptEvent(state, details)) return; + const entry = entryForEvent(state, details); + entry.requestHeaders = copyHeaders(details.requestHeaders); + }); +}, FILTER, ['requestHeaders', 'extraHeaders']); + +chrome.webRequest.onHeadersReceived.addListener(details => { + updateTab(details.tabId, state => { + if (!acceptEvent(state, details)) return; + const entry = entryForEvent(state, details); + entry.statusCode = details.statusCode ?? null; + entry.statusLine = safeString(details.statusLine || '', 200); + entry.responseHeaders = copyHeaders(details.responseHeaders); + entry.phase = 'headers'; + }); +}, FILTER, ['responseHeaders', 'extraHeaders']); + +chrome.webRequest.onBeforeRedirect.addListener(details => { + updateTab(details.tabId, state => { + if (!acceptEvent(state, details)) return; + const entry = entryForEvent(state, details); + entry.statusCode = details.statusCode ?? entry.statusCode; + entry.statusLine = safeString(details.statusLine || entry.statusLine, 200); + if (Array.isArray(details.responseHeaders) && !entry.responseHeaders.length) { + entry.responseHeaders = copyHeaders(details.responseHeaders); + } + entry.redirectUrl = safeString(details.redirectUrl, MAX_URL_LENGTH); + entry.phase = 'redirected'; + }); +}, FILTER, ['responseHeaders', 'extraHeaders']); + +chrome.webRequest.onCompleted.addListener(details => { + updateTab(details.tabId, state => { + if (!acceptEvent(state, details)) return; + const entry = currentEntry(state, details); + if (entry) { + entry.statusCode = details.statusCode ?? entry.statusCode; + entry.phase = 'completed'; + } + }); +}, FILTER); + +chrome.webRequest.onErrorOccurred.addListener(details => { + updateTab(details.tabId, state => { + if (!acceptEvent(state, details)) return; + const entry = currentEntry(state, details); + if (entry) { + entry.error = safeString(details.error, 300); + entry.phase = 'error'; + } + }); +}, FILTER); + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (!message || message.action !== 'clearTab') return; + const tabId = message.tabId; + if (!Number.isInteger(tabId) || tabId < 0) { + sendResponse({ ok: false }); + return; + } + // Nie ufaj tabId z dowolnej strony: wiadomości od treści stron nie są + // obsługiwane (brak content scripts i onMessageExternal). + updateTab(tabId, state => { + state.entries = []; + state.nextSeq = 1; + }).then(() => sendResponse({ ok: true })).catch(() => sendResponse({ ok: false })); + return true; +}); + +chrome.tabs.onRemoved.addListener(tabId => { + const previous = pendingByTab.get(tabId) || Promise.resolve(); + previous.catch(() => {}).then(() => chrome.storage.session.remove(storageKey(tabId))).catch(() => {}); +}); diff --git a/icons/icon128.png b/icons/icon128.png new file mode 100644 index 0000000..b804629 Binary files /dev/null and b/icons/icon128.png differ diff --git a/icons/icon16.png b/icons/icon16.png new file mode 100644 index 0000000..2c01c27 Binary files /dev/null and b/icons/icon16.png differ diff --git a/icons/icon32.png b/icons/icon32.png new file mode 100644 index 0000000..0dd0844 Binary files /dev/null and b/icons/icon32.png differ diff --git a/icons/icon48.png b/icons/icon48.png new file mode 100644 index 0000000..73483a2 Binary files /dev/null and b/icons/icon48.png differ diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..f5c31ae --- /dev/null +++ b/manifest.json @@ -0,0 +1,37 @@ +{ + "manifest_version": 3, + "name": "HTTP Headers — Compact", + "short_name": "HTTP Headers+", + "version": "1.2.2", + "description": "Kompaktowy podgląd HTTP z osobnymi zakładkami i stałą wysokością popupu, bez skoków przewijania.", + "minimum_chrome_version": "102", + "permissions": [ + "webRequest", + "tabs", + "storage", + "clipboardWrite" + ], + "host_permissions": [ + "http://*/*", + "https://*/*" + ], + "background": { + "service_worker": "background.js" + }, + "action": { + "default_title": "Pełne nagłówki HTTP", + "default_popup": "popup.html", + "default_icon": { + "16": "icons/icon16.png", + "32": "icons/icon32.png", + "48": "icons/icon48.png", + "128": "icons/icon128.png" + } + }, + "icons": { + "16": "icons/icon16.png", + "32": "icons/icon32.png", + "48": "icons/icon48.png", + "128": "icons/icon128.png" + } +} diff --git a/popup.css b/popup.css new file mode 100644 index 0000000..5e4ca66 --- /dev/null +++ b/popup.css @@ -0,0 +1,136 @@ +:root { + color-scheme: light dark; + --bg: #fff; + --surface: #f6f6f6; + --surface-hover: #f1f1f1; + --line: #e9e9e9; + --line-strong: #dcdcdc; + --text: #242424; + --muted: #737373; + --subtle: #939393; + --focus: #676767; + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif; + font-size: 11px; + color: var(--text); + background: var(--bg); +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +/* Stały wymiar popupu: rozmiar okna nie zmienia się w trakcie przewijania. */ +html, body { width: 580px; height: 520px; overflow: hidden; } +body { margin: 0; } +button, input, select { font: inherit; color: inherit; } +button { cursor: pointer; } +button:disabled { opacity: .45; cursor: default; } +button:focus-visible, select:focus-visible, input:focus-visible, #headersPanel:focus-visible { + outline: 1px solid var(--focus); + outline-offset: -1px; +} +/* Wysokość jest stała; przewija się wyłącznie lista nagłówków. */ +.app { display: flex; flex-direction: column; height: 520px; background: var(--bg); } +.toolbar { + flex: none; height: 32px; display: flex; align-items: center; justify-content: space-between; + padding: 0 10px; border-bottom: 1px solid var(--line); +} +.brand { font-size: 12px; font-weight: 650; letter-spacing: -.12px; } +.toolbar-actions { display: flex; align-items: center; gap: 2px; } +.plain-button { + border: 0; border-radius: 2px; background: transparent; padding: 3px 7px; + color: var(--muted); font-size: 11px; line-height: 18px; +} +.plain-button:hover:not(:disabled) { background: var(--surface-hover); color: var(--text); } +#toast { color: var(--muted); font-size: 10px; padding-right: 4px; } +#details { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; } +.overview { flex: none; min-width: 0; } +.status-line { height: 28px; display: flex; align-items: center; gap: 8px; padding: 0 10px; } +.status-line strong { font-size: 13px; line-height: 1.1; font-weight: 650; } +.resource-type, .header-counter { color: var(--muted); font-size: 10px; } +.header-counter { margin-left: auto; font-variant-numeric: tabular-nums; } +.url-line { + height: 23px; padding: 0 10px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; + background: var(--surface); border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); + font: 10px/22px ui-monospace, "SFMono-Regular", Consolas, "Liberation Mono", monospace; + color: #565656; +} +.controls { + flex: none; display: flex; align-items: center; gap: 6px; + height: 34px; padding: 4px 9px; border-bottom: 1px solid var(--line); +} +.scope-select-wrap { flex: 0 0 158px; min-width: 0; } +.request-select-wrap { flex: 1 1 auto; min-width: 0; } +.search-wrap { flex: 1 1 auto; min-width: 0; } +#details.resources-mode .search-wrap { flex: 0 0 144px; } +.controls select, .controls input { + width: 100%; height: 25px; padding: 0 7px; border: 1px solid var(--line-strong); + background: var(--bg); border-radius: 2px; outline: none; font-size: 11px; +} +.controls select { white-space: nowrap; text-overflow: ellipsis; padding-right: 18px; } +.controls input::placeholder { color: var(--subtle); } +.tabs-toolbar { + flex: none; height: 30px; display: flex; align-items: stretch; justify-content: space-between; + border-bottom: 1px solid var(--line-strong); padding: 0 8px; +} +.tabs { display: flex; align-items: stretch; gap: 12px; } +.tab { + border: 0; border-bottom: 2px solid transparent; background: none; margin-bottom: -1px; + padding: 0 4px; font-size: 11px; color: var(--muted); font-weight: 500; +} +.tab.is-active { border-bottom-color: var(--text); color: var(--text); font-weight: 650; } +.tab:not(.is-active):hover { color: var(--text); } +.tab-count { color: var(--subtle); font-size: 10px; margin-left: 2px; font-variant-numeric: tabular-nums; font-weight: 400; } +.copy-button { align-self: center; } +/* Stabilna powierzchnia przewijania, bez zmiany geometrii okna. */ +.headers-panel { + flex: 1 1 auto; min-height: 0; overflow-x: hidden; overflow-y: auto; + overscroll-behavior: contain; scrollbar-gutter: stable; +} +.table-head, .header-row { display: grid; grid-template-columns: 182px minmax(0, 1fr); } +.table-head { + position: sticky; top: 0; z-index: 2; min-height: 21px; background: var(--surface); + border-bottom: 1px solid var(--line-strong); color: var(--muted); font-size: 10px; font-weight: 600; +} +.table-head span { padding: 3px 8px 4px; } +.table-head span:first-child { padding-left: 10px; border-right: 1px solid var(--line); } +.header-row { min-height: 20px; border-bottom: 1px solid var(--line); } +.header-row:hover { background: var(--surface-hover); } +.header-row.expanded { background: var(--surface); } +.header-name { min-width: 0; border-right: 1px solid var(--line); } +.name-button, .value-button { + width: 100%; min-width: 0; display: block; border: 0; border-radius: 0; + background: transparent; text-align: left; padding: 2px 8px 1px; + line-height: 16px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; +} +.name-button { + padding-left: 10px; font-size: 11px; font-weight: 550; color: #4d4d4d; +} +.value-button { + font: 10.5px/16px ui-monospace, "SFMono-Regular", Consolas, "Liberation Mono", monospace; + color: var(--text); +} +.name-button.is-truncated, .value-button.is-truncated { cursor: pointer; } +.name-button:not(.is-truncated), .value-button:not(.is-truncated) { cursor: default; } +.header-row.expanded .name-button, .header-row.expanded .value-button { + white-space: pre-wrap; overflow: visible; overflow-wrap: anywhere; word-break: break-word; +} +.no-matches { padding: 12px 10px; color: var(--muted); text-align: center; font-size: 11px; } +.empty-state { + display: flex; flex-direction: column; flex: 1 1 auto; align-items: center; justify-content: center; + padding: 22px 18px; text-align: center; +} +.empty-state strong { font-size: 12px; font-weight: 650; } +.empty-state p { max-width: 340px; color: var(--muted); line-height: 1.4; } +.primary-button { margin-top: 3px; padding: 5px 10px; border: 1px solid var(--line-strong); background: var(--surface); border-radius: 2px; } +.primary-button:hover { background: var(--surface-hover); } +.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } +@media (prefers-color-scheme: dark) { + :root { + --bg: #1d1d1d; --surface: #272727; --surface-hover: #303030; + --line: #343434; --line-strong: #454545; + --text: #ededed; --muted: #afafaf; --subtle: #999999; --focus: #bfbfbf; + } + .url-line { color: #bfbfbf; } + .name-button { color: #c7c7c7; } + .controls select, .controls input { background: #252525; } + .controls input::placeholder { color: #929292; } + .tab.is-active { border-bottom-color: var(--text); } +} diff --git a/popup.html b/popup.html new file mode 100644 index 0000000..93ebeac --- /dev/null +++ b/popup.html @@ -0,0 +1,71 @@ + + + + + + + HTTP Headers + + + +
+
+ HTTP Headers +
+ + + +
+
+ + + +
+
+
+ — + + +
+
+
+ +
+ + + +
+ +
+
+ + +
+ +
+ +
+ +
+
+
+
+ + + diff --git a/popup.js b/popup.js new file mode 100644 index 0000000..885e96c --- /dev/null +++ b/popup.js @@ -0,0 +1,310 @@ +'use strict'; + +let tabId = -1; +let items = []; +let selectedResourceId = null; +let scope = 'document'; +let activeTab = 'response'; +let toastTimeout = null; +let lastHeaderRenderKey = null; +let hasRendered = false; + +const $ = id => document.getElementById(id); +const STATUS = { + 200: 'OK', 201: 'Created', 202: 'Accepted', 204: 'No Content', 206: 'Partial Content', + 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', + 307: 'Temporary Redirect', 308: 'Permanent Redirect', 400: 'Bad Request', + 401: 'Unauthorized', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', + 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 418: "I'm a teapot", + 422: 'Unprocessable Content', 429: 'Too Many Requests', 500: 'Internal Server Error', + 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout' +}; +const TYPES = { + main_frame: 'Dokument', sub_frame: 'Ramka', xmlhttprequest: 'Fetch / XHR', + stylesheet: 'CSS', script: 'JavaScript', image: 'Obraz', font: 'Font', + media: 'Media', websocket: 'WebSocket', ping: 'Ping', other: 'Inne' +}; + +function resources() { + return items.filter(entry => entry.type !== 'main_frame'); +} + +function currentDocument() { + const documents = items.filter(entry => entry.type === 'main_frame'); + return documents.find(entry => entry.phase !== 'redirected') || documents[0] || null; +} + +function selected() { + if (scope === 'document') return currentDocument(); + const requests = resources(); + return requests.find(entry => entry.id === selectedResourceId) || requests[0] || null; +} + +function formatHeaderLines(headers) { + return (headers || []).map(header => `${header.name}: ${header.value}`).join('\r\n'); +} + +function notify(message) { + clearTimeout(toastTimeout); + $('toast').textContent = message; + toastTimeout = setTimeout(() => { $('toast').textContent = ''; }, 1700); +} + +async function copyText(text) { + try { + await navigator.clipboard.writeText(text); + notify('Skopiowano'); + } catch { + notify('Nie udało się skopiować'); + } +} + +function hostAndPath(url) { + try { + const parsed = new URL(url); + const path = `${parsed.pathname}${parsed.search}`; + return `${parsed.hostname}${path.length > 72 ? path.slice(0, 72) + '…' : path}`; + } catch { + return url || ''; + } +} + +function loadData(state) { + // Gdy zmieniają się wyłącznie obrazki / XHR, nie odświeżaj tabeli dokumentu. + // Zbędne przebudowy DOM były przyczyną skoków podczas przewijania. + const oldSelected = selected(); + const oldSelectedJSON = JSON.stringify(oldSelected || null); + const hadEntries = items.length > 0; + items = (state?.entries || []).slice().sort((a, b) => b.timeStamp - a.timeStamp || Number(b.id) - Number(a.id)); + const requests = resources(); + if (!requests.some(entry => entry.id === selectedResourceId)) { + selectedResourceId = (requests.find(entry => entry.responseHeaders?.length) || requests[0])?.id || null; + } + if (hasRendered && scope === 'document' && hadEntries === (items.length > 0) && + oldSelectedJSON === JSON.stringify(selected() || null)) return; + hasRendered = true; + render(); +} + +function setTab(nextTab, focus = false) { + if (nextTab !== 'request' && nextTab !== 'response') return; + activeTab = nextTab; + for (const value of ['response', 'request']) { + const button = $(value === 'response' ? 'tabResponse' : 'tabRequest'); + const isActive = value === activeTab; + button.classList.toggle('is-active', isActive); + button.setAttribute('aria-selected', String(isActive)); + button.tabIndex = isActive ? 0 : -1; + } + $('headersPanel').setAttribute('aria-labelledby', activeTab === 'response' ? 'tabResponse' : 'tabRequest'); + if (focus) $(activeTab === 'response' ? 'tabResponse' : 'tabRequest').focus(); + $('headersPanel').scrollTop = 0; + renderHeaders(); +} + +function renderHeaders() { + const item = selected(); + const container = $('headersTable'); + const panel = $('headersPanel'); + const headers = item ? (activeTab === 'response' ? (item.responseHeaders || []) : (item.requestHeaders || [])) : []; + const needle = $('headerSearch').value.trim().toLocaleLowerCase(); + const renderKey = JSON.stringify([scope, item?.id || null, activeTab, needle, headers]); + if (renderKey === lastHeaderRenderKey) return; + lastHeaderRenderKey = renderKey; + const previousScrollTop = panel.scrollTop; + container.replaceChildren(); + const visible = headers.filter(header => !needle || `${header.name} ${header.value}`.toLocaleLowerCase().includes(needle)); + const fragment = document.createDocumentFragment(); + const buttons = []; + + for (const header of visible) { + const row = document.createElement('div'); + row.className = 'header-row'; + row.setAttribute('role', 'row'); + + const name = document.createElement('div'); + name.className = 'header-name'; + name.setAttribute('role', 'cell'); + const nameButton = document.createElement('button'); + nameButton.type = 'button'; + nameButton.className = 'name-button'; + nameButton.textContent = header.name; + nameButton.title = header.name; + name.append(nameButton); + + const valueCell = document.createElement('div'); + valueCell.className = 'header-value'; + valueCell.setAttribute('role', 'cell'); + const value = document.createElement('button'); + value.type = 'button'; + value.className = 'value-button'; + value.textContent = header.value ?? ''; + value.title = String(header.value ?? ''); + value.setAttribute('aria-label', `${header.name}: ${header.value ?? ''}`); + valueCell.append(value); + row.append(name, valueCell); + fragment.append(row); + buttons.push({ row, nameButton, value }); + } + + if (!visible.length) { + const empty = document.createElement('div'); + empty.className = 'no-matches'; + empty.textContent = !item + ? (scope === 'document' ? 'Brak żądania dokumentu. Odśwież stronę.' : 'Brak innych żądań.') + : headers.length ? 'Brak pasujących nagłówków' : 'Brak nagłówków'; + fragment.append(empty); + } + container.append(fragment); + + // Dopiero po dołączeniu całej tabeli mierzymy przepełnienie. + // Zwinięcie dotyczy wyłącznie wyglądu; pełne wartości są w DOM i schowku. + for (const { row, nameButton, value } of buttons) { + const longName = nameButton.scrollWidth > nameButton.clientWidth; + const longValue = value.scrollWidth > value.clientWidth || /[\r\n]/.test(value.textContent); + const toggle = () => { + const expanded = row.classList.toggle('expanded'); + if (longName) nameButton.setAttribute('aria-expanded', String(expanded)); + if (longValue) value.setAttribute('aria-expanded', String(expanded)); + }; + for (const [button, isLong, description] of [[nameButton, longName, 'nazwę'], [value, longValue, 'wartość']]) { + if (isLong) { + button.classList.add('is-truncated'); + button.setAttribute('aria-expanded', 'false'); + button.title = `Kliknij, aby rozwinąć ${description}: ${button.textContent}`; + button.addEventListener('click', toggle); + } else { + button.tabIndex = -1; + } + } + } + // Zachowaj pozycję podczas aktualizacji odpowiedzi, np. po otrzymaniu statusu. + panel.scrollTop = previousScrollTop; +} + +function render() { + const hasAny = items.length > 0; + $('emptyState').hidden = hasAny; + $('details').hidden = !hasAny; + if (!hasAny) return; + + $('scopeSelect').value = scope; + $('details').classList.toggle('resources-mode', scope === 'resources'); + $('requestSelectWrap').hidden = scope !== 'resources'; + const resourceRequests = resources(); + const select = $('requestSelect'); + if (scope === 'resources') { + const currentIds = Array.from(select.options, option => option.value).join('|'); + const nextIds = resourceRequests.map(entry => entry.id).join('|'); + if (currentIds !== nextIds) { + select.replaceChildren(); + for (const entry of resourceRequests) { + const option = document.createElement('option'); + option.value = entry.id; + select.append(option); + } + } + for (let i = 0; i < resourceRequests.length; i++) { + const entry = resourceRequests[i]; + const description = `${entry.statusCode || '…'} ${entry.method || 'GET'} · ${TYPES[entry.type] || entry.type} · ${hostAndPath(entry.url)}`; + if (select.options[i].textContent !== description) select.options[i].textContent = description; + } + select.value = selectedResourceId || ''; + select.disabled = !resourceRequests.length; + } + + const item = selected(); + const code = item?.statusCode; + $('statusText').textContent = item ? (code ? `${code} ${STATUS[code] || ''}` : (item.error || 'Oczekiwanie na odpowiedź')) : 'Brak danych'; + $('resourceType').textContent = item ? (TYPES[item.type] || item.type || '') : ''; + $('requestUrl').textContent = item ? `${item.method || 'GET'} ${item.url}` : 'Odśwież stronę, aby przechwycić dokument.'; + $('requestUrl').title = item?.url || ''; + $('headerCount').textContent = item ? `${(item.requestHeaders || []).length + (item.responseHeaders || []).length} nagłówków` : ''; + $('requestCount').textContent = item ? (item.requestHeaders || []).length : '0'; + $('responseCount').textContent = item ? (item.responseHeaders || []).length : '0'; + $('copyCurrent').disabled = !item; + renderHeaders(); +} + +async function reloadTab() { + if (tabId < 0) return; + try { + await chrome.tabs.reload(tabId); + notify('Odświeżanie…'); + } catch { + notify('Nie można odświeżyć karty'); + } +} + +async function clearTab() { + if (tabId < 0) return; + try { + const result = await chrome.runtime.sendMessage({ action: 'clearTab', tabId }); + if (!result?.ok) throw new Error('clear failed'); + loadData({ entries: [] }); + notify('Wyczyszczono'); + } catch { + notify('Nie udało się wyczyścić'); + } +} + +function bindButtons() { + $('scopeSelect').addEventListener('change', event => { + scope = event.target.value === 'resources' ? 'resources' : 'document'; + $('headersPanel').scrollTop = 0; + render(); + }); + $('requestSelect').addEventListener('change', event => { + selectedResourceId = event.target.value; + $('headersPanel').scrollTop = 0; + render(); + }); + $('headerSearch').addEventListener('input', () => { + $('headersPanel').scrollTop = 0; + renderHeaders(); + }); + $('copyCurrent').addEventListener('click', () => { + const item = selected(); + if (!item) return; + copyText(formatHeaderLines(activeTab === 'response' ? item.responseHeaders : item.requestHeaders)); + }); + for (const value of ['response', 'request']) { + const button = $(value === 'response' ? 'tabResponse' : 'tabRequest'); + button.addEventListener('click', () => setTab(value)); + button.addEventListener('keydown', event => { + if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return; + event.preventDefault(); + const next = event.key === 'Home' ? 'response' : event.key === 'End' ? 'request' + : activeTab === 'response' ? 'request' : 'response'; + setTab(next, true); + }); + } + $('reloadPage').addEventListener('click', reloadTab); + $('emptyReload').addEventListener('click', reloadTab); + $('clearHistory').addEventListener('click', clearTab); +} + +async function init() { + bindButtons(); + try { + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + if (!tab || !Number.isInteger(tab.id)) { + $('emptyState').hidden = false; + $('details').hidden = true; + return; + } + tabId = tab.id; + const key = `headers_tab_${tabId}`; + chrome.storage.onChanged.addListener((changes, area) => { + if (area === 'session' && Object.prototype.hasOwnProperty.call(changes, key)) loadData(changes[key].newValue); + }); + const stored = await chrome.storage.session.get(key); + loadData(stored[key]); + } catch { + $('emptyState').hidden = false; + $('details').hidden = true; + notify('Brak dostępu do karty'); + } +} + +init(); diff --git a/tests/test-background.js b/tests/test-background.js new file mode 100644 index 0000000..55d28c4 --- /dev/null +++ b/tests/test-background.js @@ -0,0 +1,94 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const listeners = {}; +const store = new Map(); +function event(name) { + return { addListener(callback, filter, options) { listeners[name] = { callback, filter, options }; } }; +} +const webRequest = {}; +for (const name of ['onBeforeRequest', 'onSendHeaders', 'onHeadersReceived', 'onBeforeRedirect', 'onCompleted', 'onErrorOccurred']) { + webRequest[name] = event(name); +} +const chrome = { + webRequest, + storage: { session: { + async get(key) { return { [key]: store.get(key) }; }, + async set(value) { for (const [key, data] of Object.entries(value)) store.set(key, structuredClone(data)); }, + async remove(key) { store.delete(key); } + } }, + runtime: { onMessage: event('message') }, + tabs: { onRemoved: event('removed') } +}; +vm.runInNewContext(fs.readFileSync(path.join(__dirname, '..', 'background.js'), 'utf8'), { chrome, Promise, Map, Number, Date, String, Array, console }); +function fire(name, request) { listeners[name].callback(request); } +async function flush() { + // Każde zdarzenie wykonuje jeden odczyt i zapis do storage.session. + for (let i=0; i<8; i++) await new Promise(resolve => setImmediate(resolve)); +} +const start = { tabId: 17, requestId: 'abc', method: 'GET', url: 'https://example.test/', type: 'main_frame', frameId: 0, timeStamp: 1000 }; +(async function test() { + fire('onBeforeRequest', start); + fire('onSendHeaders', { ...start, requestHeaders: [ + { name:'Accept-Encoding', value:'gzip, deflate, br, zstd' }, + { name:'Cookie', value:'session=123' } + ] }); + fire('onHeadersReceived', { ...start, statusCode:200, statusLine:'HTTP/2 200', responseHeaders: [ + { name:'Cache-Control', value:'public, max-age=600' }, + { name:'Vary', value:'Cookie' }, + { name:'Vary', value:'accept-encoding' }, + { name:'Content-Encoding', value:'zstd' } + ] }); + fire('onCompleted', { ...start, statusCode:200 }); + await flush(); + let state = store.get('headers_tab_17'); + assert.equal(state.entries.length, 1); + assert.deepEqual(Array.from(state.entries[0].responseHeaders.filter(h => h.name === 'Vary'), h => h.value), ['Cookie', 'accept-encoding']); + assert.equal(state.entries[0].requestHeaders.find(h => h.name === 'Cookie').value, 'session=123'); + assert.equal(state.entries[0].phase, 'completed'); + + fire('onBeforeRequest', { ...start, requestId:'xhr', type:'xmlhttprequest', url:'https://example.test/api', timeStamp:1100 }); + fire('onHeadersReceived', { ...start, requestId:'xhr', type:'xmlhttprequest', url:'https://example.test/api', timeStamp:1101, statusCode:204, responseHeaders:[{name:'X-A',value:'one'},{name:'x-a',value:'two'}] }); + await flush(); + state = store.get('headers_tab_17'); + assert.equal(state.entries.length, 2); + assert.deepEqual(Array.from(state.entries[0].responseHeaders, h => h.value), ['one','two']); + + fire('onBeforeRequest', { ...start, requestId:'next', url:'https://example.test/redirect', timeStamp:2000 }); + fire('onHeadersReceived', { ...start, requestId:'next', url:'https://example.test/redirect', timeStamp:2001, statusCode:302, responseHeaders:[{name:'Location',value:'/next'}] }); + fire('onBeforeRedirect', { ...start, requestId:'next', url:'https://example.test/redirect', timeStamp:2002, statusCode:302, redirectUrl:'https://example.test/next' }); + fire('onBeforeRequest', { ...start, requestId:'next', url:'https://example.test/next', timeStamp:2003 }); + fire('onHeadersReceived', { ...start, requestId:'next', url:'https://example.test/next', timeStamp:2004, statusCode:200, responseHeaders:[{name:'Vary',value:'Cookie'},{name:'Vary',value:'Accept-Encoding'}] }); + await flush(); + state = store.get('headers_tab_17'); + assert.equal(state.entries.length, 2, 'redirect steps should be separate entries'); + assert.equal(state.entries[1].statusCode, 302); + assert.equal(state.entries[0].statusCode, 200); + + fire('onBeforeRequest', { ...start, requestId:'different', url:'https://example.test/new-page', timeStamp:3000 }); + await flush(); + state = store.get('headers_tab_17'); + assert.equal(state.entries.length, 1, 'new navigation resets history'); + + // Podstrony często pobierają ponad 75 zasobów: dokument strony + // musi pozostać dostępny w popupie w domyślnym trybie. + fire('onHeadersReceived', { ...start, requestId:'different', url:'https://example.test/new-page', timeStamp:3001, statusCode:200, responseHeaders:[{name:'Vary',value:'Cookie'},{name:'Vary',value:'accept-encoding'}] }); + for (let i = 0; i < 92; i++) { + const asset = { ...start, requestId:`resource-${i}`, type:'script', url:`https://example.test/app-${i}.js`, timeStamp:3100+i }; + fire('onBeforeRequest', asset); + fire('onHeadersReceived', { ...asset, statusCode:200, responseHeaders:[{name:'content-type',value:'application/javascript'}] }); + } + await flush(); + state = store.get('headers_tab_17'); + assert.equal(state.entries.length, 75, 'history should be capped'); + assert.equal(state.entries.filter(e => e.type === 'main_frame').length, 1, 'main document must survive resource flood'); + assert.deepEqual(Array.from(state.entries.find(e => e.type === 'main_frame').responseHeaders.filter(h => h.name === 'Vary'), h => h.value), ['Cookie', 'accept-encoding']); + + listeners.message.callback({ action:'clearTab', tabId:17 }, {}, () => {}); + await flush(); + assert.equal(store.get('headers_tab_17').entries.length, 0); + console.log('OK: duplicate headers, requests, XHR, redirects, navigation reset, main document retention, clearing.'); +})().catch(error => { console.error(error); process.exitCode=1; }); diff --git a/tests/test-popup-layout.js b/tests/test-popup-layout.js new file mode 100644 index 0000000..5874b61 --- /dev/null +++ b/tests/test-popup-layout.js @@ -0,0 +1,28 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const css = fs.readFileSync(path.join(__dirname, '..', 'popup.css'), 'utf8'); +const js = fs.readFileSync(path.join(__dirname, '..', 'popup.js'), 'utf8'); +const rule = selector => { + const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const matches = Array.from(css.matchAll(new RegExp('(?:^|\\n)\\s*' + escaped + '\\s*\\{([^}]*)\\}', 'g'))); + assert.equal(matches.length, 1, `${selector}: expected exactly one CSS rule`); + return matches[0][1]; +}; +const body = rule('html, body'); +const app = rule('.app'); +const details = rule('#details'); +const panel = rule('.headers-panel'); +assert.match(body, /height\s*:\s*520px/, 'document must have a fixed height'); +assert.match(body, /overflow\s*:\s*hidden/, 'page itself must not scroll'); +assert.match(app, /height\s*:\s*520px/, 'popup must have a fixed height'); +assert.match(details, /flex\s*:\s*1\s+1\s+auto/, 'main view must fill the available space'); +assert.match(panel, /overflow-y\s*:\s*auto/, 'only the table panel should scroll'); +assert.match(panel, /overscroll-behavior\s*:\s*contain/, 'wheel scrolling must not propagate outside panel'); +assert.match(panel, /scrollbar-gutter\s*:\s*stable/, 'scrollbar must not change table width'); +assert.doesNotMatch(js, /document\.scrollingElement\.scrollTop\s*=\s*0/, 'must not reset page scrolling'); +assert.match(js, /if \(renderKey === lastHeaderRenderKey\) return;/, 'unchanged header table should not be re-rendered'); +assert.match(js, /panel\.scrollTop = previousScrollTop;/, 'keep position on header updates'); +console.log('OK: fixed-size popup, only table scrolling; live updates preserve scroll.');