Add recovery, evidence, reporting and client workflows
Browse filesFiles changed (14)
- IMPROVEMENTS.mdAdded+29
- README.md+13-5
- SECURITY.md+3-3
- SERVICE.md+2-1
- VERIFICATION.md+20-5
- index.html+174-1
- static/app.js+226-16
- static/index.html+174-1
- static/local.js+265-37
- static/style.css+44
- tests/browser_storage.cjsAdded+219
- tests/browser_ui.cjsAdded+77
- tests/detection-fixtures.cjsAdded+22
- tests/test_local.cjs+202-2
1234567891011121314151617181920212223242526272829# Business workflow improvements
This update preserves the free, static browser architecture. It adds recovery and analyst workflow capabilities without introducing a server, paid resource, Docker or model provider.
## Use the workflow
1. Create an assessment with an optional client label and explicit authorized scope. Labels organize the same browser database; they provide no access control.2. Challenge nominated candidates. A confirmed verdict requires reviewer, reference/revision, prerequisites, mitigations and a substantive validation method. These are analyst attestations, not authenticated identities or independently verified proof.3. Record remediation owner, due date, status and retest notes. Record handoffs between assigned perspectives with the next evidence request. Tracking reflects current local state; the app is not an immutable audit system.4. Use verdict and severity filters, or next-unresolved navigation. Export Markdown or print an executive report that separates confirmed, unresolved and rejected findings and includes coverage limits.5. From the register, download a workspace or selected-client backup. To recover, choose Restore backup, review the validated count and client labels, and explicitly confirm adding copies. Existing records remain intact. Legacy individual assessment JSON exports are also supported.
Restore accepts at most 5 MB and the workspace holds at most 100 assessments. Export smaller client groups or individual assessments when needed. Restore generates fresh assessment/finding IDs. Complete files are validated before mutation; storage writes are atomic. Legacy confirmed verdicts without complete structured evidence become unresolved on import. A full 200-entry history is retained; restore provenance is shown in the summary when no new history entry fits.
## Evidence ledger from implementation
| ID | Root cause / path | Evidence and disposition || --- | --- | --- || IMP-001 | Alert batches could nominate 101 findings while import allowed 100 | Runtime fixture reproduced a valid batch that could not round-trip. Fixed with a disclosed 100-candidate cap and priority for high-severity alerts; regression checks restore compatibility. || IMP-002 | Restore provenance appended to a full 200-entry history | Boundary fixture reproduced the recovery gap. Fixed by preserving all existing history and recording provenance in the summary when history is full. || IMP-003 | Redaction expanded otherwise valid fields beyond restore limits | Synthetic token-assignment fixture reproduced the mismatch. Fixed by checking lengths after redaction before save; malformed updates do not partially mutate records. |
These are recoverability and data-quality defects found during implementation, not demonstrated attacker exploitation. Security review covered the local input, rendering, import, persistence and export paths. No new exploitable vulnerability was confirmed within that bounded scope.
## Limitations
Code 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.21 unmodified lines22232425262728293031327 unmodified lines404142434445461 unmodified line48495051525354555612 unmodified lines6970717221 unmodified lines## Working flows- **Code review:** bounded Python-text patterns nominate potential eval/exec, shell-enabled invocation and embedded-credential concerns. This is not a Python parser, AST analysis, taint tracking or vulnerability validation. Matches are always unresolved candidates and may be false positives.- **Alert triage:** bounded JSON event batches nominate repeated login failures, privilege changes and malware reports. Timestamps, authenticity, duplicates and actual compromise need analyst validation.- **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 an analyst verdict and supporting note, search the register, export JSON/Markdown locally, and delete a local assessment after confirmation.Raw source, alerts and scenario prose are not retained. Generated evidence omits raw values. Names, scopes and notes may still contain sensitive information: redaction is best-effort. Use synthetic or approved minimal data for pilots.7 unmodified linespython3 -m http.server 7860 --bind 127.0.0.1```Open http://127.0.0.1:7860/static/index.html. Python only serves files; there is no Python assessment backend. Export JSON regularly: clearing site data, changing browser/profile/origin, private browsing or storage eviction can remove local records. Exports contain assessment metadata and analyst notes and must be handled accordingly.## Verify1 unmodified linenode --test tests/test_local.cjsnode --check static/app.jsnode --check static/local.js```The local development bundle also retains the earlier optional Python engine, Flask API and Gradio experiment for reference. They are not loaded or installed by the deployed Static Space. Its old runtime dependency advisories are not an active JavaScript dependency; see [verification](VERIFICATION.md) for coverage and history. No Python runtime is needed to use the hosted app.## Reuse12 unmodified linesThis is a prototype for analyst-led reviews and training. Customer teams do not share case state automatically. An analyst can conduct scoped reviews, export a report and manage the engagement separately. It does not include shared SaaS accounts, SSO/RBAC, billing, continuous monitoring, SIEM integrations or compliance certification.See [service offering](SERVICE.md), [security model](SECURITY.md), [verification](VERIFICATION.md), and [provenance](PROVENANCE.md). Validate customer demand and data-handling arrangements before a pilot. No automated count or zero-candidate result establishes that a system is secure.21 unmodified lines222324252627282930313233347 unmodified lines424344454647481 unmodified line50515253545556575859606162636412 unmodified lines7778798021 unmodified lines## Working flows- **Code review:** bounded lexical Python-text patterns mask comments/quoted examples and recognize simple subprocess imports/multiline calls to nominate potential eval/exec, shell-enabled invocation and embedded-credential concerns. This is not a Python parser, AST analysis, taint tracking or vulnerability validation. Matches are always unresolved candidates and may be false positives.- **Alert triage:** bounded JSON event batches nominate repeated login failures, privilege changes and malware reports. Timestamps, authenticity, duplicates and actual compromise need analyst validation.- **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.Raw source, alerts and scenario prose are not retained. Generated evidence omits raw values. Names, scopes and notes may still contain sensitive information: redaction is best-effort. Use synthetic or approved minimal data for pilots.7 unmodified linespython3 -m http.server 7860 --bind 127.0.0.1```Open http://127.0.0.1:7860/static/index.html. Python only serves files; there is no Python assessment backend. Use workspace backups regularly: clearing site data, changing browser/profile/origin, private browsing or storage eviction can remove local records. Exports contain assessment metadata and analyst notes and must be handled accordingly.## Verify1 unmodified linenode --test tests/test_local.cjsnode --check static/app.jsnode --check static/local.js# Optional real Chromium checks; supply an existing Playwright module path:PLAYWRIGHT_MODULE=/absolute/path/to/playwright node tests/browser_storage.cjs# With the local server running:PLAYWRIGHT_MODULE=/absolute/path/to/playwright node tests/browser_ui.cjs```Browser checks use an existing Playwright installation and its Chromium binary; they add no runtime dependency. Set `PLAYWRIGHT_EXECUTABLE_PATH` if using an existing compatible Chromium executable.The Hugging Face repository also retains the earlier Python engine, Flask API and Gradio experiment as historical reference. The standalone static source ZIP excludes those server dependencies. They are not loaded or installed by the deployed Static Space. Its old runtime dependency advisories are not an active JavaScript dependency; see [verification](VERIFICATION.md) for coverage and history. No Python runtime is needed to use the hosted app.## Reuse12 unmodified linesThis is a prototype for analyst-led reviews and training. Customer teams do not share case state automatically. An analyst can conduct scoped reviews, export a report and manage the engagement separately. It does not include shared SaaS accounts, SSO/RBAC, billing, continuous monitoring, SIEM integrations or compliance certification.See [improvement guide](IMPROVEMENTS.md), [service offering](SERVICE.md), [security model](SECURITY.md), [verification](VERIFICATION.md), and [provenance](PROVENANCE.md). Validate customer demand and data-handling arrangements before a pilot. No automated count or zero-candidate result establishes that a system is secure.
9 unmodified lines101112131415161718192021229 unmodified linesRaw submitted source/log/scenario text is not persisted. Derived assessment metadata, generated candidates, mission plans and analyst notes are stored in IndexedDB on the current browser/profile/origin. Redaction is best-effort and not a guarantee that notes or metadata contain no secrets. Never paste credentials, private keys or unnecessary personal information.Exports are created locally and contain potentially sensitive metadata/notes. They leave browser-managed storage when saved or shared. Deleting an assessment removes its current logical browser record; it does not erase downloaded reports, browser backups or forensic storage traces. Site-data clearing or storage eviction can destroy records. Export backups regularly, store them securely, and keep the same app origin/profile when reopening.Input 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. 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. Comments, strings, aliasing and formatting can 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.No password prompt, fake session or client-side role is used as an enterprise security boundary. Customer records are not synchronized across users or machines. For a business service, agree scope, approved data, export handling, retention and qualified analyst review. Shared enterprise workflows would need a separately designed and verified backend and identity system, with their own costs.9 unmodified lines101112131415161718192021229 unmodified linesRaw submitted source/log/scenario text is not persisted. Derived assessment metadata, generated candidates, mission plans and analyst notes are stored in IndexedDB on the current browser/profile/origin. Redaction is best-effort and not a guarantee that notes or metadata contain no secrets. Never paste credentials, private keys or unnecessary personal information.Exports are created locally and contain potentially sensitive metadata/notes. They leave browser-managed storage when saved or shared. Deleting an assessment removes its current logical browser record; it does not erase downloaded reports, browser backups or forensic storage traces. Site-data clearing or storage eviction can destroy records. Export backups regularly and store them securely. Restore validates bounded, allowlisted records before saving fresh copies in a single IndexedDB transaction. Existing IDs are never replaced. Imported evidence is untrusted analyst-authored data, not authenticated proof. Client labels group records and never restrict access within the browser workspace.Input 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.No password prompt, fake session or client-side role is used as an enterprise security boundary. Customer records are not synchronized across users or machines. For a business service, agree scope, approved data, export handling, retention and qualified analyst review. Shared enterprise workflows would need a separately designed and verified backend and identity system, with their own costs.
19 unmodified lines2021222324252619 unmodified lines2. Use minimal approved snippets or normalized event batches. Keep raw source/logs in the customer's controlled system.3. 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. Agree remediation ownership, retest criteria and residual risks; manage these commitments outside this prototype.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.19 unmodified lines202122232425262719 unmodified lines2. Use minimal approved snippets or normalized event batches. Keep raw source/logs in the customer's controlled system.3. 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.
123456789102 unmodified lines1314151617181910 unmodified lines30313233343536373839# Verification: final no-cost static editionDate:2026-10-31. Final runtime: private Hugging Face Static Space, sdk:static, app_file:index.html. No Docker, Gradio, compute, backend/API, model, application key or third-party runtime package is loaded by the deployed app.## Active checks- `node --test tests/test_local.cjs`: **8 tests passed**. Checks analysis without execution; malformed/large input and authorization/role validation; alert correlation/schema; scenario-specific five-role missions; redaction/Markdown escaping; persistence/review/export/deletion service behavior; serialized concurrent-update intent; record/activity caps; surfaced storage failures.- `node --check static/app.js` and `node --check static/local.js`: passed.- Optional publishing helper:4 unittest checks passed for private sdk:static creation, no compute/secrets, source allowlist and preflight validation. Python is used only for this optional publication helper, not runtime.- Independent source review: no important security or correctness issue confirmed within the static files and test scope. No external submission, eval/Function execution, remote assets or raw-submission persistence was found. User-authored evidence uses textContent; Markdown escapes markup.2 unmodified linesUsing synthetic fixtures only, the real in-app browser opened actual IndexedDB, created a Python-pattern assessment, assigned all five perspectives and saved an analyst decision. A second browser tab reopened the same origin and showed the saved assessment with zero unresolved candidates after that decision. A local JSON download was read and contained the expected saved verdict; it contained no raw `content` field. The input is never executed.Transactional IndexedDB writes resolve only on transaction completion. Record-count checks and creation, and review reads/history appends/writes, remain in one readwrite transaction. The automated concurrency tests use a serialized in-memory test store, not an actual multi-tab IndexedDB stress harness. Browser quota denial, storage eviction, transaction abort races and broad browser/version coverage remain unverified. The UI surfaces storage failures; it does not silently claim successful saves.The interface was inspected at the available narrow and wide browser surfaces. A complete WCAG audit, responsive matrix and reduced-vision testing have not been performed. Terminal typography and labels are deliberate design choices. No fonts/CDNs or external assets are requested by application code. A meta content-security policy denies network connections from the application document.10 unmodified lines## LimitsThis is an analyst-led prototype, not a multi-user SaaS, trained model, continuous monitoring platform or security certification. Code checks are limited text patterns; comments/strings may match and multiline/alias flows may be missed. No vulnerability is automatically confirmed. Raw source/log/scenario text is omitted from stored records, while names/scopes/notes may still be sensitive. Local origin/profile access and downloaded exports are security boundaries controlled by the operator.Real customer hosting, identity, shared records, encryption, backups, immutable audits, legal agreements and incident operations are outside this no-cost browser prototype. Exporting reports supports retention; no import/restore interface is implemented.## Hosted deliveryFinal static conversion and hosted browser checks are recorded in the final handoff. Repository source and settings must remain private unless the owner explicitly changes visibility. No billing or account subscription was changed.123456789102 unmodified lines1314151617181910 unmodified lines30313233343536373839404142434445464748495051525354# Verification: browser service improvementsDate:2026-10-31. Final runtime: private Hugging Face Static Space, sdk:static, app_file:index.html. No Docker, Gradio, compute, backend/API, model, application key or third-party runtime package is loaded by the deployed app.## Active checks- The prior release had 8 Node checks. The improvement suite adds versioned/legacy restore validation, hostile fields, atomic capacity failures, structured evidence, invalid dates/status, handoffs, round-trip limits and lexical detection fixtures. Final counts and browser outcomes are recorded below after integration.- `node --check static/app.js` and `node --check static/local.js`: passed.- Optional publishing helper:4 unittest checks passed for private sdk:static creation, no compute/secrets, source allowlist and preflight validation. Python is used only for this optional publication helper, not runtime.- Independent source review: no important security or correctness issue confirmed within the static files and test scope. No external submission, eval/Function execution, remote assets or raw-submission persistence was found. User-authored evidence uses textContent; Markdown escapes markup.2 unmodified linesUsing synthetic fixtures only, the real in-app browser opened actual IndexedDB, created a Python-pattern assessment, assigned all five perspectives and saved an analyst decision. A second browser tab reopened the same origin and showed the saved assessment with zero unresolved candidates after that decision. A local JSON download was read and contained the expected saved verdict; it contained no raw `content` field. The input is never executed.Transactional IndexedDB writes resolve only on transaction completion. Record-count checks and creation, and review reads/history appends/writes, remain in one readwrite transaction. Node unit tests use an in-memory store. The new Chromium integration harness uses real IndexedDB across two pages, verifies duplicate-key rollback and injects a quota exception to check real transaction rollback. Policy denial is simulated. Actual disk exhaustion, storage eviction and broad browser/version coverage remain unverified. The UI surfaces storage failures; it does not silently claim successful saves.The interface was inspected at the available narrow and wide browser surfaces. A complete WCAG audit, responsive matrix and reduced-vision testing have not been performed. Terminal typography and labels are deliberate design choices. No fonts/CDNs or external assets are requested by application code. A meta content-security policy denies network connections from the application document.10 unmodified lines## LimitsThis is an analyst-led prototype, not a multi-user SaaS, trained model, continuous monitoring platform or security certification. Code checks remain limited lexical patterns, with comment/string masking and bounded alias/multiline recognition; full Python syntax and dataflow remain unverified. No vulnerability is automatically confirmed. Raw source/log/scenario text is omitted from stored records, while names/scopes/notes may still be sensitive. Local origin/profile access and downloaded exports are security boundaries controlled by the operator.Real customer hosting, identity, shared records, encryption, backups, immutable audits, legal agreements and incident operations are outside this no-cost browser prototype. Versioned workspace/client backups and legacy single-assessment exports can be restored as fresh copies after validation. Restore has a 5 MB bound and a global 100-record capacity. Oversized workspace exports must be split by client or assessment. Local backups require operator-managed retention; there is no managed cloud backup. Structured reviewer/reference information is an attestation; remediation fields retain current state and do not form immutable audit history.## Hosted deliveryFinal static conversion and hosted browser checks are recorded in the final handoff. Repository source and settings must remain private unless the owner explicitly changes visibility. No billing or account subscription was changed.## Improvement release verificationSource checked on 2026-10-31 in the local project directory. The active engine suite passes 24 Node tests. The original detection fixture table covers positive nominations and negative comments/string/declaration examples; nested-call regression cases also pass. These are fixture results, not measured real-world precision or recall.The `browser_storage.cjs` harness passes 12 Chromium checks: actual IndexedDB reload, concurrent tab decisions, duplicate-key rollback, quota fault rollback, simulated policy denial, fresh-ID restore, malformed-file nonmutation, actual UI backup/restore, history cap, full-history recovery, concurrent 100-record cap, and no external requests or uncaught page errors.The separate `browser_ui.cjs` workflow passes creation with aliased multiline source, incomplete-confirmation guard, structured evidence and remediation save, focus restoration, verdict/severity filters, next unresolved, role handoff, printable executive report, client-filtered backup download, preview/confirmed restore, and 390px page overflow checks. Desktop and mobile screenshots were inspected. JavaScript syntax checks and all 4 optional publisher tests pass. Both HTML entries agree after their asset path normalization.Source review also fixed three UI mismatches: stale filters on creation, unclear method requirements and missing legacy-evidence warnings in print. Client labels remain organizational. Reviewer/reference history is retained in review events; complete prior tracking/evidence snapshots and immutable audits are not provided.No 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.
1 unmodified line2345678129 unmodified lines13813914014114214387 unmodified lines23123223323423523623723823924024119 unmodified lines2612622632642651 unmodified line<html lang="en"><head><meta charset="utf-8"/><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"/><meta content="width=device-width,initial-scale=1" name="viewport"/><meta content="dark" name="color-scheme"/><meta content="#171719" name="theme-color"/>129 unmodified lines<label for="scope">Authorized scope</label><input id="scope" maxlength="1000" name="scope" placeholder="Owned service, repository, or exercise boundary" required=""/><fieldset><legend>87 unmodified lines<label for="review-note">Decision evidence / note</label><textarea id="review-note" maxlength="4000" minlength="20" placeholder="Describe the evidence supporting your decision." required="" rows="4"></textarea><p class="fine">A runtime verdict requires evidence you obtained independently. This workbench does not execute source or validate exploitation.</p><div class="dialog-actions"><button data-close="" type="button">Close</button>19 unmodified lines</button></div></dialog></body></html>1 unmodified line2345678129 unmodified lines13813914014114214314414514614714814915087 unmodified lines23823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933019 unmodified lines3503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374381 unmodified line<html lang="en"><head><meta charset="utf-8"/><meta content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'" http-equiv="Content-Security-Policy"/><meta content="width=device-width,initial-scale=1" name="viewport"/><meta content="dark" name="color-scheme"/><meta content="#171719" name="theme-color"/>129 unmodified lines<label for="scope">Authorized scope</label><label for="client">Client label (optional)</label><input id="client" maxlength="120" name="client" placeholder="Unassigned"/><p class="fine">Client labels organize records in this browser. They do not restrict access.</p><input id="scope" maxlength="1000" name="scope" placeholder="Owned service, repository, or exercise boundary" required=""/><fieldset><legend>87 unmodified lines<label for="review-note">Decision evidence / note</label><fieldset class="review-fields"><legend>Analyst attestation · required for confirmations</legend><p class="fine">These entries are analyst assertions, not independent proof or verified identity.</p><div class="form-grid"><div><label for="reviewer">Reviewer label</label><input id="reviewer" maxlength="120"/></div><div><label for="reference">Evidence reference / revision</label><input id="reference" maxlength="500" placeholder="Ticket, commit, test record"/></div></div><label for="review-prerequisites">Verified prerequisites</label><textarea id="review-prerequisites" maxlength="2000" rows="2"></textarea><label for="review-mitigations">Mitigations inspected</label><textarea id="review-mitigations" maxlength="2000" rows="2"></textarea><label for="review-method">Validation method / result</label><textarea aria-describedby="review-method-help" id="review-method" maxlength="2000" rows="3"></textarea><p class="fine" id="review-method-help">For confirmed verdicts, describe the method and result in at least 20 characters, including at least 10 letters or digits.</p></fieldset><fieldset><legend>Remediation tracking</legend><div class="form-grid"><div><label for="tracking-owner">Owner</label><input id="tracking-owner" maxlength="120"/></div><div><label for="tracking-due">Target date</label><input id="tracking-due" type="date"/></div><div><label for="tracking-status">Status</label><select id="tracking-status"><option value="open">Open</option><option value="in-progress">In progress</option><option value="resolved">Resolved</option><option value="retest">Retest</option></select></div></div><label for="tracking-retest">Retest evidence / note</label><textarea id="tracking-retest" maxlength="2000" rows="2"></textarea></fieldset><textarea id="review-note" maxlength="4000" minlength="20" placeholder="Describe the evidence supporting your decision." required="" rows="4"></textarea><p class="fine">A runtime verdict requires evidence you obtained independently. This workbench does not execute source or validate exploitation.</p><div class="dialog-actions"><button id="next-unresolved" type="button">Next unresolved →</button><button data-close="" type="button">Close</button>19 unmodified lines</button></div></dialog><dialog aria-labelledby="restore-title" id="restore-dialog"><form id="restore-form"><div class="dialog-head"><h2 id="restore-title">Restore workspace backup</h2><button aria-label="Close restore" class="close" data-close="" type="button">×</button></div><p class="error-inline" hidden="" role="alert"></p><p class="fine">Choose a versioned JSON backup, up to 5 MB. Valid records are added as new copies; existing assessments are never replaced.</p><label for="restore-file">Backup file</label><input accept=".json,application/json" id="restore-file" required="" type="file"/><div class="record-section" id="restore-preview" role="status"></div><label class="attestation"><input id="restore-confirm" required="" type="checkbox"/><span>I reviewed the preview and want to add these records to this browser workspace.</span></label><div class="dialog-actions"><button data-close="" type="button">Cancel</button><button class="primary" disabled="" id="restore-submit" type="submit">Restore copies ↗</button></div></form></dialog><dialog aria-labelledby="handoff-title" id="handoff-dialog"><form id="handoff-form"><div class="dialog-head"><h2 id="handoff-title">Record a role handoff</h2><button aria-label="Close handoff" class="close" data-close="" type="button">×</button></div><p class="error-inline" hidden="" role="alert"></p><p class="fine">Records a local coordination note. This does not notify another person or run a role agent.</p><div class="form-grid"><div><label for="handoff-from">From perspective</label><select id="handoff-from"></select></div><div><label for="handoff-to">To perspective</label><select id="handoff-to"></select></div></div><label for="handoff-note">Evidence, challenge, and next action</label><textarea id="handoff-note" maxlength="2000" minlength="20" required="" rows="4"></textarea><div class="dialog-actions"><button data-close="" type="button">Cancel</button><button class="primary" type="submit">Record handoff ↗</button></div></form></dialog><section aria-label="Executive assessment report" id="print-report"></section></body></html>
1234567106 unmodified lines11411511611711811917 unmodified lines1371381391401411426 unmodified lines1491501511521531541551561571581591601613 unmodified lines1651661671681691701711728 unmodified lines1811821831841851866 unmodified lines19319419519619719819920020170 unmodified lines2722732742752762772782792802812822832842852863 unmodified lines29029129229329429529629717 unmodified lines31531631731831932032132232361 unmodified lines3853863873883893903914 unmodified lines3963973983994004018 unmodified lines4104114124134144154164174184194205 unmodified lines426427428429430431432433434435436437'use strict';const $ = (selector, root = document) => root.querySelector(selector);const state = {assessments: [], assessment: null, finding: null, tab: 'ledger'};const roles = [ ['red', '01', 'Red hat', 'Test assumptions', 'Authorized adversary perspective.'], ['blue', '02', 'Blue hat', 'Strengthen defense', 'Triage signals and plan response.'], ['white', '03', 'White hat', 'Validate evidence', 'Review causes and remediation.'], ['black', '04', 'Black hat', 'Think like an attacker', 'Bounded threat modeling only.'], ['purple', '05', 'Purple hat', 'Close the loop', 'Connect scenarios to detection.'] ];const workflows = {106 unmodified lines}function openCreate() {$('#nav-new').classList.add('active');$('#create-dialog').showModal();$('#assessment-name').focus();}17 unmodified linesconst title = el('div', undefined, 'section-title');append(title, el('h2', 'Assessment register'), el('span', `${String(state.assessments.length).padStart(2, '0')} ENGAGEMENTS`, 'count'));view.append(title);if (!state.assessments.length) {const box = empty('Start with a defined scope.', 'Review a Python snippet, triage structured alerts, or prepare a five-perspective security exercise.', button('Create first assessment ↗', openCreate, 'primary'));box.append(el('small', 'No source connections or scans run automatically.'));6 unmodified linessearch.placeholder = 'Search assessments…';search.setAttribute('aria-label', 'Search assessments');const count = el('span', '', 'count');append(toolbar, search, count);view.append(toolbar);const wrap = el('div', undefined, 'table-wrap');view.append(wrap);function draw() {const query = search.value.toLowerCase();const matches = state.assessments.filter(a => `${a.name} ${a.scope} ${a.workflow}`.toLowerCase().includes(query));count.textContent = `${matches.length} of ${state.assessments.length}`;const table = el('table');const head = el('tr');3 unmodified linesmatches.forEach(a => {const row = el('tr');const identity = el('td');append(identity, button(a.name, () => openAssessment(a.id), 'row-button'), el('span', a.scope, 'subline'));append(row, identity, el('td', workflows[a.workflow] || a.workflow), el('td', date(a.created_at), 'mono'), el('td', a.finding_count, 'mono'), el('td', a.unresolved_count, 'mono'));body.append(row);});table.append(body);8 unmodified linestry {state.assessment = (await api(`/api/assessments/${encodeURIComponent(id)}`)).assessment;state.tab = 'ledger';renderAssessment();}catch (error) {6 unmodified linesconst a = state.assessment;const view = $('#view');view.replaceChildren(button('← Assessment register', loadOverview, 'text-button back'));append(view, heading(`${workflows[a.workflow] || a.workflow} / ${date(a.created_at)}`, a.name, 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('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]) => {70 unmodified linesconst search = el('input');search.type = 'search';search.placeholder = 'Search evidence, location, verdict…';search.setAttribute('aria-label', 'Search findings');const count = el('span', '', 'count');append(toolbar, search, count);panel.append(toolbar);const wrap = el('div', undefined, 'table-wrap');panel.append(wrap);function draw() {const q = search.value.toLowerCase();const matches = a.findings.filter(f => `${f.title} ${f.location} ${f.verdict} ${f.evidence}`.toLowerCase().includes(q));count.textContent = `${matches.length} records`;const table = el('table');const head = el('tr');3 unmodified linesmatches.forEach(f => {const row = el('tr');const identity = el('td');append(identity, button(f.title, () => openFinding(f), 'row-button'), el('span', f.location, 'subline mono'));append(row, identity, el('td', f.severity, 'tag'), el('td', f.confidence, 'tag'), el('td', f.verdict, 'tag'));body.append(row);});table.append(body);17 unmodified linesappend(section, el('h3', title), el('p', displayValue(value)));body.append(section);});$('#verdict').value = f.verdict;$('#review-note').value = f.review_note || '';$('#finding-dialog').showModal();}async function download(format) {try {61 unmodified linesbusy(form, async () => {const result = await api('/api/assessments', {method: 'POST', body: JSON.stringify({name: $('#assessment-name').value.trim(), workflow: $('#workflow').value, scope: $('#scope').value.trim(), authorization: $('#authorization').checked, content: $('#content').value, roles: selected})});form.reset();4 unmodified lines$('#create-dialog').close();state.assessment = result.assessment;state.tab = 'ledger';renderAssessment();notify('Assessment created. Candidates await analyst review.');});8 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})})).assessment;$('#finding-dialog').close();renderAssessment();notify('Analyst decision recorded.');});});5 unmodified linesawait loadOverview();notify('Assessment deleted.');}));loadOverview();window.addEventListener('beforeunload', event => {const draft = $('#assessment-name').value.trim() || $('#scope').value.trim() || $('#content').value.trim();const noteChanged = $('#finding-dialog').open && state.finding && ($('#review-note').value !== (state.finding.review_note || '') || $('#verdict').value !== state.finding.verdict);if (draft || noteChanged) {event.preventDefault();event.returnValue = '';}});1234567106 unmodified lines11411511611711811912017 unmodified lines1381391401411421431441451461476 unmodified lines1541551561571581591601611621631641651661671681691703 unmodified lines1741751761771781791801811828 unmodified lines1911921931941951961976 unmodified lines20420520620720820921021121270 unmodified lines2832842852862872882892902912922932942952962972982993003013023033043053 unmodified lines30931031131231331431531631731831917 unmodified lines33733833934034134234334434534634734834935035135235361 unmodified lines4154164174184194204214 unmodified lines4264274284294304314328 unmodified lines4414424434444454464474484494504514524534545 unmodified lines460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647'use strict';const $ = (selector, root = document) => root.querySelector(selector);const state = {assessments: [], assessment: null, finding: null, tab: 'ledger', client: '', ledgerSearch: '', verdict: '', severity: '', restoreText: '', originalReview: ''};const roles = [ ['red', '01', 'Red hat', 'Test assumptions', 'Authorized adversary perspective.'], ['blue', '02', 'Blue hat', 'Strengthen defense', 'Triage signals and plan response.'], ['white', '03', 'White hat', 'Validate evidence', 'Review causes and remediation.'], ['black', '04', 'Black hat', 'Think like an attacker', 'Bounded threat modeling only.'], ['purple', '05', 'Purple hat', 'Close the loop', 'Connect scenarios to detection.'] ];const workflows = {106 unmodified lines}function openCreate() {$('#nav-new').classList.add('active');if (state.client && !$('#client').value.trim()) $('#client').value = state.client;$('#create-dialog').showModal();$('#assessment-name').focus();}17 unmodified linesconst title = el('div', undefined, 'section-title');append(title, el('h2', 'Assessment register'), el('span', `${String(state.assessments.length).padStart(2, '0')} ENGAGEMENTS`, 'count'));view.append(title);const workspaceActions = el('div', undefined, 'detail-actions');const backupAction = button('↓ Backup all clients JSON', backupWorkspace);append(workspaceActions, backupAction, button('↑ Restore backup', openRestore));view.append(workspaceActions);if (!state.assessments.length) {const box = empty('Start with a defined scope.', 'Review a Python snippet, triage structured alerts, or prepare a five-perspective security exercise.', button('Create first assessment ↗', openCreate, 'primary'));box.append(el('small', 'No source connections or scans run automatically.'));6 unmodified linessearch.placeholder = 'Search assessments…';search.setAttribute('aria-label', 'Search assessments');const count = el('span', '', 'count');const clients = selectControl('Filter by client', [['', 'All clients'], ...[...new Set(state.assessments.map(a => a.client || 'Unassigned'))].sort().map(client => [client, client])]);clients.value = state.client;clients.addEventListener('change', () => { state.client = clients.value; draw(); });append(toolbar, search, clients, count);view.append(toolbar);const wrap = el('div', undefined, 'table-wrap');view.append(wrap);function draw() {backupAction.textContent = state.client ? `↓ Backup ${state.client} JSON` : '↓ Backup all clients JSON';const query = search.value.toLowerCase();const matches = state.assessments.filter(a => (!state.client || (a.client || 'Unassigned') === state.client) && `${a.name} ${a.scope} ${a.workflow} ${a.client || 'Unassigned'}`.toLowerCase().includes(query));count.textContent = `${matches.length} of ${state.assessments.length}`;const table = el('table');const head = el('tr');3 unmodified linesmatches.forEach(a => {const row = el('tr');const identity = el('td');append(identity, button(a.name, () => openAssessment(a.id), 'row-button'), el('span', `${a.client || 'Unassigned'} / ${a.scope}`, 'subline'));append(row, identity, el('td', workflows[a.workflow] || a.workflow), el('td', date(a.created_at), 'mono'), el('td', a.finding_count, 'mono'), el('td', a.unresolved_count, 'mono'));labelCells(row, ['Assessment / scope', 'Workflow', 'Created', 'Candidates', 'Open']);body.append(row);});table.append(body);8 unmodified linestry {state.assessment = (await api(`/api/assessments/${encodeURIComponent(id)}`)).assessment;state.tab = 'ledger';state.ledgerSearch = state.verdict = state.severity = '';renderAssessment();}catch (error) {6 unmodified linesconst a = state.assessment;const view = $('#view');view.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]) => {70 unmodified linesconst search = el('input');search.type = 'search';search.placeholder = 'Search evidence, location, verdict…';search.value = state.ledgerSearch;search.setAttribute('aria-label', 'Search findings');const count = el('span', '', 'count');const verdictFilter = selectControl('Filter by verdict', [['', 'All verdicts'], ...['unresolved', 'confirmed-static', 'confirmed-runtime', 'rejected'].map(v => [v, v])]);const severityFilter = selectControl('Filter by severity', [['', 'All severities'], ...['high', 'medium', 'low'].map(v => [v, v])]);verdictFilter.value = state.verdict;severityFilter.value = state.severity;verdictFilter.addEventListener('change', () => { state.verdict = verdictFilter.value; draw(); });severityFilter.addEventListener('change', () => { state.severity = severityFilter.value; draw(); });append(toolbar, search, verdictFilter, severityFilter, count);panel.append(toolbar);const wrap = el('div', undefined, 'table-wrap');panel.append(wrap);function draw() {state.ledgerSearch = search.value;const q = search.value.toLowerCase();const matches = a.findings.filter(f => (!state.verdict || f.verdict === state.verdict) && (!state.severity || f.severity === state.severity) && `${f.title} ${f.location} ${f.verdict} ${f.evidence}`.toLowerCase().includes(q));count.textContent = `${matches.length} records`;const table = el('table');const head = el('tr');3 unmodified linesmatches.forEach(f => {const row = el('tr');const identity = el('td');const findingButton = button(f.title, () => openFinding(f), 'row-button');findingButton.dataset.finding = f.id;append(identity, findingButton, el('span', f.location, 'subline mono'));append(row, identity, el('td', f.severity, 'tag'), el('td', f.confidence, 'tag'), el('td', f.verdict, 'tag'));labelCells(row, ['Candidate / location', 'Severity', 'Confidence', 'Verdict']);body.append(row);});table.append(body);17 unmodified linesappend(section, el('h3', title), el('p', displayValue(value)));body.append(section);});$('#finding-body h2').id = 'finding-title';$('#verdict').value = f.verdict;$('#review-note').value = f.review_note || '';const review = f.review || {};const tracking = f.tracking || {};for (const [key, id] of Object.entries(reviewFields)) $(`#${id}`).value = review[key] || '';for (const [key, id] of Object.entries(trackingFields)) $(`#${id}`).value = tracking[key] || (key === 'status' ? 'open' : '');updateReviewRequirements();state.originalReview = reviewSnapshot();if (!$('#finding-dialog').open) $('#finding-dialog').showModal();$('#verdict').focus();}async function download(format) {try {61 unmodified linesbusy(form, async () => {const result = await api('/api/assessments', {method: 'POST', body: JSON.stringify({name: $('#assessment-name').value.trim(), client: $('#client').value.trim(), workflow: $('#workflow').value, scope: $('#scope').value.trim(), authorization: $('#authorization').checked, content: $('#content').value, roles: selected})});form.reset();4 unmodified lines$('#create-dialog').close();state.assessment = result.assessment;state.tab = 'ledger';state.ledgerSearch = state.verdict = state.severity = '';renderAssessment();notify('Assessment created. Candidates await analyst review.');});8 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.');});});5 unmodified linesawait loadOverview();notify('Assessment deleted.');}));window.addEventListener('beforeunload', event => {const 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 = '';}});const reviewFields = {reviewer: 'reviewer', reference: 'reference', prerequisites: 'review-prerequisites',mitigations: 'review-mitigations', method: 'review-method'};const trackingFields = {owner: 'tracking-owner', due_date: 'tracking-due', status: 'tracking-status', retest: 'tracking-retest'};function fieldValues(fields) {return Object.fromEntries(Object.entries(fields).map(([key, id]) => [key, $(`#${id}`).value.trim()]));}function reviewSnapshot() {return JSON.stringify({ verdict: $('#verdict').value, note: $('#review-note').value, review: fieldValues(reviewFields), tracking: fieldValues(trackingFields) });}function updateReviewRequirements() {const confirmed = $('#verdict').value.startsWith('confirmed-');Object.values(reviewFields).forEach(id => { $(`#${id}`).required = confirmed; });const method = $('#review-method');method.minLength = confirmed ? 20 : 0;const substantive = method.value.trim().length >= 20 && (method.value.match(/[\p{L}\p{N}]/gu) || []).length >= 10;method.setCustomValidity(confirmed && method.value && !substantive ? 'Describe the method in at least 20 characters, including 10 letters or digits.' : '');}$('#verdict').addEventListener('change', updateReviewRequirements);$('#review-method').addEventListener('input', updateReviewRequirements);function selectControl(label, entries) {const select = el('select');select.setAttribute('aria-label', label);entries.forEach(([value, text]) => {const option = el('option', text);option.value = value;select.append(option);});return select;}function labelCells(row, labels) {[...row.children].forEach((cell, i) => { cell.dataset.label = labels[i]; });}function saveText(text, filename, type = 'application/json;charset=utf-8') {const url = URL.createObjectURL(new Blob([text], { type }));const link = el('a');link.href = url;link.download = filename;document.body.append(link);link.click();link.remove();setTimeout(() => URL.revokeObjectURL(url), 1000);}async function backupWorkspace() {try {const text = await CyberLocal.backupText(state.client || undefined);saveText(text, `napolean-backup-${new Date().toISOString().slice(0, 10)}.json`);notify(`Backup exported for ${state.client || 'all clients'}. Restore it with “Restore backup”.`);} catch (error) { notify(error.message, true); }}function openRestore() {state.restoreText = '';$('#restore-form').reset();$('#restore-preview').replaceChildren();$('#restore-form .error-inline').hidden = true;$('#restore-submit').disabled = true;$('#restore-dialog').showModal();}let previewSequence = 0;$('#restore-file').addEventListener('change', async () => {const sequence = ++previewSequence;state.restoreText = '';$('#restore-submit').disabled = true;$('#restore-confirm').checked = false;$('#restore-preview').textContent = '';const file = $('#restore-file').files[0];if (!file) return;try {if (file.size > 5 * 1024 * 1024) throw new Error('Backup exceeds the 5 MB file limit.');const text = await file.text();const preview = await CyberLocal.previewBackup(text);if (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) {if (sequence === previewSequence) formError($('#restore-form'), error.message);}});$('#restore-form').addEventListener('submit', event => {event.preventDefault();if (!state.restoreText) { formError(event.currentTarget, 'Choose and validate a backup first.'); return; }busy(event.currentTarget, async () => {const result = await CyberLocal.restoreBackup(state.restoreText);state.restoreText = '';state.client = '';$('#restore-dialog').close();await loadOverview();notify(`${result.count} assessment copies restored. Existing records were preserved.`);});});$('#restore-dialog').addEventListener('close', () => {previewSequence++;state.restoreText = '';$('#restore-file').value = '';});function openHandoff() {if (state.assessment.roles.length < 2) { notify('A role handoff requires at least two assigned perspectives.'); return; }$('#handoff-form').reset();$('#handoff-form .error-inline').hidden = true;['#handoff-from', '#handoff-to'].forEach(id => {const select = $(id);select.replaceChildren();state.assessment.roles.forEach(role => {const option = el('option', `${role} hat`);option.value = role;select.append(option);});});if (state.assessment.roles.length > 1) $('#handoff-to').selectedIndex = 1;$('#handoff-dialog').showModal();}$('#handoff-form').addEventListener('submit', event => {event.preventDefault();if ($('#handoff-from').value === $('#handoff-to').value) { formError(event.currentTarget, 'Choose two different assigned perspectives.'); return; }busy(event.currentTarget, async () => {state.assessment = (await api(`/api/assessments/${state.assessment.id}`, {method: 'PATCH', body: JSON.stringify({ from: $('#handoff-from').value, to: $('#handoff-to').value, note: $('#handoff-note').value.trim() })})).assessment;$('#handoff-dialog').close();state.tab = 'coverage';renderAssessment();$('#tab-coverage').focus();notify('Role handoff recorded locally.');});});$('#next-unresolved').addEventListener('click', () => {if (reviewSnapshot() !== state.originalReview && !window.confirm('Discard unsaved changes and open the next unresolved finding?')) return;const findings = state.assessment.findings;const index = findings.findIndex(f => f.id === state.finding.id);const next = [...findings.slice(index + 1), ...findings.slice(0, index)].find(f => f.verdict === 'unresolved');if (!next) { notify('There are no other unresolved findings.'); return; }openFinding(next);$('#finding-dialog').scrollTop = 0;});function printReport() {const a = state.assessment;const report = $('#print-report');report.replaceChildren(el('p', 'NAPOLEAN / 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]) => {report.append(el('h2', title));const findings = a.findings.filter(test);if (!findings.length) report.append(el('p', 'None recorded.'));findings.forEach(f => {const section = el('article', undefined, 'print-finding');append(section, el('h3', `${f.title} · ${f.severity} / ${f.verdict}`));const review = f.review || {};const completeReview = Object.keys(reviewFields).every(key => typeof review[key] === 'string' && review[key].trim().length > 0)&& (review.method || '').trim().length >= 20&& ((review.method || '').match(/[\p{L}\p{N}]/gu) || []).length >= 10;if (f.verdict.startsWith('confirmed-') && !completeReview) {section.append(el('p', 'Legacy attestation: structured evidence is incomplete; this verdict requires renewed review.'));}for (const [label, value] of [['Location', f.location], ['Evidence', f.evidence], ['Remediation', f.remediation], ['Analyst note', f.review_note], ...Object.entries(f.review || {}).map(([key, value]) => [`Review ${key}`, value]), ...Object.entries(f.tracking || {}).map(([key, value]) => [`Tracking ${key}`, value])]) {section.append(el('p', `${label}: ${displayValue(value)}`));}report.append(section);});});report.append(el('h2', 'Coverage and limitations'));a.coverage.forEach(item => report.append(el('p', displayValue(item))));report.append(el('h2', 'Activity and handoffs'));a.activity.forEach(item => report.append(el('p', `${item.at} · ${item.action}: ${item.note}`)));window.print();}loadOverview();
1 unmodified line2345678129 unmodified lines13813914014114214387 unmodified lines23123223323423523623723823924024119 unmodified lines2612622632642651 unmodified line<html lang="en"><head><meta charset="utf-8"/><meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'"/><meta content="width=device-width,initial-scale=1" name="viewport"/><meta content="dark" name="color-scheme"/><meta content="#171719" name="theme-color"/>129 unmodified lines<label for="scope">Authorized scope</label><input id="scope" maxlength="1000" name="scope" placeholder="Owned service, repository, or exercise boundary" required=""/><fieldset><legend>87 unmodified lines<label for="review-note">Decision evidence / note</label><textarea id="review-note" maxlength="4000" minlength="20" placeholder="Describe the evidence supporting your decision." required="" rows="4"></textarea><p class="fine">A runtime verdict requires evidence you obtained independently. This workbench does not execute source or validate exploitation.</p><div class="dialog-actions"><button data-close="" type="button">Close</button>19 unmodified lines</button></div></dialog></body></html>1 unmodified line2345678129 unmodified lines13813914014114214314414514614714814915087 unmodified lines23823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933019 unmodified lines3503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374381 unmodified line<html lang="en"><head><meta charset="utf-8"/><meta content="default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'" http-equiv="Content-Security-Policy"/><meta content="width=device-width,initial-scale=1" name="viewport"/><meta content="dark" name="color-scheme"/><meta content="#171719" name="theme-color"/>129 unmodified lines<label for="scope">Authorized scope</label><label for="client">Client label (optional)</label><input id="client" maxlength="120" name="client" placeholder="Unassigned"/><p class="fine">Client labels organize records in this browser. They do not restrict access.</p><input id="scope" maxlength="1000" name="scope" placeholder="Owned service, repository, or exercise boundary" required=""/><fieldset><legend>87 unmodified lines<label for="review-note">Decision evidence / note</label><fieldset class="review-fields"><legend>Analyst attestation · required for confirmations</legend><p class="fine">These entries are analyst assertions, not independent proof or verified identity.</p><div class="form-grid"><div><label for="reviewer">Reviewer label</label><input id="reviewer" maxlength="120"/></div><div><label for="reference">Evidence reference / revision</label><input id="reference" maxlength="500" placeholder="Ticket, commit, test record"/></div></div><label for="review-prerequisites">Verified prerequisites</label><textarea id="review-prerequisites" maxlength="2000" rows="2"></textarea><label for="review-mitigations">Mitigations inspected</label><textarea id="review-mitigations" maxlength="2000" rows="2"></textarea><label for="review-method">Validation method / result</label><textarea aria-describedby="review-method-help" id="review-method" maxlength="2000" rows="3"></textarea><p class="fine" id="review-method-help">For confirmed verdicts, describe the method and result in at least 20 characters, including at least 10 letters or digits.</p></fieldset><fieldset><legend>Remediation tracking</legend><div class="form-grid"><div><label for="tracking-owner">Owner</label><input id="tracking-owner" maxlength="120"/></div><div><label for="tracking-due">Target date</label><input id="tracking-due" type="date"/></div><div><label for="tracking-status">Status</label><select id="tracking-status"><option value="open">Open</option><option value="in-progress">In progress</option><option value="resolved">Resolved</option><option value="retest">Retest</option></select></div></div><label for="tracking-retest">Retest evidence / note</label><textarea id="tracking-retest" maxlength="2000" rows="2"></textarea></fieldset><textarea id="review-note" maxlength="4000" minlength="20" placeholder="Describe the evidence supporting your decision." required="" rows="4"></textarea><p class="fine">A runtime verdict requires evidence you obtained independently. This workbench does not execute source or validate exploitation.</p><div class="dialog-actions"><button id="next-unresolved" type="button">Next unresolved →</button><button data-close="" type="button">Close</button>19 unmodified lines</button></div></dialog><dialog aria-labelledby="restore-title" id="restore-dialog"><form id="restore-form"><div class="dialog-head"><h2 id="restore-title">Restore workspace backup</h2><button aria-label="Close restore" class="close" data-close="" type="button">×</button></div><p class="error-inline" hidden="" role="alert"></p><p class="fine">Choose a versioned JSON backup, up to 5 MB. Valid records are added as new copies; existing assessments are never replaced.</p><label for="restore-file">Backup file</label><input accept=".json,application/json" id="restore-file" required="" type="file"/><div class="record-section" id="restore-preview" role="status"></div><label class="attestation"><input id="restore-confirm" required="" type="checkbox"/><span>I reviewed the preview and want to add these records to this browser workspace.</span></label><div class="dialog-actions"><button data-close="" type="button">Cancel</button><button class="primary" disabled="" id="restore-submit" type="submit">Restore copies ↗</button></div></form></dialog><dialog aria-labelledby="handoff-title" id="handoff-dialog"><form id="handoff-form"><div class="dialog-head"><h2 id="handoff-title">Record a role handoff</h2><button aria-label="Close handoff" class="close" data-close="" type="button">×</button></div><p class="error-inline" hidden="" role="alert"></p><p class="fine">Records a local coordination note. This does not notify another person or run a role agent.</p><div class="form-grid"><div><label for="handoff-from">From perspective</label><select id="handoff-from"></select></div><div><label for="handoff-to">To perspective</label><select id="handoff-to"></select></div></div><label for="handoff-note">Evidence, challenge, and next action</label><textarea id="handoff-note" maxlength="2000" minlength="20" required="" rows="4"></textarea><div class="dialog-actions"><button data-close="" type="button">Cancel</button><button class="primary" type="submit">Record handoff ↗</button></div></form></dialog><section aria-label="Executive assessment report" id="print-report"></section></body></html>
9 unmodified lines1011121314159 unmodified lines2526272829304 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697026 unmodified lines97989910010110210310410530 unmodified lines1361371381391401411423 unmodified lines1461471481491501511521531541555 unmodified lines16116216316416516638 unmodified lines20520620720820921025 unmodified lines2362372382392402412424 unmodified lines2472482492502512522532542552562572582592602612622632642656 unmodified lines2722732742752762772782792809 unmodified linesconst ROLES = ['red', 'blue', 'white', 'black', 'purple'];const VERDICTS = ['unresolved', 'confirmed-static', 'confirmed-runtime', 'rejected'];const MAX_RECORDS = 100, MAX_ACTIVITY = 200;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.');9 unmodified linesif (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('A JSON object is required.');return value;}function redact(value) {return String(value).replace(/(\b[\w.-]*(?:secret|password|passwd|token|api_?key|access_?key|private_?key)[\w.-]*\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;\r\n]+)/gi, '$1[REDACTED]')4 unmodified linesreturn {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:''};}function codeCandidates(content) {const findings = [];const lines = content.split(/\r?\n/);for (let index = 0; index < lines.length && findings.length < 100; index++) {const line = lines[index], location = `Submitted snippet line ${index + 1}`;if (/\b(?:eval|exec)\s*\(/.test(line)) findings.push(finding('Possible dynamic Python evaluation', 'high', location,'A direct eval/exec call-like text pattern was observed.','Single-line text pattern matched; arguments and source text omitted.','Check whether this is executable code and trace untrusted inputs; replace dynamic evaluation with explicit parsing.','Comments, strings, shadowed names and unreachable code can produce false positives. No syntax parsing.'));if (findings.length < 100 && /\bsubprocess\.(?:run|call|Popen|check_call|check_output)\s*\([^\n]*\bshell\s*=\s*True\b/.test(line)) {findings.push(finding('Possible shell-enabled process invocation', 'high', location,'A direct single-line subprocess call-like pattern includes shell=True.','Text pattern matched; command and source text omitted.','Verify the call and input reachability; prefer shell=False with an explicit argument list.','No parser, alias resolution or source-to-sink proof; comments and strings can match.'));}const secret = /\b[\w]*(?:secret|password|passwd|token|api_?key|access_?key|private_?key)[\w]*\s*(?::[^=\n]+)?=\s*(["'])([^\r\n]*?)\1/i.exec(line);if (findings.length < 100 && secret && secret[2].length >= 8) findings.push(finding('Possible embedded credential', 'medium', location,'A secret-like assignment pattern contains a string literal.','Possible secret-like assignment. Variable name and literal [REDACTED].','Verify whether this is an active credential; if so revoke it and move it to a secret store.','Value may be a placeholder or comment; validity and exposure are unverified.'));}return {findings, coverage:['Limited single-line regex/pattern nomination only: direct eval/exec, direct subprocess shell=True and secret-like assignments.','No Python AST or syntax parser, taint tracking, import/alias resolution, dependency audit, execution or exploit validation. Comments and strings may match; multiline patterns may be missed.','Maximum 100 candidates. No matches do not establish security; manual review is required.']};}function alertCandidates(content) {26 unmodified lines'Corroborate original sensor evidence, establish context and follow the approved incident response runbook.','Event labels are untrusted reports; approval and actual compromise are unverified.'));}return {findings,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.`,'No live telemetry, event authenticity, timestamp checks, deduplication or malware analysis. Raw logs and actor/source identifiers are discarded.']};}30 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:redact(name),workflow,scope:redact(scope),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.'}]};}3 unmodified lines.replace(/[\\`*_{}\[\]()#+.!|>~-]/g,'\\$&').replace(/[\r\n]/g,' ');}const lines = ['# Napolean Cyber Command assessment','',`Name: ${safe(assessment.name)}`,`Scope: ${safe(assessment.scope)}`,`Workflow: ${assessment.workflow}`,`Created: ${safe(assessment.created_at)}`,'',safe(assessment.summary),'','## Evidence ledger'];for (const item of assessment.findings) {lines.push('',`### ${safe(item.title)}`);for (const key of ['severity','confidence','verdict','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note']) lines.push(`${key.replaceAll('_',' ')}: ${safe(item[key])}`);}lines.push('','## Missions');for (const mission of assessment.missions) {5 unmodified linesreturn lines.join('\n')+'\n';}class IndexedDBStore {constructor(indexedDB = root.indexedDB) { this.indexedDB = indexedDB; this.opening = null; }open() {38 unmodified lines};});}update(id, mutate) {return this.transaction('readwrite',(store,done,fail)=>{const req=store.get(id); req.onsuccess=()=>{25 unmodified linesif(method==='GET') {const records=await this.store.list();records.sort((a,b)=>b.created_at.localeCompare(a.created_at));return {assessments:records.map(a=>({id:a.id,name:a.name,workflow:a.workflow,scope:a.scope,created_at:a.created_at,roles:a.roles,finding_count:a.findings.length,unresolved_count:a.findings.filter(f=>f.verdict==='unresolved').length}))};}if(method==='POST') return {assessment:await this.store.add(analyze(payload),MAX_RECORDS)};4 unmodified linesif(method==='GET' && !findingId) {const record=await this.store.get(assessmentId);if(!record) throw new Error('Assessment not found.');return {assessment:record};}if(method==='DELETE' && !findingId) return this.store.delete(assessmentId);if(method==='PATCH' && findingId) {object(payload);if(!VERDICTS.includes(payload.verdict)) throw new Error('Unsupported finding verdict.');const note=redact(text(payload.note,'Evidence note',4000,payload.verdict==='unresolved'?1:20));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.');target.verdict=payload.verdict;target.review_note=note;record.activity.push({at:now(),action:'finding_reviewed',note:`${findingId}: ${payload.verdict}. 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;});6 unmodified linesconst {assessment}=await this.request('/api/assessments/'+assessmentId);return format==='json'?JSON.stringify(assessment,null,2):markdownExport(assessment);}}let singleton;const service=()=>singleton || (singleton=new LocalService(new IndexedDBStore()));return {analyze,redact,markdownExport,LocalService,IndexedDBStore,request:(path,options)=>service().request(path,options),exportText:(assessmentId,format)=>service().exportText(assessmentId,format)};});9 unmodified lines1011121314151617189 unmodified lines282930313233343536373839404142434445464748495051525354555657585960616263644 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816926 unmodified lines19619719819920020120220320420520620730 unmodified lines2382392402412422432443 unmodified lines2482492502512522532542552562572582592602612622632642652662675 unmodified lines27327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634738 unmodified lines38638738838939039139239339439539639739839925 unmodified lines4254264274284294304314 unmodified lines4364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684696 unmodified lines4764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075089 unmodified linesconst ROLES = ['red', 'blue', 'white', 'black', 'purple'];const VERDICTS = ['unresolved', 'confirmed-static', 'confirmed-runtime', 'rejected'];const MAX_RECORDS = 100, MAX_ACTIVITY = 200;const REVIEW_FIELDS = ['reviewer','reference','prerequisites','mitigations','method'];const 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.');9 unmodified linesif (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('A JSON object is required.');return value;}function checkedObject(value, allowed, label) {object(value);if (Object.keys(value).some(key => !allowed.includes(key))) throw new Error(`${label} contains unsupported fields.`);return value;}function clean(value,label,maximum,minimum=0) {const result=redact(text(value,label,maximum,minimum));if(result.length>maximum) throw new Error(`${label} exceeds its ${maximum}-character limit after redaction. Shorten the text.`);return result;}function clientLabel(value) { return value === undefined || (typeof value==='string' && !value.trim()) ? 'Unassigned' : clean(value,'Client',120,1); }function reviewData(value={}, previous={}) {checkedObject(value,REVIEW_FIELDS,'Review');return Object.fromEntries(REVIEW_FIELDS.map(key=>[key,clean(value[key] ?? previous[key] ?? '',`Review ${key}`,key==='reviewer'?120:2000)]));}function hasReview(review) {return REVIEW_FIELDS.every(key=>review[key].trim().length>0) && review.method.trim().length>=20 && (review.method.match(/[\p{L}\p{N}]/gu)||[]).length>=10;}function dueDate(value) {if (value === '') return '';if(typeof value!=='string' || !/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(Date.parse(value+'T00:00:00Z')) || new Date(value+'T00:00:00Z').toISOString().slice(0,10)!==value) throw new Error('Due date must be a valid ISO date (YYYY-MM-DD).');return value;}function trackingData(value={}, previous={}) {checkedObject(value,TRACKING_FIELDS,'Tracking');const status=value.status ?? previous.status ?? 'open';if(!TRACKING_STATUSES.includes(status)) throw new Error('Unsupported remediation status.');return {owner:clean(value.owner ?? previous.owner ?? '', 'Remediation owner',2000),due_date:dueDate(value.due_date ?? previous.due_date ?? ''),status,retest:clean(value.retest ?? previous.retest ?? '', 'Retest note',2000)};}function redact(value) {return String(value).replace(/(\b[\w.-]*(?:secret|password|passwd|token|api_?key|access_?key|private_?key)[\w.-]*\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;\r\n]+)/gi, '$1[REDACTED]')4 unmodified linesreturn {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()};}function maskPython(content) {const chars=content.split(''),strings=[];const hide=(start,end)=>{for(let cursor=start;cursor<end;cursor++) if(chars[cursor]!=='\n'&&chars[cursor]!=='\r') chars[cursor]=' ';};let index=0;while(index<content.length) {if(content[index]==='#') {const end=content.indexOf('\n',index);const stop=end<0?content.length:end;hide(index,stop);index=stop;continue;}if(content[index]==='\\'&&content[index+1]==='\n'){chars[index]=' ';index+=2;continue;}if(content[index]!=="'"&&content[index]!=='"'){index++;continue;}const start=index,quote=content[index],width=content.slice(index,index+3)===quote.repeat(3)?3:1;index+=width;const valueStart=index;let closed=false,valueEnd=content.length;while(index<content.length) {if(content[index]==='\\'){index=Math.min(index+2,content.length);continue;}if(content.slice(index,index+width)===quote.repeat(width)){valueEnd=index;index+=width;closed=true;break;}index++;}if(closed) strings.push({start,valueLength:valueEnd-valueStart});hide(start,index);}return {masked:chars.join(''),strings};}function shellArgument(masked,opening) {const limit=Math.min(masked.length,opening+8193);let depth=1,end=-1;for(let index=opening+1;index<limit;index++) {if(masked[index]==='(') depth++;if(masked[index]===')'&&--depth===0){end=index;break;}}if(end<0) return false;const stack=[];let start=opening+1;for(let index=start;index<=end;index++) {const char=masked[index];if(index===end||(char===','&&!stack.length)) {if(/^\s*shell\s*=\s*True\s*$/.test(masked.slice(start,index))) return true;start=index+1;continue;}if('([{'.includes(char)) stack.push(char);else if(')]}'.includes(char)) stack.pop();}return false;}function codeCandidates(content) {const findings=[],{masked,strings}=maskPython(content);const modules=new Set(['subprocess']),functions=new Set();const shellFunctions=new Set(['run','call','Popen','check_call','check_output']);for(const imported of masked.matchAll(/^\s*import\s+([^\n;]+)/gm)) {for(const part of imported[1].split(',')) {const alias=/^\s*subprocess(?:\s+as\s+([A-Za-z_]\w*))?\s*$/.exec(part);if(alias) modules.add(alias[1]||'subprocess');}}for(const imported of masked.matchAll(/^\s*from\s+subprocess\s+import\s+(\([\s\S]*?\)|[^\n;]+)/gm)) {for(const part of imported[1].replace(/[()]/g,'').split(',')) {const alias=/^\s*([A-Za-z_]\w*)(?:\s+as\s+([A-Za-z_]\w*))?\s*$/.exec(part);if(alias&&shellFunctions.has(alias[1])) functions.add(alias[2]||alias[1]);}}const location=index=>`Submitted snippet line ${content.slice(0,index).split('\n').length}`;let inspected=0;const calls=/\b([A-Za-z_]\w*)(?:\s*\.\s*([A-Za-z_]\w*))?\s*\(/g;for(const call of masked.matchAll(calls)) {if(++inspected>500||findings.length>=100) break;const start=call.index,first=call[1],member=call[2];if(start>0&&/[\w.]/.test(masked[start-1])) continue;const linePrefix=masked.slice(masked.lastIndexOf('\n',start-1)+1,start);if(/\b(?:def|class)\s*$/.test(linePrefix)) continue;if(!member&&(first==='eval'||first==='exec')) findings.push(finding('Possible dynamic Python evaluation','high',location(start),'A direct eval/exec call-like pattern was observed after comment/string masking.','Lexical pattern matched; arguments and source text omitted.','Trace input reachability and builtin shadowing; replace dynamic evaluation with explicit parsing.','No syntax, scope, taint or reachability proof. Shadowed names or invalid code can produce false positives.'));const subprocessCall=(member&&modules.has(first)&&shellFunctions.has(member))||(!member&&functions.has(first));if(subprocessCall&&shellArgument(masked,call.index+call[0].length-1)&&findings.length<100) findings.push(finding('Possible shell-enabled process invocation','high',location(start),'A direct or simply imported subprocess call-like pattern has a literal top-level shell=True argument.','Bounded multiline lexical pattern matched; command and source text omitted.','Verify the imported binding and input reachability; prefer shell=False with an explicit argument list.','Simple imports only; no scope, rebinding, dataflow or exploit validation.'));}for(const literal of strings) {if(findings.length>=100) break;if(literal.valueLength<8) continue;const prefix=masked.slice(masked.lastIndexOf('\n',literal.start-1)+1,literal.start);const assignment=/^\s*([A-Za-z_]\w*)\s*(?::[^=\n]+)?=\s*[rRuUbBfF]{0,2}\s*$/.exec(prefix);if(assignment&&/(?:secret|password|passwd|token|api_?key|access_?key|private_?key)/i.test(assignment[1])) findings.push(finding('Possible embedded credential','medium',location(literal.start),'A secret-like direct assignment has a quoted string value.','Possible credential assignment. Variable name and literal [REDACTED].','Verify whether this is an active credential; if so revoke it and use a secret store.','Value may be a placeholder or dynamic string; validity and exposure are unverified.'));}return {findings,coverage:['Limited lexical regex/pattern nomination: quoted strings/comments masked for call detection, direct eval/exec, simple subprocess import aliases and bounded multiline literal shell=True arguments.','No Python AST or syntax parser, scope/rebinding resolution, taint/dataflow, dependency audit, execution or exploit validation. Wildcard/dynamic imports, f-string expressions, complex assignments and computed shell flags may be missed.','Maximum 500 call-like constructs, 8192 characters per subprocess call and 100 candidates. No matches do not establish security; manual review is required.']};}function alertCandidates(content) {26 unmodified lines'Corroborate original sensor evidence, establish context and follow the approved incident response runbook.','Event labels are untrusted reports; approval and actual compromise are unverified.'));}const omitted=Math.max(0,findings.length-100);findings.sort((a,b)=>(a.severity==='high'?0:1)-(b.severity==='high'?0:1));return {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.']};}30 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.'}]};}3 unmodified lines.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) {lines.push('',`### ${safe(item.title)}`);for (const key of ['severity','confidence','verdict','location','root_cause','input_to_impact','prerequisites','mitigations','evidence','remediation','review_note']) lines.push(`${key.replaceAll('_',' ')}: ${safe(item[key])}`);const review=reviewData(item.review),tracking=trackingData(item.tracking);for(const key of REVIEW_FIELDS) lines.push(`Review ${key}: ${safe(review[key] || '(not supplied)')}`);for(const key of TRACKING_FIELDS) lines.push(`Tracking ${key}: ${safe(tracking[key] || '(not supplied)')}`);if(item.verdict.startsWith('confirmed-') && !hasReview(review)) lines.push('Legacy attestation: structured evidence is incomplete; this verdict requires renewed review.');}lines.push('','## Missions');for (const mission of assessment.missions) {5 unmodified linesreturn lines.join('\n')+'\n';}function parseBackup(input) {if(typeof input!=='string' || input.length>5*1024*1024 || new TextEncoder().encode(input).length>5*1024*1024) throw new Error('Backup must be text no larger than 5 MB.');let parsed;try {parsed=JSON.parse(input);}catch(_){throw new Error('Backup is not valid JSON.');}object(parsed);let 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.`);return value;}function isoTime(value) {if(typeof value!=='string' || value.length>40 || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/.test(value) || !Number.isFinite(Date.parse(value))) throw new Error('Invalid assessment/activity timestamp.');dueDate(value.slice(0,10));return value;}function recordId(value) {if(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.');const missions=list(value.missions,'Missions',5,1).map(item=>{checkedObject(item,['role','title','objective','steps','deliverable','limitations'],'Mission');if(!roles.includes(item.role)) throw new Error('Mission role is outside the selected roles.');return {role:item.role,title:clean(item.title,'Mission title',500,1),objective:clean(item.objective,'Mission objective',4000,1),steps:list(item.steps,'Mission steps',20,1).map(row=>clean(row,'Mission step',4000,1)),deliverable:clean(item.deliverable,'Mission deliverable',4000,1),limitations:list(item.limitations,'Mission limitations',20,1).map(row=>clean(row,'Mission limitation',4000,1))};});if(missions.length!==roles.length || new Set(missions.map(row=>row.role)).size!==roles.length) throw new Error('Backup missions must cover exactly the selected roles.');const category=value.scenario_category ?? null;if(value.workflow==='exercise' ? !Object.hasOwn(playbooks.scenarios,category) : category!==null) throw new Error('Invalid scenario category in backup.');const activity=list(value.activity,'Activity',MAX_ACTIVITY,1).map(item=>{checkedObject(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);return {count:records.length,clients:[...new Set(records.map(row=>row.client))].sort()};}class IndexedDBStore {constructor(indexedDB = root.indexedDB) { this.indexedDB = indexedDB; this.opening = null; }open() {38 unmodified lines};});}addMany(records,maximum) {return this.transaction('readwrite',(store,done,fail)=>{const req=store.count();req.onsuccess=()=>{if(req.result+records.length>maximum){fail(new Error('Browser workspace limit: 100 assessments. Export and delete records before restoring.'));return;}try {for(const record of records) store.add(record);done(records);}catch(error){fail(error);}};});}update(id, mutate) {return this.transaction('readwrite',(store,done,fail)=>{const req=store.get(id); req.onsuccess=()=>{25 unmodified linesif(method==='GET') {const records=await this.store.list();records.sort((a,b)=>b.created_at.localeCompare(a.created_at));return {assessments:records.map(a=>({id:a.id,name:a.name,client:a.client || 'Unassigned',workflow:a.workflow,scope:a.scope,created_at:a.created_at,roles:a.roles,finding_count:a.findings.length,unresolved_count:a.findings.filter(f=>f.verdict==='unresolved').length}))};}if(method==='POST') return {assessment:await this.store.add(analyze(payload),MAX_RECORDS)};4 unmodified linesif(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) {checkedObject(payload,['from','to','note'],'Role handoff');const 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;});6 unmodified linesconst {assessment}=await this.request('/api/assessments/'+assessmentId);return format==='json'?JSON.stringify(assessment,null,2):markdownExport(assessment);}async 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;}previewBackup(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)};});
856 unmodified lines857858859856 unmodified linesfont-size: 11px;line-height: 1.7;}856 unmodified lines857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903856 unmodified linesfont-size: 11px;line-height: 1.7;}/* Business workflow controls preserve the terminal's quiet selection language. */.toolbar { flex-wrap: wrap; }.toolbar select { width: auto; max-width: 260px; min-width: 150px; }.toolbar .count { margin-left: auto; }fieldset { padding-top: 12px; border-top: 1px solid var(--border); }.review-fields legend { line-height: 1.6; }#restore-preview { max-height: 160px; overflow: auto; overflow-wrap: anywhere; font-size: 12px; line-height: 1.7; }#restore-file { max-width: 100%; }#print-report { display: none; }@media (max-width: 700px) {.toolbar input, .toolbar select { width: 100%; max-width: none; }.toolbar .count { margin-left: 0; }.table-wrap table { min-width: 0; }.table-wrap table, .table-wrap tbody { display: block; }.table-wrap thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }.table-wrap tr { display: block; border-bottom: 1px solid var(--border); padding: 14px 0; }.table-wrap td, .table-wrap td:first-child, .table-wrap td:last-child { display: grid; grid-template-columns: 102px minmax(0,1fr); gap: 8px; padding: 7px 0; text-align: left; border: 0; }.table-wrap td::before { content: attr(data-label); font: 10px ui-monospace, monospace; color: var(--muted); line-height: 1.6; }.table-wrap td:first-child { display: block; }.table-wrap td:first-child::before { display: block; margin-bottom: 6px; }.dialog-actions { flex-wrap: wrap; }.dialog-actions button { flex: 1 1 auto; min-height: 42px; }.tabs { gap: 20px; }.tab { font-size: 11px; }}@media print {:root { color-scheme: light; color: #111; background: #fff; font-size: 11pt; }body > * { display: none !important; }body > #print-report { display: block !important; }#print-report { color: #111; background: #fff; padding: 12mm 8mm; }#print-report p { font-size: 10pt; line-height: 1.5; white-space: pre-wrap; overflow-wrap: anywhere; }#print-report h1 { font-size: 25pt; }#print-report h2 { font-size: 17pt; margin-top: 22pt; break-after: avoid; }#print-report h3 { font-size: 12pt; break-after: avoid; }#print-report .eyebrow { color: #444; }.print-finding { border-top: 1px solid #bbb; padding-top: 14pt; margin-top: 14pt; }@page { margin: 12mm; }}dialog { overscroll-behavior: contain; }@media (max-width: 700px) {input, select, textarea { font-size: 16px; }}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219'use strict';// Real Chromium/IndexedDB integration checks. Uses an existing Playwright install.const assert = require('node:assert/strict');const http = require('node:http');const fs = require('node:fs/promises');const path = require('node:path');const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');const root = path.resolve(__dirname, '..');
async function main() { const server = http.createServer(async (request, response) => { try { const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname); const filename = path.resolve(root, '.' + (pathname === '/' ? '/index.html' : pathname)); if (!filename.startsWith(root + path.sep)) { response.writeHead(403).end(); return; } const body = await fs.readFile(filename); response.setHeader('Content-Type', { '.html': 'text/html', '.js': 'application/javascript', '.css': 'text/css' }[path.extname(filename)] || 'application/octet-stream'); response.end(body); } catch (_) { response.writeHead(404).end(); } }); await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); }); const origin = `http://127.0.0.1:${server.address().port}`; let browser; try { browser = 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)); await page.goto(origin); await page.waitForFunction(() => globalThis.CyberLocal && document.querySelector('#view h1')); const record = await page.evaluate(async () => { const result = await CyberLocal.request('/api/assessments', { method: 'POST', body: { name: 'Browser integration fixture', workflow: 'code', scope: 'Owned synthetic fixture', authorization: true, content: 'eval(user_input)', roles: ['red', 'blue', 'white', 'black', 'purple'] }}); return result.assessment; }); await page.reload(); await page.waitForFunction(() => globalThis.CyberLocal && document.querySelector('#view h1')); assert.equal(await page.evaluate(async id => (await CyberLocal.request('/api/assessments/' + id)).assessment.id, record.id), record.id); console.log('PASS actual IndexedDB survives page reload');
const 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(); const before = (await store.list()).length; const row = structuredClone(record); row.id = 'a'.repeat(32); let rejected = false; try { await store.addMany([row, structuredClone(row)], 100); } catch (_) { rejected = true; } return { rejected, before, after: (await store.list()).length, exists: !!(await store.get(row.id)) }; }, record); assert.deepEqual(duplicateRollback, { rejected: true, before: 1, after: 1, exists: false }); console.log('PASS actual IndexedDB duplicate-key transaction abort rolls back entire batch');
const quotaRollback = await page.evaluate(async record => { const store = new CyberLocal.IndexedDBStore(); const original = IDBObjectStore.prototype.add; const rows = ['b', 'c'].map(letter => ({ ...structuredClone(record), id: letter.repeat(32) })); let calls = 0, rejected = false; IDBObjectStore.prototype.add = function (...args) { if (++calls === 2) throw new DOMException('Synthetic quota failure', 'QuotaExceededError'); return original.apply(this, args); }; try { await store.addMany(rows, 100); } catch (_) { rejected = true; } finally { IDBObjectStore.prototype.add = original; } return { rejected, retained: (await store.list()).length, firstExists: !!(await store.get(rows[0].id)) }; }, record); assert.deepEqual(quotaRollback, { rejected: true, retained: 1, firstExists: false }); console.log('PASS quota fault injection aborts real transaction without partial batch (simulated quota)');
const denied = await page.evaluate(async () => { const store = new CyberLocal.IndexedDBStore({ open() { throw new DOMException('Synthetic storage denial', 'SecurityError'); } }); try { await store.list(); return false; } catch (error) { return /storage|privacy/i.test(error.message); } }); assert.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(); CyberLocal.previewBackup(backup); await CyberLocal.restoreBackup(backup); const after = (await CyberLocal.request('/api/assessments')).assessments; const envelope = JSON.parse(backup); return { before, after, envelope }; }); assert.equal(restore.before.length, 1); assert.equal(restore.after.length, 2); assert.equal(new Set(restore.after.map(row => row.id)).size, 2); assert.ok(restore.after.some(row => row.id !== restore.before[0].id)); const 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 () => { const before = (await CyberLocal.request('/api/assessments')).assessments.length; const envelope = JSON.parse(await CyberLocal.backupText()); // Restore must validate the entire file before adding any of its records. if (!Array.isArray(envelope.records)) throw new Error('Expected versioned records backup envelope.'); envelope.records[envelope.records.length - 1].workflow = 'invalid-workflow'; 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(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'); await page.getByRole('button', { name: /Backup all clients JSON/ }).click(); const download = await downloaded; const stream = await download.createReadStream(); let downloadedText = ''; for await (const chunk of stream) downloadedText += chunk.toString('utf8'); assert.equal(JSON.parse(downloadedText).records.length, 2); await page.getByRole('button', { name: /Restore backup/ }).click(); await page.locator('#restore-file').setInputFiles({ name: 'synthetic-backup.json', mimeType: 'application/json', buffer: Buffer.from(downloadedText) }); await page.locator('#restore-preview').filter({ hasText: '2 assessment copies' }).waitFor(); await page.locator('#restore-confirm').check(); await page.locator('#restore-submit').click(); await page.waitForFunction(async () => (await CyberLocal.request('/api/assessments')).assessments.length === 4); console.log('PASS browser UI backup download, import preview, confirmation and restore');
const historyCap = await page.evaluate(async id => { const store = new CyberLocal.IndexedDBStore(); const record = await store.update(id, row => { row.activity = Array.from({ length: 200 }, () => ({ at: new Date().toISOString(), action: 'test_fixture', note: 'Synthetic history cap fixture' })); return 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); assert.deepEqual(historyCap, { rejected: true, count: 200 }); console.log('PASS actual IndexedDB preserves full history when its 200-entry cap rejects a write');
const fullHistoryRestore = await page.evaluate(async id => { const before = (await CyberLocal.request('/api/assessments')).assessments.length; const full = (await CyberLocal.request('/api/assessments/' + id)).assessment; await CyberLocal.restoreBackup(JSON.stringify(full)); const rows = (await CyberLocal.request('/api/assessments')).assessments; const originalIds = new Set([id]); let copyWithHistory = false; for (const row of rows) { if (originalIds.has(row.id)) continue; const copy = (await CyberLocal.request('/api/assessments/' + row.id)).assessment; if (copy.activity.length === 200) copyWithHistory = true; } return { before, after: rows.length, copyWithHistory }; }, record.id); assert.equal(fullHistoryRestore.after, fullHistoryRestore.before + 1); assert.equal(fullHistoryRestore.copyWithHistory, true); console.log('PASS maximum-history assessment remains restorable without truncating its evidence');
await page.evaluate(async () => { const store = new CyberLocal.IndexedDBStore(); const remaining = 99 - (await store.list()).length; const rows = Array.from({ length: remaining }, (_, index) => CyberLocal.analyze({ name: `Synthetic capacity fixture ${index}`, workflow: 'exercise', scope: 'Owned synthetic fixture', content: 'Generic tabletop exercise', authorization: true, roles: ['blue'] })); await store.addMany(rows, 100); }); const addAtCapacity = tab => tab.evaluate(async () => { try { await CyberLocal.request('/api/assessments', { method: 'POST', body: { name: 'Synthetic concurrent capacity write', workflow: 'exercise', scope: 'Owned synthetic fixture', content: 'Generic tabletop exercise', authorization: true, roles: ['blue'] }}); return true; } catch (_) { return false; } }); const capacityResults = await Promise.all([addAtCapacity(page), addAtCapacity(second)]); assert.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'); await context.close(); } finally { if (browser) await browser.close(); await new Promise(resolve => server.close(resolve)); }}main().catch(error => { console.error(error); process.exitCode = 1; });1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677'use strict';// Run against a local-only static server: APP_URL=http://127.0.0.1:7860/ node tests/browser_ui.cjsconst assert = require('node:assert/strict');const {chromium} = require(process.env.PLAYWRIGHT_MODULE || 'playwright');(async () => { const browser = await chromium.launch({headless:true, ...(process.env.PLAYWRIGHT_EXECUTABLE_PATH ? {executablePath:process.env.PLAYWRIGHT_EXECUTABLE_PATH} : {})}); try { const 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'); await page.locator('#client').fill('Fictional retailer'); await page.locator('#scope').fill('Owned synthetic Python fixture only'); await page.locator('#content').fill('import subprocess as sp\n# eval(ignored)\nsp.run(\n command,\n shell=True\n)\neval(incoming)'); await page.locator('#authorization').check(); await page.getByRole('button',{name:'Create assessment ↗',exact:true}).click(); const candidate=page.getByRole('button',{name:'Possible shell-enabled process invocation',exact:true}); await candidate.click(); await page.locator('#verdict').selectOption('confirmed-static'); await 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); await page.getByRole('combobox',{name:'Filter by severity'}).selectOption('medium'); assert.equal(await page.locator('tbody tr').count(),0); await 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')); if(process.env.ARTIFACT_DIR) await page.screenshot({path:process.env.ARTIFACT_DIR+'/business-workflows.png',fullPage:true}); await page.getByRole('button',{name:'← Assessment register',exact:true}).click(); await page.getByRole('combobox',{name:'Filter by client'}).selectOption('Fictional retailer'); const 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(); await page.locator('#restore-file').setInputFiles({name:'backup.json',mimeType:'application/json',buffer:Buffer.from(backup)}); await page.locator('#restore-submit').waitFor({state:'visible'}); await page.waitForFunction(()=>!document.querySelector('#restore-submit').disabled); await page.locator('#restore-confirm').check(); await 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;});12345678910111213141516171819202122'use strict';// Original fixtures; counts describe nominations, never exploit validation.module.exports = [ {name:'direct dynamic evaluation',source:'eval(user_input)',expected:1}, {name:'multiline dynamic evaluation',source:'exec(\n user_input\n)',expected:1}, {name:'direct subprocess shell flag',source:'import subprocess\nsubprocess.run(command, shell=True)',expected:1}, {name:'module alias multiline shell flag',source:'import subprocess as sp\nsp.run(\n command,\n # explanation\n shell=True\n)',expected:1}, {name:'function import alias',source:'from subprocess import run as launch\nlaunch(command, shell=True)',expected:1}, {name:'parenthesized imports',source:'from subprocess import (\n run as launch,\n check_output\n)\nlaunch(command, shell=True)',expected:1}, {name:'secret assignment literal',source:'api_key = "synthetic-placeholder-123"',expected:1}, {name:'comment is not code',source:'# eval(user_input)\n# subprocess.run(cmd, shell=True)\n# api_key = "synthetic-secret"',expected:0}, {name:'quoted code is not a call',source:'example = "eval(user_input)"\nother = \'subprocess.run(cmd, shell=True)\'',expected:0}, {name:'triple quoted example',source:'text = """\neval(user_input)\nsubprocess.run(cmd, shell=True)\n"""',expected:0}, {name:'shell False',source:'import subprocess as sp\nsp.run(command, shell=False)',expected:0}, {name:'quoted True is not Boolean',source:'subprocess.run(command, shell="True")',expected:0}, {name:'nested unrelated shell argument',source:'subprocess.run(wrapper(shell=True))',expected:0}, {name:'unrelated object method',source:'object.eval(user_input)\nother.run(command,shell=True)',expected:0}, {name:'function declaration',source:'def eval(value):\n return value',expected:0}, {name:'escaped quote followed by real call',source:'example = "escaped \\" eval(ignored)"\neval(user_input)',expected:1}, {name:'nested dynamic call',source:'print(eval(user_input))',expected:1}, {name:'nested subprocess sink',source:'wrapper(subprocess.run(command, shell=True))',expected:1},];12345678 unmodified lines1617181920216 unmodified lines28293031323351 unmodified lines8586878889909127 unmodified lines119120121'use strict';const test = require('node:test');const assert = require('node:assert/strict');const {analyze, redact, markdownExport, LocalService, IndexedDBStore} = require('../static/local.js');class MemoryStore {constructor() { this.rows = new Map(); this.chain = Promise.resolve(); }8 unmodified linesif (this.rows.size >= limit) throw new Error('100');this.rows.set(record.id, structuredClone(record)); return record;}); }update(id, fn) { return this.write(() => {if (!this.rows.has(id)) throw new Error('Assessment not found.');const next = fn(structuredClone(this.rows.get(id)));6 unmodified lines}const payload = changes => ({name:'Owned lab', workflow:'code', scope:'Owned test app', authorization:true,content:'eval(user_input)\nsubprocess.run(command, shell=True)', roles:['red','blue','white','black','purple'], ...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"'}));51 unmodified linesconst {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.'})});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');27 unmodified linesconst unavailable = new IndexedDBStore(undefined);await assert.rejects(unavailable.list(),/storage|IndexedDB/i);});12345678 unmodified lines161718192021222324252627286 unmodified lines353637383940414251 unmodified lines94959697989910027 unmodified lines128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321'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(); }8 unmodified linesif (this.rows.size >= limit) throw new Error('100');this.rows.set(record.id, structuredClone(record)); return record;}); }addMany(records, limit) { return this.write(() => {if(this.rows.size+records.length>limit) throw new Error('100 assessment limit');const ids=new Set(records.map(row=>row.id));if(ids.size!==records.length || records.some(row=>this.rows.has(row.id))) throw new Error('Duplicate ID');for(const row of records) this.rows.set(row.id,structuredClone(row));return records;}); }update(id, fn) { return this.write(() => {if (!this.rows.has(id)) throw new Error('Assessment not found.');const next = fn(structuredClone(this.rows.get(id)));6 unmodified lines}const payload = changes => ({name:'Owned lab', workflow:'code', scope:'Owned test app', authorization:true,content:'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"'}));51 unmodified linesconst {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');27 unmodified linesconst unavailable = new IndexedDBStore(undefined);await assert.rejects(unavailable.list(),/storage|IndexedDB/i);});test('versioned backup previews clients and restores sanitized copies with fresh record and finding IDs', async () => {const store=new MemoryStore(), service=new LocalService(store);const first=(await service.request('/api/assessments',{method:'POST',body:payload({client:'Acme'})})).assessment;await service.request('/api/assessments',{method:'POST',body:payload({client:'Other business',workflow:'exercise',content:'A cloud tabletop'})});const backup=await service.backupText('Acme');assert.deepEqual(previewBackup(backup),{count:1,clients:['Acme']});assert.equal(JSON.parse(backup).format,'napolean-cyber-command');assert.deepEqual(await service.restoreBackup(backup),{count:1});const records=await store.list();const copy=records.find(row=>row.id!==first.id && row.client==='Acme');assert.ok(copy); assert.notEqual(copy.findings[0].id,first.findings[0].id);assert.equal(copy.name,first.name);assert.deepEqual(previewBackup(JSON.stringify(first)),{count:1,clients:['Acme']});const clientNames=(await service.request('/api/assessments')).assessments.map(row=>row.client);assert.ok(clientNames.includes('Other business'));});test('restore rejects malformed, oversized, hostile extra fields and invalid records without any mutation', async () => {const 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)]) {await assert.rejects(service.restoreBackup(input));assert.equal((await store.list()).length,0);}const malicious=structuredClone(record);malicious.scope='Owned scope password="Correct Horse Battery Staple"';await service.restoreBackup(envelope([malicious]));assert.doesNotMatch(JSON.stringify(await store.list()),/Correct Horse/);});test('restore capacity failure preserves existing records and adds no partial copies', async () => {const store=new MemoryStore(), service=new LocalService(store);for(let i=0;i<99;i++) await service.request('/api/assessments',{method:'POST',body:payload({content:'print(1)'})});const records=[analyze(payload()),analyze(payload())];await assert.rejects(service.restoreBackup(JSON.stringify({format:'napolean-cyber-command',version:1,records})),/100/);assert.equal((await store.list()).length,99);});test('confirmation requires structured evidence and remediation tracking validates dates and statuses', async () => {const service=new LocalService(new MemoryStore());const 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');const report=await service.exportText(a.id,'markdown');assert.match(report,/Executive summary/i);assert.match(report,/Fix owner/);assert.match(report,/Analyst A/);assert.ok(report.includes('Tracking status: in\\-progress'));});test('role handoffs append scoped activity and reject invalid or same-role handoffs', async () => {const service=new LocalService(new MemoryStore());const a=(await service.request('/api/assessments',{method:'POST',body:payload({roles:['red','blue']})})).assessment;const path='/api/assessments/'+a.id;for(const handoff of [{from:'red',to:'white',note:'Review this candidate.'},{from:'red',to:'red',note:'Review this candidate.'},{from:'red',to:'blue',note:''}]) {await assert.rejects(service.request(path,{method:'PATCH',body:handoff}));}const result=await service.request(path,{method:'PATCH',body:{from:'red',to:'blue',note:'Correlate this candidate with owned defensive telemetry.'}});assert.equal(result.assessment.activity.length,2);assert.equal(result.assessment.activity[1].action,'role_handoff');assert.match(result.assessment.activity[1].note,/red.*blue/);assert.match(await service.exportText(a.id,'markdown'),/Correlate this candidate/);});test('imported incomplete confirmations are explicitly downgraded and nested fields cannot smuggle raw inputs', async () => {const store=new MemoryStore(),service=new LocalService(store),record=analyze(payload());record.findings[0].verdict='confirmed-runtime';const envelope=rows=>JSON.stringify({format:'napolean-cyber-command',version:1,records:rows});await service.restoreBackup(envelope([record]));const restored=(await store.list())[0];assert.equal(restored.findings[0].verdict,'unresolved');assert.match(restored.activity.at(-1).note,/Legacy confirmations/);for(const mutate of [row=>row.findings[0].review.content='raw source',row=>row.missions[0].steps=[{}],row=>row.activity[0].raw='source',row=>row.findings[0].tracking.status='bad',row=>row.findings[0].severity='critical']) {const bad=structuredClone(record);mutate(bad);await assert.rejects(service.restoreBackup(envelope([bad])));}assert.equal((await store.list()).length,1);});test('maximum alert grouping still round trips through the bounded backup schema', async () => {const events=[];for(let i=0;i<99;i++) for(let n=0;n<5;n++) events.push({event:'login_failed',actor:String(i)});events.push({event:'privilege_change'},{event:'malware_detected'});const store=new MemoryStore(),service=new LocalService(store);const record=(await service.request('/api/assessments',{method:'POST',body:payload({workflow:'alerts',content:JSON.stringify(events)})})).assessment;assert.equal(record.findings.length,100);assert.ok(record.findings.some(f=>f.title==='Malware alert requires validation'));assert.match(record.coverage.join(' '),/1 candidate.*omitted/);assert.equal(previewBackup(await service.backupText()).count,1);});test('full legitimate activity history remains restorable without truncation',async()=>{const store=new MemoryStore(),service=new LocalService(store);const record=(await service.request('/api/assessments',{method:'POST',body:payload()})).assessment;await store.update(record.id,row=>{row.activity=Array.from({length:200},(_,index)=>({at:row.created_at,action:'finding_reviewed',note:'Evidence history entry '+index}));return row;});const backup=await service.backupText();await service.restoreBackup(backup);const copy=(await store.list()).find(row=>row.id!==record.id);assert.equal(copy.activity.length,200);assert.equal(copy.activity[199].note,'Evidence history entry 199');assert.match(copy.summary,/imported|restored/i);});test('redaction expansion cannot create records outside the bounded backup schema',async()=>{const store=new MemoryStore(),service=new LocalService(store);for(const change of [{name:'token=x '.repeat(15)},{client:'token=x '.repeat(15)},{scope:'token=x '.repeat(250)}]) {await assert.rejects(service.request('/api/assessments',{method:'POST',body:payload(change)}),/redact|limit|characters/i);}assert.equal((await store.list()).length,0);});test('invalid structured updates and handoff/activity limits never partially modify records',async()=>{const 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}`;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;});await assert.rejects(service.request('/api/assessments/'+record.id,{method:'PATCH',body:{from:'red',to:'blue',note:'New handoff'}}),/200/);assert.equal((await store.get(record.id)).activity.length,200);});test('optional blank client defaults to Unassigned while invalid types are rejected',()=>{for(const client of [undefined,'',' ']) assert.equal(analyze(payload({client})).client,'Unassigned');for(const client of [null,3,[]]) assert.throws(()=>analyze(payload({client})));});test('review activity retains prior reviewer and reference after latest evidence changes',async()=>{const 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);});test('maximum structured evidence remains backup-restorable and oversized workspace export gives an actionable error',async()=>{const 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);const large=await store.get(record.id);large.activity=Array.from({length:200},()=>({at:record.created_at,action:'review',note:'A'.repeat(8000)}));for(let i=0;i<4;i++){const copy=structuredClone(large);copy.id=i.toString(16).padStart(32,'0');store.rows.set(copy.id,copy);}await assert.rejects(service.backupText(),/5 MB.*smaller client group|5 MB.*individual assessment/);});test('bounded lexical detection fixture benchmark distinguishes code from comments and strings',()=>{const fixtures=require('./detection-fixtures.cjs');for(const fixture of fixtures) {const result=analyze(payload({content:fixture.source}));assert.equal(result.findings.length,fixture.expected,fixture.name);assert.ok(result.findings.every(row=>row.verdict==='unresolved'),fixture.name);assert.match(result.coverage.join(' '),/scope|rebinding|dataflow/i);}});test('multiline aliased calls preserve original evidence line and never retain source strings',()=>{const result=analyze(payload({content:'# heading\nimport subprocess as sp\nsp.run(\n "private-command-marker-9182",\n shell=True\n)'}));assert.equal(result.findings.length,1);assert.match(result.findings[0].location,/line 3$/);assert.doesNotMatch(JSON.stringify(result),/private-command-marker-9182/);});test('nested direct evaluation is nominated even when immediately after an outer opening parenthesis',()=>{const result=analyze(payload({content:'subprocess.run(eval(user_input), shell=True)'}));assert.equal(result.findings.length,2);assert.ok(result.findings.some(row=>row.title==='Possible dynamic Python evaluation'));const nested=analyze(payload({content:'# heading\nwrapper(\n subprocess.run(command, shell=True)\n)'}));assert.equal(nested.findings.length,1);assert.match(nested.findings[0].location,/line 3$/);});
IMPROVEMENTS.mdAdded+29
README.md+13-5
SECURITY.md+3-3
SERVICE.md+2-1
VERIFICATION.md+20-5
index.html+174-1
static/app.js+226-16
static/index.html+174-1
static/local.js+265-37
static/style.css+44
tests/browser_storage.cjsAdded+219
tests/browser_ui.cjsAdded+77
tests/detection-fixtures.cjsAdded+22
tests/test_local.cjs+202-2