import { MAX_INDEX_BYTES, readReportIndex, type ReportStep } from '../lib/report-index.ts';
const CACHE_KEY = 'daemonsec:report-index:browser:v1';
const LEGACY_CACHE_KEY = 'daemonsec:report-index:tab:v1';
const dialog = () => document.querySelector<HTMLDialogElement>('#report-index-dialog');
let session: { digest: string; steps: ReportStep[]; text: string } | null = null;
let generation = 0;
let pending: AbortController | null = null;
let durable = true;
/* Where the decrypted index may be written to browser storage.
*
* Storage belongs to an origin, not to a project. The production hostname is
* this site's alone, so saving there is safe and is what the README promises.
* A preview address is not: `http://localhost:4321` is whatever happens to be
* listening on that port, and the next project served there, in the same
* browser profile, could read a saved index long after the GPG helper stopped.
* The same goes for any plain-http address on the LAN.
*
* So anything that is not https on a real hostname keeps the index in memory
* only: it survives in-site navigation, a reload locks it again, and whatever
* an earlier version of this script saved there is removed on sight.
*/
function savesToBrowser() {
const host = location.hostname.replace(/^\[|\]$/g, '').toLowerCase();
const loopback = host === 'localhost' || host.endsWith('.localhost') || host === '::1' || host === '0.0.0.0' || /^127\./.test(host);
return location.protocol === 'https:' && !loopback;
}
function forgetStored() {
try { localStorage.removeItem(CACHE_KEY); } catch { /* Nothing readable to remove. */ }
try { sessionStorage.removeItem(LEGACY_CACHE_KEY); } catch { /* Nothing readable to remove. */ }
}
if (!savesToBrowser()) forgetStored();
function cancelPending() {
generation++;
pending?.abort();
pending = null;
}
function paintMarks(panel: HTMLDialogElement) {
for (const marker of document.querySelectorAll<HTMLElement>('[data-report-guide]')) {
const href = marker.closest<HTMLAnchorElement>('a[href]')?.href ?? location.href;
const path = new URL(href, location.href).pathname;
const base = panel.dataset.sheetBase!;
const id = path.startsWith(base) ? path.slice(base.length).replace(/\/$/, '') : '';
const orders = session?.steps.filter(step => step.sheetId === id).map(step => String(step.order).padStart(2, '0')) ?? [];
const label = orders.length ? `☧ ${orders.join(' · ')}` : '☧';
marker.querySelector('[aria-hidden]')!.textContent = label;
marker.setAttribute('aria-label', orders.length ? `Report tool guide, steps ${orders.join(', ')}` : 'Report tool guide');
marker.title = orders.length ? `Report steps ${orders.join(', ')}` : 'Report tool guide; unlock the ☧ index for its order';
if (orders.length) marker.dataset.reportStep = orders.join(',');
else delete marker.dataset.reportStep;
}
for (const button of document.querySelectorAll<HTMLElement>('[data-report-index-open]')) {
const label = session ? '☧ View tool order' : '☧ Unlock tool order';
button.title = label;
button.setAttribute('aria-label', label.slice(2));
if (button.classList.contains('report-index-link')) button.textContent = label;
}
}
function render(panel: HTMLDialogElement) {
const results = panel.querySelector('[data-report-index-results]')!;
results.replaceChildren();
panel.querySelector<HTMLElement>('[data-report-index-auth]')!.hidden = !!session;
panel.querySelector<HTMLButtonElement>('[data-report-index-lock]')!.hidden = !session;
const status = panel.querySelector<HTMLElement>('[data-report-index-status]')!;
status.textContent = session
? `${!savesToBrowser() ? 'Unlocked until this page reloads · a local preview never saves the index'
: durable ? 'Saved in this browser' : 'Unlocked · browser storage is unavailable; refresh will lock it'} · ${session.steps.length} steps in CPTS order`
: 'Locked';
if (session) {
const list = document.createElement('ol');
list.className = 'report-index__list';
for (const step of session.steps) {
const item = document.createElement('li');
const number = document.createElement('span');
number.className = 'report-index__number';
number.textContent = `☧ ${String(step.order).padStart(2, '0')}`;
const body = document.createElement('div');
const link = document.createElement('a');
link.href = `${panel.dataset.sheetBase}${step.sheetId}`;
link.textContent = step.tool;
const purpose = document.createElement('p');
purpose.textContent = step.purpose;
const pages = document.createElement('small');
pages.textContent = `Report pages ${step.pages}`;
body.append(link, purpose, pages);
item.append(number, body);
list.append(item);
}
results.append(list);
}
paintMarks(panel);
}
function clearPairing(panel: HTMLDialogElement) {
const input = panel.querySelector<HTMLInputElement>('[data-report-index-token]')!;
input.value = '';
panel.querySelector<HTMLButtonElement>('[data-report-index-unlock]')!.disabled = false;
const file = panel.querySelector<HTMLInputElement>('[data-report-index-file]')!;
file.value = '';
file.disabled = false;
}
function lockSession() {
cancelPending();
session = null;
try { localStorage.removeItem(CACHE_KEY); } catch { /* Memory still clears when storage is blocked. */ }
try { sessionStorage.removeItem(LEGACY_CACHE_KEY); } catch { /* Clear the previous tab cache too. */ }
const panel = dialog();
if (panel) { clearPairing(panel); render(panel); }
}
async function restore(panel: HTMLDialogElement) {
if (session?.digest !== panel.dataset.digest) session = null;
if (session) { render(panel); return; }
if (!savesToBrowser()) { forgetStored(); return; }
const mine = generation;
try {
let cached = localStorage.getItem(CACHE_KEY);
if (!cached) {
// Upgrade yesterday's tab-only cache after checking the same pinned digest.
try { cached = sessionStorage.getItem(LEGACY_CACHE_KEY); } catch { /* No legacy cache. */ }
}
if (!cached) return;
if (cached.length > MAX_INDEX_BYTES * 2) throw new Error('Oversized cache');
const data = JSON.parse(cached);
if (data.digest !== panel.dataset.digest || typeof data.text !== 'string') throw new Error('Expired cache');
const steps = await readReportIndex(new TextEncoder().encode(data.text).buffer, panel.dataset.digest!, panel.dataset.recipient!);
if (mine !== generation || !panel.isConnected) return;
session = { digest: data.digest, text: data.text, steps };
saveSession();
clearPairing(panel);
render(panel);
} catch {
if (mine !== generation || !panel.isConnected) return;
try { localStorage.removeItem(CACHE_KEY); } catch { durable = false; }
try { sessionStorage.removeItem(LEGACY_CACHE_KEY); } catch { /* No accessible legacy cache. */ }
}
}
function saveSession() {
if (!session) return;
if (!savesToBrowser()) { durable = false; forgetStored(); return; }
try {
localStorage.setItem(CACHE_KEY, JSON.stringify({ digest: session.digest, text: session.text }));
durable = true;
try { sessionStorage.removeItem(LEGACY_CACHE_KEY); } catch { /* The browser cache was saved. */ }
} catch { durable = false; }
}
async function acceptIndex(bytes: ArrayBuffer, panel: HTMLDialogElement, mine: number) {
const steps = await readReportIndex(bytes, panel.dataset.digest!, panel.dataset.recipient!);
if (mine !== generation || !panel.open || !panel.isConnected) return;
session = { digest: panel.dataset.digest!, steps, text: new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes) };
saveSession();
clearPairing(panel);
render(panel);
panel.querySelector<HTMLButtonElement>('[data-report-index-lock]')!.focus();
}
function consumePairing(panel: HTMLDialogElement) {
// The helper's link carries only a short-lived pairing code in the fragment, never a private key.
if (location.hash.startsWith('#gpg-pair=')) {
const token = location.hash.slice('#gpg-pair='.length);
history.replaceState(history.state, '', location.pathname + location.search);
if (/^[a-f0-9]{48}$/.test(token) && !session) {
panel.querySelector<HTMLInputElement>('[data-report-index-token]')!.value = token;
if (!panel.open) panel.showModal();
}
}
}
function bind() {
const panel = dialog();
if (!panel) return;
if (panel.dataset.bound) { consumePairing(panel); return; }
panel.dataset.bound = 'true';
if (session?.digest !== panel.dataset.digest) session = null;
render(panel);
void restore(panel);
const onClose = () => { cancelPending(); clearPairing(panel); render(panel); };
panel.addEventListener('close', onClose);
panel.addEventListener('cancel', onClose);
panel.addEventListener('click', event => {
if (event.target !== panel) return;
const box = panel.getBoundingClientRect();
const pointer = event as MouseEvent;
if (pointer.clientX < box.left || pointer.clientX > box.right || pointer.clientY < box.top || pointer.clientY > box.bottom) panel.close();
});
panel.querySelector('form')!.addEventListener('submit', async event => {
event.preventDefault();
cancelPending();
const input = panel.querySelector<HTMLInputElement>('[data-report-index-token]')!;
const token = input.value.trim();
if (!/^[a-f0-9]{48}$/.test(token)) {
panel.querySelector('[data-report-index-status]')!.textContent = 'Copy the pairing code from your GPG helper terminal.';
input.focus(); return;
}
const mine = generation;
const controller = new AbortController();
pending = controller;
const button = panel.querySelector<HTMLButtonElement>('[data-report-index-unlock]')!;
button.disabled = true;
const status = panel.querySelector<HTMLElement>('[data-report-index-status]')!;
status.textContent = 'Waiting for local GPG… Complete the Main_Key prompt to unlock.';
try {
const response = await fetch('http://127.0.0.1:47631/unlock', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token }),
credentials: 'omit', cache: 'no-store', signal: controller.signal,
});
if (!response.ok) {
const error = await response.json();
throw new Error(typeof error.error === 'string' ? error.error : 'Local GPG could not unlock the index.');
}
if (Number(response.headers.get('content-length')) > MAX_INDEX_BYTES) throw new Error('The helper returned an oversized index.');
const bytes = await response.arrayBuffer();
await acceptIndex(bytes, panel, mine);
} catch (error) {
if (mine !== generation || controller.signal.aborted || !panel.isConnected) return;
status.textContent = error instanceof TypeError
? 'Cannot reach local GPG. Start npm run unlock:helper, and allow this site’s local-network request if your browser asks.'
: error instanceof Error ? error.message : 'Unable to unlock the index.';
} finally {
if (mine === generation) { pending = null; button.disabled = false; input.value = ''; }
}
});
panel.querySelector('[data-report-index-file]')!.addEventListener('change', async event => {
const input = event.target as HTMLInputElement;
const file = input.files?.[0];
if (!file) return;
cancelPending();
const mine = generation;
const status = panel.querySelector<HTMLElement>('[data-report-index-status]')!;
input.disabled = true;
status.textContent = 'Checking decrypted index…';
try {
if (file.size > MAX_INDEX_BYTES) throw new Error('Choose the decrypted report-index.json file (under 128 KB).');
await acceptIndex(await file.arrayBuffer(), panel, mine);
} catch (error) {
if (mine === generation && panel.open && panel.isConnected) {
status.textContent = error instanceof Error ? error.message : 'Unable to read this file.';
}
} finally {
if (mine === generation) { input.disabled = false; input.value = ''; }
}
});
consumePairing(panel);
}
document.addEventListener('click', event => {
const target = event.target instanceof Element ? event.target : null;
if (target?.closest('[data-report-index-open]')) {
event.preventDefault(); bind();
const panel = dialog();
if (panel && !panel.open) { render(panel); panel.showModal(); void restore(panel); }
} else if (target?.closest('[data-report-index-close]')) dialog()?.close();
else if (target?.closest('[data-report-index-lock]')) lockSession();
});
document.addEventListener('astro:before-swap', () => {
cancelPending();
const panel = dialog();
if (panel) { clearPairing(panel); if (panel.open) panel.close(); }
});
document.addEventListener('astro:page-load', bind);
window.addEventListener('hashchange', bind);
window.addEventListener('storage', event => {
// A preview keeps nothing in storage, so nothing written there is ours to act on.
if (!savesToBrowser()) return;
if (event.key !== CACHE_KEY && event.key !== null) return;
cancelPending();
session = null;
if (event.newValue === null) {
try { sessionStorage.removeItem(LEGACY_CACHE_KEY); } catch { /* Another tab locked the browser. */ }
}
const panel = dialog();
if (panel) { clearPairing(panel); render(panel); void restore(panel); }
});
bind();