Deliver no-cost browser-only security workbench on Static Spaces
Browse filesFiles changed (14)
- PROVENANCE.md+13-10
- README.md+36-47
- SECURITY.md+14-25
- SERVICE.md+19-33
- VERIFICATION.md+24-27
- deploy_hf.py+31-45
- index.htmlAdded+265
- static/app.js+15-91
- static/index.html+26-51
- static/local.jsAdded+280
- static/playbooks.jsAdded+207
- static/style.css+16
- tests/test_deploy.py+23-33
- tests/test_local.cjsAdded+121
112334556778910111213910151112131415161718# Workflow provenance# Provenance and final runtime
The user explicitly invoked local Napolean and Napolean Security skills. This implementation expresses their commander/scope/evidence/challenge/adjudication concepts in original application code. Reading the skills did not activate upstream runtimes.The user invoked Napolean and Napolean Security, then required no Docker and no-cost hosting. The final runtime is a private Hugging Face Static Space with dependency-free HTML/CSS/JavaScript. It runs no server, GPU, model provider or upstream scanner. The evidence lifecycle and mission templates are original implementation of the requested commander/scope/discovery/challenge/adjudication concepts.
Napolean Security references AgriciDaniel/claude-cybersecurity, tanviet12/vbsec, agamm/claude-code-owasp, ghostsecurity/skills, goplussecurity/agentguard, codexstar69/bug-hunter, kenryu42/cc-safety-net, anthropics/defending-code-reference-harness, trailofbits/skills and cloudflare/security-audit-skill. None of their executables, rule sets or source files are bundled, copied or claimed to have run. Their licenses do not automatically apply to this original application. Future integrations require inspecting exact versions, licenses, permissions and data flow.Napolean Security references AgriciDaniel/claude-cybersecurity, tanviet12/vbsec, agamm/claude-code-owasp, ghostsecurity/skills, goplussecurity/agentguard, codexstar69/bug-hunter, kenryu42/cc-safety-net, anthropics/defending-code-reference-harness, trailofbits/skills and cloudflare/security-audit-skill. None of their executables, source files or rule sets are bundled or claimed to run. Their licenses do not automatically license this original application.
The new workspace had no existing repository to map; Graphify was not run. The preferred local Crawl4AI documentation fetch failed because its browser process could not launch. Official web retrieval was used instead.The original Python engine supplied the application's original role/scenario template data. Static code checks are newly implemented text patterns, not a claim that Python AST analysis was ported to the browser. No model was trained or invoked.
Primary documentation consulted on 2026-10-31:- [Hugging Face Gradio Spaces](https://huggingface.co/docs/hub/spaces-sdks-gradio): native SDK and application entry-point configuration.- [Hugging Face Docker Spaces](https://huggingface.co/docs/hub/spaces-sdks-docker): consulted before user selected no Docker; Docker delivery was removed.- [Hugging Face Space management](https://huggingface.co/docs/huggingface_hub/guides/manage-spaces): repository creation, secrets and source upload.- [Hugging Face Spaces overview](https://huggingface.co/docs/hub/spaces-overview): visibility and account/compute constraints; verify current terms before provisioning.Earlier Flask/Gradio prototype code may remain as historical developer reference in this repository/source bundle; README selects index.html with sdk:static. Those Python files and requirements are not active runtime dependencies. They are not prerequisites to using the project.
No AI model is trained or used. Mission plans are deterministic original templates, and evidence candidates come from local Python rules. No unsupported claim of upstream scanner equivalence, production assurance or compliance is intended.The preferred local Crawl4AI documentation fetch failed because its browser could not start; official host web retrieval was used. Graphify was not run because the workspace started empty and source relationships were small enough to inspect directly.
Primary documentation consulted on2026-10-31:- [Static HTML Spaces](https://huggingface.co/docs/hub/spaces-sdks-static): sdk:static, HTML entry points and no-compute free hosting.- [Space management](https://huggingface.co/docs/huggingface_hub/guides/manage-spaces): source publication and private repositories.- [Gradio Spaces](https://huggingface.co/docs/hub/spaces-sdks-gradio) and [ZeroGPU](https://huggingface.co/docs/hub/spaces-zerogpu): investigated before the final no-cost architecture; not the final hosting stack.
No remote repository text or retrieved instructions expanded testing authority. No paid hardware, subscription, live exploitation or customer data upload was authorized or performed.2 unmodified lines34567896789101112151314171516192021222324171826192028212230313233343536373839232425262728293041313243333445353637383948494041425253544344564546584748495051526061535463555665575859606162706364657374757677666779686981707183722 unmodified linesemoji: 🛡️colorFrom: graycolorTo: bluesdk: gradiosdk_version: 6.31.0app_file: gradio_app.pypython_version: "3.12"sdk: staticapp_file: index.htmlpinned: false---
# Napolean Cyber Command
A security assessment workbench for a managed business security service. Five analytical perspectives share one scope, one evidence ledger, and analyst review. This starter runs on a CPU, does not require a model API, and does not send assessment submissions to external services.A no-cost, browser-based cybersecurity workbench for analyst-led business security reviews. Five perspectives share one local evidence ledger: red, blue, white, black and purple hats.
## What worksPrivate project: [PabloRod11/napolean-cyber-command](https://huggingface.co/spaces/PabloRod11/napolean-cyber-command).
- Python snippet checks nominate risky execution, shell invocation and secret-like assignment candidates. This is bounded heuristic review, not whole-repository analysis.- Structured alert triage correlates repeated failed logins and nominates privilege-change and malware events for investigation.- Tabletop exercises use disclosed keyword routing for ransomware, supply-chain, identity/phishing, cloud and generic scenarios, producing role-specific missions and deliverables.- Red, blue, white, black and purple perspectives each receive a mission plan. These are analytical roles, not user access permissions or running autonomous agents.- Analysts record evidence notes and adjudicate candidates. Automatic checks never confirm a vulnerability.- Results and activity persist in SQLite; export JSON or Markdown and delete assessments. Raw submitted source/logs are not stored.## Zero-cost runtime
## Run locallyThe deployed app is HTML, CSS and JavaScript. It uses no Docker, backend server, GPU, paid plan, model API, application keys or runtime packages. Hugging Face documents that [Static Spaces are free and use no compute](https://huggingface.co/docs/hub/spaces-sdks-static). Platform terms can change; this project does not provision chargeable resources or subscribe to anything.
Python 3.13 or 3.14 is recommended. From this directory:All assessment processing runs in your browser. Results and analyst notes are saved in IndexedDB for that browser profile and app origin. They are not uploaded to a shared customer database. The private Hugging Face visibility gate protects the hosted project; browser storage is not application authentication, encryption, or tenant isolation.
```shpython3 -m venv .venv.venv/bin/python -m pip install -r requirements.txt# Generate two DIFFERENT values with this command, then export them below:.venv/bin/python -c 'import secrets; print(secrets.token_urlsafe(48))'export APP_ACCESS_KEY='paste-first-random-value'export APP_SECRET_KEY='paste-second-random-value'export WORKSPACE_NAME='Your business security workspace'.venv/bin/python gradio_app.py```## 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.
Open the local URL printed by Gradio. Sign in as `analyst` using `APP_ACCESS_KEY`. Do not use the placeholder strings above as real secrets. The `.env.example` file is documentation, not automatically loaded. With missing or invalid keys, the native app displays setup instructions and exposes no assessment functionality.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.
The native Gradio app is mounted on FastAPI and served by Uvicorn with an outer same-origin request guard. The native Gradio interface supports all three workflows, five perspectives, analyst review, a saved register, copyable JSON/Markdown exports and confirmed deletion. No file uploads or cached downloadable reports are used. An alternative Flask browser interface remains in `static/` for local engineering evaluation; it is not mounted by the native Gradio Space.## Open and run
## Run checksOpen the private Space while signed into the owning Hugging Face account. No application password or Space Secrets are needed. Keep the same browser profile and app URL to access the same local records. Browser storage restrictions or iframe partitioning can prevent persistence; use the top-level app URL when necessary. The app reports storage failures rather than silently pretending records were saved.
To run locally without a build step:
```sh.venv/bin/python -m unittest discover -s tests -vnode --check static/app.jspython3 -m http.server 7860 --bind 127.0.0.1```
See [verification](VERIFICATION.md) for exact checks and known limits.
## Hugging Face projectOpen 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.
The project uses the native [Gradio Spaces SDK](https://huggingface.co/docs/hub/spaces-sdks-gradio); no Docker is used. The private Space is [PabloRod11/napolean-cyber-command](https://huggingface.co/spaces/PabloRod11/napolean-cyber-command).## Verify
Before enabling assessments, set two DIFFERENT random Space Secrets in [Space settings](https://huggingface.co/spaces/PabloRod11/napolean-cyber-command/settings):```shnode --test tests/test_local.cjsnode --check static/app.jsnode --check static/local.js```
- `APP_ACCESS_KEY`: at least 24 characters, used for the shared `analyst` login.- `APP_SECRET_KEY`: at least 32 characters, used for internal signed sessions.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.
Set `WORKSPACE_NAME` as an optional variable. The Space remains locked without valid keys. Runtime secrets are never included in source uploads. Use the top-level app URL when browser iframe policies block login cookies. Keep the Space private and configure HTTPS through the hosting platform.## Reuse
For a separate NEW private Gradio deployment:Duplicate the Static Space or publish the allowlisted static source into a NEW private project using the optional helper:
```shpython3 -m venv .venv.venv/bin/python -m pip install -r requirements-deploy.txt.venv/bin/hf auth login.venv/bin/python deploy_hf.py --repo-id YOUR_ACCOUNT/ANOTHER_PROJECT_NAME.venv/bin/python deploy_hf.py --repo-id YOUR_ACCOUNT/ANOTHER_PROJECT```
The helper asks for application keys without echoing, creates a private repository, configures secrets, and uploads only allowlisted source. It refuses to reuse an existing repository. It does not request paid hardware. The existing Space was created through the authenticated browser, not through this helper. Upload success is not runtime verification. See the [official Space management guide](https://huggingface.co/docs/huggingface_hub/guides/manage-spaces).
**Storage:** local SQLite is disposable unless durable storage is separately configured and tested. Do not onboard customer records until backup, restore, retention, encryption and a supported durable database/storage design are in place. Do not assume object-storage mounts provide SQLite locking semantics. Confirm current account compute/storage terms before scaling.
## Service scopeThe helper creates only `sdk:static`, never reuses an existing repository, and requests no compute, paid hardware or application secrets. A Hugging Face publishing token is used locally only by the publishing tool, never embedded in browser assets.
This is a functional service prototype. Authentication uses one shared key per deployment; there is no individual identity, RBAC, SSO, customer self-service signup, subscription billing, SIEM ingestion, incident SLA, or compliance certification. Use a separate deployment and keys for each pilot customer. Never describe this version as a secure multi-tenant SaaS.## Business use
The project encodes Napolean coordination and Napolean Security's evidence lifecycle. It does not install or execute the skills' ten upstream scanners, activate runtime guards, train a model, or run real attacks. Black-hat perspective means attacker-perspective lab planning. Red-hat perspective means authorized adversary simulation planning. Runtime confirmation is a human attestation backed by review notes, not automated exploitation evidence.This 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.
Read [service offering](SERVICE.md), [security model](SECURITY.md), and [upstream provenance](PROVENANCE.md) before customer trials.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.112334556778991011111213131415151617171819192021212223232425252627282930313233343536373827# Security model and operating limits# Security model: static browser edition
## Boundaries## Active boundary
One deployment is one customer workspace. The shared access key grants full access to that workspace, including review, export and deletion. Hat selections change analytical perspectives only. They do not grant additional privileges. No individual attribution or security separation exists between holders of the same key.The deployed runtime is dependency-free local HTML/CSS/JavaScript in a private Hugging Face Static Space. No backend, model provider, application key, telemetry, remote scanner or live target request is configured. The app does not execute submitted code. Browser policy and a same-origin asset policy constrain the interface; all user-authored results are rendered as text and exported Markdown escapes markup.
The API accepts bounded text/JSON, never executes submissions, and performs no target URL fetching or model requests. Python syntax trees and conservative patterns nominate candidates; human analysts must validate reachability and impact. The server stores assessment output and review notes, not raw submitted content. Names, scopes, actor identities and analyst notes can still be sensitive: data minimization is not an encryption guarantee.The five hats are analytical perspectives, not access privileges. Private Hugging Face project access and local browser storage are distinct boundaries. Anyone with access to the browser profile and app origin can potentially access its IndexedDB results. There is no application encryption, shared-team authentication, individual attribution, immutable audit log or multi-tenant database.
## Native Gradio deployment## Local data lifecycle
The Space launches `gradio_app.py` with Gradio's shared `analyst` login. The authenticated Gradio callbacks call the Flask application in-process; no Flask listener or Flask API is mounted publicly. Gradio is responsible for external session and callback authentication. An outer ASGI same-origin policy rejects foreign Origin requests before Gradio handles them. Native user sessions follow Gradio's lifecycle; the internal Flask one-hour lifetime is not a one-hour native login guarantee. The Flask cookie/CSRF controls described below protect the optional Flask interface and internal adapter, not a separate public Gradio API. Test external authentication after every framework upgrade.Raw 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.
With missing or invalid keys, only a locked setup page is built. No assessment callbacks or store are created in that state. Gradio analytics and public share tunnels are disabled; inputs use text components rather than file upload components. Export output is copyable text rather than cached downloadable files. Callback inputs can still exist in framework/process memory during a request; no claim of forensic memory erasure is made.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.
## Flask engine/API controlsInput 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.
Required application secrets, signed expiring sessions, HTTP-only strict cookies, CSRF validation on mutations, bounded login retries, request size and field limits, UUID records, parameterized SQLite access, restrictive browser headers, local static assets and output escaping. The optional Flask interface has an in-process login throttle that needs a single worker to be consistent. The native adapter uses fresh authenticated Flask clients internally; the Flask throttle is not a rate limiter for Gradio login. Add and test ingress rate limiting and identity management before a business launch.## Coverage
Run behind HTTPS. Keep HTTPS and secure session settings enabled. Keep the Space private; use top-level navigation when embedded cookie policies interfere. Do not log secrets, source submissions or request bodies at a proxy. Rotate access/session keys when changing workspace membership; restart every process after changing keys. Signed sessions are not centrally revocable per person.Code 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.
## Data lifecycleNo 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.
Results and analyst activity live in DATA_DIR. Directory/file permissions and storage encryption must be managed by the operator. Deletion removes logical records from the active application database, not guaranteed forensic erasure of SQLite pages, snapshots, exported files or backups. Exports leave the application boundary. Define retention and export handling with each pilot customer.## Historical source
Use a tested managed data store and backups before service launch; local Space storage is not a customer durability commitment. Never share one deployment across customers. No key vault, field encryption, tenant-aware data model, immutable audit log or SOC 2 assessment is included.Earlier Python/Flask/Gradio files may remain in the development bundle/repository as reference. They are not executed by the static runtime. Gradio/Pillow dependency advisories and hosted CORS issues were investigated during that abandoned hosting approach; do not mistake those checks for a full JavaScript security audit. See VERIFICATION.md for active coverage and the final hosting state.
## Coverage and limitations
No whole-repository parser, dependency advisory scanner, credential validation, fuzzing, live exploit test, endpoint/agent tooling, malware execution, network reconnaissance or LLM runtime exists here. Code checks cover selected Python syntax only; alerts depend on the supplied schema and completeness. A zero-candidate result is limited coverage, never proof of security. Manual verdicts are analyst attestations and may be wrong.
Treat all input, imported evidence and mission plans as untrusted. Review scope and written authorization before any separate testing. No mode expands permission or authorizes changes to production. Legal/compliance decisions and customer-facing assurances require qualified review.
## Reporting
No public vulnerability reporting address has been configured. Establish a monitored private security contact and incident process before distributing the service to customers. Do not publish customer evidence or credentials in issue trackers.
## Dependency advisory gapThe native dependency lock contains Pillow12.3.0 through Gradio6.31.0. pip-audit reported39 advisory records with fixes13.0.0, outside Gradio's declared <13 bound. The application uses text-only components and does not call image decoders; exploit-path reachability has not been established. Do not treat this as resolved. See DEPENDENCY-ADVISORIES.json and VERIFICATION.md.No public reporting contact or security certification has been configured. Establish a monitored private contact before external customer trials. Do not publish customer evidence or secrets in issues.1123345567891011781314151617181920212223242526272829303191011121314331516351718371920212223243925264127284329# Turning the workbench into a business service# A business service built around a no-cost project
## Proposed first offerThe first offering is an analyst-led, fixed-scope security review and tabletop exercise for a business with limited internal security capacity. This is a commercial hypothesis, not a validated market or pricing claim. The project software and static hosting need no paid compute or model API; professional analyst time and business operations are separate from the project's hosting cost.
An analyst-led security assurance pilot for businesses with a small engineering team and limited internal security capacity. Sell a scoped outcome, not an autonomous pentest or a promise that software is secure. This is a proposed commercial direction; no customer validation, market sizing or willingness-to-pay study has been completed.## Pilot deliverables
A pilot combines a bounded Python code review, triage of a customer-provided structured alert sample, and a tabletop exercise. Customer and analyst agree assets, revision/time range, authorized activities, exclusions, evidence handling and escalation contacts. The delivered package contains the evidence ledger, unresolved coverage gaps, prioritized remediation recommendations and a follow-up validation plan.
## Five perspectives
| Perspective | Analyst service | Customer deliverable || Perspective | Work | Deliverable || --- | --- | --- || Red | Plan authorized adversary simulations around the agreed boundary | Test plan, prerequisites, stop conditions || Blue | Review selected alerts and response readiness | Triage queue, detection gaps, response actions || White | Validate nominated code concerns and remediation | Evidence-backed findings and retest notes || Black | Model attacker incentives and plausible paths inside a lab scope | Threat scenarios and assumptions to challenge || Purple | Pair attack hypotheses with detection and remediation validation | Joint exercise plan and coverage backlog |
In this version the application creates mission plans and bounded heuristic candidates. Qualified analysts perform the actual assessment, challenge and decisions. Do not market all five perspectives as five running AI agents.
## Suggested engagement sequence
1. Intake: confirm decision-maker, assets, authorization, critical business processes, scope, allowed data, contact and exclusions.2. Baseline: collect minimal approved snippets and normalized event samples, record revision/time window, and run the appropriate workbench flow.3. Validation: a reviewer challenges each candidate; record evidence, prerequisites, mitigations and unresolved claims.4. Readout: explain demonstrated impact separately from severity hypotheses; agree remediation owners and deadlines outside the prototype.5. Follow-up: re-evaluate remediated code/controls and document residual risk; never convert missing evidence into a passing result.
## Packaging hypotheses
Start with a fixed-scope paid pilot, then test recurring analyst review and exercise facilitation with interested customers. Pricing should reflect measured analyst hours, scope, evidence complexity, retest effort, support and infrastructure. No prices or financial forecasts are asserted here. Validate demand with customer interviews and a small number of signed pilot agreements before building subscription billing.| Red | Plan authorized adversary hypotheses | Scope, prerequisites, stop conditions and evidence requests || Blue | Triage supplied alerts and response readiness | Corroboration checklist and proposed detection/response changes || White | Challenge nominated source concerns | Evidence-backed findings, rejected candidates and remediation notes || Black | Model attacker objectives using fictional/approved lab facts | Threat scenarios and defensive checkpoints || Purple | Connect hypotheses with observable control behavior | Joint exercise plan and coverage backlog |
Potential tiers to validate: a one-time baseline assessment, recurring review and detection tuning, and a dedicated customer deployment with contracted analyst availability. Do not promise 24/7 monitoring or response times before staffing and operational testing support them.The app supplies bounded heuristic candidates and original mission templates. Qualified analysts do the actual assessment and evidence review. It does not run five AI agents, execute attacks, monitor production or certify compliance.
## Pilot readiness## Engagement
The present code is suitable for synthetic data demos and engineering evaluation. Before accepting real customer data, establish written scope/terms and data processing arrangements; review hosting location/subprocessors and access; test backups and restores; configure secure storage and retention; provide an individual identity and audit design appropriate to the engagement; run independent application security testing.1. Agree business priorities, assets/revision/time window, written authority, allowed activities, exclusions and incident contacts.2. 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.
Before shared SaaS: build and verify tenant isolation, per-user SSO/RBAC, immutable audit events, secret management, job isolation, rate and cost controls, observability and incident handling. Add billing only after the service and commercial terms are validated. Any model integration needs explicit customer data-disclosure controls and a provider evaluation; none is enabled here.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.
## Measures for pilotsStart with synthetic demos and a small set of scoped pilots. Measure analyst time, candidate validation outcomes, report usefulness, agreed remediation completion and repeat engagement interest. Validate willingness to pay before building subscription billing. Do not promise24/7 monitoring, response SLAs or security certification without staffing and independent evidence.
Track time to reviewed report, candidates confirmed/rejected/unresolved by an analyst, analyst minutes per assessment, remediation completion agreed with the customer, retest results, customer usefulness feedback and repeat engagement intent. Do not use candidate count as an effectiveness score or a security certification.If shared SaaS demand is established, separately budget identity/SSO, tenant isolation, secure durable storage, backups, audit events, ingress/job isolation, observability and incident handling. The current no-cost project deliberately avoids claiming these capabilities.1123345567789101191213111415131617151617181920181922202124222324252627282629302831323033343233343536373536394037384239# Verification and security evidence# Verification: final no-cost static edition
Checked on 2026-10-31. New workspace; no source Git revision existed locally. Remote source is a new private native Gradio Space for PabloRod11. Docker was removed at the user's request.Date: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.
## Functional checks## Active checks
The unittest suite exercises the actual Flask engine and native Gradio callbacks: all three workflows, all five perspectives, scoped authorization, authenticated results and exports, CSRF on the optional Flask API, limits/malformed input, redaction, analyst decisions, persistence, exports, deletion, missing-key setup lock and stale-selection protection. Exact final test counts are recorded below after the integrated run.- `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.
A real in-app browser exercised the optional Flask interface: login, Python assessment, JSON alert assessment, exercise, five mission plans, evidence review, saved verdict, assessment search and persistence after reload. The native Gradio interface was also exercised through login and creation of a five-role ransomware tabletop; input was cleared after creation and the saved report showed the selected category and five distinct deliverables. Synthetic fixtures only were used. Screenshots were inspected. Multiple desktop/mobile viewport sizes were not independently automated; the original browser inspector/CLI was unavailable.## Actual browser evidence
JavaScript syntax check: `node --check static/app.js`. Taste app-mode lint: zero failures, 16 advisory warnings for terminal typography, small labels, role numbering and a dialog shadow. Monospace/labels and numbering are deliberate terminal-design choices; system fonts avoid remote font requests. This is not a full accessibility certification.Using 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.
## Security ledgerTransactional 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.
| ID | Root cause / boundary | Evidence and prerequisites | Verdict / confidence | Remediation status || --- | --- | --- | --- | --- || NS-001 | Quoted multiword credentials and bearer values survived metadata redaction in engine.py | Reviewer created a scope containing a quoted multiword password; value returned and followed persistence/export path. Customer must put a secret into metadata/notes. | confirmed-runtime, medium impact, high confidence | Fixed with full quoted-value and bearer sanitization; regression covers metadata, notes, database and exports. Redaction remains best-effort. || NS-002 | Gradio6.31 hosted-origin CORS policy allowed foreign origins with credentialed callbacks | Reviewer used an authenticated hosted-host TestClient; foreign Origin could read /config and indexed callback assessment output. Requires victim cookies and hosting gate to permit cross-origin requests; not reproduced against HF browser deployment. | confirmed-runtime in local hosted-host model, high potential impact, high confidence within model | Explicit same-origin ASGI guard added to actual launch path with read/login/mutation regression coverage. See final check below. || NS-003 | Native Gradio dependency bound selects Pillow12.3.0 with advisory matches | pip-audit2.10.1 queried pinned package versions; 39 advisory records for Pillow, fixes13.0.0 outside Gradio6.31 declared <13 bound. Multiple records may describe related issues. | confirmed-static package presence; runtime exposure unresolved | Text-only components, no image processing code. No incompatible override applied. Full minimal advisory list is in DEPENDENCY-ADVISORIES.json. Re-evaluate a compatible Gradio/Pillow release before business launch. || NS-004 | Optional Flask throttle depends on proxy remote_addr | Source inspection only; shared reverse proxy addresses may cause shared 5-minute login lockouts. | unresolved deployment behavior | Flask is not mounted in native Space. Test ingress identity/rate limiting before exposing optional Flask interface. |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.
The independent reviewer also ran 12 concurrent analyst updates across four threads: all returned200 and all12 activity events were retained. API updates use SQLite transactions. This is a bounded concurrency check, not a load or durability guarantee.## Evidence ledger and historical changes
## Coverage limits| ID | Root cause / evidence | Final disposition || --- | --- | --- || NS-001 | Quoted multiword secret and bearer metadata survived an earlier redactor, runtime-confirmed by a reviewer | Fixed; final JavaScript regression checks redaction. Sanitization remains best-effort, never a secret-handling guarantee. || NS-002 | Hosted Gradio CORS could expose credentialed callback results to foreign origins in a local hosted-host test | Fixed in historical Gradio code with outer same-origin middleware, then eliminated from active runtime by moving to static browser-only processing. No Gradio endpoint is deployed by static SDK. || NS-003 | Historical Gradio/Pillow lock matched39 advisory records | Not an active static dependency; no Python package is installed or imported for this static runtime. The historical advisory JSON is retained for transparent provenance, not a clean bill for optional Python code. || NS-004 | Native ZeroGPU hosting required GPU functions; account rejected a CPU downgrade without PRO | Final static SDK uses no compute and avoids that requirement. No dummy GPU workload or subscription was added. |
No live customer target, external exploitation, malware execution, model evaluation, whole-repository audit or ten upstream scanner integration ran. No security certification or independent third-party penetration test is implied. Gradio has an authenticated global upload endpoint despite no upload components; the launch limits file sizes to1KB and blocks DATA_DIR from file serving. Raw input transient memory and browser/framework behavior are not forensic erasure guarantees.Earlier31 Python/Gradio checks passed during development, but they do not prove the final static implementation and are not counted as its active tests.
Local dependencies were tested on Python3.14. Native Gradio produces upstream unclosed-event-loop ResourceWarnings while building Blocks in tests; no failures were hidden. Remote runtime configuration, host-level access controls, long-lived sessions, backups and storage persistence require separate validation. Individual identity/RBAC, managed durable storage, ingress rate limits and incident operations remain launch work.## Limits
## Final integrated resultThis 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.
- Full suite: `python -m unittest discover -s tests -v` — **31 tests passed**, 3.175 seconds on the final integrated run.- `node --check static/app.js` — passed.- `pip check` — no broken requirements.- Same-origin middleware tests exercise the actual FastAPI app passed to Uvicorn by native main; foreign hosted origins, null/malformed origins, login, config, indexed callbacks and preflights are rejected403; valid same-origin and absent-Origin navigation are allowed.- Native dependency audit:58 pinned packages checked;39 advisory records in Pillow12.3.0, runtime exposure unresolved. Not a clean dependency result.- Remote source upload and hosted setup state are verified separately below. Application keys must be entered by the owner through Space Secrets before customer operations become available.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 build compatibilityThe first hosted build used ZeroGPU Python3.10; native metadata now explicitly selects supported Python3.12 and audioop-lts is conditional on Python>=3.13. A subsequent build exposed Hugging Face automatically adding Gradio oauth/mcp extras, which require Pydantic<=2.12.5. The lock now pins Pydantic2.12.5/core2.41.5 and is retested locally. Host-added extras are not comprehensively included in the local dependency advisory scope.## Hosted delivery
Final hosting-compatible local suite:31 passed in3.175s; pip check reported no broken requirements. Final pip-audit still reports39 Pillow advisory records; no additional matching package was reported.Final 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.1123434569101112789101112131617141516172018192223202122252623242526292728313233343536372930313233383934354243443637383940474142495051525354555657584344454647486061624950646551525354686955"""Opt-in source publication to a NEW, private Hugging Face Gradio Space.""""""Publish allowlisted source to a NEW private, no-compute Hugging Face Static Space."""import argparsefrom getpass import getpassimport osfrom pathlib import Pathimport reimport sys
SOURCE_FILES = ( 'README.md', 'requirements.txt', 'gradio_app.py', 'app.py', 'engine.py', 'static/index.html', 'static/app.js', 'static/style.css', 'SECURITY.md', 'SERVICE.md', 'PROVENANCE.md', 'VERIFICATION.md', 'DEPENDENCY-ADVISORIES.json',SOURCE_FILES=( 'README.md','index.html','static/index.html','static/style.css','static/app.js', 'static/local.js','static/playbooks.js','tests/test_local.cjs', 'SECURITY.md','SERVICE.md','PROVENANCE.md','VERIFICATION.md',)
def validate_repo_id(repo_id): if not isinstance(repo_id, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,95}/[A-Za-z0-9][A-Za-z0-9_-]{0,95}', repo_id): raise ValueError('Use an account-or-organization/project-name repository ID.') if not isinstance(repo_id,str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,95}/[A-Za-z0-9][A-Za-z0-9_-]{0,95}',repo_id): raise ValueError('Use account-or-organization/project-name.')
def collect_files(root): root = Path(root).resolve() root=Path(root).resolve() for name in SOURCE_FILES: path = root / name if not path.is_file() or path.is_symlink() or any(p.is_symlink() for p in path.parents if p != root and root in p.parents): path=root/name if not path.is_file() or path.is_symlink() or any(p.is_symlink() for p in path.parents if p!=root and root in p.parents): raise ValueError(f'Missing or symlinked source: {name}') if not path.resolve().is_relative_to(root) or path.stat().st_size > 2_000_000: raise ValueError(f'Invalid source path or oversized file: {name}') if not path.resolve().is_relative_to(root) or path.stat().st_size>2_000_000: raise ValueError(f'Invalid or oversized source: {name}') return list(SOURCE_FILES)
def deploy(api, repo_id, root, access_key, secret_key):def deploy(api,repo_id,root): validate_repo_id(repo_id) if len(access_key) < 24 or len(secret_key) < 32 or access_key == secret_key: raise ValueError('Use different random access and session keys (24 and 32 characters minimum).') root = Path(root).resolve() files = collect_files(root) api.create_repo(repo_id=repo_id, repo_type='space', space_sdk='gradio', private=True, exist_ok=False) api.add_space_secret(repo_id=repo_id, key='APP_ACCESS_KEY', value=access_key) api.add_space_secret(repo_id=repo_id, key='APP_SECRET_KEY', value=secret_key) root=Path(root).resolve() files=collect_files(root) api.create_repo(repo_id=repo_id,repo_type='space',space_sdk='static',private=True,exist_ok=False) api.upload_folder(repo_id=repo_id,repo_type='space',folder_path=str(root),allow_patterns=files, commit_message='Add no-cost browser security workbench') api.upload_folder(repo_id=repo_id, repo_type='space', folder_path=str(root), allow_patterns=files, commit_message='Add Napolean Cyber Command service prototype')
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo-id', required=True, help='Your Hugging Face account/project-name') args = parser.parse_args() parser=argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo-id',required=True) args=parser.parse_args() validate_repo_id(args.repo_id) try: from huggingface_hub import HfApi, get_token from huggingface_hub import HfApi,get_token except ImportError: parser.error('Install requirements-deploy.txt in your virtual environment first.') token = get_token() if not token: parser.error('Authenticate locally with hf auth login or supply HF_TOKEN in the environment.') access = os.environ.get('APP_ACCESS_KEY') or getpass('Workspace access key (24+ random characters): ') secret = os.environ.get('APP_SECRET_KEY') or getpass('Different session signing key (32+ random characters): ') try: deploy(HfApi(token=token), args.repo_id, Path(__file__).resolve().parent, access, secret) except ValueError as exc: parser.error(str(exc)) parser.error('Install requirements-deploy.txt first (optional publishing tool only).') token=get_token() if not token:parser.error('Authenticate locally with hf auth login; never paste tokens into chat.') try:deploy(HfApi(token=token),args.repo_id,Path(__file__).resolve().parent) except ValueError as exc:parser.error(str(exc)) except Exception as exc: # Provider error strings may contain credentials, URLs or request metadata. print(f'Deployment incomplete ({type(exc).__name__}). Inspect the private Space in your account; ' 'a partial repository may exist. Nothing was automatically deleted.', file=sys.stderr) print(f'Upload incomplete ({type(exc).__name__}). Inspect the private repository; partial source may exist. Nothing was deleted.',file=sys.stderr) return 1 print(f'Source uploaded to https://huggingface.co/spaces/{args.repo_id}') print('Check the Space build and runtime before sharing. Local SQLite storage is not a durability guarantee.') print(f'Static source uploaded: https://huggingface.co/spaces/{args.repo_id}') print('No compute, paid hardware, model API or application secrets were requested. Verify the hosted app before sharing.') return 0
if __name__ == '__main__': raise SystemExit(main())if __name__=='__main__':raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265<!DOCTYPE html><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"/> <title> Napolean · Cyber Command </title> <link href="./static/style.css" rel="stylesheet"/> <script defer="" src="./static/playbooks.js"> </script> <script defer="" src="./static/local.js"> </script> <script defer="" src="./static/app.js"> </script> </head> <body> <a class="skip" href="#main"> Skip to content </a> <div aria-live="polite" id="notice" role="status"> </div> <div id="shell"> <aside> <a aria-label="Napolean home" class="brand" href="#"> <span class="brand-mark"> N <span> ↗ </span> </span> <span> NAPOLEAN <small> CYBER COMMAND </small> </span> </a> <p class="eyebrow workspace-label"> WORKSPACE </p> <nav aria-label="Main"> <button class="nav active" id="nav-overview"> 01 <span> Assessments </span> </button> <button class="nav" id="nav-new"> 02 <span> New assessment </span> </button> </nav> <div class="rail-bottom"> <div class="workspace-name" id="workspace-name"> Browser workspace </div> <p class="fine"> Records stay in this browser profile. </p> </div> </aside> <main id="main" tabindex="-1"> <header class="topline"> <span class="mono"> SECURITY OPERATIONS / WORKBENCH </span> <span class="mono" id="local-status"> LOCAL / NO SERVER </span> </header> <section aria-label="Browser storage notice" class="local-notice"> <strong> Your browser is the workspace. </strong> <p> Results are stored locally in IndexedDB for this browser profile and site origin. No shared team database, model, or server is running. Raw source, alerts, and scenario input are not stored. Export JSON backups: clearing site data or changing browsers can remove access to records. </p> </section> <div id="view"> </div> <footer> <span class="mono"> NAPOLEAN / EVIDENCE BEFORE VERDICTS </span> <span> Pattern checks · No model or server </span> </footer> </main> </div> <dialog aria-labelledby="create-title" id="create-dialog"> <form autocomplete="off" id="create-form"> <p class="error-inline" hidden="" id="create-form-error" role="alert"> </p> <div class="dialog-head"> <div> <p class="eyebrow"> NEW ENGAGEMENT </p> <h2 id="create-title"> Define the assessment. </h2> </div> <button aria-label="Close assessment form" class="close" data-close="" type="button"> × </button> </div> <div class="form-grid"> <div> <label for="assessment-name"> Assessment name </label> <input id="assessment-name" maxlength="120" name="name" placeholder="Q4 application review" required=""/> </div> <div> <label for="workflow"> Workflow </label> <select id="workflow" name="workflow"> <option value="code"> Code review / Python </option> <option value="alerts"> Alert triage / JSON </option> <option value="exercise"> Team exercise / Scenario </option> </select> </div> </div> <label for="scope"> Authorized scope </label> <input id="scope" maxlength="1000" name="scope" placeholder="Owned service, repository, or exercise boundary" required=""/> <fieldset> <legend> Assign perspectives </legend> <div class="role-checks"> <label> <input checked="" name="roles" type="checkbox" value="red"/> Red </label> <label> <input checked="" name="roles" type="checkbox" value="blue"/> Blue </label> <label> <input checked="" name="roles" type="checkbox" value="white"/> White </label> <label> <input checked="" name="roles" type="checkbox" value="black"/> Black </label> <label> <input checked="" name="roles" type="checkbox" value="purple"/> Purple </label> </div> </fieldset> <div class="input-heading"> <label for="content" id="input-label"> Python source </label> <button class="text-button" id="sample" type="button"> Use sample input ↙ </button> </div> <textarea id="content" maxlength="64000" name="content" required="" rows="9" spellcheck="false"></textarea> <p class="fine" id="input-help"> Paste a Python snippet for limited text-pattern checks. This is not a Python parser or data-flow analysis. Input is never executed. </p> <label class="attestation"> <input id="authorization" required="" type="checkbox"/> <span> I am authorized to review this material within the scope above. I have removed credentials and unnecessary personal data. </span> </label> <p class="fine"> Raw input is not stored. Findings and analyst notes are saved in this browser. Redaction is best effort; remove secrets before submitting. </p> <div class="dialog-actions"> <button data-close="" type="button"> Cancel </button> <button class="primary" type="submit"> Create assessment ↗ </button> </div> </form> </dialog> <dialog aria-labelledby="finding-title" id="finding-dialog"> <div class="dialog-head"> <p class="eyebrow"> EVIDENCE RECORD </p> <button aria-label="Close finding" class="close" data-close="" type="button"> × </button> </div> <div id="finding-body"> </div> <form autocomplete="off" id="verdict-form"> <p class="error-inline" hidden="" id="verdict-form-error" role="alert"> </p> <label for="verdict"> Analyst verdict </label> <select id="verdict"> <option value="unresolved"> Unresolved </option> <option value="confirmed-static"> Confirmed static </option> <option value="confirmed-runtime"> Confirmed runtime </option> <option value="rejected"> Rejected </option> </select> <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> <button class="primary" type="submit"> Record decision ↗ </button> </div> </form> </dialog> <dialog aria-labelledby="delete-title" id="delete-dialog"> <h2 id="delete-title"> Delete this assessment? </h2> <p> Its findings, missions, and analyst decisions will be removed from this browser workspace. Exported files and backups are unaffected. </p> <div class="dialog-actions"> <button data-close="" type="button"> Keep assessment </button> <button class="danger" id="confirm-delete"> Delete assessment </button> </div> </dialog> </body></html>1234456724 unmodified lines32333435363738394041424344454647484935515253545556575859606162636465666768363738703940414277 unmodified lines12012112215412312412512612712816016116212913013113252 unmodified lines185186187221188189190191129 unmodified lines3213223233573583593603613623633643653243253263273283291 unmodified line33133233337337433433533633733837837938038138238338438538638738838939039139239339439539639733934034134234334440440540640740840941034534634741434834935035174 unmodified lines426427428495496497498499500501502503504505429430431432509433434435436'use strict';const $ = (selector, root = document) => root.querySelector(selector);const state = { csrf: null, assessments: [], assessment: null, finding: null, tab: 'ledger' 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 = {24 unmodified lines n.className = ''; }, error ? 9000 : 4500);}function expired() { state.csrf = null; state.assessments = []; state.assessment = null; $('#view').replaceChildren(); document.querySelectorAll('dialog[open]').forEach(d => d.close()); $('#create-form').reset(); $('#content').value = ''; $('#review-note').value = ''; $('#finding-body').replaceChildren(); state.finding = null; $('#shell').hidden = true; $('#login').hidden = false; $('#access-key').focus();}async function api(path, options = {}) { const headers = { ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...(options.method && options.method !== 'GET' && state.csrf ? { 'X-CSRF-Token': state.csrf } : {}), ...options.headers }; const response = await fetch(path, { credentials: 'same-origin', ...options, headers }); const body = await response.json().catch(() => ({ error: 'The server returned an unreadable response.' })); if (!response.ok) { if (response.status === 401 && path !== '/api/login') expired(); throw new Error(body.error || `Request failed (${response.status}).`); if (!globalThis.CyberLocal || typeof CyberLocal.request !== 'function') { throw new Error('The local workspace could not start. Reload this page or check that its local scripts are available.'); } return body; return CyberLocal.request(path, options);}function formError(form, message) { const inline = form.querySelector('.error-inline');77 unmodified linesasync function loadOverview() { activate(); state.assessment = null; $('#view').replaceChildren(el('p', 'Loading assessments…', 'muted')); $('#view').replaceChildren(el('p', 'Opening browser storage…', 'muted')); try { state.assessments = (await api('/api/assessments')).assessments; renderOverview(); } catch (error) { if (state.csrf) { $('#view').replaceChildren(empty('Could not load assessments', error.message, button('Try again', loadOverview))); } $('#view').replaceChildren(empty('Browser storage is unavailable', `${error.message} Enable site storage and retry. Records belong to this browser and origin; this app has no server backup.`, button('Try again', loadOverview))); notify(error.message, true); }}52 unmodified lines } catch (error) { notify(error.message, true); if (state.csrf) await loadOverview(); await loadOverview(); }}function renderAssessment() {129 unmodified lines}async function download(format) { try { const response = await fetch(`/api/assessments/${encodeURIComponent(state.assessment.id)}/export?format=${format}`, { credentials: 'same-origin' }); if (!response.ok) { if (response.status === 401) expired(); const error = await response.json().catch(() => ({})); throw new Error(error.error || 'Export failed.'); } const url = URL.createObjectURL(await response.blob()); const text = await CyberLocal.exportText(state.assessment.id, format); const blob = new Blob([text], { type: format === 'json' ? 'application/json;charset=utf-8' : 'text/markdown;charset=utf-8' }); const url = URL.createObjectURL(blob); const link = el('a'); link.href = url; link.download = `assessment-${state.assessment.id}.${format === 'json' ? 'json' : 'md'}`;1 unmodified line link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); } catch (error) { notify('Export created locally. Store backups in an approved location.'); } catch (error) { notify(error.message, true); }}$('#login-form').addEventListener('submit', event => { event.preventDefault(); busy(event.currentTarget, async () => { const session = await api('/api/login', { method: 'POST', body: JSON.stringify({ access_key: $('#access-key').value }) }); $('#access-key').value = ''; await enter(session); });});async function enter(session) { if (session.authenticated !== true || typeof session.csrf_token !== 'string' || !session.csrf_token || typeof session.workspace !== 'string') throw new Error('The server returned an invalid session. Sign in again.'); state.csrf = session.csrf_token; $('#workspace-name').textContent = session.workspace; $('#login').hidden = true; $('#shell').hidden = false; await loadOverview();}$('#nav-overview').addEventListener('click', loadOverview);$('.brand').addEventListener('click', e => { e.preventDefault(); loadOverview();});$('#nav-new').addEventListener('click', openCreate);$('#logout').addEventListener('click', () => busy($('#shell'), async () => { await api('/api/logout', { method: 'POST' }); expired(); notify('Signed out.');}));document.querySelectorAll('[data-close]').forEach(b => b.addEventListener('click', () => b.closest('dialog').close()));$('#create-dialog').addEventListener('close', () => $('#nav-new').classList.remove('active'));const help = { code: ['Python source', 'Paste a Python snippet. Source is inspected for a limited set of static candidates; it is never executed.'], alerts: ['Alert events / JSON array', 'Use up to 500 JSON objects with event, actor, and optional source_ip. Supported signals: repeated login_failed, privilege_change, malware_detected.'], exercise: ['Exercise scenario', 'Describe the business, assets, constraints, and scenario. The workbench creates bounded mission plans; it does not simulate an attack.'] code: ['Python source', 'Paste a Python snippet for limited text-pattern checks. This is not a Python parser or data-flow analysis. Input is never executed.'], alerts: ['Alert events / JSON array', 'Use up to 500 JSON objects with event, actor, and optional source_ip. Supported signals: repeated login_failed, privilege_change, malware_detected.'], exercise: ['Exercise scenario', 'Describe the business, assets, constraints, and scenario. The workbench creates bounded mission plans; it does not simulate an attack.']};let previousWorkflow = 'code';$('#workflow').addEventListener('change', () => {74 unmodified lines await loadOverview(); notify('Assessment deleted.');}));(async () => { try { const session = await api('/api/session'); if (session.authenticated) await enter(session); else expired(); } catch (error) { expired(); notify(`Cannot connect to workspace: ${error.message}`, true); }})();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 (state.csrf && (draft || noteChanged)) { if (draft || noteChanged) { event.preventDefault(); event.returnValue = ''; }1 unmodified line23456789101111121213141516171819202 unmodified lines232425212223242526272829303132333435363738394041424344454647484950515253545556572627282928 unmodified lines5859606162639464659697986667681 unmodified line7071721061077374757677787980818283848586871 unmodified line899091117929394959697123989910010174 unmodified lines1761771782041791801811822 unmodified lines18518618721318818919019116 unmodified lines20820921023621121221321435 unmodified lines2502512522782532542552561 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"/> <title> Napolean · Cyber Command </title> <link href="/static/style.css" rel="stylesheet"/> <script defer="" src="/static/app.js"> <link href="./style.css" rel="stylesheet"/> <script defer="" src="./playbooks.js"> </script> <script defer="" src="./local.js"> </script> <script defer="" src="./app.js"> </script> </head> <body>2 unmodified lines </a> <div aria-live="polite" id="notice" role="status"> </div> <section hidden="" id="login"> <div class="login-brand mono"> N / CYBER COMMAND </div> <form class="login-panel" id="login-form"> <p class="error-inline" hidden="" id="login-form-error" role="alert"> </p> <p class="eyebrow"> NAPOLEAN / SECURE WORKSPACE </p> <h1> Evidence first. <br/> Decisions that hold. </h1> <p class="muted"> An enterprise workbench for scoped security reviews, alert triage, and team exercises. </p> <label for="access-key"> Workspace access key </label> <input autocomplete="current-password" id="access-key" name="access_key" required="" type="password"/> <button class="primary" type="submit"> Open workspace <span aria-hidden="true"> ↗ </span> </button> <p class="fine"> Single customer deployment · Analyst-reviewed findings </p> </form> <p class="login-footer mono"> RED / BLUE / WHITE / BLACK / PURPLE </p> </section> <div hidden="" id="shell"> <div id="shell"> <aside> <a aria-label="Napolean home" class="brand" href="#"> <span class="brand-mark">28 unmodified lines </nav> <div class="rail-bottom"> <div class="workspace-name" id="workspace-name"> Browser workspace </div> <p class="fine"> Scoped input. Human decisions. Records stay in this browser profile. </p> <button class="text-button" id="logout"> Sign out ↗ </button> </div> </aside> <main id="main" tabindex="-1">1 unmodified line <span class="mono"> SECURITY OPERATIONS / WORKBENCH </span> <span class="mono" id="session-status"> ● SESSION ACTIVE <span class="mono" id="local-status"> LOCAL / NO SERVER </span> </header> <section aria-label="Browser storage notice" class="local-notice"> <strong> Your browser is the workspace. </strong> <p> Results are stored locally in IndexedDB for this browser profile and site origin. No shared team database, model, or server is running. Raw source, alerts, and scenario input are not stored. Export JSON backups: clearing site data or changing browsers can remove access to records. </p> </section> <div id="view"> </div> <footer>1 unmodified line NAPOLEAN / EVIDENCE BEFORE VERDICTS </span> <span> Local analysis · No autonomous scanning Pattern checks · No model or server </span> </footer> </main> </div> <dialog aria-labelledby="create-title" id="create-dialog"> <form id="create-form"> <form autocomplete="off" id="create-form"> <p class="error-inline" hidden="" id="create-form-error" role="alert"> </p> <div class="dialog-head">74 unmodified lines </div> <textarea id="content" maxlength="64000" name="content" required="" rows="9" spellcheck="false"></textarea> <p class="fine" id="input-help"> Paste a Python snippet. Source is inspected for a limited set of static candidates; it is never executed. Paste a Python snippet for limited text-pattern checks. This is not a Python parser or data-flow analysis. Input is never executed. </p> <label class="attestation"> <input id="authorization" required="" type="checkbox"/>2 unmodified lines </span> </label> <p class="fine"> Raw input is not retained. Findings and analyst notes are retained in this workspace. Raw input is not stored. Findings and analyst notes are saved in this browser. Redaction is best effort; remove secrets before submitting. </p> <div class="dialog-actions"> <button data-close="" type="button">16 unmodified lines </div> <div id="finding-body"> </div> <form id="verdict-form"> <form autocomplete="off" id="verdict-form"> <p class="error-inline" hidden="" id="verdict-form-error" role="alert"> </p> <label for="verdict">35 unmodified lines Delete this assessment? </h2> <p> Its findings, missions, and analyst decisions will be permanently removed. Its findings, missions, and analyst decisions will be removed from this browser workspace. Exported files and backups are unaffected. </p> <div class="dialog-actions"> <button data-close="" type="button">123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280/* Browser-only analysis and result storage. No submission leaves this module. */(function (root, factory) { 'use strict'; const playbooks = typeof module === 'object' && module.exports ? require('./playbooks.js') : root.CyberPlaybooks; const api = factory(root, playbooks); if (typeof module === 'object' && module.exports) module.exports = api; else root.CyberLocal = api;})(typeof globalThis !== 'undefined' ? globalThis : this, function (root, playbooks) { 'use strict'; const 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.'); return Array.from(root.crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join(''); } function text(value, label, maximum, minimum = 1) { if (typeof value !== 'string' || value.length > maximum || value.trim().length < minimum || /[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff]/u.test(value)) { throw new Error(`${label} must contain ${minimum}–${maximum} valid characters.`); } return value.trim(); } function object(value) { if (!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]') .replace(/(\b(?:authorization\s*:\s*)?bearer\s+)[A-Za-z0-9._~+/=-]+/gi, '$1[REDACTED]') .replace(/\b(?:hf_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9_-]{16,}|AKIA[A-Z0-9]{16})\b/g, '[REDACTED]'); } function finding(title, severity, location, rootCause, evidence, remediation, prerequisites) { return {id:id(), title, severity, confidence:'low', verdict:'unresolved', location, root_cause:rootCause, input_to_impact:'Analyst must trace input control, reachability and business impact.', prerequisites, mitigations:'Not evaluated. Inspect validation, authorization, isolation and compensating controls.', evidence, remediation, review_note:''}; } 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) { let events; try { events = JSON.parse(content); } catch (_) { throw new Error('Alerts must be a valid JSON array.'); } if (!Array.isArray(events) || events.length > 500) throw new Error('Alerts must be an array of at most 500 objects.'); const counts = new Map(); let skipped = 0, privileges = 0, malware = 0; for (const event of events) { object(event); if (Object.keys(event).some(key => !['event','actor','source_ip'].includes(key))) throw new Error('Alert objects accept only event, actor and source_ip fields.'); text(event.event, 'Alert event', 100); for (const key of ['actor','source_ip']) if (Object.hasOwn(event,key)) text(event[key], `Alert ${key}`, 200); if (event.event === 'login_failed') { const group = JSON.stringify([event.actor ?? null, event.source_ip ?? null]); counts.set(group, (counts.get(group) || 0) + 1); } else if (event.event === 'privilege_change') privileges++; else if (event.event === 'malware_detected') malware++; else skipped++; } const findings = []; for (const count of counts.values()) if (count >= 5) findings.push(finding('Repeated failed logins', 'medium', 'Submitted alert batch', 'At least five login_failed events share actor and source identifiers in this batch.', `${count} matching failures; raw actor/source values omitted.`, 'Check event timestamps, duplicates, account ownership, MFA and successful login correlations.', 'Batch may contain duplicates or unrelated periods; event authenticity is unverified.')); for (const [count,label,title,severity] of [[privileges,'privilege_change','Privilege change requires review','medium'],[malware,'malware_detected','Malware alert requires validation','high']]) { if (count) findings.push(finding(title,severity,'Submitted alert batch','A supplied event label requires human security triage.', `${count} ${label} event(s); raw logs and identity values omitted.`, '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.' ]}; } function routeScenario(content) { const lower = content.toLowerCase(); for (const [category, details] of Object.entries(playbooks.scenarios)) { if (details.keywords.some(word => new RegExp('\\b'+word.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')+'\\w*\\b','i').test(lower))) return category; } return 'generic'; } function analyze(payload) { object(payload); const name = text(payload.name,'Name',120), scope = text(payload.scope,'Scope',2000), content = text(payload.content,'Content',64000); const workflow = payload.workflow, roles = payload.roles; if (!['code','alerts','exercise'].includes(workflow)) throw new Error('Choose code, alerts or exercise.'); if (payload.authorization !== true) throw new Error('Explicit scope authorization is required.'); if (!Array.isArray(roles) || !roles.length || roles.length > 5 || roles.some(role => !ROLES.includes(role)) || new Set(roles).size !== roles.length) throw new Error('Choose one to five distinct supported roles.'); let findings,coverage,category = null; if (workflow === 'code') ({findings,coverage} = codeCandidates(content)); else if (workflow === 'alerts') ({findings,coverage} = alertCandidates(content)); else { category = routeScenario(content); findings = []; coverage = [`Tabletop keyword routing selected category: ${category}. Only this category is retained; scenario prose is discarded.`, 'First matching keyword category wins: ransomware, supply-chain, identity/phishing, cloud; otherwise generic. No semantic/model analysis.', 'No vulnerability findings, live tests or control validation are produced.']; } const missions = roles.map(role => { const [title,objective,baseSteps,baseDeliverable] = playbooks.roles[role]; let steps = [...baseSteps], deliverable = baseDeliverable; if (workflow === 'exercise') { const [step,output] = playbooks.scenarios[category][role]; steps.unshift(step); deliverable=output; } else if (workflow === 'code') steps.unshift(`Review the ${findings.length} unresolved ledger candidate(s), inspect source in your controlled system and trace input reachability.`); else steps.unshift('Corroborate the alert ledger against original sensor records; establish timestamps, duplicates, actor ownership and approvals.'); return {role,title,objective:`${objective} Workflow: ${workflow}.`,steps,deliverable, limitations:['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.'}]}; } function markdownExport(assessment) { function safe(value) { return String(value).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>') .replace(/[\\`*_{}\[\]()#+.!|>~-]/g,'\\$&').replace(/[\r\n]/g,' '); } const lines = ['# Napolean Cyber Command assessment','',`Name: ${safe(assessment.name)}`,`Scope: ${safe(assessment.scope)}`, `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) { lines.push('',`### ${mission.role}: ${safe(mission.title)}`,safe(mission.objective),...mission.steps.map(step=>'- '+safe(step)), 'Deliverable: '+safe(mission.deliverable),...mission.limitations.map(limit=>'Limitation: '+safe(limit))); } lines.push('','## Coverage',...assessment.coverage.map(item=>'- '+safe(item)),'','## Activity', ...assessment.activity.map(item=>`- ${safe(item.at)} ${safe(item.action)}: ${safe(item.note)}`)); return lines.join('\n')+'\n'; }
class IndexedDBStore { constructor(indexedDB = root.indexedDB) { this.indexedDB = indexedDB; this.opening = null; } open() { if (!this.indexedDB) return Promise.reject(new Error('Browser IndexedDB storage is unavailable. Results cannot be saved.')); if (!this.opening) this.opening = new Promise((resolve,reject) => { let request; try { request = this.indexedDB.open('napolean-cyber-command-local',1); } catch (_) { reject(new Error('Browser storage could not be opened. Check browser privacy settings.')); return; } let blocked = false; request.onupgradeneeded = () => request.result.createObjectStore('assessments',{keyPath:'id'}); request.onerror = () => reject(new Error('Browser storage could not be opened. Check privacy settings or storage quota.')); request.onblocked = () => { blocked=true; reject(new Error('Browser storage upgrade is blocked. Close other workspace tabs and reload.')); }; request.onsuccess = () => { const db = request.result; if (blocked) { db.close(); return; } db.onversionchange = () => { db.close(); this.opening=null; }; resolve(db); }; }).catch(error => { this.opening=null; throw error; }); return this.opening; } async transaction(mode, operation) { const db = await this.open(); return new Promise((resolve,reject) => { let tx, value, failure; try { tx=db.transaction('assessments',mode); } catch (_) { reject(new Error('Browser storage transaction could not start. Reload and retry.')); return; } tx.oncomplete = () => resolve(value); tx.onabort = () => reject(failure || new Error('Browser storage transaction failed. Changes were not saved; check available storage.')); tx.onerror = () => { /* onabort reports the final transactional failure. */ }; try { operation(tx.objectStore('assessments'), result=>{value=result;}, error=>{failure=error;tx.abort();}); } catch (error) { failure=error; tx.abort(); } }); } list() { return this.transaction('readonly',(store,done)=>{const req=store.getAll();req.onsuccess=()=>done(req.result);}); } get(id) { return this.transaction('readonly',(store,done)=>{const req=store.get(id);req.onsuccess=()=>done(req.result);}); } add(record, maximum) { return this.transaction('readwrite',(store,done,fail)=>{ const req=store.count(); req.onsuccess=()=>{ if(req.result>=maximum) { fail(new Error('Browser workspace limit: 100 assessments. Export and delete records before adding more.')); return; } store.add(record); done(record); }; }); } update(id, mutate) { return this.transaction('readwrite',(store,done,fail)=>{ const req=store.get(id); req.onsuccess=()=>{ if(!req.result) {fail(new Error('Assessment not found.'));return;} try {const result=mutate(req.result);store.put(result);done(result);} catch(error) {fail(error);} }; }); } delete(id) { return this.transaction('readwrite',(store,done,fail)=>{ const req=store.get(id);req.onsuccess=()=>{ if(!req.result){fail(new Error('Assessment not found.'));return;} store.delete(id);done({ok:true}); }; }); } } class LocalService { constructor(store) { this.store=store; } async request(path, options={}) { const method=(options.method || 'GET').toUpperCase(); const route=String(path).split('?')[0]; let payload=options.body; if(typeof payload==='string') { if(payload.length>280000) throw new Error('Request is too large.'); try{payload=JSON.parse(payload);}catch(_){throw new Error('A JSON object is required.');} } if(route==='/api/assessments') { if(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)}; } const match=/^\/api\/assessments\/([a-f0-9]{32})(?:\/findings\/([a-f0-9]{32}))?$/.exec(route); if(!match) throw new Error('Unsupported local workspace route.'); const [,assessmentId,findingId]=match; if(method==='GET' && !findingId) { const record=await this.store.get(assessmentId); if(!record) throw new Error('Assessment not found.'); return {assessment:record}; } 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; }); return {assessment}; } throw new Error('Unsupported local workspace operation.'); } async exportText(assessmentId,format) { if(!['json','markdown'].includes(format)) throw new Error('Export format must be json or markdown.'); const {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)};});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207/* Original bounded role and scenario guidance shared with the reference engine. */(function (root, factory) { 'use strict'; const data = factory(); if (typeof module === 'object' && module.exports) module.exports = data; else root.CyberPlaybooks = data;})(typeof globalThis !== 'undefined' ? globalThis : this, function () { 'use strict'; return { "roles": { "red": [ "Adversary simulation", "Evaluate scoped attack hypotheses against approved assets.", [ "Confirm asset ownership, written scope, stop conditions and test window.", "Describe plausible attack paths and required access; use only isolated fixtures.", "Challenge each hypothesis against existing controls and submit evidence to the commander." ], "A scoped simulation plan with prerequisites, control checks and evidence requests." ], "blue": [ "Defense and incident triage", "Identify defensive evidence and proportionate response actions.", [ "Establish baseline telemetry, asset criticality and incident ownership.", "Correlate candidate indicators with independent evidence and document competing explanations.", "Propose containment and detection changes for human approval; submit gaps for adjudication." ], "A triage checklist, proposed detections and response decision record." ], "white": [ "Independent application review", "Validate source-level candidates and document remediation.", [ "Trace inputs through authentication, authorization and trust boundaries.", "Attempt to refute each candidate using validation, reachability and compensating controls.", "Record a verdict with evidence and a scoped regression test before declaring a fix." ], "An evidence-backed review ledger and remediation checklist." ], "black": [ "Attacker-perspective laboratory", "Model attacker objectives in an isolated, authorized training environment.", [ "Use fictional targets or explicitly owned laboratory assets; document prohibited actions.", "Describe attacker incentives, prerequisites and boundary crossings without performing exploitation.", "Challenge the modeled path against mitigations; give defenders evidence requirements for adjudication." ], "A bounded threat model and tabletop scenario with defensive checkpoints." ], "purple": [ "Joint control validation", "Connect adversary hypotheses to observable detection and response outcomes.", [ "Pair each hypothesis with a defensive owner and expected telemetry.", "Define an isolated exercise, measurable success criteria and benign evidence fixtures.", "Compare expected and observed signals; challenge attribution and adjudicate coverage gaps jointly." ], "A joint exercise plan and detection-coverage improvement backlog." ] }, "scenarios": { "ransomware": { "keywords": [ "ransomware", "encrypt", "extortion" ], "red": [ "Model a lab-only path from a fictional foothold to payroll encryption; define stop conditions before any simulation.", "Ransomware attack-path worksheet and approved lab boundaries." ], "blue": [ "Walk through endpoint isolation, incident declaration, backup integrity checks and restoration priorities without changing live systems.", "Ransomware triage and recovery decision checklist." ], "white": [ "Review least privilege, backup separation and restore evidence; challenge whether encryption paths remain reachable.", "Backup-control and privilege review with requested evidence." ], "black": [ "Model extortion incentives, access prerequisites and data exposure using fictional documents only.", "Fictional extortion threat model with prevention checkpoints." ], "purple": [ "Pair each modeled encryption stage with endpoint telemetry and a recovery exercise acceptance criterion.", "Ransomware detection matrix and timed restore exercise plan." ] }, "supply-chain": { "keywords": [ "supply-chain", "supply chain", "third-party", "dependency", "package", "vendor" ], "red": [ "Model how a fictional compromised package could cross a build-to-release boundary without introducing malicious code.", "Supply-chain attack-path worksheet for an isolated fixture." ], "blue": [ "Identify build logs, artifact provenance and release owners needed to corroborate a package-compromise report.", "Package incident triage and release containment checklist." ], "white": [ "Review dependency pinning, artifact signatures, build permissions and reproducibility evidence.", "Dependency and build integrity review checklist." ], "black": [ "Describe a fictional supplier adversary objective and required trust relationships; use no real poisoned packages.", "Supplier threat model and trust-boundary inventory." ], "purple": [ "Map a benign dependency-change fixture to build alerts, release gates and response owners.", "Supply-chain control exercise with observable release gates." ] }, "identity/phishing": { "keywords": [ "phishing", "identity", "identities", "credential", "password", "mfa", "login" ], "red": [ "Model a fictional credential-capture-to-account-access path; use dummy identities and no messages to real users.", "Authorized identity simulation outline with dummy-account boundaries." ], "blue": [ "Identify authentication logs, MFA events and session revocation decisions needed for an account-takeover tabletop.", "Identity incident triage and session containment checklist." ], "white": [ "Review MFA enrollment, recovery flows, session expiry and privilege approval evidence.", "Identity-control review and recovery-flow evidence requests." ], "black": [ "Describe attacker incentives and prerequisites for a fictional account takeover without creating lures or collecting credentials.", "Fictional account-takeover threat model." ], "purple": [ "Map a benign failed-login fixture and dummy privilege change to detections and account recovery criteria.", "Identity detection matrix and recovery exercise plan." ] }, "cloud": { "keywords": [ "cloud", "aws", "azure", "gcp", "bucket", "kubernetes", "iam" ], "red": [ "Model an isolated cloud trust-boundary crossing using a fictional role and test resource; prohibit production changes.", "Cloud role-path worksheet and test-resource scope." ], "blue": [ "Identify cloud audit logs, role-session provenance and resource ownership before proposing containment.", "Cloud alert triage and role-containment decision checklist." ], "white": [ "Review IAM policies, public exposure, secret access and tenant boundaries using supplied policy evidence.", "Cloud policy and isolation review checklist." ], "black": [ "Model fictional cloud-role abuse incentives and prerequisites without obtaining credentials or touching live resources.", "Cloud trust-boundary threat model." ], "purple": [ "Pair a benign test-role action with audit events, alert ownership and a rollback acceptance criterion.", "Cloud control exercise with audit-log expectations." ] }, "generic": { "keywords": [], "red": [ "Select one fictional business asset and model a scoped adversary hypothesis with explicit prerequisites.", "Generic adversary hypothesis and laboratory scope worksheet." ], "blue": [ "Establish incident owners, business-critical assets and evidence collection priorities for the tabletop.", "Business incident triage and escalation worksheet." ], "white": [ "Inventory trust boundaries, approvals and compensating controls that an analyst must validate.", "Business control evidence checklist." ], "black": [ "Describe a fictional adversary objective and resource constraints using only approved tabletop facts.", "Fictional business threat model." ], "purple": [ "Connect one tabletop hypothesis to a detection owner, expected evidence and measurable response target.", "Joint tabletop control validation worksheet." ] } }};});840 unmodified lines841842843844845846847848849850851852853854855856857858859840 unmodified lines outline:1px solid #e5566f; outline-offset:4px}
.local-notice { padding: 18px 0; border-bottom: 1px solid var(--border);}.local-notice strong { font-size: 12px; font-weight: 500;}.local-notice p { margin: 8px 0 0; max-width: 1040px; color: var(--muted); font-size: 11px; line-height: 1.7;}3 unmodified lines456789107891011131415161718192021222324252627282930313233343536373839121314151617181920212223242526272829303142323344343 unmodified linesfrom deploy_hf import collect_files, deploy, validate_repo_id
class FakeHub: def __init__(self): self.calls = [] def create_repo(self, **kw): self.calls.append(('create', kw)) def add_space_secret(self, **kw): self.calls.append(('secret', kw)) def upload_folder(self, **kw): self.calls.append(('upload', kw)) def __init__(self): self.calls=[] def create_repo(self,**kw): self.calls.append(('create',kw)) def upload_folder(self,**kw): self.calls.append(('upload',kw))
class DeploymentTests(unittest.TestCase): def test_manifest_excludes_customer_data_and_keys(self): root = Path(__file__).resolve().parents[1] files = collect_files(root) self.assertIn('app.py', files) self.assertIn('gradio_app.py', files) self.assertNotIn('Dockerfile', files) self.assertIn('engine.py', files) self.assertFalse(any(p.startswith('data/') or '.env' in p for p in files)) self.assertFalse(any('tests' in p for p in files))
def test_creation_is_private_and_does_not_reuse_repo(self): api = FakeHub() deploy(api, 'example/cyber-command', Path(__file__).resolve().parents[1], 'a'*30, 'b'*40) create = api.calls[0][1] self.assertEqual(create, dict(repo_id='example/cyber-command', repo_type='space', space_sdk='gradio', private=True, exist_ok=False)) self.assertEqual([c[0] for c in api.calls], ['create','secret','secret','upload']) upload = api.calls[-1][1] self.assertNotIn('data/', upload['allow_patterns']) self.assertEqual(upload['repo_type'], 'space')
def test_bad_ids_and_secrets_cause_no_network_mutation(self): for value in ('public', '../escape', 'a/b/c', 'a/b?token=secret'): with self.assertRaises(ValueError): validate_repo_id(value) api = FakeHub() with self.assertRaises(ValueError): deploy(api, 'example/cyber-command', Path('.'), 'short', 'b'*40) self.assertEqual(api.calls, [])
def test_static_manifest_excludes_server_keys_and_customer_data(self): files=collect_files(Path(__file__).resolve().parents[1]) self.assertIn('static/local.js',files) self.assertIn('static/index.html',files) for excluded in ('app.py','gradio_app.py','requirements.txt','Dockerfile','.env','data/'): self.assertNotIn(excluded,files) def test_creation_is_private_static_without_compute_or_secrets(self): api=FakeHub() deploy(api,'example/cyber-command',Path(__file__).resolve().parents[1]) self.assertEqual(api.calls[0],('create',dict(repo_id='example/cyber-command',repo_type='space',space_sdk='static',private=True,exist_ok=False))) self.assertEqual([x[0] for x in api.calls],['create','upload']) self.assertEqual(api.calls[-1][1]['repo_type'],'space') def test_bad_id_prevents_network_mutation(self): api=FakeHub() for value in ('public','../escape','a/b/c','a/b?token=secret'): with self.assertRaises(ValueError):validate_repo_id(value) with self.assertRaises(ValueError):deploy(api,'bad',Path('.')) self.assertEqual(api.calls,[]) def test_missing_source_is_rejected(self): with tempfile.TemporaryDirectory() as d: with self.assertRaises(ValueError): collect_files(Path(d)) with self.assertRaises(ValueError):collect_files(Path(d))
if __name__ == '__main__': unittest.main()if __name__=='__main__':unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121'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(); } async list() { return structuredClone([...this.rows.values()]); } async get(id) { return structuredClone(this.rows.get(id)); } write(fn) { const next = this.chain.then(fn); this.chain = next.catch(() => {}); return next; } add(record, limit) { return this.write(() => { if (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))); this.rows.set(id, structuredClone(next)); return structuredClone(next); }); } delete(id) { return this.write(() => { if (!this.rows.delete(id)) throw new Error('Assessment not found.'); return {ok: true}; }); }}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"'})); assert.equal(result.findings.length, 3); assert.ok(result.findings.every(f => f.verdict === 'unresolved')); assert.equal(result.missions.length, 5); assert.match(result.coverage.join(' '), /regex|pattern/i); assert.doesNotMatch(JSON.stringify(result), /private-secret-9823|eval\(user_input\)/); assert.equal(analyze(payload({content:'print("hello")'})).findings.length, 0);});
test('local input validation rejects malformed or oversized scope workflows and roles', () => { for (const update of [{authorization:false},{authorization:'true'},{scope:''},{workflow:'scan'}, {roles:[]}, {roles:['red','red']},{roles:['admin']},{roles:['red',{}]},{content:3},{content:'a'.repeat(64001)}, {content:'eval(x)'+' '.repeat(64000)},{name:'n'.repeat(121)}]) { assert.throws(() => analyze(payload(update))); } for (const invalid of [[],null,3,'text']) assert.throws(() => analyze(invalid));});
test('alerts group failures, retain no logs, disclose unsupported labels and validate schema', () => { const events = Array.from({length:5}, () => ({event:'login_failed',actor:'alice-private',source_ip:'192.0.2.1'})); events.push({event:'privilege_change'},{event:'malware_detected'},{event:'custom'}); const result = analyze(payload({workflow:'alerts',content:JSON.stringify(events)})); assert.equal(result.findings.length,3); assert.match(result.coverage.join(' '),/1 event\(s\) skipped/); assert.doesNotMatch(JSON.stringify(result),/alice-private|192\.0\.2\.1/); for (const content of ['{}','[1]','bad','[{"event":3}]','[{"event":"x","extra":1}]', JSON.stringify(Array.from({length:501},()=>({event:'x'})))]) { assert.throws(() => analyze(payload({workflow:'alerts',content}))); }});
test('exercise scenario keywords change role-specific missions without retaining scenario prose', () => { const ransomware = analyze(payload({workflow:'exercise',content:'Unique prose 3512 ransomware encrypts payroll'})); const phishing = analyze(payload({workflow:'exercise',content:'Unique prose 4512 phishing targets identities'})); assert.equal(ransomware.scenario_category,'ransomware'); assert.equal(phishing.scenario_category,'identity/phishing'); assert.notDeepEqual(ransomware.missions[0].steps,phishing.missions[0].steps); assert.equal(ransomware.findings.length,0); assert.doesNotMatch(JSON.stringify(ransomware)+JSON.stringify(phishing),/Unique prose/);});
test('redaction removes quoted multiword assignments and bearer metadata; markdown escapes markup', () => { const value = redact('password="Correct Horse Battery Staple" Authorization: Bearer private-token-315'); assert.doesNotMatch(value,/Correct Horse|private-token-315/); const assessment = analyze(payload({name:'<img src=x onerror=alert(1)>',scope:'Owned scope password="Correct Horse Battery Staple"'})); assert.doesNotMatch(markdownExport(assessment), /<img|Correct Horse/); assert.match(markdownExport(assessment), /</);});
test('service persists ledger decisions and exports, validates notes, and deletes', async () => { const store = new MemoryStore(), service = new LocalService(store); assert.deepEqual(await service.request('/api/assessments'),{assessments:[]}); const {assessment:a} = await service.request('/api/assessments',{method:'POST',body:JSON.stringify(payload())}); const base = '/api/assessments/'+a.id; await assert.rejects(service.request(base+'/findings/'+a.findings[0].id,{method:'PATCH',body:JSON.stringify({verdict:'confirmed-static',note:'yes'})})); const review = await service.request(base+'/findings/'+a.findings[0].id,{method:'PATCH',body:JSON.stringify({verdict:'confirmed-static',note:'Traced taint in the owned test fixture.'})}); 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'); assert.equal((await fresh.request('/api/assessments')).assessments[0].unresolved_count,1); assert.match(await fresh.exportText(a.id,'markdown'),/Traced taint/); assert.equal(JSON.parse(await fresh.exportText(a.id,'json')).id,a.id); await assert.rejects(fresh.exportText(a.id,'html')); assert.deepEqual(await fresh.request(base,{method:'DELETE'}),{ok:true}); await assert.rejects(fresh.request(base)); await assert.rejects(fresh.request('/api/login',{method:'POST',body:'{}'}));});
test('concurrent reviews append atomically and bounded history prevents silent truncation', async () => { const store = new MemoryStore(), service = new LocalService(store); const {assessment:a} = await service.request('/api/assessments',{method:'POST',body:payload()}); const path = `/api/assessments/${a.id}/findings/${a.findings[0].id}`; await Promise.all(['First','Second'].map(word => service.request(path,{method:'PATCH',body:{verdict:'unresolved',note:word+' independent evidence review.'}}))); const record = (await service.request('/api/assessments/'+a.id)).assessment; assert.equal(record.activity.length,3); assert.match(JSON.stringify(record.activity),/First/); assert.match(JSON.stringify(record.activity),/Second/); await store.update(a.id, row => {row.activity=Array.from({length:200},()=>({at:'x',action:'review',note:'x'})); return row;}); await assert.rejects(service.request(path,{method:'PATCH',body:{verdict:'unresolved',note:'One more review'}}),/200/);});
test('record count is bounded and storage failure is surfaced instead of apparent success', async () => { const store = new MemoryStore(), service = new LocalService(store); for (let i=0;i<100;i++) await service.request('/api/assessments',{method:'POST',body:payload({content:'print(1)'})}); await assert.rejects(service.request('/api/assessments',{method:'POST',body:payload()}),/100/); const broken = new LocalService({list:async()=>{throw new Error('storage failed');}}); await assert.rejects(broken.request('/api/assessments'),/storage failed/); const unavailable = new IndexedDBStore(undefined); await assert.rejects(unavailable.list(),/storage|IndexedDB/i);});PROVENANCE.md+13-10
README.md+36-47
SECURITY.md+14-25
SERVICE.md+19-33
VERIFICATION.md+24-27
deploy_hf.py+31-45
index.htmlAdded+265
static/app.js+15-91
static/index.html+26-51
static/local.jsAdded+280
static/playbooks.jsAdded+207
static/style.css+16
tests/test_deploy.py+23-33
tests/test_local.cjsAdded+121