repositories

daemon-sec-lotl

DÆMONBins: GTFOBins × LOLBAS × WADComs × LOOBins in one filterable catalog

clonegit clone https://git.daemon-sec.xyz/daemon-sec-lotl.git
app.tsTypeScript464 lines17.7 KiBraw download
// Progressive enhancement, re-run after every (view-transition) navigation.

import { initHero } from './hero';
import { initDmn } from './dmn/init';
import { initPalette, paintChrome } from './palette';

/* The OS setting or the site's own switch (`<html data-motion="reduce">`,
   set from the catalog's display panel) both count as reduced motion. */
function reducedMotion(): boolean {
  return (
    window.matchMedia('(prefers-reduced-motion: reduce)').matches ||
    document.documentElement.dataset.motion === 'reduce'
  );
}

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 and dot
  // fields have no way to notice the mode changed. They listen 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 = reducedMotion();
      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 as KeyboardEvent).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;
}

function initUnscramble(): void {
  document.querySelectorAll<HTMLElement>('.sheet-title, .subcat h2, .download-library__head h2, .prose > h2').forEach((node) => {
    if (!node.hasAttribute('data-unscramble')) node.dataset.unscramble = node.textContent ?? '';
  });

  const nodes = document.querySelectorAll<HTMLElement>('[data-unscramble]:not([data-unscramble-bound])');
  const reduced = reducedMotion();

  const resolve = (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);
  };

  const observer = !reduced && 'IntersectionObserver' in window
    ? new window.IntersectionObserver((entries, current) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) return;
          const node = entry.target as HTMLElement;
          resolve(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) resolve(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 = reducedMotion();
  const nodes = document.querySelectorAll<HTMLElement>([
    '[data-reveal]:not([data-reveal-bound])',
    '.subcat:not([data-reveal-bound])',
    '.download-library__head:not([data-reveal-bound])',
    '.record: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);
  });
}

/**
 * Roll every `[data-count]` number up from zero to its target the first time it
 * scrolls into view. The final value is server-rendered as the element's text,
 * so with JS off (or under reduced motion) the real number is always shown; the
 * animation only replaces it briefly. Used by the hero stats and the platform
 * ledger.
 */
function initCounters(): void {
  const nodes = document.querySelectorAll<HTMLElement>('[data-count]:not([data-count-bound])');
  if (!nodes.length) return;
  const reduced = reducedMotion();

  const run = (el: HTMLElement): void => {
    const target = parseInt(el.dataset.count || '0', 10) || 0;
    if (reduced) { el.textContent = target.toLocaleString(); return; }
    const dur = 1100;
    const start = performance.now();
    const tick = (now: number): void => {
      const p = Math.min(1, (now - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      el.textContent = Math.round(target * eased).toLocaleString();
      if (p < 1) requestAnimationFrame(tick);
      else el.textContent = target.toLocaleString();
    };
    requestAnimationFrame(tick);
  };

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

  nodes.forEach((node) => {
    node.dataset.countBound = '1';
    const rect = node.getBoundingClientRect();
    if (reduced || !observer || rect.top < window.innerHeight * 0.95) run(node);
    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>';

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';

    const langEl = document.createElement('span');
    langEl.className = 'code-pane__lang';
    langEl.textContent = lang.replace(/[^a-z0-9+#-]/gi, '').slice(0, 16) || 'text';

    const copy = document.createElement('button');
    copy.className = 'code-copy';
    copy.type = 'button';
    const setLabel = (icon: string, word: string) => {
      copy.innerHTML = icon;
      copy.append(document.createTextNode(word));
    };
    setLabel(COPY_ICON, 'Copy');

    // The feedback lives on the button for 1400ms rather than in a toast
    // across the page — you copied this block, not the document.
    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();
      }
      setLabel(CHECK_ICON, 'Copied');
      copy.classList.add('copied');
      setTimeout(() => { setLabel(COPY_ICON, 'Copy'); copy.classList.remove('copied'); }, 1400);
    });

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

    // 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',
};

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 m = (node.textContent ?? '').match(/^\s*\[!(\w+)\]([+-]?)\s?/);
    if (!m) return;

    const variant = CALLOUT_ALIASES[m[1].toLowerCase()] ?? 'note';
    bq.setAttribute('data-callout', variant);
    node.textContent = (node.textContent ?? '').slice(m[0].length);
    // 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';
    label.textContent = 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;
        links.forEach((l) => l.classList.remove('active'));
        byId.get(id)?.classList.add('active');
      });
    },
    { rootMargin: '-70px 0px -70% 0px', threshold: 0 }
  );
  heads.forEach((h) => obs.observe(h));
}

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

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