Translated ['src/pentesting-web/hacking-with-cookies/README.md'] to it

This commit is contained in:
Translator 2025-05-18 03:05:08 +00:00
parent 2446a6b9eb
commit 7990bc926f
2 changed files with 146 additions and 124 deletions

View File

@ -12,7 +12,7 @@ La data di scadenza di un cookie è determinata dall'attributo `Expires`. Al con
### Domain
Gli host che ricevono un cookie sono specificati dall'attributo `Domain`. Per impostazione predefinita, questo è impostato sull'host che ha emesso il cookie, escludendo i suoi sottodomini. Tuttavia, quando l'attributo `Domain` è esplicitamente impostato, comprende anche i sottodomini. Questo rende la specifica dell'attributo `Domain` un'opzione meno restrittiva, utile per scenari in cui è necessario condividere i cookie tra sottodomini. Ad esempio, impostando `Domain=mozilla.org`, i cookie diventano accessibili sui suoi sottodomini come `developer.mozilla.org`.
Gli host che ricevono un cookie sono specificati dall'attributo `Domain`. Per impostazione predefinita, questo è impostato sull'host che ha emesso il cookie, senza includere i suoi sottodomini. Tuttavia, quando l'attributo `Domain` è esplicitamente impostato, comprende anche i sottodomini. Questo rende la specifica dell'attributo `Domain` un'opzione meno restrittiva, utile per scenari in cui è necessario condividere cookie tra sottodomini. Ad esempio, impostare `Domain=mozilla.org` rende i cookie accessibili sui suoi sottodomini come `developer.mozilla.org`.
### Path
@ -58,10 +58,10 @@ Questo impedisce al **client** di accedere al cookie (ad esempio tramite **Javas
#### **Bypasses**
- Se la pagina **invia i cookie come risposta** a una richiesta (ad esempio in una pagina **PHPinfo**), è possibile abusare dell'XSS per inviare una richiesta a questa pagina e **rubare i cookie** dalla risposta (controlla un esempio in [https://hackcommander.github.io/posts/2022/11/12/bypass-httponly-via-php-info-page/](https://hackcommander.github.io/posts/2022/11/12/bypass-httponly-via-php-info-page/)).
- Se la pagina **invia i cookie come risposta** a una richiesta (ad esempio in una pagina **PHPinfo**), è possibile abusare dell'XSS per inviare una richiesta a questa pagina e **rubare i cookie** dalla risposta (controlla un esempio in [https://blog.hackcommander.com/posts/2022/11/12/bypass-httponly-via-php-info-page/](https://blog.hackcommander.com/posts/2022/11/12/bypass-httponly-via-php-info-page/)).
- Questo potrebbe essere bypassato con richieste **TRACE** **HTTP** poiché la risposta del server (se questo metodo HTTP è disponibile) rifletterà i cookie inviati. Questa tecnica è chiamata **Cross-Site Tracking**.
- Questa tecnica è evitata dai **browser moderni non permettendo l'invio di una richiesta TRACE** da JS. Tuttavia, sono stati trovati alcuni bypass in software specifici come l'invio di `\r\nTRACE` invece di `TRACE` a IE6.0 SP2.
- Un altro modo è lo sfruttamento di vulnerabilità zero-day dei browser.
- Questa tecnica è evitata dai **browser moderni non permettendo l'invio di una richiesta TRACE** da JS. Tuttavia, sono stati trovati alcuni bypass in software specifici come inviare `\r\nTRACE` invece di `TRACE` a IE6.0 SP2.
- Un altro modo è lo sfruttamento di vulnerabilità zero/day dei browser.
- È possibile **sovrascrivere i cookie HttpOnly** eseguendo un attacco di overflow del Cookie Jar:
{{#ref}}
@ -141,7 +141,7 @@ Questo attacco costringe un utente autenticato a eseguire azioni indesiderate su
### Empty Cookies
(Controlla ulteriori dettagli nella [ricerca originale](https://blog.ankursundara.com/cookie-bugs/)) I browser consentono la creazione di cookie senza un nome, il che può essere dimostrato tramite JavaScript come segue:
(Controlla ulteriori dettagli nella [ricerca originale](https://blog.ankursundara.com/cookie-bugs/)) I browser consentono la creazione di cookie senza nome, il che può essere dimostrato tramite JavaScript come segue:
```js
document.cookie = "a=v1"
document.cookie = "=test value;" // Setting an empty named cookie
@ -179,7 +179,7 @@ RENDER_TEXT="hello world; JSESSIONID=13371337; ASDF=end";
- Zope cerca una virgola per iniziare a analizzare il cookie successivo.
- Le classi di cookie di Python iniziano a analizzare su un carattere di spazio.
Questa vulnerabilità è particolarmente pericolosa nelle applicazioni web che si basano sulla protezione CSRF basata su cookie, poiché consente agli attaccanti di iniettare cookie CSRF-token falsificati, potenzialmente eludendo le misure di sicurezza. Il problema è aggravato dalla gestione dei nomi di cookie duplicati da parte di Python, dove l'ultima occorrenza sovrascrive quelle precedenti. Solleva anche preoccupazioni per i cookie `__Secure-` e `__Host-` in contesti insicuri e potrebbe portare a bypass di autorizzazione quando i cookie vengono passati a server di backend suscettibili alla falsificazione.
Questa vulnerabilità è particolarmente pericolosa nelle applicazioni web che si basano sulla protezione CSRF basata su cookie, poiché consente agli attaccanti di iniettare cookie CSRF-token falsificati, potenzialmente eludendo le misure di sicurezza. Il problema è aggravato dalla gestione dei nomi di cookie duplicati da parte di Python, dove l'ultima occorrenza sovrascrive quelle precedenti. Solleva anche preoccupazioni per i cookie `__Secure-` e `__Host-` in contesti insicuri e potrebbe portare a bypass di autorizzazione quando i cookie vengono passati a server back-end suscettibili alla falsificazione.
### Cookies $version
@ -191,7 +191,7 @@ Secondo [**questo blogpost**](https://portswigger.net/research/bypassing-wafs-wi
Secondo [**questo blogpost**](https://portswigger.net/research/stealing-httponly-cookies-with-the-cookie-sandwich-technique), è possibile utilizzare la tecnica del cookie sandwich per rubare cookie HttpOnly. Questi sono i requisiti e i passaggi:
- Trovare un luogo dove un apparente **cookie inutile è riflesso nella risposta**
- Trovare un luogo dove un apparente **cookie è riflesso nella risposta**
- **Creare un cookie chiamato `$Version`** con valore `1` (puoi farlo in un attacco XSS da JS) con un percorso più specifico in modo che ottenga la posizione iniziale (alcuni framework come Python non necessitano di questo passaggio)
- **Creare il cookie che viene riflesso** con un valore che lascia un **aperto doppio apice** e con un percorso specifico in modo che sia posizionato nel database dei cookie dopo il precedente (`$Version`)
- Poi, il cookie legittimo andrà successivamente nell'ordine
@ -204,26 +204,26 @@ document.cookie = `param1="start`;
// any cookies inside the sandwich will be placed into param1 value server-side
document.cookie = `param2=end";`;
```
### WAF bypasses
### Bypass dei WAF
#### Cookies $version
Controlla la sezione precedente.
#### Bypassing value analysis with quoted-string encoding
#### Analisi del valore di bypass con codifica di stringa quotata
Questo parsing indica di disattivare l'escape dei valori all'interno dei cookie, quindi "\a" diventa "a". Questo può essere utile per bypassare i WAF come:
Questo parsing indica di disattivare i valori scappati all'interno dei cookie, quindi "\a" diventa "a". Questo può essere utile per bypassare i WAF come:
- `eval('test') => forbidden`
- `"\e\v\a\l\(\'\t\e\s\t\'\)" => allowed`
- `eval('test') => vietato`
- `"\e\v\a\l\(\'\t\e\s\t\'\)" => consentito`
#### Bypassing cookie-name blocklists
#### Bypass delle blacklist dei nomi dei cookie
Nell'RFC2109 è indicato che una **virgola può essere usata come separatore tra i valori dei cookie**. Ed è anche possibile aggiungere **spazi e tabulazioni prima e dopo il segno di uguale**. Pertanto, un cookie come `$Version=1; foo=bar, abc = qux` non genera il cookie `"foo":"bar, admin = qux"` ma i cookie `foo":"bar"` e `"admin":"qux"`. Nota come vengono generati 2 cookie e come "admin" ha rimosso lo spazio prima e dopo il segno di uguale.
#### Bypassing value analysis with cookie splitting
#### Bypass dell'analisi del valore con la suddivisione dei cookie
Infine, diverse backdoor si unirebbero in una stringa diversi cookie passati in intestazioni di cookie differenti come in:
Infine, diverse backdoor si unirebbero in una stringa diversi cookie passati in intestazioni di cookie diverse come in:
```
GET / HTTP/1.1
Host: example.com
@ -269,9 +269,9 @@ padBuster http://web.com/home.jsp?UID=7B216A634951170FF851D6CC68FC9537858795A28E
```
Padbuster farà diversi tentativi e ti chiederà quale condizione è la condizione di errore (quella che non è valida).
Poi inizierà a decrittografare il cookie (potrebbe richiedere diversi minuti)
Poi inizierà a decrittografare il cookie (potrebbe richiedere diversi minuti).
Se l'attacco è stato eseguito con successo, allora potresti provare a crittografare una stringa a tua scelta. Ad esempio, se desideri **encrypt** **user=administrator**
Se l'attacco è stato eseguito con successo, allora potresti provare a crittografare una stringa a tua scelta. Ad esempio, se desideri **encrypt** **user=administrator**.
```
padbuster http://web.com/index.php 1dMjA5hfXh0jenxJQ0iW6QXKkzAGIWsiDAKV3UwJPT2lBP+zAD0D0w== 8 -cookies thecookie=1dMjA5hfXh0jenxJQ0iW6QXKkzAGIWsiDAKV3UwJPT2lBP+zAD0D0w== -plaintext user=administrator
```

View File

@ -1,27 +1,28 @@
/**
* HackTricks AI Chat Widget v1.15 Markdown rendering + sanitised
* ------------------------------------------------------------------------
* Replaces the static placeholder with a three-dot **bouncing** loader
* Renders assistant replies as Markdown while purging any unsafe HTML
* (XSS-safe via DOMPurify)
* ------------------------------------------------------------------------
* HackTricks AI Chat Widget v1.16 resizable sidebar
* ---------------------------------------------------
* Markdown rendering + sanitised (same as before)
* NEW: dragtoresize panel, width persists via localStorage
*/
(function () {
const LOG = "[HackTricks-AI]";
/* ---------------- User-tunable constants ---------------- */
const MAX_CONTEXT = 3000; // highlighted-text char limit
const MAX_QUESTION = 500; // question char limit
const LOG = "[HackTricksAI]";
/* ---------------- Usertunable constants ---------------- */
const MAX_CONTEXT = 3000; // highlightedtext char limit
const MAX_QUESTION = 500; // question char limit
const MIN_W = 250; // ← resize limits →
const MAX_W = 600;
const DEF_W = 350; // default width (if nothing saved)
const TOOLTIP_TEXT =
"💡 Highlight any text on the page,\nthen click to ask HackTricks AI about it";
"💡 Highlight any text on the page,\nthen click to ask HackTricks AI about it";
const API_BASE = "https://www.hacktricks.ai/api/assistants/threads";
const BRAND_RED = "#b31328"; // HackTricks brand
const BRAND_RED = "#b31328";
/* ------------------------------ State ------------------------------ */
let threadId = null;
let isRunning = false;
/* ---------- helpers ---------- */
const $ = (sel, ctx = document) => ctx.querySelector(sel);
if (document.getElementById("ht-ai-btn")) {
console.warn(`${LOG} Widget already injected.`);
@ -31,44 +32,37 @@
? document.addEventListener("DOMContentLoaded", init)
: init());
/* ==================================================================== */
/* 🔗 1. 3rd-party libs → Markdown & sanitiser */
/* ==================================================================== */
/* =================================================================== */
/* 🔗 1. 3rdparty libs → Markdown & sanitiser */
/* =================================================================== */
function loadScript(src) {
return new Promise((resolve, reject) => {
return new Promise((res, rej) => {
const s = document.createElement("script");
s.src = src;
s.onload = resolve;
s.onerror = () => reject(new Error(`Failed to load ${src}`));
s.onload = res;
s.onerror = () => rej(new Error(`Failed to load ${src}`));
document.head.appendChild(s);
});
}
async function ensureDeps() {
const deps = [];
if (typeof marked === "undefined") {
if (typeof marked === "undefined")
deps.push(loadScript("https://cdn.jsdelivr.net/npm/marked/marked.min.js"));
}
if (typeof DOMPurify === "undefined") {
if (typeof DOMPurify === "undefined")
deps.push(
loadScript(
"https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.2.5/purify.min.js"
)
);
}
if (deps.length) await Promise.all(deps);
}
const mdToSafeHTML = (md) =>
DOMPurify.sanitize(marked.parse(md, { mangle: false, headerIds: false }), {
USE_PROFILES: { html: true }
});
function mdToSafeHTML(md) {
// 1⃣ Markdown → raw HTML
const raw = marked.parse(md, { mangle: false, headerIds: false });
// 2⃣ Purify
return DOMPurify.sanitize(raw, { USE_PROFILES: { html: true } });
}
/* ==================================================================== */
/* =================================================================== */
async function init() {
/* ----- make sure marked & DOMPurify are ready before anything else */
try {
await ensureDeps();
} catch (e) {
@ -76,14 +70,14 @@
return;
}
console.log(`${LOG} Injecting widget… v1.15`);
console.log(`${LOG} Injecting widget… v1.16`);
await ensureThreadId();
injectStyles();
const btn = createFloatingButton();
createTooltip(btn);
const panel = createSidebar();
const panel = createSidebar(); // ← panel with resizer
const chatLog = $("#ht-ai-chat");
const sendBtn = $("#ht-ai-send");
const inputBox = $("#ht-ai-question");
@ -100,15 +94,8 @@
function addMsg(text, cls) {
const b = document.createElement("div");
b.className = `ht-msg ${cls}`;
// ✨ assistant replies rendered as Markdown + sanitised
if (cls === "ht-ai") {
b.innerHTML = mdToSafeHTML(text);
} else {
// user / context bubbles stay plain-text
b.textContent = text;
}
b[cls === "ht-ai" ? "innerHTML" : "textContent"] =
cls === "ht-ai" ? mdToSafeHTML(text) : text;
chatLog.appendChild(b);
chatLog.scrollTop = chatLog.scrollHeight;
return b;
@ -116,30 +103,28 @@
const LOADER_HTML =
'<span class="ht-loading"><span></span><span></span><span></span></span>';
function setInputDisabled(d) {
const setInputDisabled = (d) => {
inputBox.disabled = d;
sendBtn.disabled = d;
}
function clearThreadCookie() {
};
const clearThreadCookie = () => {
document.cookie = "threadId=; Path=/; Max-Age=0";
threadId = null;
}
function resetConversation() {
threadId = null;
};
const resetConversation = () => {
chatLog.innerHTML = "";
clearThreadCookie();
panel.classList.remove("open");
}
};
/* ------------------- Panel open / close ------------------- */
btn.addEventListener("click", () => {
if (!savedSelection) {
alert("Please highlight some text first to then ask HackTricks AI about it.");
alert("Please highlight some text first.");
return;
}
if (savedSelection.length > MAX_CONTEXT) {
alert(
`Highlighted text is too long (${savedSelection.length} chars). Max allowed: ${MAX_CONTEXT}.`
);
alert(`Highlighted text is too long. Max ${MAX_CONTEXT} chars.`);
return;
}
chatLog.innerHTML = "";
@ -157,11 +142,10 @@
addMsg("Please wait until the current operation completes.", "ht-ai");
return;
}
isRunning = true;
setInputDisabled(true);
const loadingBubble = addMsg("", "ht-ai");
loadingBubble.innerHTML = LOADER_HTML;
const loading = addMsg("", "ht-ai");
loading.innerHTML = LOADER_HTML;
const content = context
? `### Context:\n${context}\n\n### Question to answer:\n${question}`
@ -178,43 +162,39 @@
try {
const e = await res.json();
if (e.error) err = `Error: ${e.error}`;
else if (res.status === 429)
err = "Rate limit exceeded. Please try again later.";
else if (res.status === 429) err = "Rate limit exceeded.";
} catch (_) {}
loadingBubble.textContent = err;
loading.textContent = err;
return;
}
const data = await res.json();
loadingBubble.remove();
loading.remove();
if (Array.isArray(data.response))
data.response.forEach((p) => {
data.response.forEach((p) =>
addMsg(
p.type === "text" && p.text && p.text.value
? p.text.value
: JSON.stringify(p),
"ht-ai"
);
});
)
);
else if (typeof data.response === "string")
addMsg(data.response, "ht-ai");
else addMsg(JSON.stringify(data, null, 2), "ht-ai");
} catch (e) {
console.error("Error sending message:", e);
loadingBubble.textContent = "An unexpected error occurred.";
loading.textContent = "An unexpected error occurred.";
} finally {
isRunning = false;
setInputDisabled(false);
chatLog.scrollTop = chatLog.scrollHeight;
}
}
async function handleSend() {
const q = inputBox.value.trim();
if (!q) return;
if (q.length > MAX_QUESTION) {
alert(
`Your question is too long (${q.length} chars). Max allowed: ${MAX_QUESTION}.`
);
alert(`Question too long (${q.length}). Max ${MAX_QUESTION}.`);
return;
}
inputBox.value = "";
@ -228,9 +208,9 @@
handleSend();
}
});
}
} /* end init */
/* ==================================================================== */
/* =================================================================== */
async function ensureThreadId() {
const m = document.cookie.match(/threadId=([^;]+)/);
if (m && m[1]) {
@ -241,62 +221,67 @@
const r = await fetch(API_BASE, { method: "POST", credentials: "include" });
const d = await r.json();
if (!r.ok || !d.threadId) throw new Error(`${r.status} ${r.statusText}`);
threadId = d.threadId;
threadId = d.threadId;
document.cookie =
`threadId=${threadId}; Path=/; Secure; SameSite=Strict; Max-Age=7200`;
} catch (e) {
console.error("Error creating threadId:", e);
alert("Failed to initialise the conversation. Please refresh and try again.");
alert("Failed to initialise the conversation. Please refresh.");
throw e;
}
}
/* ==================================================================== */
/* =================================================================== */
function injectStyles() {
const css = `
#ht-ai-btn{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);width:60px;height:60px;border-radius:50%;background:#1e1e1e;color:#fff;font-size:28px;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:99999;box-shadow:0 2px 8px rgba(0,0,0,.4);transition:opacity .2s}
#ht-ai-btn:hover{opacity:.85}
@media(max-width:768px){#ht-ai-btn{display:none}}
#ht-ai-tooltip{position:fixed;padding:6px 8px;background:#111;color:#fff;border-radius:4px;font-size:13px;white-space:pre-wrap;pointer-events:none;opacity:0;transform:translate(-50%,-8px);transition:opacity .15s ease,transform .15s ease;z-index:100000}
#ht-ai-tooltip.show{opacity:1;transform:translate(-50%,-12px)}
#ht-ai-panel{position:fixed;top:0;right:0;height:100%;width:350px;max-width:90vw;background:#000;color:#fff;display:flex;flex-direction:column;transform:translateX(100%);transition:transform .3s ease;z-index:100000;font-family:system-ui,-apple-system,Segoe UI,Roboto,"Helvetica Neue",Arial,sans-serif}
#ht-ai-panel.open{transform:translateX(0)}
@media(max-width:768px){#ht-ai-panel{display:none}}
#ht-ai-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid #333}
#ht-ai-header .ht-actions{display:flex;gap:8px;align-items:center}
#ht-ai-close,#ht-ai-reset{cursor:pointer;font-size:18px;background:none;border:none;color:#fff;padding:0}
#ht-ai-close:hover,#ht-ai-reset:hover{opacity:.7}
#ht-ai-chat{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;font-size:14px}
.ht-msg{max-width:90%;line-height:1.4;padding:10px 12px;border-radius:8px;white-space:pre-wrap;word-wrap:break-word}
.ht-user{align-self:flex-end;background:${BRAND_RED}}
.ht-ai{align-self:flex-start;background:#222}
.ht-context{align-self:flex-start;background:#444;font-style:italic;font-size:13px}
#ht-ai-input{display:flex;gap:8px;padding:12px 16px;border-top:1px solid #333}
#ht-ai-question{flex:1;min-height:40px;max-height:120px;resize:vertical;padding:8px;border-radius:6px;border:none;font-size:14px}
#ht-ai-send{padding:0 18px;border:none;border-radius:6px;background:${BRAND_RED};color:#fff;font-size:14px;cursor:pointer}
#ht-ai-send:disabled{opacity:.5;cursor:not-allowed}
/* Loader animation */
.ht-loading{display:inline-flex;align-items:center;gap:4px}
.ht-loading span{width:6px;height:6px;border-radius:50%;background:#888;animation:ht-bounce 1.2s infinite ease-in-out}
.ht-loading span:nth-child(2){animation-delay:0.2s}
.ht-loading span:nth-child(3){animation-delay:0.4s}
@keyframes ht-bounce{0%,80%,100%{transform:scale(0);}40%{transform:scale(1);} }
::selection{background:#ffeb3b;color:#000}
::-moz-selection{background:#ffeb3b;color:#000}`;
#ht-ai-btn{position:fixed;bottom:20px;left:50%;transform:translateX(-50%);min-width:60px;height:60px;border-radius:30px;background:linear-gradient(45deg, #b31328, #d42d3f, #2d5db4, #3470e4);background-size:300% 300%;animation:gradientShift 8s ease infinite;color:#fff;font-size:18px;display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:99999;box-shadow:0 2px 8px rgba(0,0,0,.4);transition:opacity .2s;padding:0 20px}
#ht-ai-btn span{margin-left:8px;font-weight:bold}
@keyframes gradientShift{0%{background-position:0% 50%}50%{background-position:100% 50%}100%{background-position:0% 50%}}
#ht-ai-btn:hover{opacity:.85}
@media(max-width:768px){#ht-ai-btn{display:none}}
#ht-ai-tooltip{position:fixed;padding:6px 8px;background:#111;color:#fff;border-radius:4px;font-size:13px;white-space:pre-wrap;pointer-events:none;opacity:0;transform:translate(-50%,-8px);transition:opacity .15s ease,transform .15s ease;z-index:100000}
#ht-ai-tooltip.show{opacity:1;transform:translate(-50%,-12px)}
#ht-ai-panel{position:fixed;top:0;right:0;height:100%;max-width:90vw;background:#000;color:#fff;display:flex;flex-direction:column;transform:translateX(100%);transition:transform .3s ease;z-index:100000;font-family:system-ui,-apple-system,Segoe UI,Roboto,"Helvetica Neue",Arial,sans-serif}
#ht-ai-panel.open{transform:translateX(0)}
@media(max-width:768px){#ht-ai-panel{display:none}}
#ht-ai-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid #333}
#ht-ai-header .ht-actions{display:flex;gap:8px;align-items:center}
#ht-ai-close,#ht-ai-reset{cursor:pointer;font-size:18px;background:none;border:none;color:#fff;padding:0}
#ht-ai-close:hover,#ht-ai-reset:hover{opacity:.7}
#ht-ai-chat{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;font-size:14px}
.ht-msg{max-width:90%;line-height:1.4;padding:10px 12px;border-radius:8px;white-space:pre-wrap;word-wrap:break-word}
.ht-user{align-self:flex-end;background:${BRAND_RED}}
.ht-ai{align-self:flex-start;background:#222}
.ht-context{align-self:flex-start;background:#444;font-style:italic;font-size:13px}
#ht-ai-input{display:flex;gap:8px;padding:12px 16px;border-top:1px solid #333}
#ht-ai-question{flex:1;min-height:40px;max-height:120px;resize:vertical;padding:8px;border-radius:6px;border:none;font-size:14px}
#ht-ai-send{padding:0 18px;border:none;border-radius:6px;background:${BRAND_RED};color:#fff;font-size:14px;cursor:pointer}
#ht-ai-send:disabled{opacity:.5;cursor:not-allowed}
/* Loader */
.ht-loading{display:inline-flex;align-items:center;gap:4px}
.ht-loading span{width:6px;height:6px;border-radius:50%;background:#888;animation:ht-bounce 1.2s infinite ease-in-out}
.ht-loading span:nth-child(2){animation-delay:0.2s}
.ht-loading span:nth-child(3){animation-delay:0.4s}
@keyframes ht-bounce{0%,80%,100%{transform:scale(0);}40%{transform:scale(1);} }
::selection{background:#ffeb3b;color:#000}
::-moz-selection{background:#ffeb3b;color:#000}
/* NEW: resizer handle */
#ht-ai-resizer{position:absolute;left:0;top:0;width:6px;height:100%;cursor:ew-resize;background:transparent}
#ht-ai-resizer:hover{background:rgba(255,255,255,.05)}`;
const s = document.createElement("style");
s.id = "ht-ai-style";
s.textContent = css;
document.head.appendChild(s);
}
/* =================================================================== */
function createFloatingButton() {
const d = document.createElement("div");
d.id = "ht-ai-btn";
d.textContent = "🤖";
d.innerHTML = "🤖<span>HackTricksAI</span>";
document.body.appendChild(d);
return d;
}
function createTooltip(btn) {
const t = document.createElement("div");
t.id = "ht-ai-tooltip";
@ -311,11 +296,16 @@
btn.addEventListener("mouseleave", () => t.classList.remove("show"));
}
/* =================================================================== */
function createSidebar() {
const saved = parseInt(localStorage.getItem("htAiWidth") || DEF_W, 10);
const width = Math.min(Math.max(saved, MIN_W), MAX_W);
const p = document.createElement("div");
p.id = "ht-ai-panel";
p.style.width = width + "px"; // ← applied width
p.innerHTML = `
<div id="ht-ai-header"><strong>HackTricks AI Chat</strong>
<div id="ht-ai-header"><strong>HackTricks AI Chat</strong>
<div class="ht-actions">
<button id="ht-ai-reset" title="Reset"></button>
<span id="ht-ai-close" title="Close"></span>
@ -326,7 +316,39 @@
<textarea id="ht-ai-question" placeholder="Type your question…"></textarea>
<button id="ht-ai-send">Send</button>
</div>`;
/* NEW: resizer strip */
const resizer = document.createElement("div");
resizer.id = "ht-ai-resizer";
p.appendChild(resizer);
document.body.appendChild(p);
addResizeLogic(resizer, p);
return p;
}
/* ---------------- resize behaviour ---------------- */
function addResizeLogic(handle, panel) {
let startX, startW, dragging = false;
const onMove = (e) => {
if (!dragging) return;
const dx = startX - e.clientX; // dragging leftwards ⇒ +dx
let newW = startW + dx;
newW = Math.min(Math.max(newW, MIN_W), MAX_W);
panel.style.width = newW + "px";
};
const onUp = () => {
if (!dragging) return;
dragging = false;
localStorage.setItem("htAiWidth", parseInt(panel.style.width, 10));
document.removeEventListener("mousemove", onMove);
document.removeEventListener("mouseup", onUp);
};
handle.addEventListener("mousedown", (e) => {
dragging = true;
startX = e.clientX;
startW = parseInt(window.getComputedStyle(panel).width, 10);
document.addEventListener("mousemove", onMove);
document.addEventListener("mouseup", onUp);
});
}
})();