export interface ReportStep { order: number; tool: string; purpose: string; pages: string; sheetId: string; } export const MAX_INDEX_BYTES = 128 * 1024; // The digest binds the selected local file to this site's encrypted payload. export async function readReportIndex(bytes: ArrayBuffer, digest: string, recipient: string): Promise { if (!bytes.byteLength || bytes.byteLength > MAX_INDEX_BYTES) throw new Error('Choose the decrypted report-index.json file (under 128 KB).'); const actual = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', bytes)), b => b.toString(16).padStart(2, '0')).join(''); if (actual !== digest) throw new Error('This file does not match the encrypted index. Download and decrypt the current file.'); const data = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)); if (data?.version !== 1 || data.recipient !== recipient || !Array.isArray(data.steps) || !data.steps.length || data.steps.length > 256) { throw new Error('Unsupported tool index.'); } const text = (value: unknown, max: number) => typeof value === 'string' && value.trim().length > 0 && value.length <= max; return data.steps.map((step: ReportStep, i: number) => { if (step?.order !== i + 1 || !text(step.tool, 160) || !text(step.purpose, 600) || !text(step.pages, 100) || typeof step.sheetId !== 'string' || !/^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/.test(step.sheetId)) { throw new Error('Invalid tool index entry.'); } return { order: step.order, tool: step.tool, purpose: step.purpose, pages: step.pages, sheetId: step.sheetId }; }); }