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
report-index-persistence.test.mjsJavaScript162 lines9.3 KiBraw download
import assert from 'node:assert/strict';
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import { Window } from 'happy-dom';

const CACHE_KEY = 'daemonsec:report-index:browser:v1';
const LEGACY_KEY = 'daemonsec:report-index:tab:v1';
const lock = JSON.parse(await readFile(new URL('../src/data/report-index-lock.json', import.meta.url), 'utf8'));
const bytes = Buffer.from(JSON.stringify({ version: 1, recipient: lock.recipient, steps: [
  { order: 1, tool: 'First use', purpose: 'Browser fixture', pages: '1', sheetId: 'exploitation/sqlmap' },
  { order: 2, tool: 'Repeated use', purpose: 'Browser fixture', pages: '2', sheetId: 'exploitation/sqlmap' },
] }));
const digest = createHash('sha256').update(bytes).digest('hex');
const cached = JSON.stringify({ digest, text: bytes.toString() });
const html = await readFile(new URL('../dist/sheets/exploitation/sqlmap/index.html', import.meta.url), 'utf8');
const modal = html.match(/<dialog id="report-index-dialog"[\s\S]*?<\/dialog>/)[0].replace(lock.plaintextSha256, digest);
const markup = `<button data-report-index-open>☧</button><h1><span data-report-guide><span aria-hidden="true">☧</span></span></h1>${modal}`;
let instance = 0;

async function until(check) {
  for (let i = 0; i < 100; i++) {
    if (check()) return;
    await new Promise(resolve => setTimeout(resolve, 10));
  }
  assert.fail('The report index did not reach the expected state.');
}

async function browser(t, { cache, legacy, blocked = false, origin = 'https://cheatsheet.daemon-sec.xyz' } = {}) {
  const window = new Window({ url: `${origin}/sheets/exploitation/sqlmap` });
  for (const key of ['window', 'document', 'Element', 'location', 'history', 'localStorage', 'sessionStorage']) {
    globalThis[key] = window[key];
  }
  if (cache) window.localStorage.setItem(CACHE_KEY, cache);
  if (legacy) window.sessionStorage.setItem(LEGACY_KEY, legacy);
  if (blocked) {
    Object.defineProperty(window.localStorage, 'setItem', { configurable: true, value: () => { throw new Error('Storage blocked'); } });
  }
  window.document.body.innerHTML = markup;
  await import(`../src/scripts/report-index.ts?test=${++instance}`);
  t.after(() => window.happyDOM.abort());
  const panel = () => window.document.querySelector('dialog');
  const status = () => window.document.querySelector('[data-report-index-status]').textContent;
  const open = () => window.document.querySelector('[data-report-index-open]').click();
  const importFile = (content = bytes) => {
    const input = panel().querySelector('[data-report-index-file]');
    Object.defineProperty(input, 'files', { configurable: true, value: [{ size: content.length,
      arrayBuffer: async () => content.buffer.slice(content.byteOffset, content.byteOffset + content.byteLength) }] });
    input.dispatchEvent(new window.Event('change', { bubbles: true }));
  };
  return { window, panel, status, open, importFile };
}

test('one JSON import saves ordered posts through Close, navigation and a new browser page', async t => {
  const b = await browser(t);
  b.open(); b.importFile();
  await until(() => b.status().startsWith('Saved in this browser'));
  assert.equal(b.panel().querySelectorAll('.report-index__list li').length, 2);
  assert.equal(b.window.document.querySelector('h1 [data-report-guide]').textContent, '☧ 01 · 02');
  assert.equal(b.window.localStorage.getItem(CACHE_KEY), cached);
  b.panel().close(); b.open();
  assert.match(b.status(), /2 steps in CPTS order/);
  b.window.document.dispatchEvent(new b.window.Event('astro:before-swap'));
  b.window.document.body.innerHTML = markup;
  b.window.document.dispatchEvent(new b.window.Event('astro:page-load'));
  assert.match(b.status(), /Saved in this browser/);
  const next = await browser(t, { cache: b.window.localStorage.getItem(CACHE_KEY) });
  await until(() => next.status().startsWith('Saved in this browser'));
  next.open();
  assert.equal(next.panel().querySelectorAll('.report-index__list li').length, 2);
});

test('Lock removes saved access and a storage event locks another open page', async t => {
  const b = await browser(t, { cache: cached });
  await until(() => b.status().startsWith('Saved in this browser'));
  b.open(); b.panel().querySelector('[data-report-index-lock]').click();
  assert.equal(b.status(), 'Locked');
  assert.equal(b.window.localStorage.getItem(CACHE_KEY), null);
  assert.equal(b.window.document.querySelector('h1 [data-report-guide]').textContent, '☧');
  b.importFile(); await until(() => b.status().startsWith('Saved in this browser'));
  b.window.localStorage.removeItem(CACHE_KEY);
  b.window.dispatchEvent(new b.window.StorageEvent('storage', { key: CACHE_KEY, newValue: null }));
  assert.equal(b.status(), 'Locked');
  assert.equal(b.panel().querySelectorAll('.report-index__list li').length, 0);
});

test('corrupt and outdated saved indexes are discarded and legacy tab access is upgraded', async t => {
  for (const cache of [JSON.stringify({ digest, text: 'corrupt' }), JSON.stringify({ digest: 'outdated', text: bytes.toString() })]) {
    const b = await browser(t, { cache });
    await until(() => b.window.localStorage.getItem(CACHE_KEY) === null);
    assert.equal(b.status(), 'Locked');
    assert.equal(b.panel().querySelectorAll('.report-index__list li').length, 0);
  }
  const migrated = await browser(t, { legacy: cached });
  await until(() => migrated.status().startsWith('Saved in this browser'));
  assert.equal(migrated.window.localStorage.getItem(CACHE_KEY), cached);
  assert.equal(migrated.window.sessionStorage.getItem(LEGACY_KEY), null);
});

test('a mismatched JSON cannot unlock and blocked storage reports temporary access', async t => {
  const b = await browser(t, { blocked: true });
  b.open(); b.importFile(Buffer.from('{}'));
  await until(() => b.status().includes('does not match'));
  assert.equal(b.panel().querySelectorAll('.report-index__list li').length, 0);
  b.importFile();
  await until(() => b.status().includes('browser storage is unavailable'));
  b.panel().close(); b.open();
  assert.match(b.status(), /refresh will lock it/);
});

test('navigating to an updated index clears the old visible order before restoring storage', async t => {
  const b = await browser(t, { cache: cached });
  await until(() => b.status().startsWith('Saved in this browser'));
  b.window.document.dispatchEvent(new b.window.Event('astro:before-swap'));
  b.window.document.body.innerHTML = markup.replace(digest, 'updated-index');
  b.window.document.dispatchEvent(new b.window.Event('astro:page-load'));
  assert.equal(b.status(), 'Locked');
  assert.equal(b.panel().querySelectorAll('.report-index__list li').length, 0);
  await until(() => b.window.localStorage.getItem(CACHE_KEY) === null);
});

// A preview address is shared by whatever project is served there next, in the
// same browser profile. The decrypted index must never be written to it.
for (const origin of ['http://localhost:4321', 'http://127.0.0.1:4321', 'http://[::1]:4321', 'http://192.168.1.20:4321', 'https://preview.localhost']) {
  test(`unlocking on ${origin} keeps the index in memory and out of browser storage`, async t => {
    const b = await browser(t, { origin });
    b.open(); b.importFile();
    await until(() => b.status().startsWith('Unlocked until this page reloads'));
    assert.match(b.status(), /a local preview never saves the index · 2 steps in CPTS order/);
    assert.equal(b.panel().querySelectorAll('.report-index__list li').length, 2);
    assert.equal(b.window.localStorage.getItem(CACHE_KEY), null);
    assert.equal(b.window.sessionStorage.getItem(LEGACY_KEY), null);
    assert.equal(b.window.localStorage.length + b.window.sessionStorage.length, 0, 'nothing at all may be stored');
    // In-site navigation keeps the unlocked order; it lives in the page's memory.
    b.window.document.dispatchEvent(new b.window.Event('astro:before-swap'));
    b.window.document.body.innerHTML = markup;
    b.window.document.dispatchEvent(new b.window.Event('astro:page-load'));
    assert.match(b.status(), /Unlocked until this page reloads/);
    assert.equal(b.window.localStorage.getItem(CACHE_KEY), null);
    // A fresh page on the same origin starts locked: there is nothing to restore.
    const next = await browser(t, { origin });
    next.open();
    await new Promise(resolve => setTimeout(resolve, 50));
    assert.equal(next.status(), 'Locked');
    assert.equal(next.panel().querySelectorAll('.report-index__list li').length, 0);
  });
}

test('a preview removes an index an earlier version saved there and does not restore it', async t => {
  const b = await browser(t, { origin: 'http://localhost:4321', cache: cached, legacy: cached });
  assert.equal(b.window.localStorage.getItem(CACHE_KEY), null, 'the saved copy must be gone as soon as the script loads');
  assert.equal(b.window.sessionStorage.getItem(LEGACY_KEY), null);
  b.open();
  await new Promise(resolve => setTimeout(resolve, 50));
  assert.equal(b.status(), 'Locked');
  assert.equal(b.panel().querySelectorAll('.report-index__list li').length, 0);
  // Something else on the shared origin writing the key must not unlock this page.
  b.window.localStorage.setItem(CACHE_KEY, cached);
  b.window.dispatchEvent(new b.window.StorageEvent('storage', { key: CACHE_KEY, newValue: cached }));
  await new Promise(resolve => setTimeout(resolve, 50));
  assert.equal(b.status(), 'Locked');
});