Harden analyst edits and add manual findings, remediation queue and frozen reports
Browse filesFiles changed (18)
- IMPROVEMENTS.md+8
- README.md+3
- SECURITY.md+6
- SERVICE.md+1-1
- SOURCE-MANIFEST.jsonAdded+28
- VERIFICATION.md+12
- docs/superpowers/plans/2026-10-31-business-improvements.mdAdded+18
- docs/superpowers/plans/2026-11-02-analyst-reliability.mdAdded+22
- docs/superpowers/specs/2026-10-31-business-improvements-design.mdAdded+15
- docs/superpowers/specs/2026-11-02-analyst-reliability-design.mdAdded+17
- index.html+80-4
- static/app.js+188-15
- static/index.html+80-4
- static/local.js+167-23
- static/style.css+7
- tests/browser_storage.cjs+88-9
- tests/browser_ui.cjs+144-4
- tests/test_local.cjs+183-14
26 unmodified lines27282926 unmodified linesCode nomination remains lexical and low confidence. It does not execute Python, provide taint tracking or prove exploitable input flow. Detection fixtures measure their own examples and are not a general accuracy claim. Browser evidence covers installed Chromium; other engines, actual disk exhaustion, storage eviction and a full accessibility audit remain unverified. Quota and policy-denial tests use labeled fault injection.The update is delivered as source and a refreshed ZIP. See the deployment receipt for publication status and the verified private Space revision.26 unmodified lines272829303132333435363726 unmodified linesCode nomination remains lexical and low confidence. It does not execute Python, provide taint tracking or prove exploitable input flow. Detection fixtures measure their own examples and are not a general accuracy claim. Browser evidence covers installed Chromium; other engines, actual disk exhaustion, storage eviction and a full accessibility audit remain unverified. Quota and policy-denial tests use labeled fault injection.The update is delivered as source and a refreshed ZIP. See the deployment receipt for publication status and the verified private Space revision.## Analyst reliability release — 2026-11-02Finding saves now require the loaded revision. If another tab saves first, the stale form keeps its draft and offers an explicit reload/discard choice. Close, X and Escape protect unsaved review and manual-finding fields; old dialog errors clear on a fresh finding. Deleting a client’s last assessment resets an invalid client filter to All clients.Alert failures with neither actor nor source are counted as unattributed rather than correlated as one identity. Markdown, print and the remediation queue use the same totals: unresolved validation, confirmed static/runtime, rejected, and confirmed-only non-resolved remediation.Use Add analyst finding for discoveries outside the heuristic patterns. Entries start unresolved/low confidence and require the usual evidence review. The Remediation tab filters confirmed findings by owner, status and overdue date in UTC. Reports captures up to three frozen structured versions, with JSON/Markdown download and print. SHA-256 detects corruption; it does not authenticate authorship or evidence. Restore verifies snapshot digests before committing any imported records.
26 unmodified lines27282930313226 unmodified lines- **Exercises:** disclosed keyword routing selects ransomware, supply-chain, identity/phishing, cloud or generic tabletop missions. No model or simulated attack runs.- **Five perspectives:** scoped adversary planning, defense, independent review, attacker-perspective lab modeling and joint detection validation. They are analytical perspectives, not running autonomous agents or user permission roles.- **Evidence:** record structured analyst evidence, remediation ownership and retest notes; filter candidates by verdict/severity and hand off work among assigned perspectives. Confirmation is an analyst attestation, not automated proof.- **Client delivery:** organize by client label, export Markdown, and print an executive report with verdict counts and coverage limits. Client labels provide organization within one browser workspace.- **Recovery:** download a versioned workspace or client backup, preview a validated file, and restore additive copies atomically. Existing records are never replaced. Legacy single-assessment JSON exports are accepted after validation.26 unmodified lines27282930313233343526 unmodified lines- **Exercises:** disclosed keyword routing selects ransomware, supply-chain, identity/phishing, cloud or generic tabletop missions. No model or simulated attack runs.- **Five perspectives:** scoped adversary planning, defense, independent review, attacker-perspective lab modeling and joint detection validation. They are analytical perspectives, not running autonomous agents or user permission roles.- **Evidence:** record structured analyst evidence, remediation ownership and retest notes; filter candidates by verdict/severity and hand off work among assigned perspectives. Confirmation is an analyst attestation, not automated proof.- **Analyst findings:** add a bounded evidence-backed candidate manually; it starts unresolved with low confidence and uses the same human review process. Stale finding saves are rejected so a second tab cannot silently overwrite a newer decision. Unsaved finding, manual-entry and handoff drafts prompt before dismissal.- **Remediation queue:** filter confirmed findings by owner, status and overdue date (UTC). Rejected and unresolved candidates are excluded from open remediation totals.- **Report versions:** capture up to three frozen local reports per assessment, export JSON/Markdown or print a saved version. SHA-256 detects corruption, not authenticated authorship or tamper-proof signing.- **Client delivery:** organize by client label, export Markdown, and print an executive report with verdict counts and coverage limits. Client labels provide organization within one browser workspace.- **Recovery:** download a versioned workspace or client backup, preview a validated file, and restore additive copies atomically. Existing records are never replaced. Legacy single-assessment JSON exports are accepted after validation.
13 unmodified lines14151617181913 unmodified linesInput and storage limits bound normal operations. Scope authorization and analyst evidence are required by the workflow, but local UI checks do not establish legal authorization or certify security. Inspect caller context, reachability and mitigations before confirming findings. Structured reviewer, reference, prerequisite, mitigation and method fields support this review; labels do not authenticate a reviewer. Remediation state and handoff notes are editable local records, not an immutable audit trail. No code execution, target URL fetching, credential validation, exploit generation, dependency advisory lookup or continuous monitoring runs.## CoverageCode nomination uses conservative text patterns, not a Python AST/parser. Lexical masking reduces comment/string call matches and bounded import recognition handles common aliases; unsupported Python syntax, shadowing and formatting can still cause misses or false positives. Alert interpretation trusts supplied labels; timestamps, duplicates and authenticity remain unverified. Exercise categories use disclosed keyword routing. Every automatic candidate remains unresolved until a human records a verdict.13 unmodified lines14151617181920212223242513 unmodified linesInput and storage limits bound normal operations. Scope authorization and analyst evidence are required by the workflow, but local UI checks do not establish legal authorization or certify security. Inspect caller context, reachability and mitigations before confirming findings. Structured reviewer, reference, prerequisite, mitigation and method fields support this review; labels do not authenticate a reviewer. Remediation state and handoff notes are editable local records, not an immutable audit trail. No code execution, target URL fetching, credential validation, exploit generation, dependency advisory lookup or continuous monitoring runs.## Concurrent edits and frozen reportsFinding saves require the revision originally loaded by the editor. The comparison and write occur atomically in IndexedDB; a stale editor must explicitly reload before retrying. This prevents accidental overwrites within a shared origin/profile, not malicious changes by someone controlling that profile. Assessment revisions also guard asynchronous report capture against intervening writes.Up to three structured report snapshots are stored inside each assessment. They omit nested snapshots and preserve captured evidence independently of later edits. Snapshot exports and restores verify SHA-256 over validated canonical data. Backup preview checks schema and size; digest checks finish before restore writes. An attacker able to alter data can also recompute a digest: this is corruption detection, not a signature, authenticated identity or immutable audit record. Snapshot evidence remains sensitive and needs the same retention and export controls as current records.## CoverageCode nomination uses conservative text patterns, not a Python AST/parser. Lexical masking reduces comment/string call matches and bounded import recognition handles common aliases; unsupported Python syntax, shadowing and formatting can still cause misses or false positives. Alert interpretation trusts supplied labels; timestamps, duplicates and authenticity remain unverified. Exercise categories use disclosed keyword routing. Every automatic candidate remains unresolved until a human records a verdict.
20 unmodified lines2122232425262720 unmodified lines3. Run bounded local checks; challenge candidates and record evidence/mitigations before choosing a verdict.4. Export a report and explain demonstrated impact separately from severity hypotheses and missing coverage.5. Record remediation owner, due date, state and retest notes. Use role handoff notes to document the next evidence request. Agree commitments and residual risks with the customer.6. Deliver the executive print view or Markdown report through approved channels and save a versioned backup. Test recovery with synthetic records before relying on it for an engagement.Each browser/profile/origin has its own records. Teams do not automatically share cases, and there is no managed customer database. Share reports through the customer's approved channels. Validate retention, export handling, consent and data processing arrangements before accepting sensitive material.20 unmodified lines2122232425262720 unmodified lines3. Run bounded local checks; challenge candidates and record evidence/mitigations before choosing a verdict.4. Export a report and explain demonstrated impact separately from severity hypotheses and missing coverage.5. Record remediation owner, due date, state and retest notes. Use role handoff notes to document the next evidence request. Agree commitments and residual risks with the customer.6. Capture a frozen report version after analyst review (up to three per assessment), then deliver its print view or Markdown report through approved channels and save a workspace backup. Use the confirmed-only remediation queue to track owners, statuses and overdue dates in UTC. Manually discovered findings can be added as unresolved candidates and reviewed through the same evidence workflow. Test recovery with synthetic records before relying on it for an engagement.Each browser/profile/origin has its own records. Teams do not automatically share cases, and there is no managed customer database. Share reports through the customer's approved channels. Validate retention, export handling, consent and data processing arrangements before accepting sensitive material.
12345678910111213141516171819202122232425262728{ "README.md": "42d51b8ffbfcabcfec2e7478edcd9f186042c0e4ecd68959591896cbd01ea9b5", "index.html": "b68f4fa4547262a982f62b6642988356506dd3b172ce12548d73a7eb9fcec613", "static/index.html": "6070e314211e6d606c2ef85d51d3997f1e721fb5d7679379b05e93094b51fab1", "static/style.css": "9edb2efef1330a7e95c96bfc75623f5580f43c3388959c093a407a018331619a", "static/app.js": "b2f35f740419d387e03f698ea7af26fc9b8a0146e2c7af0de249c2c95fe8af1d", "static/local.js": "3b7af173868dbd040e9b37777e4a99f8198663fbd087755ecf515a5247ef1f78", "static/playbooks.js": "3907230561f4573801651297fde26d835d964783a175363b6434c8a4e312e80c", "tests/test_local.cjs": "551de9a5542cc871b5b718fa2eeca10b403c9d1684202d408e785c31f5f0e2bf", "tests/browser_storage.cjs": "338a8d86dcf7e1b0907314157c4377943c2fed16c7510262b8b0a48cb8ab0a80", "tests/browser_ui.cjs": "9bd1e9b605b266166d66dc3582ef49d015035a31fdb6cef0b09c461ed8045fbc", "tests/detection-fixtures.cjs": "1d9fed45afab9f37d7d2715a8dcf0c2e1e6c80c57821509df44d07e22b12383b", "SECURITY.md": "a6ef94dd35f203c780189275266a9ae5b230f47fdede649014a330de14549d1f", "SERVICE.md": "d4c6c10a5835daa65f30e00ccce944aa36ad84b93f25916ee4ad6975b581d430", "PROVENANCE.md": "8ff7cec5424c7ddbb7472b3420d0be5e40db7061f823c671936edf126205f1dc", "VERIFICATION.md": "53b4b8f908e6491165b119d252c83943d467eaa410a42f24d605a7eeb9a79aa7", "IMPROVEMENTS.md": "fcc525ae92ffe52963726a5d19dec71a42120dee0bdb30bcbdde296366b2968e", "deploy_hf.py": "071a76bd17d825dc892fdd6d514294248db324ed93251500bb4e2c74671a3bff", "requirements-deploy.txt": "81672301ff63877bdaf3f00b06ebed759f2d2e04f4372c57024fef78c0ea42bf", "tests/test_deploy.py": "95fcbd4f01ade35dd55f35c589fce3c6043f8c95197ab23d84aea032a0321416", "docs/superpowers/specs/2026-10-31-business-improvements-design.md": "036f59ddfb6733bd46209681e1342f1380625adde151a6bfb859f2526647a069", "docs/superpowers/plans/2026-10-31-business-improvements.md": "ea62d134e27d136491bb07eaafcabc70e27b4c1a7554869fcfa2ae48214b141c", "static/logo.svg": "03adb4e95e4c9ccfe438d9d8a47dddaa960bd8a3633b82149f3061757c3c096a", "static/logo-print.svg": "aa5c551d2cb6f8c7131a8b24948fdd31667913e97a2ea08f51795069487ef273", "static/favicon.svg": "eb535ad41f1e22491f0c7613aae75b08724128fbc05789d1606eac54b3f520a7", "docs/superpowers/plans/2026-11-02-analyst-reliability.md": "3bdf439649b81d4d4103e29fcd7b93532c136005a3391daccb013b7c7fd6bc8d", "docs/superpowers/specs/2026-11-02-analyst-reliability-design.md": "060254765a96aabece0b3388585273d05abed1e280ab6abe18633e5d2d9349e6"}51 unmodified lines52535451 unmodified linesNo Docker, server-side analysis, paid resource, model API or runtime dependency was added. Browser tests use an already installed Playwright/Chromium setup. No Graphify mapping or upstream scanner runtime was needed for this small known source tree; source searches and direct inspection supplied navigation evidence. Final coverage remains bounded; no exploitable finding was confirmed in this reviewed local flow.The local deployment receipt records publication status and the verified hosted revision. An initial browser interruption was resolved by reopening the correct HTTPS project tab.51 unmodified lines52535455565758596061626364656651 unmodified linesNo Docker, server-side analysis, paid resource, model API or runtime dependency was added. Browser tests use an already installed Playwright/Chromium setup. No Graphify mapping or upstream scanner runtime was needed for this small known source tree; source searches and direct inspection supplied navigation evidence. Final coverage remains bounded; no exploitable finding was confirmed in this reviewed local flow.The local deployment receipt records publication status and the verified hosted revision. An initial browser interruption was resolved by reopening the correct HTTPS project tab.## Analyst reliability release — 2026-11-02The engine suite now passes 34 Node checks, including exact finding revisions, same-finding concurrent conflicts with explicit reload/retry, unattributed alerts, confirmed-only remediation totals, manual provenance and transactional caps, three frozen report versions, snapshot capture races, unchanged historical exports after edits, legacy/v2 backups, digest-tamper rejection before mutation and the 5 MB single-record growth limit. JavaScript syntax and all four optional publisher tests pass. Final real-browser outcomes are recorded below.The five reproduced defects were reliability/data-quality problems: stale updates overwrote newer tracking, dialog dismissal lost drafts, a removed client label stranded the register, missing alert identity fields created a false group, and rejected candidates inflated remediation totals. They are fixed within the local workspace model. Manual findings, the confirmed-only queue and frozen reports do not add authenticated reviewers, shared access, cloud persistence or tamper-proof audits.The updated real Chromium storage harness passes 15 checks, including same-finding conflict handling, frozen snapshot limits/integrity, fresh current IDs with historical IDs preserved, legacy restore, transactional rollback, capacity bounds and no external requests or uncaught page errors. Source review traced snapshot validation, safe rendering/export and asynchronous hash-to-transaction revision checking. No exploitable vulnerability was confirmed within this bounded source and synthetic-browser coverage.A near-limit regression verifies that a valid exported record within four bytes of the 5 MB limit still restores. When adding restore provenance would exceed that limit, the imported history and summary are retained without a new annotation; current IDs are still regenerated and snapshot hashes remain verified.Final integrated UI workflow passes: concurrent stale-save conflict and explicit reload/reopen, canceled Close/X/Escape draft preservation for review/manual/handoff, structured review, concurrent manual entry selection, confirmed owner/status/overdue queue, frozen JSON download, print totals, backup preview/restore, client reset after deletion, anonymous alerts, 390px overflow and no uncaught page errors. Desktop/mobile screenshots were inspected. Final source checks: 34 Node tests, 15 Chromium storage checks, full Chromium UI workflow, 4 optional publisher tests and both JavaScript syntax checks passed. No runtime dependency, Docker, paid resource or external request was added.
123456789101112131415161718# Business improvements implementation plan
**Goal:** Deliver the accepted review improvements in sequence using the existing free static application.**Architecture:** Vanilla JavaScript and IndexedDB. No network runtime, Docker, paid infrastructure, new runtime dependency or claim of tenant isolation. Existing records remain readable.**Authority:** User requested all proposed improvements one by one. Preserve current visual identity; implementation decisions below are commander defaults.
1. Versioned backup and restore: export an envelope with format/version/records. Validate the complete bounded document, sanitize accepted fields, preview record counts, then atomically add copies with new IDs. Never replace existing records. Reject malformed/oversized documents without mutation.2. Structured evidence and reporting: reviewer label, reference/revision, prerequisites, mitigations and method required for confirmations. Treat these as analyst attestations. Add remediation owner, due date, status and retest note. Markdown executive summary and browser print view separate verdict counts and disclose limits. Record role handoff notes.3. Browser persistence verification: real IndexedDB multi-tab writes, denied/aborted transactions and restore rollback; use existing browser capabilities with no paid tools.4. Detection fixtures and improvements: ignore Python comments/string contents for call nomination, recognize imported subprocess aliases and bounded multiline calls. Keep nomination low confidence; disclose remaining parser/dataflow limits. Add positive/negative benchmark fixtures.5. Client organization: optional client label defaults to Unassigned for legacy records. Filter register and workspace backup by client. No tenant/access-control claim.6. Mobile/accessibility: responsive record tables, verdict/severity filters, focus restoration after save and next unresolved action. Preserve keyboard navigation.
For each stage: write meaningful regression cases, observe failures, implement, run related checks; integrate only after interfaces settle. Root owns source packaging/docs and final verification. Engine owner owns local.js and Node tests; UI owner owns app.js, both HTML entries and style.css. Security review is read-only. No automatic publication in this improvement mission.
## Execution outcome
All six stages implemented and checked. Root integrated security/browser review fixes and refreshed static-only packaging. See VERIFICATION.md for exact checks and residual limits. No publication performed.12345678910111213141516171819202122# Analyst reliability and service workflow implementation plan
**Goal:** Fix the five reproduced defects, add the three accepted service features, then publish the verified release to the existing private Static Space.**Architecture:** Existing vanilla JS and IndexedDB, outlined Interval branding. No Docker, new runtime dependency, paid resource, cloud customer database or external requests.**Authority:** User explicitly requested proceeding one by one then pushing. Implementation choices below are commander defaults.
## Sequence and acceptance
1. Stale saves: findings have revision integers (legacy defaults 0). PATCH requires expected_revision, checked atomically against the current finding. Successful writes increment finding and assessment revision. Conflicts preserve the current record and the unsaved form, with an explicit reload/discard choice. Missing preconditions cannot silently bypass protection.2. Draft protection: Close, X and Escape preserve the review form unless the user confirms discarding changes. Clear old record errors when switching finding. Canceling a discard leaves all fields intact.3. Client filter: after refresh/deletion, invalid selected client resets to All clients; visible selection, register and backup scope agree.4. Unattributed alerts: failures without actor and source identifiers do not claim identity correlation. Disclose omitted/unattributed counts; findings remain unresolved.5. Report totals: only confirmed, non-resolved findings count as remediation work; unresolved validation and rejected findings have separate totals. Reuse a shared summary calculation for Markdown, print and queue.6. Manual findings: bounded analyst-created evidence fields, always unresolved/low-confidence with origin manual. No submitted code execution, arbitrary verdict injection, or new authorization claim. Global 100-finding cap and 200-event cap remain transactional.7. Remediation queue: confirmed findings only, showing owner/due/status with owner/status/overdue filters, keyboard access and responsive layout. Use UTC calendar dates consistently for overdue comparison.8. Versioned report snapshots: at most 3 locally saved frozen snapshots per assessment. A snapshot captures sanitized report source data without nested snapshots, a version/time/source revision and SHA-256 of canonical captured data. Render/export through existing safe Markdown/DOM functions; no arbitrary imported HTML/Markdown rendering. Digest is corruption detection, not authentication. Restore validates snapshot schema and hashes before any write; snapshot source IDs stay historical. Current assessment IDs are still refreshed on restore. Preserve legacy backup support with explicit schema version handling.
## Ownership and checks
Backend owns static/local.js and tests/test_local.cjs. Frontend owns static/app.js, both HTML entries and static/style.css. Reviewer owns tests/browser_storage.cjs and tests/browser_ui.cjs, and read-only security integration review. Root owns shared contracts, docs, source manifest/ZIP and publication. No recursive delegation.
Each stage uses a failing meaningful regression then a passing implementation check. Final evidence: fresh Node/unit and publishing checks; real Chromium stale-write and draft/client/report/manual/queue/snapshot workflows; malformed/tampered snapshot import nonmutation; old backups still restore; mobile and print inspection. Push only reviewed allowlisted source with correct static/ and tests/ paths; verify private/Running and hosted behavior. No customer data or browser profiles uploaded.123456789101112131415# Analyst service improvements
The user approved implementing all findings from the project review, one by one. Keep the existing static browser application and visual design, with no Docker or chargeable runtime.
An analyst should recover local work from an exported backup, document the evidence behind each verdict, track remediation and hand off tasks among the five perspectives. A client label organizes assessments within the same browser workspace. It provides no access control. A printable executive view and Markdown report support delivery to business customers.
Restore treats every uploaded file as untrusted data: bounded, versioned, allowlisted validation before preview, and fresh IDs for additive copies. The write must be one transaction, preserving existing records and rolling back on errors. Existing single-assessment exports should remain recoverable when they pass the same validation. Imported notes remain unverified analyst statements.
Confirmation requires a reviewer label, source reference/revision, prerequisites, mitigations and validation method. These fields attest to work done outside the app; they do not authenticate reviewers or validate exploitation. Remediation tracking records owner, due date, status and retest notes. Role handoff notes record decisions without launching agents or live tests.
Code nomination should reduce comment/string false positives and recognize bounded multiline subprocess calls and common imports. It remains a limited lexical check, without Python execution, full parsing, taint tracking or security certification. Named positive and negative fixtures provide inspectable detection evidence.
Actual Chromium IndexedDB tests should check concurrent updates across pages, atomic restore, and error handling. Injected storage failures must be labeled as simulations, not real disk exhaustion. The interface should retain keyboard focus after review, support next-unresolved navigation, expose severity/verdict filters, and make records readable on narrow screens.
Builder decisions: no additional runtime dependency; additive copies rather than replacing IDs; client label defaults to Unassigned; same global limit of 100 records and 200 history entries. New metadata can be exported and must be treated as potentially sensitive. Publication remains a separate operation from source implementation.1234567891011121314151617# Analyst reliability release
The owner approved implementing the five reproduced review findings and the three proposed service features, then pushing the finished release. Preserve the free static architecture, no Docker, browser-local persistence, Interval identity, and honest analyst-attestation language.
Protect a finding from stale saves with optimistic revision checks in its actual IndexedDB transaction. A conflict leaves newer stored fields and the user's unsaved form intact. Closing a changed review requires a discard decision. Refreshing the register must keep client selection, visible records and backup scope consistent.
Unattributed failed-login events must not claim shared actor/source identity. Report calculations must separate unresolved validation, rejected candidates and confirmed remediation work. Sharing one summary function avoids independent counting rules.
An analyst can add a scoped manual finding when the limited automatic rules do not nominate it. New manual findings are unresolved and low confidence, carry an origin label, respect existing field/finding/history limits, and use the same review requirements as automatic candidates. Evidence can contain sensitive information; redaction remains best effort.
A remediation queue shows only confirmed findings with ownership, date and state, with owner/status/overdue controls. Calendar comparisons use UTC dates and label that convention. Rejected candidates do not become action items automatically.
Report snapshots capture sanitized report data without other snapshots, a local sequence number, creation time, source revision and SHA-256 of canonical data. Save at most three per assessment. Later finding edits cannot alter captured content through application operations. A digest detects corruption when compared with an independent expected value; it cannot authenticate a reviewer or stop an owner of the browser/profile from rewriting local data. Render snapshots via the existing text/escaped-Markdown paths, never as imported HTML.
Backup version 2 carries optional revisions, origin and snapshots; legacy version 1 and single-assessment exports remain supported. Preview checks schema and limits; restore also checks digests before starting its atomic batch. Current assessment/finding IDs become fresh copies while captured historical report IDs remain historical. Imported claims remain unverified attestations.
Review and verify each change with regressions, actual Chromium workflows, malformed/tampered import checks, and desktop/mobile/print inspection. Publish allowlisted source only after integrated checks pass. Keep the previous source ZIP locally as a rollback reference; do not upload records or browser profiles.9 unmodified lines101112131415161718192021186 unmodified lines208209210211212213210 unmodified lines4244254264274289 unmodified linesNapolean · Cyber Command</title><link href="./static/favicon.svg" rel="icon" type="image/svg+xml"/><link href="./static/style.css" rel="stylesheet"/><script defer="" src="./static/playbooks.js"></script><script defer="" src="./static/local.js"></script><script defer="" src="./static/app.js"></script></head><body>186 unmodified lines<form autocomplete="off" id="verdict-form"><p class="error-inline" hidden="" id="verdict-form-error" role="alert"></p><label for="verdict">Analyst verdict</label>210 unmodified lines</dialog><section aria-label="Executive assessment report" id="print-report"></section></body></html>9 unmodified lines101112131415161718192021186 unmodified lines208209210211212213214215216210 unmodified lines4274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035049 unmodified linesNapolean · Cyber Command</title><link href="./static/favicon.svg" rel="icon" type="image/svg+xml"/><link href="./static/style.css?v=20261102-analyst" rel="stylesheet"/><script defer="" src="./static/playbooks.js?v=20261102-analyst"></script><script defer="" src="./static/local.js?v=20261102-analyst"></script><script defer="" src="./static/app.js?v=20261102-analyst"></script></head><body>186 unmodified lines<form autocomplete="off" id="verdict-form"><p class="error-inline" hidden="" id="verdict-form-error" role="alert"></p><button hidden="" id="reload-finding" type="button">Reload latest finding</button><label for="verdict">Analyst verdict</label>210 unmodified lines</dialog><section aria-label="Executive assessment report" id="print-report"></section><dialog aria-labelledby="manual-title" id="manual-dialog"><form id="manual-form"><div class="dialog-head"><h2 id="manual-title">Add analyst finding</h2><button aria-label="Close manual finding" class="close" data-close="" type="button">×</button></div><p class="error-inline" hidden="" role="alert"></p><p class="fine">Records a bounded analyst candidate. New findings are always unresolved with low confidence; no code is executed.</p><label for="manual-title-input">Finding title</label><input id="manual-title-input" maxlength="500" name="title" required=""/><label for="manual-severity">Severity</label><select id="manual-severity" name="severity"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option></select><div id="manual-fields"><label for="manual-location">Location / source revision</label><textarea id="manual-location" maxlength="4000" name="location" required="" rows="2"></textarea><label for="manual-root_cause">Root cause</label><textarea id="manual-root_cause" maxlength="4000" name="root_cause" required="" rows="2"></textarea><label for="manual-input_to_impact">Input-to-impact path</label><textarea id="manual-input_to_impact" maxlength="4000" name="input_to_impact" required="" rows="2"></textarea><label for="manual-prerequisites">Prerequisites</label><textarea id="manual-prerequisites" maxlength="4000" name="prerequisites" required="" rows="2"></textarea><label for="manual-mitigations">Mitigations inspected</label><textarea id="manual-mitigations" maxlength="4000" name="mitigations" required="" rows="2"></textarea><label for="manual-evidence">Supporting evidence</label><textarea id="manual-evidence" maxlength="4000" name="evidence" required="" rows="2"></textarea><label for="manual-remediation">Recommended remediation</label><textarea id="manual-remediation" maxlength="4000" name="remediation" required="" rows="2"></textarea></div><div class="dialog-actions"><button data-close="" type="button">Cancel</button><button class="primary" type="submit">Add unresolved finding ↗</button></div></form></dialog></body></html>
55 unmodified lines565758596061626364656667685 unmodified lines7475767778798052 unmodified lines13313413513613713867 unmodified lines2062072082092102112127 unmodified lines2202212222232242252268 unmodified lines2352362372382392402412422432 unmodified lines24624724824925025177 unmodified lines32933033133233333437 unmodified lines37237337437537637737862 unmodified lines4414424434444454464474484494504514524534549 unmodified lines46446546646746846947076 unmodified lines54754854955055155255356 unmodified lines6106116126136146156166172 unmodified lines62062162262362462562622 unmodified lines64965065165255 unmodified linesinline.hidden = true;inline.textContent = '';}const buttons = [...form.querySelectorAll('button')];buttons.forEach(b => b.disabled = true);form.setAttribute('aria-busy', 'true');try {await fn();}catch (error) {if (inline && !form.closest('[hidden]') && (!form.closest('dialog') || form.closest('dialog').open)) {inline.textContent = error.message;inline.hidden = false;5 unmodified lines}}finally {buttons.forEach(b => b.disabled = false);form.removeAttribute('aria-busy');}}52 unmodified lines}function renderOverview() {const view = $('#view');view.replaceChildren();append(view, heading('COMMAND CENTER / OVERVIEW', 'Your security work, in evidence.', 'Scope a review. Challenge the findings. Record the decision.', button('+ New assessment', openCreate, 'primary')), strip());const title = el('div', undefined, 'section-title');67 unmodified linesview.replaceChildren(button('← Assessment register', loadOverview, 'text-button back'));append(view, heading(`${workflows[a.workflow] || a.workflow} / ${date(a.created_at)}`, a.name, `${a.client || 'Unassigned'} / ${a.scope}`), strip(a.roles));const actions = el('div', undefined, 'detail-actions');append(actions, button('↓ Export JSON', () => download('json')), button('↓ Export Markdown', () => download('markdown')), button('Print executive report', printReport), button('Record handoff', openHandoff), button('Delete assessment', () => $('#delete-dialog').showModal(), 'text-button'));view.append(actions);const stats = el('div', undefined, 'stats');[['Candidates', a.findings.length], ['Awaiting decision', a.findings.filter(f => f.verdict === 'unresolved').length], ['Perspectives assigned', a.roles.length]].forEach(([label, value]) => {7 unmodified linesconst panel = el('section');panel.id = 'assessment-panel';panel.setAttribute('role', 'tabpanel');[['ledger', 'Evidence ledger'], ['missions', 'Missions'], ['coverage', 'Coverage & activity']].forEach(([key, label]) => {const node = button(label, () => {state.tab = key;renderAssessment();8 unmodified linestabs.addEventListener('keydown', event => {if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;event.preventDefault();const keys = ['ledger', 'missions', 'coverage'];const index = keys.indexOf(state.tab);state.tab = keys[event.key === 'Home' ? 0 : event.key === 'End' ? 2 : (index + (event.key === 'ArrowRight' ? 1 : 2)) % 3];renderAssessment();$(`#tab-${state.tab}`).focus();});2 unmodified lines});append(view, tabs, panel);if (state.tab === 'ledger') renderLedger(panel, a);if (state.tab === 'missions') a.missions.forEach(m => {const article = el('article', undefined, 'mission');const head = el('div', undefined, 'mission-header');77 unmodified linesreturn String(value || 'None recorded.');}function openFinding(f) {state.finding = f;const body = $('#finding-body');body.replaceChildren(el('h2', f.title), el('p', `${f.severity.toUpperCase()} SEVERITY / ${f.confidence.toUpperCase()} CONFIDENCE`, 'eyebrow'));37 unmodified linesloadOverview();});$('#nav-new').addEventListener('click', openCreate);document.querySelectorAll('[data-close]').forEach(b => b.addEventListener('click', () => b.closest('dialog').close()));$('#create-dialog').addEventListener('close', () => $('#nav-new').classList.remove('active'));const help = {code: ['Python source', 'Paste a Python snippet for limited text-pattern checks. This is not a Python parser or data-flow analysis. Input is never executed.'], alerts: ['Alert events / JSON array', 'Use up to 500 JSON objects with event, actor, and optional source_ip. Supported signals: repeated login_failed, privilege_change, malware_detected.'], exercise: ['Exercise scenario', 'Describe the business, assets, constraints, and scenario. The workbench creates bounded mission plans; it does not simulate an attack.']62 unmodified linesbusy(event.currentTarget, async () => {state.assessment = (await api(`/api/assessments/${encodeURIComponent(state.assessment.id)}/findings/${encodeURIComponent(state.finding.id)}`, {method: 'PATCH', body: JSON.stringify({verdict: $('#verdict').value, note, review: fieldValues(reviewFields), tracking: fieldValues(trackingFields)})})).assessment;const savedId = state.finding.id;$('#finding-dialog').close();renderAssessment();const target = [...document.querySelectorAll('[data-finding]')].find(node => node.dataset.finding === savedId);(target || $('#tab-ledger')).focus();notify('Analyst decision recorded.');});});9 unmodified linesconst draft = $('#client').value.trim() || $('#assessment-name').value.trim() || $('#scope').value.trim() || $('#content').value.trim();const noteChanged = $('#finding-dialog').open && state.finding && reviewSnapshot() !== state.originalReview;const handoffDraft = $('#handoff-dialog').open && $('#handoff-note').value.trim();if (draft || noteChanged || handoffDraft) {event.preventDefault();event.returnValue = '';}76 unmodified linesif (sequence !== previewSequence) return;state.restoreText = text;const clientLabels = (preview.clients || []).slice(0, 15).join(', ');$('#restore-preview').textContent = `${preview.count} assessment copies will be added. Clients: ${clientLabels || 'Unassigned'}${(preview.clients || []).length > 15 ? '…' : ''}. Existing records remain unchanged.`;$('#restore-form .error-inline').hidden = true;$('#restore-submit').disabled = false;} catch (error) {56 unmodified linesopenFinding(next);$('#finding-dialog').scrollTop = 0;});function printReport() {const a = state.assessment;const report = $('#print-report');const reportLogo = el('img', undefined, 'report-logo');reportLogo.src = new URL('logo-print.svg', $('.brand-logo').src).href;2 unmodified linesreportLogo.height = 80;report.replaceChildren(reportLogo, el('p', 'CLIENT ASSESSMENT', 'eyebrow'), el('h1', a.name));append(report, el('p', `Client: ${a.client || 'Unassigned'} · Scope: ${a.scope}`), el('p', `Assessment: ${a.id} · Created: ${date(a.created_at)} · Report: ${date(new Date().toISOString())}`));const counts = ['unresolved', 'confirmed-static', 'confirmed-runtime', 'rejected'].map(verdict => `${verdict}: ${a.findings.filter(f => f.verdict === verdict).length}`).join(' / ');append(report, el('h2', 'Executive summary'), el('p', counts), el('p', 'Verdicts and reviewer labels are analyst attestations. They are not independently verified evidence, verified identities, or a security certification. Pattern checks do not execute source or prove exploitability. Remediation status is analyst-maintained.'));const groups = [ ['Confirmed findings', f => f.verdict.startsWith('confirmed-')], ['Unresolved candidates', f => f.verdict === 'unresolved'], ['Rejected candidates', f => f.verdict === 'rejected'] ];groups.forEach(([title, test]) => {22 unmodified linesa.activity.forEach(item => report.append(el('p', `${item.at} · ${item.action}: ${item.note}`)));window.print();}loadOverview();55 unmodified lines5657585960616263646566676869705 unmodified lines7677787980818252 unmodified lines13513613713813914014167 unmodified lines2092102112122132142157 unmodified lines2232242252262272282298 unmodified lines2382392402412422432442452462 unmodified lines24925025125225325425525677 unmodified lines33433533633733833934037 unmodified lines37837938038138238338438538638738838939039139239339439539639739839962 unmodified lines4624634644654664674684694704714724734744759 unmodified lines48548648748848949049149276 unmodified lines56957057157257357457556 unmodified lines6326336346356366376386392 unmodified lines64264364464564664764864965022 unmodified lines67367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482555 unmodified linesinline.hidden = true;inline.textContent = '';}const controls = [...form.querySelectorAll('button, input, select, textarea')];const disabledStates = controls.map(control => control.disabled);controls.forEach(control => { control.disabled = true; });form.setAttribute('aria-busy', 'true');try {await fn();}catch (error) {if (error.code === 'CONFLICT' && form.id === 'verdict-form') $('#reload-finding').hidden = false;if (inline && !form.closest('[hidden]') && (!form.closest('dialog') || form.closest('dialog').open)) {inline.textContent = error.message;inline.hidden = false;5 unmodified lines}}finally {controls.forEach((control, index) => { control.disabled = disabledStates[index]; });form.removeAttribute('aria-busy');}}52 unmodified lines}function renderOverview() {const view = $('#view');if (state.client && !state.assessments.some(a => (a.client || 'Unassigned') === state.client)) state.client = '';view.replaceChildren();append(view, heading('COMMAND CENTER / OVERVIEW', 'Your security work, in evidence.', 'Scope a review. Challenge the findings. Record the decision.', button('+ New assessment', openCreate, 'primary')), strip());const title = el('div', undefined, 'section-title');67 unmodified linesview.replaceChildren(button('← Assessment register', loadOverview, 'text-button back'));append(view, heading(`${workflows[a.workflow] || a.workflow} / ${date(a.created_at)}`, a.name, `${a.client || 'Unassigned'} / ${a.scope}`), strip(a.roles));const actions = el('div', undefined, 'detail-actions');append(actions, button('↓ Export JSON', () => download('json')), button('↓ Export Markdown', () => download('markdown')), button('Print executive report', () => printReport()), button('Add analyst finding', openManual), button('Record handoff', openHandoff), button('Delete assessment', () => $('#delete-dialog').showModal(), 'text-button'));view.append(actions);const stats = el('div', undefined, 'stats');[['Candidates', a.findings.length], ['Awaiting decision', a.findings.filter(f => f.verdict === 'unresolved').length], ['Perspectives assigned', a.roles.length]].forEach(([label, value]) => {7 unmodified linesconst panel = el('section');panel.id = 'assessment-panel';panel.setAttribute('role', 'tabpanel');[['ledger', 'Evidence ledger'], ['queue', 'Remediation'], ['reports', 'Reports'], ['missions', 'Missions'], ['coverage', 'Coverage & activity']].forEach(([key, label]) => {const node = button(label, () => {state.tab = key;renderAssessment();8 unmodified linestabs.addEventListener('keydown', event => {if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;event.preventDefault();const keys = ['ledger', 'queue', 'reports', 'missions', 'coverage'];const index = keys.indexOf(state.tab);state.tab = keys[event.key === 'Home' ? 0 : event.key === 'End' ? keys.length - 1 : (index + (event.key === 'ArrowRight' ? 1 : keys.length - 1)) % keys.length];renderAssessment();$(`#tab-${state.tab}`).focus();});2 unmodified lines});append(view, tabs, panel);if (state.tab === 'ledger') renderLedger(panel, a);if (state.tab === 'queue') renderQueue(panel, a);if (state.tab === 'reports') renderReports(panel, a);if (state.tab === 'missions') a.missions.forEach(m => {const article = el('article', undefined, 'mission');const head = el('div', undefined, 'mission-header');77 unmodified linesreturn String(value || 'None recorded.');}function openFinding(f) {clearFindingError();state.finding = f;const body = $('#finding-body');body.replaceChildren(el('h2', f.title), el('p', `${f.severity.toUpperCase()} SEVERITY / ${f.confidence.toUpperCase()} CONFIDENCE`, 'eyebrow'));37 unmodified linesloadOverview();});$('#nav-new').addEventListener('click', openCreate);document.querySelectorAll('[data-close]').forEach(b => b.addEventListener('click', () => {const dialog = b.closest('dialog');if (dialog.id === 'finding-dialog' && !allowFindingDiscard()) return;if (dialog.id === 'manual-dialog' && !allowManualDiscard()) return;if (dialog.id === 'handoff-dialog' && !allowHandoffDiscard()) return;dialog.close();}));$('#finding-dialog').addEventListener('cancel', event => {if (!allowFindingDiscard()) event.preventDefault();});$('#manual-dialog').addEventListener('cancel', event => {if (!allowManualDiscard()) event.preventDefault();});$('#handoff-dialog').addEventListener('cancel', event => {if (!allowHandoffDiscard()) event.preventDefault();});$('#create-dialog').addEventListener('close', () => $('#nav-new').classList.remove('active'));const help = {code: ['Python source', 'Paste a Python snippet for limited text-pattern checks. This is not a Python parser or data-flow analysis. Input is never executed.'], alerts: ['Alert events / JSON array', 'Use up to 500 JSON objects with event, actor, and optional source_ip. Supported signals: repeated login_failed, privilege_change, malware_detected.'], exercise: ['Exercise scenario', 'Describe the business, assets, constraints, and scenario. The workbench creates bounded mission plans; it does not simulate an attack.']62 unmodified linesbusy(event.currentTarget, async () => {state.assessment = (await api(`/api/assessments/${encodeURIComponent(state.assessment.id)}/findings/${encodeURIComponent(state.finding.id)}`, {method: 'PATCH', body: JSON.stringify({expected_revision: state.finding.revision || 0, verdict: $('#verdict').value, note, review: fieldValues(reviewFields), tracking: fieldValues(trackingFields)})})).assessment;const savedId = state.finding.id;$('#finding-dialog').close();renderAssessment();const target = [...document.querySelectorAll('[data-finding]')].find(node => node.dataset.finding === savedId);(target || $(`#tab-${state.tab}`)).focus();notify('Analyst decision recorded.');});});9 unmodified linesconst draft = $('#client').value.trim() || $('#assessment-name').value.trim() || $('#scope').value.trim() || $('#content').value.trim();const noteChanged = $('#finding-dialog').open && state.finding && reviewSnapshot() !== state.originalReview;const handoffDraft = $('#handoff-dialog').open && $('#handoff-note').value.trim();const manualDraft = $('#manual-dialog').open && manualSnapshot() !== state.manualOriginal;if (draft || noteChanged || handoffDraft || manualDraft) {event.preventDefault();event.returnValue = '';}76 unmodified linesif (sequence !== previewSequence) return;state.restoreText = text;const clientLabels = (preview.clients || []).slice(0, 15).join(', ');$('#restore-preview').textContent = `${preview.count} assessment copies will be added. Clients: ${clientLabels || 'Unassigned'}${(preview.clients || []).length > 15 ? '…' : ''}. Existing records remain unchanged. Snapshot digests are checked during restore. This preview does not verify analyst identity or authenticate evidence.`;$('#restore-form .error-inline').hidden = true;$('#restore-submit').disabled = false;} catch (error) {56 unmodified linesopenFinding(next);$('#finding-dialog').scrollTop = 0;});function printReport(data = state.assessment, snapshot = null) {const a = data;const report = $('#print-report');const reportLogo = el('img', undefined, 'report-logo');reportLogo.src = new URL('logo-print.svg', $('.brand-logo').src).href;2 unmodified linesreportLogo.height = 80;report.replaceChildren(reportLogo, el('p', 'CLIENT ASSESSMENT', 'eyebrow'), el('h1', a.name));append(report, el('p', `Client: ${a.client || 'Unassigned'} · Scope: ${a.scope}`), el('p', `Assessment: ${a.id} · Created: ${date(a.created_at)} · Report: ${date(new Date().toISOString())}`));const totals = CyberLocal.summarize(a);const counts = `Unresolved validation: ${totals.unresolved} / Confirmed static: ${totals.confirmed_static} / Confirmed runtime: ${totals.confirmed_runtime} / Rejected: ${totals.rejected} / Open remediation: ${totals.open_remediation}`;if (snapshot) report.append(el('p', `Frozen report v${snapshot.version} · ${snapshot.created_at} · Source revision ${snapshot.source_revision} · SHA-256 ${snapshot.sha256}. Digest detects corruption; it does not authenticate identity or evidence.`));append(report, el('h2', 'Executive summary'), el('p', counts), el('p', 'Verdicts and reviewer labels are analyst attestations. They are not independently verified evidence, verified identities, or a security certification. Pattern checks do not execute source or prove exploitability. Remediation status is analyst-maintained.'));const groups = [ ['Confirmed findings', f => f.verdict.startsWith('confirmed-')], ['Unresolved candidates', f => f.verdict === 'unresolved'], ['Rejected candidates', f => f.verdict === 'rejected'] ];groups.forEach(([title, test]) => {22 unmodified linesa.activity.forEach(item => report.append(el('p', `${item.at} · ${item.action}: ${item.note}`)));window.print();}function clearFindingError() {const error = $('#verdict-form .error-inline');error.hidden = true;error.textContent = '';$('#reload-finding').hidden = true;}function allowFindingDiscard() {return !state.finding || reviewSnapshot() === state.originalReview || window.confirm('Discard unsaved changes to this finding?');}$('#reload-finding').addEventListener('click', async () => {if (!window.confirm('Reload the latest saved finding and discard your unsaved changes?')) return;let reloaded = false;await busy($('#verdict-form'), async () => {const id = state.finding.id;const current = (await api(`/api/assessments/${state.assessment.id}`)).assessment;const finding = current.findings.find(f => f.id === id);if (!finding) throw new Error('This finding no longer exists. Close the dialog and refresh the register.');state.assessment = current;renderAssessment();openFinding(finding);reloaded = true;notify('Latest saved finding loaded.');});if (reloaded) $('#verdict').focus();});const manualFields = ['location', 'root_cause', 'input_to_impact', 'prerequisites', 'mitigations', 'evidence', 'remediation'];function manualSnapshot() {return JSON.stringify({ title: $('#manual-title-input').value, severity: $('#manual-severity').value, fields: manualFields.map(key => $(`#manual-${key}`).value) });}function allowManualDiscard() {return manualSnapshot() === state.manualOriginal || window.confirm('Discard unsaved analyst finding evidence?');}function allowHandoffDiscard() {return !$('#handoff-note').value.trim() || window.confirm('Discard the unsaved role handoff note?');}function openManual() {$('#manual-form').reset();state.manualOriginal = manualSnapshot();$('#manual-form .error-inline').hidden = true;$('#manual-dialog').showModal();$('#manual-title-input').focus();}$('#manual-form').addEventListener('submit', event => {event.preventDefault();busy(event.currentTarget, async () => {const payload = { title: $('#manual-title-input').value.trim(), severity: $('#manual-severity').value };manualFields.forEach(key => { payload[key] = $(`#manual-${key}`).value.trim(); });state.assessment = (await api(`/api/assessments/${state.assessment.id}/findings`, { method: 'POST', body: JSON.stringify(payload) })).assessment;$('#manual-dialog').close();state.tab = 'ledger';state.ledgerSearch = state.verdict = state.severity = '';renderAssessment();// The successful transaction appends this submission after any concurrent additions.const finding = state.assessment.findings[state.assessment.findings.length - 1];if (finding) openFinding(finding);notify('Analyst candidate added as unresolved / low confidence.');});});function renderQueue(panel, assessment) {const totals = CyberLocal.summarize(assessment);append(panel, heading('CONFIRMED FINDINGS ONLY', 'Remediation queue', `${totals.open_remediation} open remediation items. Unresolved candidates require validation before remediation tracking.`));const confirmed = assessment.findings.filter(f => f.verdict === 'confirmed-static' || f.verdict === 'confirmed-runtime');const toolbar = el('div', undefined, 'toolbar');const owners = [...new Set(confirmed.map(f => (f.tracking || {}).owner || ''))].sort();const owner = selectControl('Filter remediation by owner', [['', 'All owners'], ...owners.map(value => [JSON.stringify(value), value || 'Unassigned owner'])]);const status = selectControl('Filter remediation by status', [['', 'All statuses'], ...['open', 'in-progress', 'resolved', 'retest'].map(value => [value, value])]);const label = el('label', undefined, 'inline-check');const overdue = el('input');overdue.type = 'checkbox';overdue.id = 'queue-overdue';append(label, overdue, el('span', 'Overdue only (UTC)'));const count = el('span', '', 'count');append(toolbar, owner, status, label, count);const wrap = el('div', undefined, 'table-wrap');append(panel, toolbar, wrap);function draw() {const today = new Date().toISOString().slice(0, 10);const rows = confirmed.filter(f => {const t = f.tracking || {};return (!owner.value || (t.owner || '') === JSON.parse(owner.value))&& (!status.value || (t.status || 'open') === status.value)&& (!overdue.checked || (t.due_date && t.due_date < today && t.status !== 'resolved'));});count.textContent = `${rows.length} confirmed items`;const table = el('table');const head = el('tr');const labels = ['Finding', 'Owner', 'Due date (UTC)', 'Status'];labels.forEach(text => head.append(el('th', text)));table.append(append(el('thead'), head));const body = el('tbody');rows.forEach(f => {const t = f.tracking || {};const row = el('tr');const identity = el('td');const link = button(f.title, () => openFinding(f), 'row-button');link.dataset.finding = f.id;append(identity, link, el('span', `${f.severity} / ${f.verdict}`, 'subline'));const late = t.due_date && t.due_date < today && t.status !== 'resolved';append(row, identity, el('td', t.owner || 'Unassigned'), el('td', `${t.due_date || 'No target date'}${late ? ' / overdue' : ''}`, 'mono'), el('td', t.status || 'open', 'tag'));labelCells(row, labels);body.append(row);});table.append(body);wrap.replaceChildren(table);if (!rows.length) wrap.append(el('p', 'No confirmed findings match these filters.', 'muted'));}[owner, status, overdue].forEach(control => control.addEventListener('change', draw));draw();}function renderReports(panel, assessment) {append(panel, heading('FROZEN LOCAL RECORDS', 'Report versions', 'Capture the current saved assessment. Later edits do not change a frozen report. Maximum three versions per assessment.'));panel.append(el('p', 'SHA-256 checks detect data corruption. They do not authenticate analyst identity, establish evidence authenticity, or provide tamper-proof signing.', 'fine'));const error = el('p', '', 'error-inline');error.setAttribute('role', 'alert');error.hidden = true;panel.append(error);const create = button('Create frozen report', () => busy(panel, async () => {const result = await CyberLocal.createSnapshot(assessment.id, assessment.revision || 0);state.assessment = result.assessment;renderAssessment();$('#tab-reports').focus();notify(`Frozen report version ${result.snapshot.version} created.`);}), 'primary');create.id = 'create-report';create.disabled = (assessment.snapshots || []).length >= 3;panel.append(create);const snapshots = assessment.snapshots || [];if (!snapshots.length) panel.append(empty('No report versions yet.', 'Create a frozen report after saving analyst decisions and remediation tracking.'));snapshots.forEach(snapshot => {const article = el('article', undefined, 'mission');append(article, el('h3', `Version ${snapshot.version}`), el('p', `${snapshot.created_at} / source revision ${snapshot.source_revision}`, 'mono'), el('p', `SHA-256: ${snapshot.sha256}`, 'snapshot-hash fine'));const actions = el('div', undefined, 'detail-actions');['json', 'markdown'].forEach(format => actions.append(button(`Download v${snapshot.version} ${format === 'json' ? 'JSON' : 'Markdown'}`, async () => {try {const text = await CyberLocal.exportSnapshot(assessment.id, snapshot.id, format);saveText(text, `report-${assessment.id}-v${snapshot.version}.${format === 'json' ? 'json' : 'md'}`, format === 'json' ? 'application/json;charset=utf-8' : 'text/markdown;charset=utf-8');} catch (error) { notify(error.message, true); }})));actions.append(button(`Print version ${snapshot.version}`, async () => {try {await CyberLocal.exportSnapshot(assessment.id, snapshot.id, 'json');printReport(snapshot.data, snapshot);} catch (error) { notify(error.message, true); }}));append(article, actions);panel.append(article);});}loadOverview();
9 unmodified lines101112131415161718192021186 unmodified lines208209210211212213210 unmodified lines4244254264274289 unmodified linesNapolean · Cyber Command</title><link href="./favicon.svg" rel="icon" type="image/svg+xml"/><link href="./style.css" rel="stylesheet"/><script defer="" src="./playbooks.js"></script><script defer="" src="./local.js"></script><script defer="" src="./app.js"></script></head><body>186 unmodified lines<form autocomplete="off" id="verdict-form"><p class="error-inline" hidden="" id="verdict-form-error" role="alert"></p><label for="verdict">Analyst verdict</label>210 unmodified lines</dialog><section aria-label="Executive assessment report" id="print-report"></section></body></html>9 unmodified lines101112131415161718192021186 unmodified lines208209210211212213214215216210 unmodified lines4274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035049 unmodified linesNapolean · Cyber Command</title><link href="./favicon.svg" rel="icon" type="image/svg+xml"/><link href="./style.css?v=20261102-analyst" rel="stylesheet"/><script defer="" src="./playbooks.js?v=20261102-analyst"></script><script defer="" src="./local.js?v=20261102-analyst"></script><script defer="" src="./app.js?v=20261102-analyst"></script></head><body>186 unmodified lines<form autocomplete="off" id="verdict-form"><p class="error-inline" hidden="" id="verdict-form-error" role="alert"></p><button hidden="" id="reload-finding" type="button">Reload latest finding</button><label for="verdict">Analyst verdict</label>210 unmodified lines</dialog><section aria-label="Executive assessment report" id="print-report"></section><dialog aria-labelledby="manual-title" id="manual-dialog"><form id="manual-form"><div class="dialog-head"><h2 id="manual-title">Add analyst finding</h2><button aria-label="Close manual finding" class="close" data-close="" type="button">×</button></div><p class="error-inline" hidden="" role="alert"></p><p class="fine">Records a bounded analyst candidate. New findings are always unresolved with low confidence; no code is executed.</p><label for="manual-title-input">Finding title</label><input id="manual-title-input" maxlength="500" name="title" required=""/><label for="manual-severity">Severity</label><select id="manual-severity" name="severity"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option></select><div id="manual-fields"><label for="manual-location">Location / source revision</label><textarea id="manual-location" maxlength="4000" name="location" required="" rows="2"></textarea><label for="manual-root_cause">Root cause</label><textarea id="manual-root_cause" maxlength="4000" name="root_cause" required="" rows="2"></textarea><label for="manual-input_to_impact">Input-to-impact path</label><textarea id="manual-input_to_impact" maxlength="4000" name="input_to_impact" required="" rows="2"></textarea><label for="manual-prerequisites">Prerequisites</label><textarea id="manual-prerequisites" maxlength="4000" name="prerequisites" required="" rows="2"></textarea><label for="manual-mitigations">Mitigations inspected</label><textarea id="manual-mitigations" maxlength="4000" name="mitigations" required="" rows="2"></textarea><label for="manual-evidence">Supporting evidence</label><textarea id="manual-evidence" maxlength="4000" name="evidence" required="" rows="2"></textarea><label for="manual-remediation">Recommended remediation</label><textarea id="manual-remediation" maxlength="4000" name="remediation" required="" rows="2"></textarea></div><div class="dialog-actions"><button data-close="" type="button">Cancel</button><button class="primary" type="submit">Add unresolved finding ↗</button></div></form></dialog></body></html>
13 unmodified lines14151617181946 unmodified lines6667686970717298 unmodified lines1711721731741751761771781791801811821832 unmodified lines1861871881891901911928 unmodified lines20120220320420520631 unmodified lines23823924024124224324424524624724824925025125225325425525625725822 unmodified lines2812822832842852862872882892902918 unmodified lines30030130230330430530630730830931031131231331431531631731831932012 unmodified lines33333433533633733833934034188 unmodified lines4304314324334344354364374384394404414421 unmodified line4444454464474484494504514524534544554564574584594604614624634644654664674684694708 unmodified lines4794804814824834844854861 unmodified line48848949049149249349449549649749849950050150250350450550650750813 unmodified linesconst TRACKING_FIELDS = ['owner','due_date','status','retest'];const TRACKING_STATUSES = ['open','in-progress','resolved','retest'];const now = () => new Date().toISOString();function id() {if (!root.crypto || !root.crypto.getRandomValues) throw new Error('Secure browser randomness is unavailable; use HTTPS or localhost.');return Array.from(root.crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');46 unmodified lines.replace(/\b(?:hf_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9_-]{16,}|AKIA[A-Z0-9]{16})\b/g, '[REDACTED]');}function finding(title, severity, location, rootCause, evidence, remediation, prerequisites) {return {id:id(), title, severity, confidence:'low', verdict:'unresolved', location,root_cause:rootCause, input_to_impact:'Analyst must trace input control, reachability and business impact.',prerequisites, mitigations:'Not evaluated. Inspect validation, authorization, isolation and compensating controls.',evidence, remediation, review_note:'',review:reviewData(),tracking:trackingData()};98 unmodified linestry { events = JSON.parse(content); } catch (_) { throw new Error('Alerts must be a valid JSON array.'); }if (!Array.isArray(events) || events.length > 500) throw new Error('Alerts must be an array of at most 500 objects.');const counts = new Map();let skipped = 0, privileges = 0, malware = 0;for (const event of events) {object(event);if (Object.keys(event).some(key => !['event','actor','source_ip'].includes(key))) throw new Error('Alert objects accept only event, actor and source_ip fields.');text(event.event, 'Alert event', 100);for (const key of ['actor','source_ip']) if (Object.hasOwn(event,key)) text(event[key], `Alert ${key}`, 200);if (event.event === 'login_failed') {const group = JSON.stringify([event.actor ?? null, event.source_ip ?? null]);counts.set(group, (counts.get(group) || 0) + 1);} else if (event.event === 'privilege_change') privileges++;2 unmodified lines}const findings = [];for (const count of counts.values()) if (count >= 5) findings.push(finding('Repeated failed logins', 'medium', 'Submitted alert batch','At least five login_failed events share actor and source identifiers in this batch.',`${count} matching failures; raw actor/source values omitted.`,'Check event timestamps, duplicates, account ownership, MFA and successful login correlations.','Batch may contain duplicates or unrelated periods; event authenticity is unverified.'));8 unmodified linesreturn {findings:findings.slice(0,100),coverage:['Limited batch correlation of login_failed, privilege_change and malware_detected labels.',`${skipped} event(s) skipped because their labels are unsupported by these local rules.`,`${omitted} candidate(s) omitted beyond the 100-finding limit; high-severity event candidates are prioritized.`,'No live telemetry, event authenticity, timestamp checks, deduplication or malware analysis. Raw logs and actor/source identifiers are discarded.']};31 unmodified lineslimitations:['Planning guidance only; requires a qualified analyst and separate approval for live actions.','No executable agents, scanners, model inference or upstream security tools are running.']};});return {id:id(),name:clean(name,'Name',120,1),client:clientLabel(payload.client),workflow,scope:clean(scope,'Scope',2000,1),created_at:now(),roles:[...roles],findings,missions,scenario_category:category,summary:`${findings.length} unresolved candidate(s) from limited browser-local checks. Human validation required; this is not a security certification.`,coverage,activity:[{at:now(),action:'created',note:'Scope authorization attested; bounded local analysis completed. Raw submission discarded.'}]};}function markdownExport(assessment) {function safe(value) {return String(value).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/[\\`*_{}\[\]()#+.!|>~-]/g,'\\$&').replace(/[\r\n]/g,' ');}const lines = ['# Napolean Cyber Command assessment','',`Name: ${safe(assessment.name)}`,`Scope: ${safe(assessment.scope)}`,`Client: ${safe(assessment.client || 'Unassigned')}`,`Workflow: ${assessment.workflow}`,`Created: ${safe(assessment.created_at)}`,'','## Executive summary',safe(assessment.summary),...VERDICTS.map(verdict=>`${verdict}: ${assessment.findings.filter(item=>item.verdict===verdict).length}`),`High-severity candidates: ${assessment.findings.filter(item=>item.severity==='high').length}`,`Open remediation items: ${assessment.findings.filter(item=>!item.tracking || item.tracking.status!=='resolved').length}`,'Confirmations are analyst attestations, not automated proof. Client labels organize this browser; they do not isolate tenants.','','## Evidence ledger'];for (const item of assessment.findings) {22 unmodified lineslet records;if(Object.hasOwn(parsed,'format')) {checkedObject(parsed,['format','version','records'],'Backup');if(parsed.format!=='napolean-cyber-command' || parsed.version!==1 || !Array.isArray(parsed.records)) throw new Error('Unsupported backup format or version.');records=parsed.records;} else records=[parsed];if(records.length>MAX_RECORDS) throw new Error('Backup exceeds the 100 assessment limit.');return records.map(validateRecord);}function list(value,label,maximum,minimum=0) {if(!Array.isArray(value) || value.length<minimum || value.length>maximum) throw new Error(`${label} must contain ${minimum}–${maximum} entries.`);8 unmodified linesif(typeof value!=='string' || !/^[a-f0-9]{32}$/.test(value)) throw new Error('Invalid record identifier.');return value;}function validateRecord(value) {checkedObject(value,['id','name','client','workflow','scope','created_at','roles','findings','missions','scenario_category','summary','coverage','activity'],'Assessment');if(!['code','alerts','exercise'].includes(value.workflow)) throw new Error('Unsupported workflow in backup.');const roles=list(value.roles,'Roles',5,1).map(role=>{if(!ROLES.includes(role)) throw new Error('Unsupported role in backup.');return role;});if(new Set(roles).size!==roles.length) throw new Error('Duplicate roles in backup.');const findings=list(value.findings,'Findings',100).map(item=>{checkedObject(item,['id','title','severity','confidence','verdict','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note','review','tracking'],'Finding');if(!['high','medium','low'].includes(item.severity) || !['low','medium'].includes(item.confidence) || !VERDICTS.includes(item.verdict)) throw new Error('Unsupported finding enum in backup.');const result={id:recordId(item.id),severity:item.severity,confidence:item.confidence,verdict:item.verdict};for(const key of ['title','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note']) result[key]=clean(item[key],`Finding ${key}`,key==='title'?500:4000,key==='review_note'?0:1);result.review=reviewData(item.review);result.tracking=trackingData(item.tracking);if(result.verdict.startsWith('confirmed-') && !hasReview(result.review)) result.verdict='unresolved';return result;});if(new Set(findings.map(row=>row.id)).size!==findings.length) throw new Error('Duplicate finding IDs in backup.');12 unmodified linescheckedObject(item,['at','action','note'],'Activity');return {at:isoTime(item.at),action:clean(item.action,'Activity action',80,1),note:clean(item.note,'Activity note',8000,1)};});return {id:recordId(value.id),name:clean(value.name,'Name',120,1),client:clientLabel(value.client),workflow:value.workflow,scope:clean(value.scope,'Scope',2000,1),created_at:isoTime(value.created_at),roles,findings,missions,scenario_category:category,summary:clean(value.summary,'Summary',4000,1),coverage:list(value.coverage,'Coverage',20,1).map(row=>clean(row,'Coverage note',4000,1)),activity};}function previewBackup(input) {const records=parseBackup(input);88 unmodified lines}if(method==='POST') return {assessment:await this.store.add(analyze(payload),MAX_RECORDS)};}const match=/^\/api\/assessments\/([a-f0-9]{32})(?:\/findings\/([a-f0-9]{32}))?$/.exec(route);if(!match) throw new Error('Unsupported local workspace route.');const [,assessmentId,findingId]=match;if(method==='GET' && !findingId) {const record=await this.store.get(assessmentId);if(!record) throw new Error('Assessment not found.');return {assessment:{...record,client:record.client || 'Unassigned'}};}if(method==='DELETE' && !findingId) return this.store.delete(assessmentId);if(method==='PATCH' && !findingId) {1 unmodified lineconst from=payload.from,to=payload.to,note=clean(payload.note,'Handoff note',2000,1);if(!ROLES.includes(from)||!ROLES.includes(to)||from===to) throw new Error('Choose two distinct supported roles for the handoff.');const assessment=await this.store.update(assessmentId,record=>{if(!record.roles.includes(from)||!record.roles.includes(to)) throw new Error('Handoff roles must be selected for this assessment.');if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Export this record and start a new assessment.');record.activity.push({at:now(),action:'role_handoff',note:`${from} → ${to}: ${note}`});return record;});return {assessment};}if(method==='PATCH' && findingId) {checkedObject(payload,['verdict','note','review','tracking'],'Finding review');if(!VERDICTS.includes(payload.verdict)) throw new Error('Unsupported finding verdict.');const verdict=payload.verdict,note=clean(payload.note,'Evidence note',4000,verdict==='unresolved'?1:20);const reviewInput=payload.review,trackingInput=payload.tracking;const assessment=await this.store.update(assessmentId, record=>{if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Export this record and start a new assessment.');const target=record.findings.find(f=>f.id===findingId);if(!target) throw new Error('Finding not found.');const review=reviewData(reviewInput,target.review),tracking=trackingData(trackingInput,target.tracking);if(verdict.startsWith('confirmed-')&&!hasReview(review)) throw new Error('Confirmation requires reviewer, reference, prerequisites, mitigations and a substantive method (20+ characters).');target.verdict=verdict;target.review_note=note;target.review=review;target.tracking=tracking;record.activity.push({at:now(),action:'finding_reviewed',note:`${findingId}: ${verdict}. Reviewer: ${review.reviewer || '(unspecified)'}. Reference: ${review.reference || '(unspecified)'}. Analyst evidence: ${note}`});record.summary=`${record.findings.length} candidate(s); ${record.findings.filter(f=>f.verdict==='unresolved').length} unresolved. Verdicts reflect browser-local analyst decisions, not automated proof.`;return record;});return {assessment};8 unmodified linesasync backupText(client) {if(client!==undefined) text(client,'Client filter',120);const rows=await this.store.list();const records=rows.filter(row=>client===undefined || (row.client || 'Unassigned')===client).map(validateRecord);const result=JSON.stringify({format:'napolean-cyber-command',version:1,records},null,2);if(new TextEncoder().encode(result).length>5*1024*1024) throw new Error('Backup exceeds 5 MB. Export a smaller client group or individual assessment.');parseBackup(result);return result;1 unmodified linepreviewBackup(input) {return previewBackup(input);}async restoreBackup(input) {const records=parseBackup(input);for(const record of records) {const replacements=new Map([[record.id,id()]]);record.id=replacements.get(record.id);for(const item of record.findings){const old=item.id;item.id=id();replacements.set(old,item.id);}for(const entry of record.activity) for(const [before,after] of replacements) entry.note=entry.note.replaceAll(before,after);if(record.activity.length<MAX_ACTIVITY) record.activity.push({at:now(),action:'restored',note:'Imported as a new browser-local copy. Legacy confirmations without complete structured evidence were set unresolved; imported evidence is an analyst attestation, not proof.'});record.summary=`${record.findings.length} imported candidate(s); ${record.findings.filter(f=>f.verdict==='unresolved').length} unresolved. Imported claims require analyst review. Legacy confirmations without complete structured evidence were set unresolved. Existing activity history was retained.`;}if(records.length) await this.store.addMany(records,MAX_RECORDS);return {count:records.length};}}let singleton;const service=()=>singleton || (singleton=new LocalService(new IndexedDBStore()));return {analyze,redact,markdownExport,LocalService,IndexedDBStore,previewBackup,request:(path,options)=>service().request(path,options),exportText:(assessmentId,format)=>service().exportText(assessmentId,format),backupText:client=>service().backupText(client),restoreBackup:input=>service().restoreBackup(input)};});13 unmodified lines1415161718192021222324252627282930313233343546 unmodified lines8283848586878898 unmodified lines1871881891901911921931941951961971981992002012022 unmodified lines2052062072082092102118 unmodified lines22022122222322422522622731 unmodified lines25926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828922 unmodified lines3123133143153163173183193203213228 unmodified lines33133233333433533633733833934034134234334434534634734834935035135235335435535635712 unmodified lines37037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441588 unmodified lines5045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355361 unmodified line5385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715728 unmodified lines5815825835845855865875885891 unmodified line59159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165213 unmodified linesconst TRACKING_FIELDS = ['owner','due_date','status','retest'];const TRACKING_STATUSES = ['open','in-progress','resolved','retest'];const now = () => new Date().toISOString();function revision(value=0) {if(!Number.isSafeInteger(value)||value<0) throw new Error('Invalid record revision.');return value;}function advanceRevision(value) {const current=revision(value);if(current===Number.MAX_SAFE_INTEGER) throw new Error('Revision limit reached. Export this record and start a new assessment.');return current+1;}function conflict(message='This finding changed in another view. Reload the latest record before saving again.') {const error=new Error(message);error.code='CONFLICT';return error;}function normalizeRecord(record) {return {...record,client:record.client||'Unassigned',revision:revision(record.revision),snapshots:record.snapshots||[],findings:record.findings.map(item=>({...item,revision:revision(item.revision),origin:item.origin||'heuristic',review:reviewData(item.review),tracking:trackingData(item.tracking)}))};}function id() {if (!root.crypto || !root.crypto.getRandomValues) throw new Error('Secure browser randomness is unavailable; use HTTPS or localhost.');return Array.from(root.crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join('');46 unmodified lines.replace(/\b(?:hf_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9_-]{16,}|AKIA[A-Z0-9]{16})\b/g, '[REDACTED]');}function finding(title, severity, location, rootCause, evidence, remediation, prerequisites) {return {id:id(), title, severity, confidence:'low', verdict:'unresolved', location,revision:0,origin:'heuristic',root_cause:rootCause, input_to_impact:'Analyst must trace input control, reachability and business impact.',prerequisites, mitigations:'Not evaluated. Inspect validation, authorization, isolation and compensating controls.',evidence, remediation, review_note:'',review:reviewData(),tracking:trackingData()};98 unmodified linestry { events = JSON.parse(content); } catch (_) { throw new Error('Alerts must be a valid JSON array.'); }if (!Array.isArray(events) || events.length > 500) throw new Error('Alerts must be an array of at most 500 objects.');const counts = new Map();let skipped = 0, privileges = 0, malware = 0, unattributed = 0, partial = 0;for (const event of events) {object(event);if (Object.keys(event).some(key => !['event','actor','source_ip'].includes(key))) throw new Error('Alert objects accept only event, actor and source_ip fields.');text(event.event, 'Alert event', 100);for (const key of ['actor','source_ip']) if (Object.hasOwn(event,key)) text(event[key], `Alert ${key}`, 200);if (event.event === 'login_failed') {const hasActor=Object.hasOwn(event,'actor'),hasSource=Object.hasOwn(event,'source_ip');if(!hasActor&&!hasSource){unattributed++;continue;}if(!hasActor||!hasSource) partial++;const group = JSON.stringify([event.actor ?? null, event.source_ip ?? null]);counts.set(group, (counts.get(group) || 0) + 1);} else if (event.event === 'privilege_change') privileges++;2 unmodified lines}const findings = [];for (const count of counts.values()) if (count >= 5) findings.push(finding('Repeated failed logins', 'medium', 'Submitted alert batch','At least five login_failed events share their provided actor/source identifiers in this batch; missing identifiers are not inferred.',`${count} matching failures; raw actor/source values omitted.`,'Check event timestamps, duplicates, account ownership, MFA and successful login correlations.','Batch may contain duplicates or unrelated periods; event authenticity is unverified.'));8 unmodified linesreturn {findings:findings.slice(0,100),coverage:['Limited batch correlation of login_failed, privilege_change and malware_detected labels.',`${skipped} event(s) skipped because their labels are unsupported by these local rules.`,`${unattributed} unattributed login_failed event(s) omitted from correlation because both actor and source identifiers are missing.`,`${partial} login_failed event(s) have only one identifier; grouping does not establish a shared identity or source beyond the supplied field.`,`${omitted} candidate(s) omitted beyond the 100-finding limit; high-severity event candidates are prioritized.`,'No live telemetry, event authenticity, timestamp checks, deduplication or malware analysis. Raw logs and actor/source identifiers are discarded.']};31 unmodified lineslimitations:['Planning guidance only; requires a qualified analyst and separate approval for live actions.','No executable agents, scanners, model inference or upstream security tools are running.']};});return {id:id(),name:clean(name,'Name',120,1),client:clientLabel(payload.client),workflow,scope:clean(scope,'Scope',2000,1),created_at:now(),revision:0,snapshots:[],roles:[...roles],findings,missions,scenario_category:category,summary:`${findings.length} unresolved candidate(s) from limited browser-local checks. Human validation required; this is not a security certification.`,coverage,activity:[{at:now(),action:'created',note:'Scope authorization attested; bounded local analysis completed. Raw submission discarded.'}]};}function summarize(assessment) {const result={unresolved:0,confirmed_static:0,confirmed_runtime:0,rejected:0,open_remediation:0};for(const item of assessment.findings) {const key=item.verdict.replaceAll('-','_');if(Object.hasOwn(result,key)) result[key]++;if(['confirmed-static','confirmed-runtime'].includes(item.verdict)&&item.tracking?.status!=='resolved') result.open_remediation++;}return result;}function markdownExport(assessment) {function safe(value) {return String(value).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/[\\`*_{}\[\]()#+.!|>~-]/g,'\\$&').replace(/[\r\n]/g,' ');}const totals=summarize(assessment);const lines = ['# Napolean Cyber Command assessment','',`Name: ${safe(assessment.name)}`,`Scope: ${safe(assessment.scope)}`,`Client: ${safe(assessment.client || 'Unassigned')}`,`Workflow: ${assessment.workflow}`,`Created: ${safe(assessment.created_at)}`,'','## Executive summary',safe(assessment.summary),...VERDICTS.map(verdict=>`${verdict}: ${totals[verdict.replaceAll('-','_')]}`),`High-severity candidates: ${assessment.findings.filter(item=>item.severity==='high').length}`,`Open remediation items: ${totals.open_remediation}`,'Confirmations are analyst attestations, not automated proof. Client labels organize this browser; they do not isolate tenants.','','## Evidence ledger'];for (const item of assessment.findings) {22 unmodified lineslet records;if(Object.hasOwn(parsed,'format')) {checkedObject(parsed,['format','version','records'],'Backup');if(parsed.format!=='napolean-cyber-command' || ![1,2].includes(parsed.version) || !Array.isArray(parsed.records)) throw new Error('Unsupported backup format or version.');records=parsed.records;} else records=[parsed];if(records.length>MAX_RECORDS) throw new Error('Backup exceeds the 100 assessment limit.');return records.map(row=>validateRecord(row));}function list(value,label,maximum,minimum=0) {if(!Array.isArray(value) || value.length<minimum || value.length>maximum) throw new Error(`${label} must contain ${minimum}–${maximum} entries.`);8 unmodified linesif(typeof value!=='string' || !/^[a-f0-9]{32}$/.test(value)) throw new Error('Invalid record identifier.');return value;}function validateRecord(value,options={}) {const fields=['id','name','client','workflow','scope','created_at','revision','roles','findings','missions','scenario_category','summary','coverage','activity'];if(options.allowSnapshots!==false) fields.push('snapshots');checkedObject(value,fields,'Assessment');if(!['code','alerts','exercise'].includes(value.workflow)) throw new Error('Unsupported workflow in backup.');const roles=list(value.roles,'Roles',5,1).map(role=>{if(!ROLES.includes(role)) throw new Error('Unsupported role in backup.');return role;});if(new Set(roles).size!==roles.length) throw new Error('Duplicate roles in backup.');const findings=list(value.findings,'Findings',100).map(item=>{checkedObject(item,['id','title','severity','confidence','verdict','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note','review','tracking','revision','origin'],'Finding');if(!['high','medium','low'].includes(item.severity) || !['low','medium'].includes(item.confidence) || !VERDICTS.includes(item.verdict)) throw new Error('Unsupported finding enum in backup.');if(item.origin!==undefined&&!['heuristic','manual'].includes(item.origin)) throw new Error('Unsupported finding origin.');const result={id:recordId(item.id),severity:item.severity,confidence:item.confidence,verdict:item.verdict,revision:revision(item.revision),origin:item.origin||'heuristic'};for(const key of ['title','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note']) result[key]=clean(item[key],`Finding ${key}`,key==='title'?500:4000,key==='review_note'?0:1);result.review=reviewData(item.review);result.tracking=trackingData(item.tracking);if(result.verdict.startsWith('confirmed-') && !hasReview(result.review)) {if(options.snapshotData) throw new Error('Snapshot confirmations require complete structured evidence. Review legacy attestations before freezing this report.');result.verdict='unresolved';}return result;});if(new Set(findings.map(row=>row.id)).size!==findings.length) throw new Error('Duplicate finding IDs in backup.');12 unmodified linescheckedObject(item,['at','action','note'],'Activity');return {at:isoTime(item.at),action:clean(item.action,'Activity action',80,1),note:clean(item.note,'Activity note',8000,1)};});const result={id:recordId(value.id),name:clean(value.name,'Name',120,1),client:clientLabel(value.client),workflow:value.workflow,scope:clean(value.scope,'Scope',2000,1),created_at:isoTime(value.created_at),revision:revision(value.revision),roles,findings,missions,scenario_category:category,summary:clean(value.summary,'Summary',4000,1),coverage:list(value.coverage,'Coverage',20,1).map(row=>clean(row,'Coverage note',4000,1)),activity};if(options.allowSnapshots!==false) {result.snapshots=list(value.snapshots===undefined?[]:value.snapshots,'Snapshots',3).map((snapshot,index)=>{const checked=validateSnapshot(snapshot);if(checked.version!==index+1) throw new Error('Snapshot versions must form the sequence 1, 2, 3.');return checked;});if(new Set(result.snapshots.map(row=>row.id)).size!==result.snapshots.length) throw new Error('Duplicate snapshot IDs.');}return result;}function validateSnapshot(value) {checkedObject(value,['id','version','created_at','source_revision','sha256','data'],'Snapshot');if(!Number.isSafeInteger(value.version)||value.version<1||value.version>3) throw new Error('Unsupported report snapshot version.');if(typeof value.sha256!=='string'||!/^[a-f0-9]{64}$/.test(value.sha256)) throw new Error('Invalid snapshot SHA-256 digest.');if(!Object.hasOwn(value,'source_revision')||!Number.isSafeInteger(value.source_revision)||value.source_revision<0) throw new Error('Snapshot source revision is required.');if(!Object.hasOwn(object(value.data),'revision')) throw new Error('Captured report revision is required.');const data=validateRecord(value.data,{allowSnapshots:false,snapshotData:true});const source=revision(value.source_revision);if(data.revision!==source) throw new Error('Snapshot source revision does not match its captured report.');return {id:recordId(value.id),version:value.version,created_at:isoTime(value.created_at),source_revision:source,sha256:value.sha256,data};}async function hashData(data) {if(!root.crypto?.subtle) throw new Error('Report snapshots require secure browser SHA-256 support. Use HTTPS or localhost.');const digest=await root.crypto.subtle.digest('SHA-256',new TextEncoder().encode(JSON.stringify(data)));return Array.from(new Uint8Array(digest),byte=>byte.toString(16).padStart(2,'0')).join('');}async function verifySnapshots(records) {for(const record of records) for(const snapshot of record.snapshots||[]) {if(await hashData(snapshot.data)!==snapshot.sha256) throw new Error('Snapshot SHA-256 integrity check failed. Nothing was restored.');}}function recordBackupBytes(record) {const envelope={format:'napolean-cyber-command',version:2,records:[record]};return new TextEncoder().encode(JSON.stringify(envelope,null,2)).length;}function assertRecordSize(record) {if(recordBackupBytes(record)>5*1024*1024) throw new Error('This change would exceed the 5 MB restorable report limit. Export the current report and start a new assessment. Nothing was saved.');}function previewBackup(input) {const records=parseBackup(input);88 unmodified lines}if(method==='POST') return {assessment:await this.store.add(analyze(payload),MAX_RECORDS)};}const manualMatch=/^\/api\/assessments\/([a-f0-9]{32})\/findings$/.exec(route);if(manualMatch&&method==='POST') {const fields=['title','severity','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation'];checkedObject(payload,fields,'Manual finding');if(!['high','medium','low'].includes(payload.severity)) throw new Error('Choose a supported manual finding severity.');const added={id:id(),severity:payload.severity,confidence:'low',verdict:'unresolved',origin:'manual',revision:0,review_note:'',review:reviewData(),tracking:trackingData()};for(const field of fields) if(field!=='severity') added[field]=clean(payload[field],`Manual ${field}`,field==='title'?500:4000,1);const assessment=await this.store.update(manualMatch[1],record=>{record=normalizeRecord(record);if(record.findings.length>=100) throw new Error('Assessment limit: 100 findings. Start a new assessment before adding another.');if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Export this record and start a new assessment.');record.findings.push(added);record.revision=advanceRevision(record.revision);record.activity.push({at:now(),action:'manual_finding_added',note:`${added.id}: ${added.title}. Analyst-entered candidate; unresolved and low confidence.`});record.summary=`${record.findings.length} candidate(s); ${summarize(record).unresolved} unresolved. Manual entries are analyst observations requiring validation.`;assertRecordSize(record);return record;});return {assessment};}const match=/^\/api\/assessments\/([a-f0-9]{32})(?:\/findings\/([a-f0-9]{32}))?$/.exec(route);if(!match) throw new Error('Unsupported local workspace route.');const [,assessmentId,findingId]=match;if(method==='GET' && !findingId) {const record=await this.store.get(assessmentId);if(!record) throw new Error('Assessment not found.');return {assessment:normalizeRecord(record)};}if(method==='DELETE' && !findingId) return this.store.delete(assessmentId);if(method==='PATCH' && !findingId) {1 unmodified lineconst from=payload.from,to=payload.to,note=clean(payload.note,'Handoff note',2000,1);if(!ROLES.includes(from)||!ROLES.includes(to)||from===to) throw new Error('Choose two distinct supported roles for the handoff.');const assessment=await this.store.update(assessmentId,record=>{record=normalizeRecord(record);if(!record.roles.includes(from)||!record.roles.includes(to)) throw new Error('Handoff roles must be selected for this assessment.');if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Export this record and start a new assessment.');record.activity.push({at:now(),action:'role_handoff',note:`${from} → ${to}: ${note}`});record.revision=advanceRevision(record.revision);assertRecordSize(record);return record;});return {assessment};}if(method==='PATCH' && findingId) {checkedObject(payload,['verdict','note','review','tracking','expected_revision'],'Finding review');if(!Number.isSafeInteger(payload.expected_revision)||payload.expected_revision<0) throw conflict('An exact finding revision is required. Reload the latest finding before saving.');if(!VERDICTS.includes(payload.verdict)) throw new Error('Unsupported finding verdict.');const verdict=payload.verdict,expectedRevision=payload.expected_revision,note=clean(payload.note,'Evidence note',4000,verdict==='unresolved'?1:20);const reviewInput=payload.review,trackingInput=payload.tracking;const assessment=await this.store.update(assessmentId, record=>{record=normalizeRecord(record);const target=record.findings.find(f=>f.id===findingId);if(!target) throw new Error('Finding not found.');if(target.revision!==expectedRevision) throw conflict();if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Export this record and start a new assessment.');const review=reviewData(reviewInput,target.review),tracking=trackingData(trackingInput,target.tracking);if(verdict.startsWith('confirmed-')&&!hasReview(review)) throw new Error('Confirmation requires reviewer, reference, prerequisites, mitigations and a substantive method (20+ characters).');target.verdict=verdict;target.review_note=note;target.review=review;target.tracking=tracking;target.revision=advanceRevision(target.revision);record.revision=advanceRevision(record.revision);record.activity.push({at:now(),action:'finding_reviewed',note:`${findingId}: ${verdict}. Reviewer: ${review.reviewer || '(unspecified)'}. Reference: ${review.reference || '(unspecified)'}. Analyst evidence: ${note}`});record.summary=`${record.findings.length} candidate(s); ${record.findings.filter(f=>f.verdict==='unresolved').length} unresolved. Verdicts reflect browser-local analyst decisions, not automated proof.`;assertRecordSize(record);return record;});return {assessment};8 unmodified linesasync backupText(client) {if(client!==undefined) text(client,'Client filter',120);const rows=await this.store.list();const records=rows.filter(row=>client===undefined || (row.client || 'Unassigned')===client).map(row=>validateRecord(row));await verifySnapshots(records);const result=JSON.stringify({format:'napolean-cyber-command',version:2,records},null,2);if(new TextEncoder().encode(result).length>5*1024*1024) throw new Error('Backup exceeds 5 MB. Export a smaller client group or individual assessment.');parseBackup(result);return result;1 unmodified linepreviewBackup(input) {return previewBackup(input);}async restoreBackup(input) {const records=parseBackup(input);await verifySnapshots(records);for(const record of records) {const originalSummary=record.summary,originalHistoryLength=record.activity.length;const replacements=new Map([[record.id,id()]]);record.id=replacements.get(record.id);for(const item of record.findings){const old=item.id;item.id=id();replacements.set(old,item.id);}for(const entry of record.activity) for(const [before,after] of replacements) entry.note=entry.note.replaceAll(before,after);if(record.activity.length<MAX_ACTIVITY) record.activity.push({at:now(),action:'restored',note:'Imported as a new browser-local copy. Legacy confirmations without complete structured evidence were set unresolved; imported evidence is an analyst attestation, not proof.'});record.summary=`${record.findings.length} imported candidate(s); ${record.findings.filter(f=>f.verdict==='unresolved').length} unresolved. Imported claims require analyst review. Legacy confirmations without complete structured evidence were set unresolved. Existing activity history was retained.`;if(recordBackupBytes(record)>5*1024*1024) {// A legitimate export near the limit must remain restorable. New IDs already// distinguish the copy; retain history/summary rather than truncate evidence.record.activity.length=originalHistoryLength;record.summary=originalSummary;}assertRecordSize(record);}if(records.length) await this.store.addMany(records,MAX_RECORDS);return {count:records.length};}async createSnapshot(assessmentId,expected_revision) {if(!Number.isSafeInteger(expected_revision)||expected_revision<0) throw conflict('An exact assessment revision is required. Reload before creating a snapshot.');const {assessment:current}=await this.request('/api/assessments/'+assessmentId);if(current.revision!==expected_revision) throw conflict('This assessment changed. Reload its latest revision before creating a snapshot.');if(current.snapshots.length>=3) throw new Error('Assessment limit: 3 snapshots. Export existing reports before starting a new assessment.');if(current.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries. Snapshot creation was not saved.');const {snapshots:excluded,...base}=current;const data=validateRecord(base,{allowSnapshots:false,snapshotData:true});const snapshot={id:id(),version:current.snapshots.length+1,created_at:now(),source_revision:data.revision,sha256:await hashData(data),data};const assessment=await this.store.update(assessmentId,record=>{record=normalizeRecord(record);if(record.revision!==expected_revision) throw conflict('This assessment changed while its snapshot was prepared. Reload before retrying.');if(record.snapshots.length>=3) throw new Error('Assessment limit: 3 snapshots.');if(record.activity.length>=MAX_ACTIVITY) throw new Error('Assessment limit: 200 activity entries.');record.snapshots=[...record.snapshots,snapshot];record.revision=advanceRevision(record.revision);record.activity.push({at:now(),action:'report_snapshot_created',note:`${snapshot.id}: report version ${snapshot.version}; source revision ${snapshot.source_revision}; SHA-256 ${snapshot.sha256}. Digest detects corruption, not authorship.`});assertRecordSize(record);return record;});return {assessment,snapshot};}async exportSnapshot(assessmentId,snapshotId,format) {if(!['json','markdown'].includes(format)) throw new Error('Snapshot export format must be json or markdown.');const {assessment}=await this.request('/api/assessments/'+assessmentId);const source=assessment.snapshots.find(row=>row.id===snapshotId);if(!source) throw new Error('Report snapshot not found.');const snapshot=validateSnapshot(source);await verifySnapshots([{snapshots:[snapshot]}]);if(format==='json') return JSON.stringify(snapshot,null,2);return `# Frozen report snapshot ${snapshot.version}\n\nCreated: ${snapshot.created_at}\nSource revision: ${snapshot.source_revision}\nSHA-256: ${snapshot.sha256}\nDigest detects corruption, not authentication or authorship.\n\n${markdownExport(snapshot.data)}`;}}let singleton;const service=()=>singleton || (singleton=new LocalService(new IndexedDBStore()));return {analyze,redact,markdownExport,summarize,LocalService,IndexedDBStore,previewBackup,request:(path,options)=>service().request(path,options),exportText:(assessmentId,format)=>service().exportText(assessmentId,format),backupText:client=>service().backupText(client),restoreBackup:input=>service().restoreBackup(input),createSnapshot:(assessmentId,expected_revision)=>service().createSnapshot(assessmentId,expected_revision),exportSnapshot:(assessmentId,snapshotId,format)=>service().exportSnapshot(assessmentId,snapshotId,format)};});
883 unmodified lines884885886883 unmodified lines}#print-report .report-logo { width:210px; height:80px; display:block; margin-bottom:18px; }883 unmodified lines884885886887888889890891892893883 unmodified lines}#print-report .report-logo { width:210px; height:80px; display:block; margin-bottom:18px; }.tabs { overflow-x: auto; white-space: nowrap; }.tab { flex-shrink: 0; }.inline-check { display: flex; align-items: center; gap: 8px; margin: 0; font-size: 12px; }.inline-check input { width: 17px; height: 17px; min-height: 17px; accent-color: #a0a1a7; }.snapshot-hash { overflow-wrap: anywhere; }#reload-finding { margin-bottom: 14px; }
27 unmodified lines2829303132333435363738394014 unmodified lines555657585960616263646566676869707129 unmodified lines10110210310410510610 unmodified lines1171181191201211221231241251269 unmodified lines13613713813914014118 unmodified lines16016116216316416516640 unmodified lines20720820921021121227 unmodified linesbrowser = await chromium.launch({ headless: true, ...(process.env.PLAYWRIGHT_EXECUTABLE_PATH ? { executablePath: process.env.PLAYWRIGHT_EXECUTABLE_PATH } : {}) });const context = await browser.newContext({ serviceWorkers: 'block' });const externalRequests = [];await context.route('**/*', route => {if (!route.request().url().startsWith(origin + '/')) {externalRequests.push(route.request().url());return route.abort();}return route.continue();});const page = await context.newPage();const errors = [];page.on('pageerror', error => errors.push(error.message));14 unmodified linesconst second = await context.newPage();await second.goto(origin);await second.waitForFunction(() => !!globalThis.CyberLocal);const review = (tab, label) => tab.evaluate(async ({ id, fid, label }) => {await CyberLocal.request(`/api/assessments/${id}/findings/${fid}`, { method: 'PATCH', body: {verdict: 'unresolved', note: `${label} independent synthetic evidence review.`}});}, { id: record.id, fid: record.findings[0].id, label });await Promise.all([review(page, 'First tab'), review(second, 'Second tab')]);const reviewed = await page.evaluate(async id => (await CyberLocal.request('/api/assessments/' + id)).assessment, record.id);assert.equal(reviewed.activity.length, 3);assert.match(JSON.stringify(reviewed.activity), /First tab/);assert.match(JSON.stringify(reviewed.activity), /Second tab/);console.log('PASS actual IndexedDB concurrent tabs retain both review events');const duplicateRollback = await page.evaluate(async record => {const store = new CyberLocal.IndexedDBStore();29 unmodified linesassert.equal(denied, true);console.log('PASS storage denial is surfaced (simulated browser policy)');const restore = await page.evaluate(async () => {const before = (await CyberLocal.request('/api/assessments')).assessments;const backup = await CyberLocal.backupText();10 unmodified linesconst copied = await page.evaluate(async original => {const summaries = (await CyberLocal.request('/api/assessments')).assessments;const copy = (await CyberLocal.request('/api/assessments/' + summaries.find(row => row.id !== original.id).id)).assessment;return { original: original.findings.map(row => row.id), copied: copy.findings.map(row => row.id) };}, record);assert.equal(copied.original.length, copied.copied.length);assert.ok(copied.copied.every(id => !copied.original.includes(id)));console.log('PASS versioned backup restores into actual IndexedDB with fresh record IDs');const invalid = await page.evaluate(async () => {9 unmodified linesassert.deepEqual(invalid, { before: 2, after: 2, rejected: true });console.log('PASS whole invalid backup is rejected without mutating actual IndexedDB');await page.reload();await page.getByRole('button', { name: /Backup all clients JSON/ }).waitFor();const downloaded = page.waitForEvent('download');18 unmodified linesreturn row;});let rejected = false;try { await CyberLocal.request(`/api/assessments/${id}/findings/${record.findings[0].id}`, { method: 'PATCH', body: { verdict: 'unresolved', note: 'Synthetic review beyond the history cap.' } }); }catch (_) { rejected = true; }return { rejected, count: (await store.get(id)).activity.length };}, record.id);40 unmodified linesassert.equal(capacityResults.filter(Boolean).length, 1);assert.equal(await page.evaluate(async () => (await CyberLocal.request('/api/assessments')).assessments.length), 100);console.log('PASS actual IndexedDB concurrent tabs enforce the 100-record workspace limit atomically');assert.deepEqual(externalRequests, []);assert.deepEqual(errors, []);console.log('PASS no external network requests or uncaught page errors');27 unmodified lines282930313233343536373839404114 unmodified lines565758596061626364656667686970717273747576777879808182838485868788899029 unmodified lines12012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115210 unmodified lines1631641651661671681691701711721731741759 unmodified lines18518618718818919019119219319419519619719819920020118 unmodified lines22022122222322422522640 unmodified lines26726826927027127227327427527627727827928028128228328428528628728828929029127 unmodified linesbrowser = await chromium.launch({ headless: true, ...(process.env.PLAYWRIGHT_EXECUTABLE_PATH ? { executablePath: process.env.PLAYWRIGHT_EXECUTABLE_PATH } : {}) });const context = await browser.newContext({ serviceWorkers: 'block' });const externalRequests = [];const localRequestsOnly = route => {if (!route.request().url().startsWith(origin + '/')) {externalRequests.push(route.request().url());return route.abort();}return route.continue();};await context.route('**/*', localRequestsOnly);const page = await context.newPage();const errors = [];page.on('pageerror', error => errors.push(error.message));14 unmodified linesconst second = await context.newPage();await second.goto(origin);await second.waitForFunction(() => !!globalThis.CyberLocal);const review = (tab, label) => tab.evaluate(async ({ id, fid, label, revision }) => {try {await CyberLocal.request(`/api/assessments/${id}/findings/${fid}`, { method: 'PATCH', body: {expected_revision: revision, verdict: 'unresolved', note: `${label} independent synthetic evidence review.`,tracking: { owner: label, status: 'resolved', due_date: '2026-12-01', retest: `${label} synthetic retest evidence` }}});return { label, saved: true };} catch (error) { return { label, saved: false, code: error.code }; }}, { id: record.id, fid: record.findings[0].id, label, revision: record.findings[0].revision || 0 });const outcomes = await Promise.all([review(page, 'First tab'), review(second, 'Second tab')]);assert.equal(outcomes.filter(row => row.saved).length, 1);const loser = outcomes.find(row => !row.saved), winner = outcomes.find(row => row.saved);assert.equal(loser.code, 'CONFLICT');const current = await page.evaluate(async id => (await CyberLocal.request('/api/assessments/' + id)).assessment, record.id);assert.equal(current.findings[0].tracking.owner, winner.label);assert.equal(current.findings[0].tracking.status, 'resolved');assert.equal(current.activity.length, 2, 'rejected stale write adds no event');await second.evaluate(async ({ id, fid, label }) => {const fresh = (await CyberLocal.request('/api/assessments/' + id)).assessment.findings.find(row => row.id === fid);await CyberLocal.request(`/api/assessments/${id}/findings/${fid}`, { method: 'PATCH', body: {expected_revision: fresh.revision, verdict: 'unresolved', note: `${label} independent synthetic evidence review after explicit reload.`}});}, { id: record.id, fid: record.findings[0].id, label: loser.label });const reviewed = await page.evaluate(async id => (await CyberLocal.request('/api/assessments/' + id)).assessment, record.id);assert.equal(reviewed.activity.length, 3);assert.match(JSON.stringify(reviewed.activity), /First tab/);assert.match(JSON.stringify(reviewed.activity), /Second tab/);assert.equal(reviewed.findings[0].tracking.owner, winner.label);console.log('PASS actual IndexedDB stale write conflicts, preserves current tracking, and explicit reload/retry retains both notes');const duplicateRollback = await page.evaluate(async record => {const store = new CyberLocal.IndexedDBStore();29 unmodified linesassert.equal(denied, true);console.log('PASS storage denial is surfaced (simulated browser policy)');const snapshots = await page.evaluate(async id => {let assessment = (await CyberLocal.request('/api/assessments/' + id)).assessment;const first = await CyberLocal.createSnapshot(id, assessment.revision || 0);const snapshot = first.snapshot;const frozen = await CyberLocal.exportSnapshot(id, snapshot.id, 'json');assessment = (await CyberLocal.request('/api/assessments/' + id)).assessment;const finding = assessment.findings[0];await CyberLocal.request(`/api/assessments/${id}/findings/${finding.id}`, { method: 'PATCH', body: {expected_revision: finding.revision, verdict: 'unresolved', note: 'Later synthetic evidence must not alter the captured snapshot.'}});const unchanged = frozen === await CyberLocal.exportSnapshot(id, snapshot.id, 'json');for (let index = 0; index < 2; index++) {assessment = (await CyberLocal.request('/api/assessments/' + id)).assessment;await CyberLocal.createSnapshot(id, assessment.revision);}assessment = (await CyberLocal.request('/api/assessments/' + id)).assessment;let capped = false;try { await CyberLocal.createSnapshot(id, assessment.revision); } catch (_) { capped = true; }return { unchanged, capped, count: assessment.snapshots.length, snapshot, frozen };}, record.id);assert.equal(snapshots.unchanged, true);assert.equal(snapshots.capped, true);assert.equal(snapshots.count, 3);assert.equal(Object.hasOwn(snapshots.snapshot.data, 'snapshots'), false);assert.match(snapshots.snapshot.sha256, /^[a-f0-9]{64}$/);console.log('PASS SHA-256 report snapshots stay frozen after later edits, contain no nested snapshots and enforce the three-snapshot cap');const restore = await page.evaluate(async () => {const before = (await CyberLocal.request('/api/assessments')).assessments;const backup = await CyberLocal.backupText();10 unmodified linesconst copied = await page.evaluate(async original => {const summaries = (await CyberLocal.request('/api/assessments')).assessments;const copy = (await CyberLocal.request('/api/assessments/' + summaries.find(row => row.id !== original.id).id)).assessment;return { original: original.findings.map(row => row.id), copied: copy.findings.map(row => row.id), snapshots: copy.snapshots };}, record);assert.equal(copied.original.length, copied.copied.length);assert.ok(copied.copied.every(id => !copied.original.includes(id)));assert.equal(copied.snapshots[0].id, snapshots.snapshot.id, 'historical snapshot ID stays historical on restore');assert.deepEqual(copied.snapshots[0].data, snapshots.snapshot.data);assert.equal(copied.snapshots[0].sha256, snapshots.snapshot.sha256);console.log('PASS versioned backup restores into actual IndexedDB with fresh record IDs');const invalid = await page.evaluate(async () => {9 unmodified linesassert.deepEqual(invalid, { before: 2, after: 2, rejected: true });console.log('PASS whole invalid backup is rejected without mutating actual IndexedDB');const tampered = await page.evaluate(async () => {const before = (await CyberLocal.request('/api/assessments')).assessments.length;const envelope = JSON.parse(await CyberLocal.backupText());envelope.records[envelope.records.length - 1].snapshots[0].data.name = 'Tampered synthetic snapshot title';let rejected = false;try { await CyberLocal.restoreBackup(JSON.stringify(envelope)); } catch (_) { rejected = true; }return { before, after: (await CyberLocal.request('/api/assessments')).assessments.length, rejected };});assert.deepEqual(tampered, { before: 2, after: 2, rejected: true });console.log('PASS tampered snapshot digest rejects the whole backup before any IndexedDB mutation');await page.reload();await page.getByRole('button', { name: /Backup all clients JSON/ }).waitFor();const downloaded = page.waitForEvent('download');18 unmodified linesreturn row;});let rejected = false;try { await CyberLocal.request(`/api/assessments/${id}/findings/${record.findings[0].id}`, { method: 'PATCH', body: { expected_revision: record.findings[0].revision || 0, verdict: 'unresolved', note: 'Synthetic review beyond the history cap.' } }); }catch (_) { rejected = true; }return { rejected, count: (await store.get(id)).activity.length };}, record.id);40 unmodified linesassert.equal(capacityResults.filter(Boolean).length, 1);assert.equal(await page.evaluate(async () => (await CyberLocal.request('/api/assessments')).assessments.length), 100);console.log('PASS actual IndexedDB concurrent tabs enforce the 100-record workspace limit atomically');const legacyContext = await browser.newContext({ serviceWorkers: 'block' });await legacyContext.route('**/*', localRequestsOnly);const legacyPage = await legacyContext.newPage();legacyPage.on('pageerror', error => errors.push(error.message));await legacyPage.goto(origin);await legacyPage.waitForFunction(() => !!globalThis.CyberLocal);const legacyResult = await legacyPage.evaluate(async source => {const legacy = structuredClone(source);delete legacy.revision; delete legacy.snapshots;for (const finding of legacy.findings) { delete finding.revision; delete finding.origin; }const result = await CyberLocal.restoreBackup(JSON.stringify({ format: 'napolean-cyber-command', version: 1, records: [legacy] }));const rows = (await CyberLocal.request('/api/assessments')).assessments;const restored = (await CyberLocal.request('/api/assessments/' + rows[0].id)).assessment;return { count: result.count, records: rows.length, freshId: restored.id !== source.id, snapshots: restored.snapshots || [] };}, record);assert.deepEqual(legacyResult, { count: 1, records: 1, freshId: true, snapshots: [] });await legacyContext.close();console.log('PASS legacy v1 backup restores into a fresh browser context');assert.deepEqual(externalRequests, []);assert.deepEqual(errors, []);console.log('PASS no external network requests or uncaught page errors');
7 unmodified lines89101112138 unmodified lines222324252627282930312 unmodified lines34353637383940414243444546474849503 unmodified lines545556575859604 unmodified lines656667686970717273747576777 unmodified linesconst context = await browser.newContext({viewport:{width:1440,height:1000}});const page = await context.newPage();const errors=[]; page.on('pageerror',error=>errors.push(error.message));await page.goto(process.env.APP_URL || 'http://127.0.0.1:7860/');await page.getByRole('button',{name:'Create first assessment ↗',exact:true}).click();await page.locator('#assessment-name').fill('Synthetic retailer review');8 unmodified linesawait page.locator('#review-note').fill('Reviewed only against this synthetic owned fixture.');await page.getByRole('button',{name:'Record decision ↗',exact:true}).click();assert.equal(await page.locator('#finding-dialog').evaluate(e=>e.open),true,'incomplete confirmation stays open');for (const [selector,value] of Object.entries({'#reviewer':'Synthetic analyst','#reference':'fixture revision 1','#review-prerequisites':'Caller controls command in the fixture.','#review-mitigations':'No validation in this bounded fixture.','#review-method':'Manual source trace of the synthetic owned fixture.','#tracking-owner':'Fictional application team','#tracking-due':'2026-12-01','#tracking-retest':'Recheck argument-list replacement in owned fixture.'})) await page.locator(selector).fill(value);await page.locator('#tracking-status').selectOption('in-progress');await page.getByRole('button',{name:'Record decision ↗',exact:true}).click();await page.locator('#finding-dialog').waitFor({state:'hidden'});assert.equal(await candidate.evaluate(e=>document.activeElement===e),true,'focus returns to saved candidate');await page.getByRole('combobox',{name:'Filter by verdict'}).selectOption('confirmed-static');assert.equal(await page.locator('tbody tr').count(),1);2 unmodified linesawait page.getByRole('combobox',{name:'Filter by severity'}).selectOption('');await page.getByRole('combobox',{name:'Filter by verdict'}).selectOption('');await candidate.click();await page.locator('#next-unresolved').click();assert.match(await page.locator('#finding-title').innerText(),/dynamic Python/);await page.getByRole('button',{name:'Close finding',exact:true}).click();await page.getByRole('button',{name:'Record handoff',exact:true}).click();await page.locator('#handoff-note').fill('Blue team: verify detection for the bounded shell invocation scenario.');await page.locator('#handoff-form button[type=submit]').click();await page.locator('#handoff-dialog').waitFor({state:'hidden'});await page.getByRole('button',{name:'Print executive report',exact:true}).click();await page.emulateMedia({media:'print'});assert.equal(await page.locator('#print-report').isVisible(),true);assert.match(await page.locator('#print-report').innerText(),/Synthetic analyst|confirmed-static: 1/);await page.emulateMedia({media:'screen'});await page.evaluate(()=>{document.activeElement.blur();window.scrollTo(0,0);});await page.waitForFunction(()=>!document.querySelector('#notice').classList.contains('visible'));3 unmodified linesconst downloadPromise=page.waitForEvent('download');await page.getByRole('button',{name:/Backup.*JSON/}).click();const download=await downloadPromise;const fs=require('node:fs/promises');const backup=await fs.readFile(await download.path(),'utf8');assert.equal(JSON.parse(backup).records.length,1);await page.getByRole('button',{name:'↑ Restore backup',exact:true}).click();4 unmodified linesawait page.locator('#restore-submit').click();await page.locator('#restore-dialog').waitFor({state:'hidden'});assert.equal(await page.locator('tbody tr').count(),2,'restored copy visible beside original');await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true,'mobile page has no horizontal overflow');await page.evaluate(()=>{document.activeElement.blur();window.scrollTo(0,0);});await page.waitForFunction(()=>!document.querySelector('#notice').classList.contains('visible'));if(process.env.ARTIFACT_DIR) await page.screenshot({path:process.env.ARTIFACT_DIR+'/business-mobile.png',fullPage:true});assert.deepEqual(errors,[]);console.log('PASS browser UI: create, incomplete-confirmation guard, structured review, tracking, saved-focus, handoff, print, client backup, restore, mobile overflow, no page errors');await context.close();} finally {await browser.close();}})().catch(error=>{console.error(error);process.exitCode=1;});7 unmodified lines8910111213141516171819202122232425268 unmodified lines35363738394041424344454647484950515253542 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631643 unmodified lines1681691701711721734 unmodified lines1781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162177 unmodified linesconst context = await browser.newContext({viewport:{width:1440,height:1000}});const page = await context.newPage();const errors=[]; page.on('pageerror',error=>errors.push(error.message));async function assertProtectedDraft(dialogId) {const dialog=page.locator(dialogId);const values=()=>dialog.evaluate(root=>Object.fromEntries([...root.querySelectorAll('input,select,textarea')].map(el=>[el.id,el.type==='checkbox'?el.checked:el.value])));const original=await values();for(const action of ['x','close','escape']) {page.once('dialog',prompt=>prompt.dismiss());if(action==='x') await dialog.locator('[data-close]').first().click();else if(action==='close') await dialog.locator('[data-close]').last().click();else await page.keyboard.press('Escape');assert.equal(await dialog.evaluate(el=>el.open),true,`${dialogId} ${action} cancellation stays open`);assert.deepEqual(await values(),original,`${dialogId} ${action} cancellation preserves all draft fields`);}}await page.goto(process.env.APP_URL || 'http://127.0.0.1:7860/');await page.getByRole('button',{name:'Create first assessment ↗',exact:true}).click();await page.locator('#assessment-name').fill('Synthetic retailer review');8 unmodified linesawait page.locator('#review-note').fill('Reviewed only against this synthetic owned fixture.');await page.getByRole('button',{name:'Record decision ↗',exact:true}).click();assert.equal(await page.locator('#finding-dialog').evaluate(e=>e.open),true,'incomplete confirmation stays open');for (const [selector,value] of Object.entries({'#reviewer':'Synthetic analyst','#reference':'fixture revision 1','#review-prerequisites':'Caller controls command in the fixture.','#review-mitigations':'No validation in this bounded fixture.','#review-method':'Manual source trace of the synthetic owned fixture.','#tracking-owner':'Fictional application team','#tracking-due':'2000-01-01','#tracking-retest':'Recheck argument-list replacement in owned fixture.'})) await page.locator(selector).fill(value);await page.locator('#tracking-status').selectOption('in-progress');await page.evaluate(()=>{const original=CyberLocal.request;let release;const gate=new Promise(resolve=>{release=resolve;});CyberLocal.request=(path,options)=>options?.method==='PATCH'?gate.then(()=>original(path,options)):original(path,options);window.__releaseSyntheticWrite=()=>{CyberLocal.request=original;release();};});await page.getByRole('button',{name:'Record decision ↗',exact:true}).click();assert.equal(await page.locator('#verdict-form').evaluate(form=>[...form.querySelectorAll('button,input,select,textarea')].every(control=>control.disabled)),true,'pending save freezes all draft controls (simulated latency)');await page.evaluate(()=>{window.__releaseSyntheticWrite();delete window.__releaseSyntheticWrite;});await page.locator('#finding-dialog').waitFor({state:'hidden'});assert.equal(await page.locator('#review-note').isDisabled(),false,'draft controls become editable after save');assert.equal(await candidate.evaluate(e=>document.activeElement===e),true,'focus returns to saved candidate');await page.getByRole('combobox',{name:'Filter by verdict'}).selectOption('confirmed-static');assert.equal(await page.locator('tbody tr').count(),1);2 unmodified linesawait page.getByRole('combobox',{name:'Filter by severity'}).selectOption('');await page.getByRole('combobox',{name:'Filter by verdict'}).selectOption('');await candidate.click();const second=await context.newPage();second.on('pageerror',error=>errors.push(error.message));await second.goto(process.env.APP_URL || 'http://127.0.0.1:7860/');await second.getByRole('button',{name:'Synthetic retailer review',exact:true}).click();await second.getByRole('button',{name:'Possible shell-enabled process invocation',exact:true}).click();await second.locator('#reviewer').fill('Newer synthetic analyst');await second.locator('#reference').fill('fixture revision 2');await second.locator('#tracking-owner').fill('Newer application team');await second.locator('#tracking-status').selectOption('retest');await second.locator('#review-note').fill('Newer saved synthetic evidence from the second tab.');await second.getByRole('button',{name:'Record decision ↗',exact:true}).click();await second.locator('#finding-dialog').waitFor({state:'hidden'});await page.locator('#review-note').fill('Unsaved stale draft from the first synthetic tab.');const formValues=()=>page.locator('#verdict-form').evaluate(form=>Object.fromEntries([...form.querySelectorAll('input,select,textarea')].map(el=>[el.id,el.value])));const staleDraft=await formValues();await page.getByRole('button',{name:'Record decision ↗',exact:true}).click();await page.locator('#reload-finding').waitFor();assert.deepEqual(await formValues(),staleDraft,'conflicting save preserves every unsaved field');assert.equal(await second.evaluate(async()=>{const a=(await CyberLocal.request('/api/assessments')).assessments[0];return (await CyberLocal.request('/api/assessments/'+a.id)).assessment.findings.find(f=>f.title.includes('shell-enabled')).tracking.owner;}),'Newer application team');page.once('dialog',dialog=>dialog.accept());await page.locator('#reload-finding').click();await page.waitForFunction(()=>document.querySelector('#reviewer').value==='Newer synthetic analyst');assert.equal(await page.locator('#tracking-owner').inputValue(),'Newer application team');await page.getByRole('button',{name:'Close finding',exact:true}).click();await second.close();console.log('PASS stale UI save preserves draft/current tracking until explicit latest-record reload');await candidate.click();for(const [selector,value] of Object.entries({'#review-note':'Unsaved synthetic draft note retained for close checks.','#reviewer':'Unsaved reviewer','#reference':'Unsaved reference','#review-prerequisites':'Unsaved prerequisites','#review-mitigations':'Unsaved mitigation details','#review-method':'Unsaved validation method details long enough.','#tracking-owner':'Unsaved remediation owner','#tracking-due':'2001-01-01','#tracking-retest':'Unsaved synthetic retest details'})) await page.locator(selector).fill(value);await page.locator('#verdict').selectOption('confirmed-runtime');await page.locator('#tracking-status').selectOption('in-progress');const draft=await formValues();for(const action of ['x','close','escape']) {page.once('dialog',dialog=>dialog.dismiss());if(action==='x') await page.getByRole('button',{name:'Close finding',exact:true}).click();else if(action==='close') await page.locator('#finding-dialog').getByRole('button',{name:'Close',exact:true}).click();else await page.keyboard.press('Escape');assert.equal(await page.locator('#finding-dialog').evaluate(el=>el.open),true);assert.deepEqual(await formValues(),draft,`${action} cancellation preserves every draft field`);}page.once('dialog',dialog=>dialog.accept());await page.getByRole('button',{name:'Close finding',exact:true}).click();await page.locator('#finding-dialog').waitFor({state:'hidden'});await candidate.click();assert.equal(await page.locator('#reviewer').inputValue(),'Newer synthetic analyst','accepted discard returns to saved evidence');await page.locator('#next-unresolved').click();assert.match(await page.locator('#finding-title').innerText(),/dynamic Python/);await page.getByRole('button',{name:'Close finding',exact:true}).click();await page.getByRole('button',{name:'Record handoff',exact:true}).click();await page.locator('#handoff-note').fill('Blue team: verify detection for the bounded shell invocation scenario.');await assertProtectedDraft('#handoff-dialog');await page.locator('#handoff-form button[type=submit]').click();await page.locator('#handoff-dialog').waitFor({state:'hidden'});await page.evaluate(async()=>{const a=(await CyberLocal.request('/api/assessments')).assessments[0];const body={title:'Other tab manual finding',severity:'low'};for(const field of ['location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation']) body[field]='Synthetic other tab '+field;await CyberLocal.request(`/api/assessments/${a.id}/findings`,{method:'POST',body});});// The current view is deliberately stale: the new manual entry must open its own result.await page.getByRole('button',{name:'Add analyst finding',exact:true}).click();await page.locator('#manual-title-input').fill('Synthetic manual finding');await page.locator('#manual-severity').selectOption('medium');for(const field of ['location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation']) await page.locator('#manual-'+field).fill('Synthetic owned fixture '+field+' evidence.');await assertProtectedDraft('#manual-dialog');await page.locator('#manual-form button[type=submit]').click();await page.locator('#manual-dialog').waitFor({state:'hidden'});await page.locator('#finding-dialog').waitFor({state:'visible'});assert.equal(await page.locator('#finding-title').innerText(),'Synthetic manual finding');assert.equal(await page.locator('#verdict').inputValue(),'unresolved','manual findings always begin unresolved');await page.locator('#verdict').selectOption('rejected');await page.locator('#review-note').fill('Synthetic candidate rejected after owned fixture review.');await page.getByRole('button',{name:'Record decision ↗',exact:true}).click();await page.locator('#finding-dialog').waitFor({state:'hidden'});await page.locator('#tab-queue').click();assert.equal(await page.locator('#assessment-panel tbody tr').count(),1,'queue contains confirmed findings only');await page.getByRole('combobox',{name:'Filter remediation by owner'}).selectOption({label:'Newer application team'});await page.getByRole('combobox',{name:'Filter remediation by status'}).selectOption('retest');await page.locator('#queue-overdue').check();assert.equal(await page.locator('#assessment-panel tbody tr').count(),1,'UTC overdue confirmed item remains visible');await page.getByRole('combobox',{name:'Filter remediation by status'}).selectOption('resolved');assert.equal(await page.locator('#assessment-panel tbody tr').count(),0);await page.locator('#tab-reports').click();await page.locator('#create-report').click();await page.getByRole('button',{name:'Download v1 JSON',exact:true}).waitFor();const frozenDownload=page.waitForEvent('download');await page.getByRole('button',{name:'Download v1 JSON',exact:true}).click();const frozen=await frozenDownload;const fs=require('node:fs/promises');const frozenText=await fs.readFile(await frozen.path(),'utf8');assert.match(frozenText,/Newer synthetic analyst/);await page.getByRole('button',{name:'Print executive report',exact:true}).click();await page.emulateMedia({media:'print'});assert.equal(await page.locator('#print-report').isVisible(),true);assert.match(await page.locator('#print-report').innerText(),/Newer synthetic analyst|confirmed-static: 1/);assert.match(await page.locator('#print-report').innerText(),/Open remediation(?: items)?: 1\b/,'rejected and unresolved candidates do not inflate remediation total');await page.emulateMedia({media:'screen'});await page.evaluate(()=>{document.activeElement.blur();window.scrollTo(0,0);});await page.waitForFunction(()=>!document.querySelector('#notice').classList.contains('visible'));3 unmodified linesconst downloadPromise=page.waitForEvent('download');await page.getByRole('button',{name:/Backup.*JSON/}).click();const download=await downloadPromise;const backup=await fs.readFile(await download.path(),'utf8');assert.equal(JSON.parse(backup).records.length,1);await page.getByRole('button',{name:'↑ Restore backup',exact:true}).click();4 unmodified linesawait page.locator('#restore-submit').click();await page.locator('#restore-dialog').waitFor({state:'hidden'});assert.equal(await page.locator('tbody tr').count(),2,'restored copy visible beside original');await page.evaluate(async()=>{await CyberLocal.request('/api/assessments',{method:'POST',body:{name:'Other client fixture',client:'Other client',scope:'Owned synthetic fixture',workflow:'exercise',content:'Generic tabletop',roles:['blue'],authorization:true}});});await page.locator('#nav-overview').click();await page.getByRole('combobox',{name:'Filter by client'}).selectOption('Fictional retailer');for(let index=0;index<2;index++) {await page.getByRole('button',{name:'Synthetic retailer review',exact:true}).first().click();await page.getByRole('button',{name:'Delete assessment',exact:true}).click();await page.locator('#confirm-delete').click();await page.locator('#delete-dialog').waitFor({state:'hidden'});await page.getByRole('combobox',{name:'Filter by client'}).waitFor();}assert.equal(await page.getByRole('combobox',{name:'Filter by client'}).inputValue(),'','last filtered client deletion resets visible selection');assert.equal(await page.locator('tbody tr').count(),1);await page.getByRole('button',{name:'Other client fixture',exact:true}).waitFor();assert.match(await page.getByRole('button',{name:/Backup.*JSON/}).innerText(),/all clients/,'backup scope agrees with reset selection');const alertAndReport=await page.evaluate(()=>{const fixture={name:'Synthetic totals',scope:'Owned fixture',workflow:'alerts',roles:['blue'],authorization:true,content:JSON.stringify(Array.from({length:5},()=>({event:'login_failed'})))};const anonymous=CyberLocal.analyze(fixture);const rejected=CyberLocal.analyze({...fixture,workflow:'code',content:'eval(x)'});rejected.findings[0].verdict='rejected';return {anonymous,markdown:CyberLocal.markdownExport(rejected),summary:CyberLocal.summarize(rejected)};});assert.ok(!alertAndReport.anonymous.findings.some(f=>/share actor and source identifiers/.test(f.root_cause)),'missing identity fields never claim shared identity');assert.match(alertAndReport.anonymous.coverage.join(' '),/unattribut|missing.*identif/i);assert.equal(alertAndReport.summary.open_remediation,0);assert.match(alertAndReport.markdown,/Open remediation items: 0/);await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true,'mobile page has no horizontal overflow');await page.evaluate(()=>{document.activeElement.blur();window.scrollTo(0,0);});await page.waitForFunction(()=>!document.querySelector('#notice').classList.contains('visible'));if(process.env.ARTIFACT_DIR) await page.screenshot({path:process.env.ARTIFACT_DIR+'/business-mobile.png',fullPage:true});assert.deepEqual(errors,[]);console.log('PASS browser UI: create, CAS conflict/reload, draft protection Close/X/Escape, structured review, manual finding, confirmed queue, report snapshot, print totals, backup/restore, client reset, anonymous alerts, mobile overflow, no page errors');await context.close();} finally {await browser.close();}})().catch(error=>{console.error(error);process.exitCode=1;});
123456729 unmodified lines37383940414250 unmodified lines939495969798991006 unmodified lines10710810911011111211311411511611711811912012112227 unmodified lines15015115215315415515619 unmodified lines17617717817918018118218318418518618768 unmodified lines25625725825926026126210 unmodified lines2732742752762772782792803 unmodified lines28428528628728828929028 unmodified lines319320321'use strict';const test = require('node:test');const assert = require('node:assert/strict');const {analyze, redact, markdownExport, LocalService, IndexedDBStore, previewBackup} = require('../static/local.js');class MemoryStore {constructor() { this.rows = new Map(); this.chain = Promise.resolve(); }29 unmodified linescontent:'eval(user_input)\nsubprocess.run(command, shell=True)', roles:['red','blue','white','black','purple'], ...changes});const evidence = changes => ({reviewer:'Analyst A',reference:'Owned fixture revision 123',prerequisites:'User-controlled input reaches the reviewed sink.',mitigations:'Reviewed input validation and sandbox boundaries.',method:'Manually traced source to sink in the owned test fixture.',...changes});test('local analysis nominates unresolved candidates without executing source', () => {const result = analyze(payload({content:'eval(user_input)\nsubprocess.run(command, shell=True)\npassword="private-secret-9823"'}));50 unmodified linesassert.deepEqual(await service.request('/api/assessments'),{assessments:[]});const {assessment:a} = await service.request('/api/assessments',{method:'POST',body:JSON.stringify(payload())});const base = '/api/assessments/'+a.id;await assert.rejects(service.request(base+'/findings/'+a.findings[0].id,{method:'PATCH',body:JSON.stringify({verdict:'confirmed-static',note:'yes'})}));const review = await service.request(base+'/findings/'+a.findings[0].id,{method:'PATCH',body:JSON.stringify({verdict:'confirmed-static',note:'Traced taint in the owned test fixture.',review:evidence()})});assert.equal(review.assessment.findings[0].verdict,'confirmed-static');const fresh = new LocalService(store);assert.equal((await fresh.request(base)).assessment.findings[0].verdict,'confirmed-static');6 unmodified linesawait assert.rejects(fresh.request('/api/login',{method:'POST',body:'{}'}));});test('concurrent reviews append atomically and bounded history prevents silent truncation', async () => {const store = new MemoryStore(), service = new LocalService(store);const {assessment:a} = await service.request('/api/assessments',{method:'POST',body:payload()});const path = `/api/assessments/${a.id}/findings/${a.findings[0].id}`;await Promise.all(['First','Second'].map(word => service.request(path,{method:'PATCH',body:{verdict:'unresolved',note:word+' independent evidence review.'}})));const record = (await service.request('/api/assessments/'+a.id)).assessment;assert.equal(record.activity.length,3);assert.match(JSON.stringify(record.activity),/First/); assert.match(JSON.stringify(record.activity),/Second/);await store.update(a.id, row => {row.activity=Array.from({length:200},()=>({at:'x',action:'review',note:'x'})); return row;});await assert.rejects(service.request(path,{method:'PATCH',body:{verdict:'unresolved',note:'One more review'}}),/200/);});test('record count is bounded and storage failure is surfaced instead of apparent success', async () => {27 unmodified linesconst store=new MemoryStore(), service=new LocalService(store), record=analyze(payload());const envelope=records=>JSON.stringify({format:'napolean-cyber-command',version:1,records});for(const input of ['bad','{}','[]',JSON.stringify({format:'other',version:1,records:[]}),JSON.stringify({format:'napolean-cyber-command',version:2,records:[]}),envelope([{...record,content:'Raw source must never enter storage'}]),envelope([record,{...record,roles:['unknown']}]),' '.repeat(5*1024*1024+1)]) {19 unmodified linesconst a=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;const path=`/api/assessments/${a.id}/findings/${a.findings[0].id}`;for(const review of [undefined,evidence({reference:''}),evidence({method:'yes'}),evidence({method:'.'.repeat(30)}),evidence({reviewer:'A'.repeat(121)})]) {await assert.rejects(service.request(path,{method:'PATCH',body:{verdict:'confirmed-static',note:'Verified the owned source and reachable input.',review}}));}for(const tracking of [{due_date:'2026-02-31'},{due_date:'2026-1-1'},{status:'done'},{owner:42}]) {await assert.rejects(service.request(path,{method:'PATCH',body:{verdict:'unresolved',note:'Review in progress.',tracking}}));}const result=await service.request(path,{method:'PATCH',body:{verdict:'confirmed-static',note:'Verified the owned source and reachable input.',review:evidence(),tracking:{owner:'Fix owner',due_date:'2026-12-01',status:'in-progress',retest:'Regression test pending.'}}});assert.equal(result.assessment.findings[0].review.reviewer,'Analyst A');assert.equal(result.assessment.findings[0].tracking.due_date,'2026-12-01');68 unmodified linesconst path=`/api/assessments/${record.id}/findings/${record.findings[0].id}`;for(const update of [{review:evidence({reference:''}),verdict:'confirmed-static'}, {tracking:{due_date:'2027-02-29'},verdict:'unresolved'},{tracking:{retest:3},verdict:'unresolved'},{review:evidence({method:'token=x '.repeat(250)}),verdict:'confirmed-static'}]) {await assert.rejects(service.request(path,{method:'PATCH',body:{note:'Evidence remains unchanged on invalid updates.',...update}}));assert.deepEqual((await service.request('/api/assessments/'+record.id)).assessment,record);}await store.update(record.id,row=>{row.activity=Array.from({length:200},()=>({at:row.created_at,action:'review',note:'Preserved history'}));return row;});10 unmodified linesconst store=new MemoryStore(),service=new LocalService(store);const record=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;const path=`/api/assessments/${record.id}/findings/${record.findings[0].id}`;await service.request(path,{method:'PATCH',body:{verdict:'confirmed-static',note:'First review of reachable owned fixture.',review:evidence({reviewer:'First analyst',reference:'First revision 11'})}});const result=await service.request(path,{method:'PATCH',body:{verdict:'unresolved',note:'Second review needs more evidence.',review:evidence({reviewer:'Second analyst',reference:'Second revision 22'})}});assert.match(result.assessment.activity[1].note,/First analyst/);assert.match(result.assessment.activity[1].note,/First revision 11/);assert.match(result.assessment.activity[2].note,/Second analyst/);assert.equal(previewBackup(await service.backupText()).count,1);3 unmodified linesconst store=new MemoryStore(),service=new LocalService(store);const record=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;const path=`/api/assessments/${record.id}/findings/${record.findings[0].id}`;await service.request(path,{method:'PATCH',body:{verdict:'confirmed-static',note:'N'.repeat(4000),review:evidence({reviewer:'R'.repeat(120),reference:'F'.repeat(2000),prerequisites:'P'.repeat(2000),mitigations:'M'.repeat(2000),method:'T'.repeat(2000)}),tracking:{owner:'O'.repeat(2000),due_date:'2028-02-29',status:'retest',retest:'Q'.repeat(2000)}}});assert.equal(previewBackup(await service.backupText()).count,1);28 unmodified linesassert.equal(nested.findings.length,1);assert.match(nested.findings[0].location,/line 3$/);});123456729 unmodified lines37383940414243444550 unmodified lines969798991001011021036 unmodified lines11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514627 unmodified lines17417517617717817918019 unmodified lines20020120220320420520620720820921021168 unmodified lines28028128228328428528610 unmodified lines2972982993003013023033043 unmodified lines30830931031131231331428 unmodified lines343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490'use strict';const test = require('node:test');const assert = require('node:assert/strict');const {analyze, redact, markdownExport, LocalService, IndexedDBStore, previewBackup, summarize} = require('../static/local.js');class MemoryStore {constructor() { this.rows = new Map(); this.chain = Promise.resolve(); }29 unmodified linescontent:'eval(user_input)\nsubprocess.run(command, shell=True)', roles:['red','blue','white','black','purple'], ...changes});const evidence = changes => ({reviewer:'Analyst A',reference:'Owned fixture revision 123',prerequisites:'User-controlled input reaches the reviewed sink.',mitigations:'Reviewed input validation and sandbox boundaries.',method:'Manually traced source to sink in the owned test fixture.',...changes});const manual=changes=>({title:'Observed access-control gap',severity:'medium',location:'Owned app review item',root_cause:'Authorization requires further review.',input_to_impact:'Analyst must validate cross-account access.',prerequisites:'Two authorized test accounts.',mitigations:'Server authorization unverified.',evidence:'Analyst observation in the owned fixture.',remediation:'Validate ownership checks and add regression coverage.',...changes});test('local analysis nominates unresolved candidates without executing source', () => {const result = analyze(payload({content:'eval(user_input)\nsubprocess.run(command, shell=True)\npassword="private-secret-9823"'}));50 unmodified linesassert.deepEqual(await service.request('/api/assessments'),{assessments:[]});const {assessment:a} = await service.request('/api/assessments',{method:'POST',body:JSON.stringify(payload())});const base = '/api/assessments/'+a.id;await assert.rejects(service.request(base+'/findings/'+a.findings[0].id,{method:'PATCH',body:JSON.stringify({expected_revision:0,verdict:'confirmed-static',note:'yes'})}));const review = await service.request(base+'/findings/'+a.findings[0].id,{method:'PATCH',body:JSON.stringify({expected_revision:0,verdict:'confirmed-static',note:'Traced taint in the owned test fixture.',review:evidence()})});assert.equal(review.assessment.findings[0].verdict,'confirmed-static');const fresh = new LocalService(store);assert.equal((await fresh.request(base)).assessment.findings[0].verdict,'confirmed-static');6 unmodified linesawait assert.rejects(fresh.request('/api/login',{method:'POST',body:'{}'}));});test('concurrent stale reviews conflict then explicit reload preserves both decisions and bounded history', async () => {const store = new MemoryStore(), service = new LocalService(store);const {assessment:a} = await service.request('/api/assessments',{method:'POST',body:payload()});const path = `/api/assessments/${a.id}/findings/${a.findings[0].id}`;const results=await Promise.allSettled(['First','Second'].map(word => service.request(path,{method:'PATCH',body:{expected_revision:0,verdict:'unresolved',note:word+' independent evidence review.'}})));assert.equal(results.filter(result=>result.status==='fulfilled').length,1);const failed=results.find(result=>result.status==='rejected');assert.equal(failed.reason.code,'CONFLICT');const loser=results[0].status==='rejected'?'First':'Second';await service.request(path,{method:'PATCH',body:{expected_revision:1,verdict:'unresolved',note:loser+' independent evidence review.'}});const record = (await service.request('/api/assessments/'+a.id)).assessment;assert.equal(record.activity.length,3);assert.match(JSON.stringify(record.activity),/First/); assert.match(JSON.stringify(record.activity),/Second/);await store.update(a.id, row => {row.activity=Array.from({length:200},()=>({at:'x',action:'review',note:'x'})); return row;});await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:2,verdict:'unresolved',note:'One more review'}}),/200/);});test('finding saves require exact revision and GET normalizes legacy revisions without silent overwrites',async()=>{const store=new MemoryStore(),service=new LocalService(store);const original=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;assert.equal(original.revision,0);assert.equal(original.findings[0].revision,0);const path=`/api/assessments/${original.id}/findings/${original.findings[0].id}`;for(const expected_revision of [undefined,-1,0.5,'0',1]) {await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision,verdict:'unresolved',note:'Preserve the latest analyst decision.'}}),error=>error.code==='CONFLICT');assert.deepEqual(await store.get(original.id),original);}const saved=(await service.request(path,{method:'PATCH',body:{expected_revision:0,verdict:'unresolved',note:'Saved current revision without a stale overwrite.'}})).assessment;assert.equal(saved.revision,1);assert.equal(saved.findings[0].revision,1);const legacy=analyze(payload());delete legacy.revision;for(const finding of legacy.findings) delete finding.revision;await store.add(legacy,100);const fetched=(await service.request('/api/assessments/'+legacy.id)).assessment;assert.equal(fetched.revision,0);assert.equal(fetched.findings[0].revision,0);});test('record count is bounded and storage failure is surfaced instead of apparent success', async () => {27 unmodified linesconst store=new MemoryStore(), service=new LocalService(store), record=analyze(payload());const envelope=records=>JSON.stringify({format:'napolean-cyber-command',version:1,records});for(const input of ['bad','{}','[]',JSON.stringify({format:'other',version:1,records:[]}),JSON.stringify({format:'napolean-cyber-command',version:3,records:[]}),envelope([{...record,content:'Raw source must never enter storage'}]),envelope([record,{...record,roles:['unknown']}]),' '.repeat(5*1024*1024+1)]) {19 unmodified linesconst a=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;const path=`/api/assessments/${a.id}/findings/${a.findings[0].id}`;for(const review of [undefined,evidence({reference:''}),evidence({method:'yes'}),evidence({method:'.'.repeat(30)}),evidence({reviewer:'A'.repeat(121)})]) {await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'Verified the owned source and reachable input.',review}}));}for(const tracking of [{due_date:'2026-02-31'},{due_date:'2026-1-1'},{status:'done'},{owner:42}]) {await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:0,verdict:'unresolved',note:'Review in progress.',tracking}}));}const result=await service.request(path,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'Verified the owned source and reachable input.',review:evidence(),tracking:{owner:'Fix owner',due_date:'2026-12-01',status:'in-progress',retest:'Regression test pending.'}}});assert.equal(result.assessment.findings[0].review.reviewer,'Analyst A');assert.equal(result.assessment.findings[0].tracking.due_date,'2026-12-01');68 unmodified linesconst path=`/api/assessments/${record.id}/findings/${record.findings[0].id}`;for(const update of [{review:evidence({reference:''}),verdict:'confirmed-static'}, {tracking:{due_date:'2027-02-29'},verdict:'unresolved'},{tracking:{retest:3},verdict:'unresolved'},{review:evidence({method:'token=x '.repeat(250)}),verdict:'confirmed-static'}]) {await assert.rejects(service.request(path,{method:'PATCH',body:{expected_revision:0,note:'Evidence remains unchanged on invalid updates.',...update}}));assert.deepEqual((await service.request('/api/assessments/'+record.id)).assessment,record);}await store.update(record.id,row=>{row.activity=Array.from({length:200},()=>({at:row.created_at,action:'review',note:'Preserved history'}));return row;});10 unmodified linesconst store=new MemoryStore(),service=new LocalService(store);const record=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;const path=`/api/assessments/${record.id}/findings/${record.findings[0].id}`;await service.request(path,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'First review of reachable owned fixture.',review:evidence({reviewer:'First analyst',reference:'First revision 11'})}});const result=await service.request(path,{method:'PATCH',body:{expected_revision:1,verdict:'unresolved',note:'Second review needs more evidence.',review:evidence({reviewer:'Second analyst',reference:'Second revision 22'})}});assert.match(result.assessment.activity[1].note,/First analyst/);assert.match(result.assessment.activity[1].note,/First revision 11/);assert.match(result.assessment.activity[2].note,/Second analyst/);assert.equal(previewBackup(await service.backupText()).count,1);3 unmodified linesconst store=new MemoryStore(),service=new LocalService(store);const record=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;const path=`/api/assessments/${record.id}/findings/${record.findings[0].id}`;await service.request(path,{method:'PATCH',body:{expected_revision:0,verdict:'confirmed-static',note:'N'.repeat(4000),review:evidence({reviewer:'R'.repeat(120),reference:'F'.repeat(2000),prerequisites:'P'.repeat(2000),mitigations:'M'.repeat(2000),method:'T'.repeat(2000)}),tracking:{owner:'O'.repeat(2000),due_date:'2028-02-29',status:'retest',retest:'Q'.repeat(2000)}}});assert.equal(previewBackup(await service.backupText()).count,1);28 unmodified linesassert.equal(nested.findings.length,1);assert.match(nested.findings[0].location,/line 3$/);});test('unattributed login failures are disclosed without fabricated identity correlation',()=>{const anonymous=Array.from({length:5},()=>({event:'login_failed'}));const result=analyze(payload({workflow:'alerts',content:JSON.stringify(anonymous)}));assert.equal(result.findings.length,0);assert.match(result.coverage.join(' '),/5.*unattributed|5.*missing both/i);const partial=analyze(payload({workflow:'alerts',content:JSON.stringify(Array.from({length:5},()=>({event:'login_failed',source_ip:'192.0.2.1'})))}));assert.equal(partial.findings.length,1);assert.match(partial.coverage.join(' '),/5.*one identifier/i);assert.doesNotMatch(partial.findings[0].root_cause,/share actor and source/);});test('shared report totals count only confirmed nonresolved remediation work',()=>{const record=analyze(payload());const base=record.findings[0];record.findings=[['unresolved','open'],['rejected','open'],['confirmed-static','open'],['confirmed-runtime','retest'],['confirmed-static','resolved']].map(([verdict,status])=>({...structuredClone(base),verdict,tracking:{...base.tracking,status}}));assert.deepEqual(summarize(record),{unresolved:1,confirmed_static:2,confirmed_runtime:1,rejected:1,open_remediation:2});assert.match(markdownExport(record),/Open remediation items: 2/);record.findings=[{...base,verdict:'unresolved',tracking:{...base.tracking,status:'open'}}];assert.equal(summarize(record).open_remediation,0);});test('manual findings impose unresolved low-confidence provenance and preserve bounded evidence',async()=>{const store=new MemoryStore(),service=new LocalService(store);const initial=(await service.request('/api/assessments',{method:'POST',body:payload({content:'print(1)'})})).assessment;const path=`/api/assessments/${initial.id}/findings`;const saved=(await service.request(path,{method:'POST',body:manual({evidence:'Authorization: Bearer private-token-9833'})})).assessment;const added=saved.findings[0];assert.equal(added.origin,'manual');assert.equal(added.verdict,'unresolved');assert.equal(added.confidence,'low');assert.equal(added.revision,0);assert.equal(saved.revision,1);assert.equal(saved.activity.at(-1).action,'manual_finding_added');assert.doesNotMatch(JSON.stringify(saved),/private-token-9833/);assert.equal(summarize(saved).open_remediation,0);const before=await store.get(saved.id);for(const update of [{verdict:'confirmed-runtime'},{origin:'heuristic'},{title:''},{severity:'critical'},{content:'raw source'}, {evidence:'x'.repeat(4001)}]) {await assert.rejects(service.request(path,{method:'POST',body:manual(update)}));assert.deepEqual(await store.get(saved.id),before);}assert.equal(previewBackup(await service.backupText()).count,1);});test('manual additions enforce finding and activity limits in the same transaction',async()=>{const store=new MemoryStore(),service=new LocalService(store);const record=(await service.request('/api/assessments',{method:'POST',body:payload({content:'print(1)'})})).assessment;const path=`/api/assessments/${record.id}/findings`;await store.update(record.id,row=>{row.findings=Array.from({length:99},()=>analyze(payload()).findings[0]);return row;});const results=await Promise.allSettled([1,2].map(()=>service.request(path,{method:'POST',body:manual()})));assert.equal(results.filter(result=>result.status==='fulfilled').length,1);assert.equal((await store.get(record.id)).findings.length,100);await store.update(record.id,row=>{row.findings=[];row.activity=Array.from({length:200},()=>({at:row.created_at,action:'review',note:'Preserved'}));return row;});await assert.rejects(service.request(path,{method:'POST',body:manual()}),/200/);assert.equal((await store.get(record.id)).findings.length,0);});test('snapshots freeze canonical report data with SHA256 and survive later edits unchanged',async()=>{const {createHash}=require('node:crypto');const store=new MemoryStore(),service=new LocalService(store);const initial=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;assert.deepEqual(initial.snapshots,[]);const first=await service.createSnapshot(initial.id,0);assert.equal(first.assessment.revision,1);assert.equal(first.snapshot.version,1);assert.equal(first.snapshot.source_revision,0);assert.equal(first.snapshot.data.revision,0);assert.equal(Object.hasOwn(first.snapshot.data,'snapshots'),false);assert.equal(first.snapshot.sha256,createHash('sha256').update(JSON.stringify(first.snapshot.data)).digest('hex'));const exported=await service.exportSnapshot(initial.id,first.snapshot.id,'json');await service.request(`/api/assessments/${initial.id}/findings/${initial.findings[0].id}`,{method:'PATCH',body:{expected_revision:0,verdict:'unresolved',note:'Changed after the frozen report snapshot.'}});assert.equal(await service.exportSnapshot(initial.id,first.snapshot.id,'json'),exported);const markdown=await service.exportSnapshot(initial.id,first.snapshot.id,'markdown');assert.match(markdown,/SHA-256/);assert.doesNotMatch(markdown,/Changed after the frozen/);const second=await service.createSnapshot(initial.id,2);assert.equal(second.snapshot.version,2);const third=await service.createSnapshot(initial.id,3);assert.equal(third.snapshot.version,3);const before=await store.get(initial.id);await assert.rejects(service.createSnapshot(initial.id,4),/3 snapshot/);assert.deepEqual(await store.get(initial.id),before);});test('snapshot CAS prevents stale or simultaneous captures without partial history writes',async()=>{const store=new MemoryStore(),service=new LocalService(store);const initial=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;for(const expected of [undefined,-1,'0',1]) await assert.rejects(service.createSnapshot(initial.id,expected),error=>error.code==='CONFLICT');const results=await Promise.allSettled([service.createSnapshot(initial.id,0),service.createSnapshot(initial.id,0)]);assert.equal(results.filter(row=>row.status==='fulfilled').length,1);assert.equal(results.find(row=>row.status==='rejected').reason.code,'CONFLICT');const current=await store.get(initial.id);assert.equal(current.snapshots.length,1);assert.equal(current.activity.length,2);});test('backupv2 verifies every historical digest before atomic restore and accepts legacyv1 reports',async()=>{const store=new MemoryStore(),service=new LocalService(store);const initial=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;const created=await service.createSnapshot(initial.id,0);const text=await service.backupText();const envelope=JSON.parse(text);assert.equal(envelope.version,2);assert.deepEqual(await service.restoreBackup(text),{count:1});const copies=await store.list();const restored=copies.find(row=>row.id!==initial.id);assert.equal(restored.snapshots[0].id,created.snapshot.id);assert.deepEqual(restored.snapshots[0].data,created.snapshot.data);assert.notEqual(restored.id,created.snapshot.data.id);const before=await store.list();const tampered=structuredClone(envelope);tampered.records[0].snapshots[0].data.name='Changed historical report';await assert.rejects(service.restoreBackup(JSON.stringify(tampered)),/digest|SHA|integrity/i);assert.deepEqual(await store.list(),before);const nested=structuredClone(envelope);nested.records[0].snapshots[0].data.snapshots=[];await assert.rejects(service.restoreBackup(JSON.stringify(nested)),/unsupported|snapshot/i);const legacy=analyze(payload());delete legacy.revision;delete legacy.snapshots;for(const finding of legacy.findings){delete finding.revision;delete finding.origin;}assert.deepEqual(await service.restoreBackup(JSON.stringify({format:'napolean-cyber-command',version:1,records:[legacy]})),{count:1});});test('snapshot growth beyond a restorable single-record backup limit fails without changing the record',async()=>{const store=new MemoryStore(),service=new LocalService(store);const initial=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;await store.update(initial.id,row=>{row.activity=Array.from({length:185},()=>({at:row.created_at,action:'review',note:'A'.repeat(8000)}));return row;});await service.createSnapshot(initial.id,0);await service.createSnapshot(initial.id,1);const before=await store.get(initial.id);await assert.rejects(service.createSnapshot(initial.id,2),/5 MB/);assert.deepEqual(await store.get(initial.id),before);assert.equal(previewBackup(await service.backupText()).count,1);});test('a valid near-5MB exported record restores without provenance annotations pushing it over the limit',async()=>{const store=new MemoryStore(),service=new LocalService(store),record=analyze(payload());const base=record.findings[0];record.findings=Array.from({length:100},(_,index)=>{const row=structuredClone(base);row.id=index.toString(16).padStart(32,'0');row.title='T'.repeat(500);for(const key of ['location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note']) row[key]='E'.repeat(4000);row.review=evidence({reviewer:'R'.repeat(120),reference:'F'.repeat(1000),prerequisites:'P'.repeat(1000),mitigations:'M'.repeat(1000),method:'D'.repeat(1000)});row.tracking={owner:'O'.repeat(1000),due_date:'',status:'open',retest:'Q'.repeat(1000)};return row;});const entry=length=>({at:record.created_at,action:'review',note:'H'.repeat(length)});const bytes=()=>Buffer.byteLength(JSON.stringify({format:'napolean-cyber-command',version:2,records:[record]},null,2));const limit=5*1024*1024;let low=1,high=199;while(low<high){const middle=Math.ceil((low+high)/2);record.activity=Array.from({length:middle},()=>entry(8000));if(bytes()<limit)low=middle;else high=middle-1;}record.activity=Array.from({length:low},()=>entry(8000));record.activity.push(entry(1));low=1;high=8000;while(low<high){const middle=Math.ceil((low+high)/2);record.activity.at(-1).note='H'.repeat(middle);if(bytes()<limit)low=middle;else high=middle-1;}record.activity.at(-1).note='H'.repeat(low);assert.ok(bytes()<limit&&bytes()>limit-5);await store.add(record,100);const backup=await service.backupText();assert.equal(previewBackup(backup).count,1);assert.deepEqual(await service.restoreBackup(backup),{count:1});const restored=(await store.list()).find(row=>row.id!==record.id);assert.equal(restored.activity.length,record.activity.length);assert.equal(restored.summary,record.summary);});
IMPROVEMENTS.md+8
README.md+3
SECURITY.md+6
SERVICE.md+1-1
SOURCE-MANIFEST.jsonAdded+28
VERIFICATION.md+12
docs/superpowers/plans/2026-10-31-business-improvements.mdAdded+18
docs/superpowers/plans/2026-11-02-analyst-reliability.mdAdded+22
docs/superpowers/specs/2026-10-31-business-improvements-design.mdAdded+15
docs/superpowers/specs/2026-11-02-analyst-reliability-design.mdAdded+17
index.html+80-4
static/app.js+188-15
static/index.html+80-4
static/local.js+167-23
static/style.css+7
tests/browser_storage.cjs+88-9
tests/browser_ui.cjs+144-4
tests/test_local.cjs+183-14