repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
app.tsTypeScript516 lines21.2 KiBraw download
// Progressive enhancement, re-run after every (view-transition) navigation.

import { initPalette, paintChrome } from './palette.ts';

function applyTheme(next: 'light' | 'dark'): void {
  document.documentElement.setAttribute('data-theme', next);
  try { localStorage.setItem('theme', next); } catch {}
  document.documentElement.style.colorScheme = next;
  paintChrome();
  // A canvas bitmap does not inherit the cascade, so the contour field has
  // no way to notice the mode changed. It listens for this.
  dispatchEvent(new Event('daemonmodechange'));
}

function initTheme(): void {
  const toggles = document.querySelectorAll<HTMLButtonElement>('[data-theme-toggle]');
  toggles.forEach((btn) => {
    if (btn.dataset.bound) return;
    btn.dataset.bound = '1';
    btn.addEventListener('click', () => {
      const cur = document.documentElement.getAttribute('data-theme') === 'light' ? 'light' : 'dark';
      const next: 'light' | 'dark' = cur === 'light' ? 'dark' : 'light';
      const root = document.documentElement;

      // Feature/consent gate: no View Transitions or reduced-motion -> flip instantly.
      const startVT = (document as unknown as {
        startViewTransition?: (cb: () => void) => { finished: Promise<void> };
      }).startViewTransition;
      const reduce = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
      if (!startVT || reduce) { applyTheme(next); return; }

      // Origin + radius for the circular reveal: expand from the toggle's centre
      // out to the farthest viewport corner so the circle always covers the screen.
      const r = btn.getBoundingClientRect();
      const x = r.left + r.width / 2;
      const y = r.top + r.height / 2;
      const endR = Math.hypot(Math.max(x, innerWidth - x), Math.max(y, innerHeight - y));
      root.style.setProperty('--vt-x', `${x}px`);
      root.style.setProperty('--vt-y', `${y}px`);
      root.style.setProperty('--vt-r', `${endR}px`);

      root.classList.add('theme-vt');
      const t = startVT.call(document, () => applyTheme(next));
      t.finished.finally(() => root.classList.remove('theme-vt'));
    });
  });
}

function initMobileNav(): void {
  const toggles = document.querySelectorAll<HTMLButtonElement>('[data-mobile-nav-toggle]');
  toggles.forEach((toggle) => {
    if (toggle.dataset.bound) return;
    const menuId = toggle.getAttribute('aria-controls');
    const menu = menuId ? document.getElementById(menuId) : null;
    if (!menu) return;

    const setOpen = (open: boolean): void => {
      toggle.setAttribute('aria-expanded', String(open));
      toggle.setAttribute('aria-label', open ? 'Close navigation' : 'Open navigation');
      menu.hidden = !open;
    };

    toggle.dataset.bound = '1';
    toggle.addEventListener('click', () => {
      setOpen(toggle.getAttribute('aria-expanded') !== 'true');
    });

    menu.addEventListener('click', (event) => {
      if ((event.target as Element).closest('a')) setOpen(false);
    });

    toggle.closest('.site-header')?.addEventListener('keydown', (event) => {
      if (event.key !== 'Escape' || toggle.getAttribute('aria-expanded') !== 'true') return;
      setOpen(false);
      toggle.focus();
    });
  });
}

/* The retired site resolved labels left-to-right through this exact ASCII
   pool over nine 32ms steps. Keeping the source string in data-unscramble
   means the page is correct before JS, remains searchable, and exposes the
   final label to assistive technology while the visual text briefly settles. */
const UNSCRAMBLE_POOL = '/\\|<>=+*·#%';
const UNSCRAMBLE_STEPS = 9;

function scrambled(text: string, step: number): string {
  const settled = Math.ceil((text.length * step) / UNSCRAMBLE_STEPS);
  let value = text.slice(0, settled);
  for (let i = settled; i < text.length; i += 1) {
    const char = text[i];
    value += /\s/.test(char)
      ? char
      : UNSCRAMBLE_POOL[(i * 7 + step * 3) % UNSCRAMBLE_POOL.length];
  }
  return value;
}

/** Settle `node`'s text into `finalText` through the scramble pool. Shared by
 *  the headings (on scroll) and the copy control (on press). */
function resolveText(node: HTMLElement, finalText: string): void {
  let step = 0;
  node.textContent = scrambled(finalText, step);
  const timer = window.setInterval(() => {
    step += 1;
    if (step >= UNSCRAMBLE_STEPS) {
      clearInterval(timer);
      node.textContent = finalText;
      return;
    }
    node.textContent = scrambled(finalText, step);
  }, 32);
}

function initUnscramble(): void {
  document.querySelectorAll<HTMLElement>('.sheet-title, .subcat h2, .download-library__head h2, .prose > h2').forEach((node) => {
    // Animate only the label so report badges retain their markup and meaning.
    const label = node.querySelector<HTMLElement>('[data-title-text]') ?? node;
    if (!label.hasAttribute('data-unscramble')) label.dataset.unscramble = label.textContent ?? '';
  });

  const nodes = document.querySelectorAll<HTMLElement>('[data-unscramble]:not([data-unscramble-bound])');
  const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const observer = !reduced && 'IntersectionObserver' in window
    ? new window.IntersectionObserver((entries, current) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) return;
          const node = entry.target as HTMLElement;
          resolveText(node, node.dataset.unscramble ?? node.textContent ?? '');
          current.unobserve(node);
        });
      }, { rootMargin: '0px 0px -8% 0px', threshold: 0.25 })
    : null;

  nodes.forEach((node) => {
    node.dataset.unscrambleBound = '1';
    const finalText = node.dataset.unscramble ?? node.textContent ?? '';
    node.setAttribute('aria-label', finalText);
    if (reduced || !finalText) {
      node.textContent = finalText;
      return;
    }

    const rect = node.getBoundingClientRect();
    if (!observer || rect.top < window.innerHeight * 0.92) resolveText(node, finalText);
    else observer.observe(node);
  });
}

/**
 * Bring the archive into view in short, staggered runs as the reader moves
 * down a page. The hidden state is applied by script rather than baked into
 * the stylesheet, so every word remains visible if JavaScript is unavailable.
 */
function initScrollReveal(): void {
  const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const nodes = document.querySelectorAll<HTMLElement>([
    '.subcat:not([data-reveal-bound])',
    '.download-library__head:not([data-reveal-bound])',
    '.rec:not([data-reveal-bound])',
    '.download-row:not([data-reveal-bound])',
    '.prose > h2:not([data-reveal-bound])',
    '.prose > h3:not([data-reveal-bound])',
    '.prose > p:not([data-reveal-bound])',
    '.prose > blockquote:not([data-reveal-bound])',
    '.prose > figure:not([data-reveal-bound])',
    '.prose > .table-scroll:not([data-reveal-bound])',
  ].join(','));

  if (!nodes.length) return;

  nodes.forEach((node, index) => {
    node.dataset.revealBound = '1';
    // Only nearby siblings cascade; long indexes should not accumulate delay.
    node.style.setProperty('--reveal-delay', `${(index % 6) * 70}ms`);
    if (reduced) node.classList.add('is-revealed');
    else node.classList.add('scroll-reveal');
  });

  if (reduced || !('IntersectionObserver' in window)) {
    nodes.forEach((node) => node.classList.add('is-revealed'));
    return;
  }

  const observer = new window.IntersectionObserver((entries, current) => {
    entries.forEach((entry) => {
      if (!entry.isIntersecting) return;
      (entry.target as HTMLElement).classList.add('is-revealed');
      current.unobserve(entry.target);
    });
  }, { rootMargin: '0px 0px -9% 0px', threshold: 0.06 });

  nodes.forEach((node) => {
    const rect = node.getBoundingClientRect();
    if (rect.top < window.innerHeight * 0.94) node.classList.add('is-revealed');
    else observer.observe(node);
  });
}

/** A two-pixel signal line makes page position readable on the longer CPTS sheets. */
function initScrollProgress(): void {
  let progress = document.querySelector<HTMLElement>('[data-scroll-progress]');
  if (!progress) {
    progress = document.createElement('div');
    progress.className = 'scroll-progress';
    progress.dataset.scrollProgress = '1';
    progress.setAttribute('aria-hidden', 'true');
    document.body.append(progress);
  }
  if (progress.dataset.bound) return;
  progress.dataset.bound = '1';

  let ticking = false;
  const update = (): void => {
    const range = Math.max(1, document.documentElement.scrollHeight - window.innerHeight);
    progress!.style.setProperty('--scroll-progress', String(Math.min(1, Math.max(0, window.scrollY / range))));
    ticking = false;
  };
  const requestUpdate = (): void => {
    if (ticking) return;
    ticking = true;
    window.requestAnimationFrame(update);
  };

  window.addEventListener('scroll', requestUpdate, { passive: true });
  window.addEventListener('resize', requestUpdate, { passive: true });
  update();
}

/**
 * Every code block becomes the archive's terminal block: the language at
 * the left of a caption bar, the copy control at the right, both in the
 * 9.5px mono the rest of the site labels things in.
 *
 * No window chrome and no traffic-light dots — this is a printed listing
 * of terminal output, not a simulated window. The plate under it stays
 * dark in both modes (see prose.css).
 */
const COPY_ICON =
  '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="12" height="12"/><path d="M5 15H4a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1"/></svg>';
const CHECK_ICON =
  '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M20 6 9 17l-5-5"/></svg>';

/** How long a block stays "Copied". The caption's draining rule runs on the
 *  same figure (`--copied-ms` in prose.css) — change them together. */
const COPIED_MS = 1700;

function enhanceCode(): void {
  const blocks = document.querySelectorAll<HTMLPreElement>('.prose pre.astro-code:not([data-enhanced])');
  blocks.forEach((pre) => {
    pre.dataset.enhanced = '1';
    const lang = pre.getAttribute('data-language') || 'text';

    const pane = document.createElement('figure');
    /* `.plate` pins the night palette for the pane's subtree so the caption
       tokens and corner brackets read as a terminal on the cream page too;
       `.corners` adds the cyberdeck brackets; the pane is `position: relative`
       in prose.css, so both anchor without further help. */
    pane.className = 'code-pane plate corners';
    const bar = document.createElement('figcaption');
    bar.className = 'code-pane__bar';

    // A fence with no language is the common case (most listings are a bare
    // command or its output), and Shiki reports it as `plaintext`. Printing
    // that above six thousand blocks labels nothing, so those stay unlabelled
    // and the caption carries only the copy control.
    const langEl = document.createElement('span');
    langEl.className = 'code-pane__lang';
    const name = lang.replace(/[^a-z0-9+#-]/gi, '').slice(0, 16);
    langEl.textContent = /^(plaintext|plain|text|txt)?$/i.test(name) ? '' : name;

    const copy = document.createElement('button');
    copy.className = 'code-copy';
    copy.type = 'button';
    // Icon and word are separate nodes so each can be swapped, and the word
    // scrambled, without rebuilding the other.
    const icon = document.createElement('span');
    icon.className = 'code-copy__icon';
    const word = document.createElement('span');
    word.className = 'code-copy__word';
    copy.append(icon, word);
    const setLabel = (svg: string, text: string) => {
      icon.innerHTML = svg;
      word.textContent = text;
      // The accessible name is set outright, so a screen reader hears
      // "Copied" and never the half-settled scramble.
      copy.setAttribute('aria-label', text);
    };
    setLabel(COPY_ICON, 'Copy');

    // The sweep line that runs down the block on copy. Its own element
    // because `.corners` has spent both of the pane's pseudo-elements.
    const sweep = document.createElement('span');
    sweep.className = 'code-pane__sweep';
    sweep.setAttribute('aria-hidden', 'true');

    // The feedback lives on the block rather than in a toast across the
    // page — you copied this block, not the document. Pressing copy grabs
    // it: the corner brackets pinch in and spring back gold, a scan line
    // runs down the listing, the word settles from COPY into COPIED through
    // the site's scramble while the tick draws itself, and a gold rule under
    // the caption drains away over the time the confirmation stays up. All
    // of the motion is CSS keyed off `.is-copied` (prose.css) and is skipped
    // under reduced motion, where the word and the colour simply change.
    let reset = 0;
    copy.addEventListener('click', async () => {
      const text = pre.innerText;
      try {
        await navigator.clipboard.writeText(text);
      } catch {
        const ta = document.createElement('textarea');
        ta.value = text; document.body.appendChild(ta); ta.select();
        try { document.execCommand('copy'); } catch {}
        ta.remove();
      }
      window.clearTimeout(reset);
      setLabel(CHECK_ICON, 'Copied');
      copy.classList.add('copied');
      // Dropping the class and forcing a reflow restarts the run, so a
      // second press mid-animation plays it again from the top.
      pane.classList.remove('is-copied');
      void pane.offsetWidth;
      pane.style.setProperty('--sweep', `${pane.offsetHeight}px`);
      pane.classList.add('is-copied');

      const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches
        || document.documentElement.dataset.motion === 'reduce';
      if (!reduced) resolveText(word, 'Copied');

      reset = window.setTimeout(() => {
        setLabel(COPY_ICON, 'Copy');
        copy.classList.remove('copied');
        pane.classList.remove('is-copied');
      }, COPIED_MS);
    });

    bar.append(langEl, copy);
    pre.parentNode?.insertBefore(pane, pre);
    pane.append(bar, pre, sweep);

    // The CRT film. Its own element rather than a pseudo, because `.corners`
    // has already spent both of the pane's pseudo-elements.
    const film = document.createElement('div');
    film.className = 'scanlines';
    film.setAttribute('aria-hidden', 'true');
    pane.append(film);
  });
}

/**
 * Obsidian/GitHub `> [!type]` callouts. The markdown pipeline renders these
 * as plain blockquotes whose first line is the literal `[!type]` marker (no
 * rehype plugin is in the build, by design). Here every blockquote is framed
 * as a terminal callout (.callout + .corners, styled in prose.css); when a
 * marker is present its type keys the accent and a mono label replaces the
 * marker text. Plain blockquotes are left with the frame and no label, so the
 * page reads right with JS off too.
 */
const CALLOUT_ALIASES: Record<string, string> = {
  note: 'note', abstract: 'note', summary: 'note', tldr: 'note',
  info: 'info', todo: 'info',
  tip: 'tip', hint: 'tip', important: 'tip',
  success: 'success', check: 'success', done: 'success',
  question: 'question', help: 'question', faq: 'question',
  warning: 'warning', caution: 'warning', attention: 'warning',
  failure: 'danger', fail: 'danger', missing: 'danger',
  danger: 'danger', error: 'danger', bug: 'danger',
  example: 'example', quote: 'quote', cite: 'quote',
};
const CALLOUT_LABEL: Record<string, string> = {
  note: 'Note', info: 'Info', tip: 'Tip', success: 'Success',
  question: 'FAQ', warning: 'Warning', danger: 'Danger',
  example: 'Example', quote: 'Quote',
};

/* Callouts written the plain way: a blockquote that simply opens with the
   emoji. Same treatment as a `[!type]` marker — typed, labelled, and the
   emoji itself dropped, as it is from the headings. */
const CALLOUT_EMOJI: Record<string, string> = {
  '⚠': 'warning', '💡': 'tip', '✅': 'success', 'ℹ': 'info', '🚨': 'danger', '❌': 'danger', '📝': 'note',
};

function firstTextNode(el: Element): Text | null {
  const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
  let n = walker.nextNode();
  while (n && !(n.textContent ?? '').trim()) n = walker.nextNode();
  return (n as Text) ?? null;
}

function enhanceCallouts(): void {
  document.querySelectorAll<HTMLQuoteElement>('.prose blockquote:not([data-callout-done])').forEach((bq) => {
    bq.dataset.calloutDone = '1';
    bq.classList.add('callout', 'corners');

    const first = bq.firstElementChild;
    if (!first) return;
    const node = firstTextNode(first);
    if (!node) return;
    const text = node.textContent ?? '';
    const m = text.match(/^\s*\[!(\w+)\]([+-]?)\s?/);
    const lead = [...text.trimStart()][0] ?? '';
    const byEmoji = m ? undefined : CALLOUT_EMOJI[lead];
    if (!m && !byEmoji) return;

    const kind = m ? m[1].toLowerCase() : '';
    const variant = byEmoji ?? CALLOUT_ALIASES[kind] ?? 'note';
    bq.setAttribute('data-callout', variant);
    // The marker goes; so does an emoji's variation selector and the space
    // after it, which would otherwise indent the first line.
    node.textContent = m ? text.slice(m[0].length) : text.trimStart().slice(lead.length).replace(/^\uFE0F?\s*/, '');
    // If the marker was the whole first line, drop the now-empty node so the
    // label is not trailed by a blank paragraph.
    if (!(first.textContent ?? '').trim() && !first.querySelector('*')) first.remove();

    const label = document.createElement('div');
    label.className = 'callout__label';
    // A type the site has no styling of its own for (`[!terminal]`, `[!opsec]`)
    // is drawn as a note but keeps the author's word as its label.
    label.textContent = kind && !(kind in CALLOUT_ALIASES) ? kind : CALLOUT_LABEL[variant] ?? variant;
    bq.insertBefore(label, bq.firstChild);
  });
}

function wrapTables(): void {
  document.querySelectorAll<HTMLTableElement>('.prose table:not([data-wrapped])').forEach((t) => {
    t.dataset.wrapped = '1';
    const scroll = document.createElement('div');
    scroll.className = 'table-scroll';
    t.parentNode?.insertBefore(scroll, t);
    scroll.appendChild(t);
  });
}

function initTOC(): void {
  const toc = document.querySelector('.toc');
  if (!toc) return;
  const links = Array.from(toc.querySelectorAll<HTMLAnchorElement>('a[href^="#"]'));
  if (!links.length) return;
  const byId = new Map(links.map((l) => [decodeURIComponent(l.getAttribute('href')!.slice(1)), l]));
  const heads = Array.from(document.querySelectorAll<HTMLElement>('.prose h2[id], .prose h3[id]'));
  const obs = new IntersectionObserver(
    (entries) => {
      entries.forEach((e) => {
        if (!e.isIntersecting) return;
        const id = (e.target as HTMLElement).id;
        const link = byId.get(id);
        links.forEach((l) => l.classList.remove('active'));
        if (!link) return;
        link.classList.add('active');
        // On a long sheet the rail scrolls on its own, so the section being
        // read can be out of sight in it. Move the rail, never the page —
        // `scrollIntoView` would scroll both.
        const box = link.closest<HTMLElement>('.toc');
        if (!box || box.scrollHeight <= box.clientHeight) return;
        const top = link.getBoundingClientRect().top - box.getBoundingClientRect().top;
        const head = box.querySelector('summary')?.getBoundingClientRect().height ?? 0;
        if (top < head + 8) box.scrollTop += top - head - 8;
        else if (top + link.offsetHeight > box.clientHeight - 8) box.scrollTop += top + link.offsetHeight - box.clientHeight + 8;
      });
    },
    { rootMargin: '-70px 0px -70% 0px', threshold: 0 }
  );
  heads.forEach((h) => obs.observe(h));
}

// `init` re-runs on every view-transition swap, so the window listener is
// bound once here and re-reads the current button each time it fires;
// binding inside `initBackToTop` would stack a listener per navigation.
let backToTopBound = false;

function syncBackToTop(): void {
  const btn = document.querySelector<HTMLButtonElement>('#to-top');
  if (btn) btn.classList.toggle('is-visible', window.scrollY > 600);
}

function initBackToTop(): void {
  const btn = document.querySelector<HTMLButtonElement>('#to-top');
  if (!btn) return;
  // A page that barely scrolls does not need the control at all, so it stays
  // `hidden` rather than fading in over a screenful of content.
  if (document.documentElement.scrollHeight < window.innerHeight * 2) return;
  btn.hidden = false;

  btn.addEventListener('click', () => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    window.scrollTo({ top: 0, behavior: reduced ? 'auto' : 'smooth' });
    // Focus follows the scroll so keyboard and screen-reader users land at the
    // top of the document rather than staying parked on the button.
    document.querySelector<HTMLElement>('#main')?.focus({ preventScroll: true });
  });

  if (!backToTopBound) {
    window.addEventListener('scroll', syncBackToTop, { passive: true });
    backToTopBound = true;
  }
  syncBackToTop();
}

function init(): void {
  initTheme();
  initPalette();
  initMobileNav();
  initUnscramble();
  enhanceCode();
  enhanceCallouts();
  wrapTables();
  initScrollReveal();
  initScrollProgress();
  initTOC();
  initBackToTop();
}

document.addEventListener('astro:page-load', init);
if (document.readyState !== 'loading') init();
else document.addEventListener('DOMContentLoaded', init);