diff --git a/bin/renovate-run.sh b/bin/renovate-run.sh index 29ab801a..507267bc 100755 --- a/bin/renovate-run.sh +++ b/bin/renovate-run.sh @@ -15,7 +15,7 @@ export MSYS_NO_PATHCONV=1 MSYS2_ARG_CONV_EXCL='*' . "$(dirname "${BASH_SOURCE[0]}")/lib/docker-config.sh" TARGET="${1:?usage: renovate-run.sh [local|pr]}" MODE="${2:-local}" -IMG="renovate/renovate:44.173.0" +IMG="renovate/renovate:44.245.0" if [ "$MODE" = "pr" ]; then : "${RENOVATE_TOKEN:?RENOVATE_TOKEN required for pr mode}" diff --git a/bin/test/nested-checkout-exclusion.test.mjs b/bin/test/nested-checkout-exclusion.test.mjs index ddcbb765..71162a36 100644 --- a/bin/test/nested-checkout-exclusion.test.mjs +++ b/bin/test/nested-checkout-exclusion.test.mjs @@ -73,6 +73,7 @@ const HELPER = { 'sast-python-bandit': ['bin/python-lane-scan.mjs', [/SCAN_EXCLUDE_ROOTS\.map\(\(d\) => `\*\/\$\{d\}\/\*`\)/, /'-x', `[^`]*\$\{nested\}`/]], 'lint-python-ruff': ['bin/python-lane-scan.mjs', [/SCAN_EXCLUDE_ROOTS\.flatMap\(\(d\) => \['--extend-exclude', d\]\)/]], 'deps-ruby-bundler-audit': ['bin/bundler-audit-scan.mjs', CLASSIFIER], + 'deps-malware-list': ['bin/malware-list.mjs', DOTDIRS], 'jackson-caseinsensitive-guard': ['bin/guard-jackson-caseinsensitive.mjs', CLASSIFIER], 'eol-runtime': ['bin/eol-scan.mjs', CLASSIFIER], 'container-base-images': ['bin/base-images.mjs', CLASSIFIER], diff --git a/docs/EXIT-CODES.md b/docs/EXIT-CODES.md index 7b73551b..cef5f28a 100644 --- a/docs/EXIT-CODES.md +++ b/docs/EXIT-CODES.md @@ -8,7 +8,7 @@ nothing about exit status; `prose` means it does, in a shape the extractor does Neither is a claim about what the command returns. What may change between releases is in [STABILITY.md](STABILITY.md). -367 commands: 167 declared, 13 prose, 187 undeclared. Of the declared, 133 use only codes 0–13, the range Node itself exits with (1 on an uncaught exception), and 34 declare a code of 20 or above. +368 commands: 168 declared, 13 prose, 187 undeclared. Of the declared, 134 use only codes 0–13, the range Node itself exits with (1 on an uncaught exception), and 34 declare a code of 20 or above. ## `commitwork` subcommands @@ -625,6 +625,13 @@ Undeclared: `list`, `run`, `scan`, `brief`, `sarif`, `reindex`, `sbom-review`, ` | 0 | ran | | 2 | could not run | +### `bin/malware-list.mjs` + +| Exit | Meaning | +|---:|---| +| 0 | ran (no list, or no lockfile, is a declared void with filesScanned 0) | +| 2 | could not run (a list that exists but cannot be read or parsed) | + ### `bin/md-view.mjs` | Exit | Meaning | diff --git a/docs/REFERENCE.md b/docs/REFERENCE.md index af826327..6950afe3 100644 --- a/docs/REFERENCE.md +++ b/docs/REFERENCE.md @@ -10,9 +10,9 @@ verified against the code. Check definitions are indexed in [MANIFEST-MAP.md](MA | Surface | Total | Documented | Undocumented | |---|---:|---:|---:| -| Commands (a usage line in the header) | 349 | 285 | 64 | -| Exit codes (declared in the header) | 365 | 165 | 200 | -| `CW_*` environment variables (described in an `env` header) | 965 | 233 | 732 | +| Commands (a usage line in the header) | 352 | 288 | 64 | +| Exit codes (declared in the header) | 368 | 168 | 200 | +| `CW_*` environment variables (described in an `env` header) | 968 | 235 | 733 | | Lane manifest check keys in use (described in the schema) | 45 | 43 | 2 | Commands are the population of `bin/exit-codes.mjs`: top-level `bin/`, `monitor/` and `cra/` @@ -106,7 +106,7 @@ bin/ab-loop.mjs — the prompt A/B loop backbone, runnable today. ### `bin/actions-gaps.mjs` -actions-gaps.mjs — four GitHub Actions workflow findings the fleet could not see: a job on a self-hosted runner, a privileged trigger (workflow_run / pull_request_target) whose job checks out or downloads the triggering… +actions-gaps.mjs — five GitHub Actions workflow findings the fleet could not see: a job on a self-hosted runner, a privileged trigger (workflow_run / pull_request_target) whose job checks out or downloads the triggering… - Usage: `node bin/actions-gaps.mjs [rootDir] exit 0 ran · 2 could not run` - Exit: 0 ran · 2 could not run @@ -403,6 +403,13 @@ bin/cobolwork-remediate.mjs — cobolwork remediation from a terminal: draft and - Option: `--dir (or CW_COBOLWORK_REMEDIATION_DIR) is where job files live; default reports/cobolwork-remediation.` - Exit: 0 done · 1 refused, failed, or a verdict other than pass · 2 usage +### `bin/codeql-frontier.mjs` + +bin/codeql-frontier.mjs — where untrusted data leaves the code CodeQL can follow. + +- Usage: `node bin/codeql-frontier.mjs (run by a CodeQL lane, after analyze)` +- Exit: 0 always. This is a side measurement: the lane's verdict is its own analyze, and a frontier that could not run is recorded as such (state failed / unsupported / no-database), never as an empty frontier. + ### `bin/codeql-go-build.mjs` What CodeQL runs to extract Go, in place of its autobuilder. @@ -786,6 +793,15 @@ bin/format-phase.mjs — remediation #19: the pre-commit formatting phase, built - Option: `--write fix them and restage exactly those files; exit 0` - Exit: stated in the header in a form not tabulated (prose) +### `bin/frontier-review.mjs` + +bin/frontier-review.mjs — draft, emit and check the taint-frontier worksheets (cra/frontier-review.mjs). + +- Usage: `node bin/frontier-review.mjs draft [--repo ]` +- Usage: `node bin/frontier-review.mjs emit [--repo ]` +- Usage: `node bin/frontier-review.mjs status [--repo ]` +- Exit: 0 done; status always, its JSON naming any worksheet it could not use · 1 draft or emit: a worksheet could not be used, or a decision does not validate (named on stderr; nothing is written for that repository) · 2 usage + ### `bin/gate-ratchet.mjs` commitwork gate ratchet — fail on NEW debt, never on inherited debt. @@ -1044,6 +1060,13 @@ commitwork — mainline (feature d) git-graph harvester. - Option: `--out output dir (default: /../sitemap/data)` - Exit: undeclared +### `bin/malware-list.mjs` + +malware-list.mjs — every resolved npm and PyPI package in the tree's lockfiles, looked up in a known-malicious package list the OPERATOR supplies. + +- Usage: `node bin/malware-list.mjs [rootDir]` +- Exit: 0 ran (no list, or no lockfile, is a declared void with filesScanned 0) · 2 could not run (a list that exists but cannot be read or parsed) + ### `bin/manifest-map.mjs` commitwork — manifest-map: an index into a manifest nobody should read whole. @@ -2798,7 +2821,7 @@ cra/watch.mjs — exploited-vulnerability watch with CRA Art. ## Environment variables -965 `CW_*` names read by tracked non-test sources: 836 by name, and +968 `CW_*` names read by tracked non-test sources: 839 by name, and 129 indirect (quoted in a file that reads the environment by a computed key, so the read is likely but not shown). At most 6 readers are listed per name. A description is taken from a reader's `env` header section when one has it, otherwise from another file's, which is named. @@ -3293,6 +3316,9 @@ a reader's `env` header section when one has it, otherwise from another file's, | `CW_MAIL_RETRY_MS` | direct | `lib/mail.mjs` | undocumented | | `CW_MAIL_TIMEOUT_MS` | direct | `lib/mail.mjs` | undocumented | | `CW_MAIL_TRANSPORT` | direct | `lib/mail.mjs` | undocumented | +| `CW_MALWARE_LIST_NPM` | direct | `bin/malware-list.mjs` | undocumented | +| `CW_MALWARE_LIST_PYPI` | direct | `bin/malware-list.mjs` | list paths; default ~/.commitwork/malware-lists/{npm,pypi}.json | +| `CW_MALWARE_LIST_ROOT` | direct | `bin/malware-list.mjs` | overrides rootDir | | `CW_MANIFESTS_DIR` | direct | `admin/routes/scanners.mjs`, `monitor/lane-roster.mjs` | undocumented | | `CW_MAP_STORE` | direct | `monitor/sync-map-history.mjs` | undocumented | | `CW_MCP_EMISSIONS` | indirect | `monitor/store-paths.mjs` | the ledger, default monitor/private/mcp-emissions.jsonl (`mcp/emission-ledger.mjs`) | @@ -3477,7 +3503,7 @@ a reader's `env` header section when one has it, otherwise from another file's, | `CW_RENOVATE_REPO` | direct | `monitor/renovate-status.mjs` | undocumented | | `CW_REPORTS_DIR` | direct | `admin/routes/determinations.mjs`, `bin/advisory-index.mjs`, `bin/md-view.mjs`, `cra/advisory-aliases.mjs`, `cra/dataflow-evidence.mjs` | undocumented | | `CW_REPORTS_ROOT` | direct | `bin/test-run.mjs`, `monitor/area-coverage.mjs`, `monitor/lane-timing.mjs`, `monitor/perf-feedback.mjs`, `monitor/store-paths.mjs` | holds the digest, its delivery ledger and the job journal <reports>/scheduled-job-journal.jsonl (`bin/digest-scheduled.mjs`) | -| `CW_REPORT_DIR` | direct | `admin/routes/journey.mjs`, `bin/a11y-scan.mjs`, `bin/boot-harness.sh`, `bin/codeql-model-pack.mjs`, `bin/codeql-swift-build.sh`, `bin/commitwork.mjs` and 11 more | undocumented | +| `CW_REPORT_DIR` | direct | `admin/routes/journey.mjs`, `bin/a11y-scan.mjs`, `bin/boot-harness.sh`, `bin/codeql-frontier.mjs`, `bin/codeql-model-pack.mjs`, `bin/codeql-swift-build.sh` and 12 more | undocumented | | `CW_REPORT_FORMATS` | indirect | `monitor/settings.mjs` | undocumented | | `CW_REPO_IDENTITIES` | direct | `bin/lib/release-names-head-scan.mjs` | undocumented | | `CW_REPO_IDENTITY_LEDGER` | direct | `lib/repo-identity.mjs` | undocumented | @@ -3773,7 +3799,7 @@ a reader's `env` header section when one has it, otherwise from another file's, ## Manifest keys -Lane manifests (`$schema` is `manifest.schema.json`): `manifests/build-health.json` (6), `manifests/hermetic-tests.json` (1), `manifests/quality-gates.json` (5), `manifests/runtime.json` (7), `manifests/security-baseline.json` (92); 111 checks in all. +Lane manifests (`$schema` is `manifest.schema.json`): `manifests/build-health.json` (6), `manifests/hermetic-tests.json` (1), `manifests/quality-gates.json` (5), `manifests/runtime.json` (7), `manifests/security-baseline.json` (93); 112 checks in all. A nested key is written `parent.child`. A key the schema declares and no check uses is listed with 0. ### Check keys @@ -3785,7 +3811,7 @@ A nested key is written `parent.child`. A key the schema declares and no check u | `act.enabled` | 0 | undocumented | | `act.job` | 0 | Optional specific job id to run (act -j). | | `aliasOf` | 2 | This check reports into another check's category. | -| `appliesIfExists` | 51 | During `scan`, only run this check if at least one of these paths exists in the repo (e.g. package.json). | +| `appliesIfExists` | 52 | During `scan`, only run this check if at least one of these paths exists in the repo (e.g. package.json). | | `appliesIfGit` | 5 | During `scan`, only run this check if the target is a git repo. | | `appliesIfSourceExt` | 25 | Only run this check if a source file with one of these extensions exists in the tree (bounded walk, vendored/build dirs skipped). | | `containment` | 3 | A lane's exclusion from a group, declared as DATA rather than argued in prose. | @@ -3793,29 +3819,29 @@ A nested key is written `parent.child`. A key the schema declares and no check u | `containment.reason` | 3 | Why the exclusion exists, in terms a reader can check. | | `containment.reviewBy` | 3 | When this exclusion must be revisited, as an ISO-8601 UTC instant. | | `coverageSignals` | 4 | Patterns in this check's log that mean a LANE OF THE CHECK DID NOT RUN, even though the tool exited 0. | -| `description` | 111 | undocumented | -| `egress` | 111 | What this lane reaches over the network, declared so the host sandbox can deny everything else. | +| `description` | 112 | undocumented | +| `egress` | 112 | What this lane reaches over the network, declared so the host sandbox can deny everything else. | | `envPassthrough` | 5 | Credential-shaped environment names (…_TOKEN, …_SECRET, …_API_KEY, …_BEARER_x) this analyser lane may inherit from the operator's environment. | | `executesRepoCode` | 13 | This lane runs the scanned repository's own build, test or install code. | -| `formatNotes` | 90 | Scanner-specific FORMAT FACTS composed into every triage handoff alongside remediationPrompt — the exact mechanics of this scanner's suppression/config syntax (e.g. a .gitleaksignore line IS the finding's Fingerprint fi… | -| `groups` | 111 | Membership tags; lets `run <group>` select this check in addition to the top-level groups map. | -| `id` | 111 | Stable check id, conventionally matching the workflow filename stem. | -| `local` | 111 | Shell commands run in sequence (fail-fast) in repoPath. | +| `formatNotes` | 91 | Scanner-specific FORMAT FACTS composed into every triage handoff alongside remediationPrompt — the exact mechanics of this scanner's suppression/config syntax (e.g. a .gitleaksignore line IS the finding's Fingerprint fi… | +| `groups` | 112 | Membership tags; lets `run <group>` select this check in addition to the top-level groups map. | +| `id` | 112 | Stable check id, conventionally matching the workflow filename stem. | +| `local` | 112 | Shell commands run in sequence (fail-fast) in repoPath. | | `notALane` | 17 | Why this check feeds no lane: it writes an inventory, a count or a status that no reader derives a finding from. | -| `notes` | 71 | undocumented | +| `notes` | 72 | undocumented | | `producesIfExists` | 1 | Artifact globs (e.g. *.jar) that must exist somewhere in the repo for an empty-clean result to be trustworthy; otherwise the check is recorded as a void ('no scannable artifact — build first'). | -| `remediationPrompt` | 88 | A prompt an operator can feed to an AI coding assistant to remediate this scanner's findings — templated guidance, not per-finding text. | -| `report` | 111 | Declares the structured artifact this check writes (into $CW_REPORT_DIR) so `scan` can parse finding counts. | +| `remediationPrompt` | 89 | A prompt an operator can feed to an AI coding assistant to remediate this scanner's findings — templated guidance, not per-finding text. | +| `report` | 112 | Declares the structured artifact this check writes (into $CW_REPORT_DIR) so `scan` can parse finding counts. | | `report.exitCodes` | 92 | Every exit code the tool can end with, each marked measured (the report is a result) or unmeasured (it is not). | -| `report.file` | 111 | Filename written under $CW_REPORT_DIR. | +| `report.file` | 112 | Filename written under $CW_REPORT_DIR. | | `report.findingsExit` | 4 | Exit codes the tool documents as meaning it ran and reported findings. | -| `report.format` | 111 | Report format. | +| `report.format` | 112 | Report format. | | `report.log` | 19 | Filename (under $CW_REPORT_DIR) of the tool's own log. | -| `requires` | 111 | Gating conditions. | +| `requires` | 112 | Gating conditions. | | `requires.docker` | 4 | Requires a running Docker daemon. | | `requires.secrets` | 2 | Env vars that must be set (checked in process env and repoPath/.env). | | `requires.services` | 7 | Free-text service prerequisites surfaced to the user (e.g. 'docker daemon', 'live Supabase'). Informational. | -| `requires.tools` | 111 | Executables that must be on PATH. | +| `requires.tools` | 112 | Executables that must be on PATH. | | `requiresRepoTrust` | 2 | The lane's command runs a script the scanned repository supplies, not a bundled scanner. | | `requiresUrl` | 10 | Runtime scanner: needs a live base URL (--url/--urls/commitwork.url/$CW_TARGET_URL). | | `reuse` | 3 | Declares the lane's result a function of inputs bin/lib/lane-reuse.mjs can key: the scanned tree's files, this check, the files under the commitwork root listed in inputs (and their local imports), the tool versions, th… | @@ -3823,7 +3849,7 @@ A nested key is written `parent.child`. A key the schema declares and no check u | `reuse.inputs` | 2 | Paths under the commitwork root the lane reads or executes. | | `reuse.outputs` | 3 | Files the lane writes into CW_REPORT_DIR, as names or * patterns; must include report.file. | | `reuse.packs` | 2 | Query packs the tool loads locally: codeql keys the CodeQL package cache and the repository's CodeQL models, joern the query database installed beside the joern-scan launcher. | -| `sandboxExtraReads` | 18 | Paths this lane must read beyond the host sandbox's fixed set (the scanned tree, commitwork, the system prefixes, the node prefix, TMPDIR, the prefix of each `requires.tools` binary, ~/.gitconfig). | +| `sandboxExtraReads` | 19 | Paths this lane must read beyond the host sandbox's fixed set (the scanned tree, commitwork, the system prefixes, the node prefix, TMPDIR, the prefix of each `requires.tools` binary, ~/.gitconfig). | | `sandboxExtraWrites` | 42 | Paths this lane must write beyond $CW_REPORT_DIR and TMPDIR: a tool's own cache (~/.semgrep, ~/Library/Caches/trivy, ~/.codeql). | | `sandboxLoopback` | 2 | The lane's tool connects over TCP loopback to worker processes it starts itself. | | `scopeNotes` | 20 | Named limits on what this check can see (e.g. 'language', 'codeql-extractor-baseline'). | diff --git a/docs/THREAT-MODEL.md b/docs/THREAT-MODEL.md index c8636ed3..44f14e29 100644 --- a/docs/THREAT-MODEL.md +++ b/docs/THREAT-MODEL.md @@ -261,7 +261,7 @@ under `brief --pc`. `CW_SANDBOX=off` is set (R5). Lanes that fetch and run a pinned tool include `retire@6.1.0`, `@cyclonedx/cyclonedx-npm@6.0.1` - and `renovate@44.173.0` through `npx --prefix` (R6), the semgrep and CodeQL packs, and the docker + and `renovate@44.245.0` through `npx --prefix` (R6), the semgrep and CodeQL packs, and the docker images for osv-scanner, GuardDog, Renovate and dep-scan. `deep` adds the three contained build lanes. Not determined: whether CodeQL's NuGet restore in `sast-codeql-csharp` (`--build-mode=none`) runs diff --git a/fixtures/scan-canary/EXPECTED.json b/fixtures/scan-canary/EXPECTED.json index ab5d8413..efcd21f3 100644 --- a/fixtures/scan-canary/EXPECTED.json +++ b/fixtures/scan-canary/EXPECTED.json @@ -948,6 +948,13 @@ "want": "OUT OF SCOPE, permanently. Three synthetic workflows that bin/test/actions-grade.test.mjs feeds to the grading command; refused.yml carries an expression both parsers refuse by design. No runner executes them, and counting them would report test inputs as this repository's CI.", "blockedBy": "Belongs in checks[actions-zizmor].scopeNotes as a MINUS entry, like the dirty canary's. Recorded here beside it for the same reason.", "isGapNotPolicy": false + }, + { + "lane": "zizmor", + "path": "fixtures/semgrep-workflows/.github/", + "want": "OUT OF SCOPE, permanently. Synthetic workflows that monitor/test/semgrep-workflows.test.mjs scans to show the workflow prompt rules firing and staying quiet; .semgrepignore already keeps them out of the self-scan. No runner executes them, and counting them would report test inputs as this repository's CI.", + "blockedBy": "Belongs in checks[actions-zizmor].scopeNotes as a MINUS entry, like the dirty canary's. Recorded here beside it for the same reason.", + "isGapNotPolicy": false } ] }, diff --git a/flow/dfd-adapter.mjs b/flow/dfd-adapter.mjs index 7725773a..4ee2860e 100644 --- a/flow/dfd-adapter.mjs +++ b/flow/dfd-adapter.mjs @@ -476,7 +476,10 @@ export function repoRelative(p, root = null) { let x = String(p || '').replace(/\\/g, '/'); if (x.startsWith('file://')) { try { x = decodeURIComponent(new URL(x).pathname); } catch { x = x.slice(7); } } const r = root ? String(root).replace(/\\/g, '/').replace(/\/+$/, '') : null; + // cra/dataflow-evidence.mjs findingFileOf strips `file:///` whole to join the rollup, so an absolute trace path arrives without its leading slash + const bare = r ? r.replace(/^\/+/, '') : null; if (r && x.startsWith(`${r}/`)) x = x.slice(r.length + 1); + else if (bare && x.startsWith(`${bare}/`)) x = x.slice(bare.length + 1); return x.replace(/^(\.\/)+/, ''); } diff --git a/flow/dfd-cli.mjs b/flow/dfd-cli.mjs index b4f6add6..199aeceb 100644 --- a/flow/dfd-cli.mjs +++ b/flow/dfd-cli.mjs @@ -38,6 +38,7 @@ import { renderPathsHtml } from '../lib/dfd-paths-render.mjs'; import { renderMapHtml } from '../lib/dfd-map-render.mjs'; import { renderStoryHtml } from '../lib/dfd-story-render.mjs'; import { renderReplayHtml } from '../lib/dfd-replay-render.mjs'; +import { renderRecordHtml } from '../lib/dfd-record-render.mjs'; import { writeAtomic } from '../monitor/lockfile.mjs'; import { isMainModule } from '../lib/is-main.mjs'; @@ -49,7 +50,7 @@ export const DEFAULT_MAX = 150; const VALUE_FLAGS = ['from', 'repo', 'codeql', 'prefix', 'focus', 'hops', 'direction', 'collapse', 'collapse-all-groups-over', 'orientation', 'max', 'emit', 'fonts', 'title', 'findings', 'coverage', 'verdicts', 'view', 'out']; const BOOL_FLAGS = ['tests', 'imports', 'functions', 'taint-only', 'scanner-only', 'issues', 'only-live', 'help']; const EMIT = ['html', 'model', 'analysis']; -export const VIEWS = Object.freeze(['classic', 'paths', 'map', 'story', 'replay']); +export const VIEWS = Object.freeze(['classic', 'paths', 'map', 'story', 'replay', 'record']); const FONTS = ['inline', 'none', 'served']; const DIRECTIONS = ['in', 'out', 'both']; const WHOLE = { hops: 'hops', max: 'max', 'collapse-all-groups-over': 'collapseOver' }; @@ -113,7 +114,9 @@ drawing reader who does not know the code: one fixed picture of the findings and what surrounds them, lit a layer at a time (the picture, the lines data follows, the findings, each change set, what is left); shows "plain" names · - replay: change sets step by step on a process flow, beside the file tree + replay: change sets step by step on a process flow, beside the file tree · + record: every node in group or layer lanes by hop from the sources, findings + under the node they sit on, patches replayed in a chosen order over a subset --title the diagram's title findings overlay @@ -177,6 +180,7 @@ export function parseArgs(argv) { if (opts.view === 'map' && opts.collapse !== undefined) return { error: '--view map opens and closes groups on the page, so it takes no --collapse' }; if (opts.view === 'story' && opts.collapse !== undefined) return { error: '--view story chooses what to draw from the findings, so it takes no --collapse' }; if (opts.view === 'replay' && opts.collapse !== undefined) return { error: '--view replay opens and closes groups on the page, so it takes no --collapse' }; + if (opts.view === 'record' && opts.collapse !== undefined) return { error: '--view record draws every node in its lane, so it takes no --collapse' }; if (opts.issues && opts.codeql === undefined) return { error: '--issues places a scan\'s results, so it needs --codeql' }; if (opts.view === 'paths' && opts.collapse !== undefined) return { error: '--view paths draws its own levels from the document\'s nested groups, so it takes no --collapse' }; if (opts.fonts !== undefined && !FONTS.includes(opts.fonts)) return { error: `--fonts takes one of ${FONTS.join(', ')}` }; @@ -458,7 +462,7 @@ function emit(opts, got, { stdout, fail }) { const { model, collapse, drawn } = got; const emitWhat = opts.emit || 'html'; const max = opts.max ?? DEFAULT_MAX; - if (emitWhat === 'html' && !['map', 'story', 'replay'].includes(opts.view) && drawn > max) { + if (emitWhat === 'html' && !['map', 'story', 'replay', 'record'].includes(opts.view) && drawn > max) { return fail(EXIT.SIZE, `${drawn} elements is more than --max ${max}: a diagram that size is not readable. Narrow it with --prefix or --focus (and --hops), collapse groups with --collapse or --collapse-all-groups-over, or raise --max.`); } let text; @@ -467,6 +471,7 @@ function emit(opts, got, { stdout, fail }) { let mapStats = null; let storyStats = null; let replayStats = null; + let recordStats = null; if (emitWhat === 'model') text = `${JSON.stringify(model, null, 2)}\n`; else if (emitWhat === 'analysis') text = `${JSON.stringify(analyse(model), null, 2)}\n`; else if (opts.view === 'paths') { @@ -485,6 +490,10 @@ function emit(opts, got, { stdout, fail }) { const got = renderReplayHtml(model, opts.title !== undefined ? { title: opts.title } : {}); text = got.html; replayStats = got.stats; + } else if (opts.view === 'record') { + const got = renderRecordHtml(model, opts.title !== undefined ? { title: opts.title } : {}); + text = got.html; + recordStats = got.stats; } else ({ html: text, stats } = renderHtml(model, { fonts: opts.fonts || 'inline', collapse, orientation: opts.orientation || 'auto', onlyLive: !!opts['only-live'] })); if (opts.out === undefined) { stdout.write(text); return EXIT.OK; } writeAtomic(opts.out, text, { mkdir: true }); @@ -492,7 +501,8 @@ function emit(opts, got, { stdout, fail }) { const mapWord = mapStats ? `, map view: ${mapStats.elements} code element(s), ${mapStats.leaves} folded, ${mapStats.issues} issue(s), ${mapStats.drawn} box(es) drawn at first` : ''; const storyWord = storyStats ? `, story view: ${storyStats.drawn} box(es) drawn, ${storyStats.hidden} left out, ${storyStats.places} finding(s), ${storyStats.stages} stage(s)` : ''; const replayWord = replayStats ? `, replay view: ${replayStats.sets} change set(s), ${replayStats.findings} issue(s), ${replayStats.drawable} drawable element(s), ${replayStats.files} file(s)` : ''; - const drawing = replayStats ? replayWord : storyStats ? storyWord : mapStats ? mapWord : pathStats ? pathWord : stats ? `, ${stats.orientation} ${stats.width}x${stats.height}, ${stats.crossings} crossing(s), ${stats.collisions} label collision(s)` : ''; + const recordWord = recordStats ? `, record view: ${recordStats.elements} element(s), ${recordStats.findings} finding(s), ${recordStats.patches} patch(es) in ${recordStats.sets} change set(s), ${recordStats.lanes.group} group lane(s), ${recordStats.lanes.layer} layer lane(s), outcomes by ${recordStats.outcomeRule === 'declared' ? 'declared impact' : 'sink rule'}, layout faults ${recordStats.audit.group.nan + recordStats.audit.group.through + recordStats.audit.group.overlap + recordStats.audit.layer.nan + recordStats.audit.layer.through + recordStats.audit.layer.overlap}` : ''; + const drawing = recordStats ? recordWord : replayStats ? replayWord : storyStats ? storyWord : mapStats ? mapWord : pathStats ? pathWord : stats ? `, ${stats.orientation} ${stats.width}x${stats.height}, ${stats.crossings} crossing(s), ${stats.collisions} label collision(s)` : ''; const u = model.source?.unknown; const unknown = u ? `; unknown: ${u.unanalysable} of ${u.files} file(s) not analysed, ${Object.values(u.unsupportedLanguages || {}).reduce((a, b) => a + b, 0)} in other languages, ${u.computedSites} computed site(s)` : ''; const c = got.coverage; diff --git a/flow/test/dfd-record-cli.test.mjs b/flow/test/dfd-record-cli.test.mjs new file mode 100644 index 00000000..f419b964 --- /dev/null +++ b/flow/test/dfd-record-cli.test.mjs @@ -0,0 +1,42 @@ +// commitwork dfd --view record (flow/dfd-cli.mjs): the flag, what it refuses, and the page it writes. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, writeFileSync, readFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { parseArgs, main, VIEWS } from '../dfd-cli.mjs'; +import { RECORD, SINKS } from '../../lib/test/fixtures/dfd-record-model.mjs'; + +const io = () => { const out = []; const err = []; return { out, err, stdout: { write: (s) => out.push(s) }, stderr: { write: (s) => err.push(s) } }; }; + +test('record is a view, and it takes no --collapse', () => { + // Arrange + const cases = [['--from', 'x.json', '--view', 'record'], ['--from', 'x.json', '--view', 'record', '--collapse', 'g']]; + // Act + const got = cases.map((argv) => parseArgs(argv)); + // Assert + assert.ok(VIEWS.includes('record')); + assert.equal(got[0].error, undefined); + assert.equal(got[0].opts.view, 'record'); + assert.equal(got[1].error, '--view record draws every node in its lane, so it takes no --collapse'); +}); + +test('--view record writes its page whatever --max says, with the title given and the counts and layout faults on stdout', async () => { + // Arrange + const dir = mkdtempSync(join(tmpdir(), 'flow-dfd-record-')); + writeFileSync(join(dir, 'm.json'), JSON.stringify(RECORD())); + writeFileSync(join(dir, 's.json'), JSON.stringify(SINKS())); + const a = io(); + const b = io(); + // Act + const code = await main(['--from', join(dir, 'm.json'), '--view', 'record', '--max', '2', '--title', 'Parcel record', '--out', join(dir, 'r.html')], a); + const html = readFileSync(join(dir, 'r.html'), 'utf8'); + const sinks = await main(['--from', join(dir, 's.json'), '--view', 'record', '--out', join(dir, 's.html')], b); + // Assert + assert.equal(code, 0, a.err.join('')); + assert.match(a.out.join(''), /, record view: 16 element\(s\), 7 finding\(s\), 4 patch\(es\) in 3 change set\(s\), 5 group lane\(s\), 5 layer lane\(s\), outcomes by declared impact, layout faults 0/); + assert.match(html, /Parcel record — record<\/title>/); + assert.equal(sinks, 0, b.err.join('')); + assert.match(b.out.join(''), /outcomes by sink rule, layout faults 0/); + assert.ok(readFileSync(join(dir, 's.html'), 'utf8').includes('Parcel intake service')); +}); diff --git a/flow/test/dfd-story-cli.test.mjs b/flow/test/dfd-story-cli.test.mjs index 9ffb7e81..bd65d74a 100644 --- a/flow/test/dfd-story-cli.test.mjs +++ b/flow/test/dfd-story-cli.test.mjs @@ -19,7 +19,7 @@ test('story is a view, and it takes no --collapse', () => { // act const got = cases.map((argv) => parseArgs(argv)); // assert - assert.deepEqual(VIEWS, ['classic', 'paths', 'map', 'story', 'replay']); + assert.deepEqual(VIEWS, ['classic', 'paths', 'map', 'story', 'replay', 'record']); assert.equal(got[0].error, undefined); assert.match(got[1].error, /--view story chooses what to draw from the findings, so it takes no --collapse/); assert.match(got[2].error, /--view takes one of classic, paths, map, story, replay/); diff --git a/lib/dfd-record-client.js b/lib/dfd-record-client.js new file mode 100644 index 00000000..44beb140 --- /dev/null +++ b/lib/dfd-record-client.js @@ -0,0 +1,188 @@ +// lib/dfd-record-client.js — record view drawing and wiring; every decision is createRecordCore's. + +export function mountRecordView(document, createRecordCore, env = {}) { + const timers = env.timers || { set: (fn, ms) => setTimeout(fn, ms), clear: (t) => clearTimeout(t) }; + const $ = (id) => document.getElementById(id); + const esc = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, '''); + const clip = (s, n) => { const t = String(s); return t.length <= n ? t : `${t.slice(0, Math.max(1, n - 1))}…`; }; + const many = (n, one) => `${n} ${n === 1 ? one : `${one}s`}`; + const link = (kind, id, text) => `<button type="button" class="lk" data-sel="${kind}" data-id="${esc(id)}">${esc(text)}</button>`; + const option = (value, text, on) => `<option value="${esc(value)}"${on ? ' selected' : ''}>${esc(text)}</option>`; + const core = createRecordCore(JSON.parse($('dfd-data').textContent)); + const GLYPH = { + actor: 'M8 2.2 L14.4 13.6 L1.6 13.6 Z', + store: 'M2.8 2.8 H13.2 V13.2 H2.8 Z', + log: 'M2.8 4 Q8 1 13.2 4 V12 Q8 15 2.8 12 Z', + process: 'M8 1.4 L14.6 8 L8 14.6 L1.4 8 Z', + external: 'M4.6 2 H11.4 L14.8 8 L11.4 14 H4.6 L1.2 8 Z', + outcome: 'M8 1 L11.2 8 L8 15 L4.8 8 Z', + route: 'M3 2.6 H13 V8.6 L8 13.8 L3 8.6 Z', + drain: 'M1.8 2.6 H14.2 L9.6 8.6 V14 L6.4 12.4 V8.6 Z', + }; + const PRIM_WORD = { actor: 'actor that starts flows', store: 'data store', log: 'log store', process: 'process', external: 'external system', outcome: 'outcome', route: 'route test without a node', drain: 'log drain' }; + const V = { mode: 'group', order: 'sets', dim: 'changeset', active: new Set(core.orders.sets.map((k) => k.id)), k: core.orders.sets.length, sel: null, tab: 'findings', playing: null }; + + const order = () => core.orders[V.order].filter((k) => V.active.has(k.id)); + const state = () => core.step(V.order, V.active, V.k); + const glyph = (prim, x, y, cls = '') => `<path class="gl p-${prim}${cls}" transform="translate(${x} ${y})" d="${GLYPH[prim]}"/>`; + + function drawGrid(st) { + const L = core.layout(V.mode); + const G = L.geo; + const fx = V.sel ? core.focus(V.sel.kind, V.sel.id) : null; + const isSel = (kind, id) => !!V.sel && V.sel.kind === kind && V.sel.id === id; + let h = `<svg class="rec${fx ? ' has-em' : ''}" viewBox="0 0 ${L.width} ${L.height}" width="${L.width}" height="${L.height}" role="group" aria-label="${esc(`Record by ${V.mode === 'layer' ? 'layer' : 'group'}: ${many(L.lanes.length, 'lane')}, ${many(L.cols.length, 'hop column')}, step ${st.k} of ${st.total}, ${many(st.open, 'finding')} open`)}">`; + L.lanes.forEach((l, i) => { + h += `<rect class="band b${i % 2}${l.boundary ? ' bd' : ''}" x="0" y="${l.top}" width="${L.width}" height="${l.h}"/>` + + `<text class="lh" x="10" y="${l.top + 18}"><title>${esc(l.name)}${esc(clip(l.name, 22))}` + + `${esc(clip(l.sub, 26))}`; + }); + for (const c of L.cols) h += `${esc(c.text)}${esc(c.sub)}`; + for (const d of L.stems) h += ``; + for (const e of L.edges) { + const cls = [`e k-${e.kind}`, e.existence !== 'confirmed' ? `ex-${e.existence}` : '', e.flow && st.red.has(e.id) ? 'red' : '', e.flow && st.closed.has(e.id) ? 'closed' : '', fx && fx.edges.has(e.id) ? 'em' : '', isSel('flow', e.id) ? 'on' : ''].filter(Boolean).join(' '); + const title = e.flow ? `${core.nodeName(e.flow.from)} → ${core.nodeName(e.flow.to)}${e.label ? `: ${e.label}` : ''}` : `${core.nodeName(e.from.id)} → log drain`; + h += `${esc(title)}${e.gate ? `` : ''}`; + } + for (const m of L.markers) { + if (m.kind === 'finding') h += `${esc(m.id)}`; + else h += `${esc(m.id)}`; + } + for (const u of L.units) { + if (u.type === 'drain') { h += `${glyph('drain', u.x + 6, u.y + u.h / 2 - 8)}Log drain`; continue; } + if (u.type === 'route') { h += `${glyph('route', u.x + 3, u.y + 1, ' sm')}${esc(clip(u.id, 24))}`; continue; } + const cls = ['u', `p-${u.prim}`, core.outcomes.has(u.id) ? 'outcome' : '', st.exposed.has(u.id) ? 'exposed' : '', fx && fx.units.has(u.id) ? 'em' : '', isSel('node', u.id) ? 'on' : ''].filter(Boolean).join(' '); + const top = u.y + (u.h - u.lines.length * 13) / 2 + 10; + h += `` + + `${glyph(u.prim, u.x + 6, u.y + u.h / 2 - 8)}` + + `${u.lines.map((t, i) => `${esc(t)}`).join('')}`; + for (const r of u.tray) { + const s = st.state.get(r.id); + h += `${esc(clip(r.id, 12))} ${esc(clip(r.finding.title || '', Math.max(4, 23 - Math.min(12, r.id.length))))}`; + } + for (const t of u.tests) h += `${glyph('route', t.x + 3, t.y + 1, ' sm')}${esc(clip(t.id, 22))}`; + } + $('grid').innerHTML = `${h}`; + } + + function drawRail(st) { + const pos = new Map(order().map((k, i) => [k.id, i + 1])); + const groups = core.groupsOf(V.dim, V.mode); + let h = `

Patches${V.active.size} / ${core.orders.sets.length}

`; + groups.forEach((g, gi) => { + const on = g.ids.filter((id) => V.active.has(id)).length; + h += `
${on}/${g.ids.length}
`; + for (const id of g.ids) { + const k = core.patch(id); + const n = pos.get(id); + h += `
${link('patch', id, clip(id, 10))}${esc(clip(core.name(k) === id ? '' : core.name(k), 18))}` + + (n ? `` : '–') + '
'; + } + }); + $('rail').innerHTML = h; + } + + function drawBar(st) { + $('pb-scrub').max = String(st.total); + $('pb-scrub').value = String(st.k); + $('pb-play').textContent = V.playing === null ? 'Play' : 'Pause'; + $('pb-play').setAttribute('aria-pressed', V.playing === null ? 'false' : 'true'); + $('pb-out').textContent = `Step ${st.k} of ${st.total} · ${st.patch ? `${st.patch} landed` : 'nothing landed'} · ${st.open} open`; + } + + function drawAccount(st) { + const n = (s) => [...st.state.values()].filter((v) => v === s).length; + const last = st.patch ? core.sets.find((s) => s.patches.some((k) => k.id === st.patch)) : null; + const exposed = [...st.exposed]; + $('account').innerHTML = `

Step ${st.k} of ${st.total}

${last ? esc(last.title) : 'Before any patch'}

` + + `
Open
${n('open')}
Fixed, untested
${n('fixed')}
Fixed, tested
${n('proven')}
Dismissed
${n('dismissed')}
` + + `

Outcomes on an open path: ${exposed.length}

${exposed.length ? `
    ${exposed.map((id) => `
  • ${link('node', id, core.nodeName(id))}
  • `).join('')}
` : ''}` + + `

${many(st.red.size, 'flow')} on open paths · ${many(st.closed.size, 'flow')} closed

`; + } + + function drawSel(st) { + const d = V.sel ? core.detail(V.sel.kind, V.sel.id, st) : null; + if (!d) { $('sel').innerHTML = '

Selection

No selection. Pick a chip, a row, a marker or a flow.

'; return; } + $('sel').innerHTML = `

${esc(d.kicker)}

${esc(d.title)}

${d.rows.map(([k, v]) => `
${esc(k)}
${esc(v)}
`).join('')}
` + + d.links.filter(([, l]) => l.length).map(([label, l]) => `

${esc(label)} ${l.length}

    ${l.map((r) => `
  • ${link(r.kind, r.id, clip(r.text, 70))}
  • `).join('')}
`).join(''); + } + + function drawTables(st) { + const T = core.tables(st); + const words = { flows: 'Flows', findings: 'Findings', patches: 'Patches', routes: 'Routes' }; + $('tabs').innerHTML = Object.keys(words).map((k) => ``).join(''); + const t = T[V.tab]; + const rowClass = (r) => { const c = [r.cls, V.sel && V.sel.kind === r.kind && V.sel.id === r.id ? 'on' : ''].filter(Boolean).join(' '); return c ? ` class="${c}"` : ''; }; + $('table').innerHTML = t.rows.length + ? `${t.head.map((c) => ``).join('')}${t.rows.map((r) => `${r.cells.map((c) => ``).join('')}`).join('')}
${esc(c)}
${esc(c)}
` + : `

No ${words[V.tab].toLowerCase()} in this document.

`; + } + + function drawLegend() { + const sw = (prim) => ``; + const line = (cls) => ``; + const rule = core.outcomeRule === 'declared' ? 'Outcome: a node with a declared impact, or the target of a rejected flow.' : 'Outcome: no node declares an impact, so every node that receives flows and sends none, other than a process, counts as an outcome.'; + $('legend').innerHTML = `
    ${Object.keys(GLYPH).map((p) => `
  • ${sw(p)} ${esc(PRIM_WORD[p])}
  • `).join('')}
` + + `
  • ${line('k-in')} flow inside a lane
  • ${line('k-cross')} flow crossing lanes, ticks at the crossing
  • ${line('k-error')} error flow
  • ${line('k-return')} feedback or retry
  • ${line('k-drain')} into the log drain
  • ${line('k-in ex-unknown')} existence unknown
  • ${line('k-in ex-contradicted')} existence contradicted
  • ${line('k-in red')} on an open path to an outcome
  • ${line('k-in closed')} closed by a landed patch
` + + `
  • open
  • fixed, untested
  • fixed, tested
  • dismissed
  • patch guard, filled once landed
` + + `

Columns are hops from the sources along flows. ${esc(rule)}

`; + } + + function draw() { + const st = state(); + V.k = st.k; + drawGrid(st); drawRail(st); drawBar(st); drawAccount(st); drawSel(st); drawTables(st); + } + const goStep = (k) => { V.k = Math.max(0, Math.min(Number(k) || 0, order().length)); draw(); }; + const pick = (kind, id) => { V.sel = kind && id !== undefined && id !== '' ? { kind, id } : null; draw(); }; + const stop = () => { if (V.playing !== null) { timers.clear(V.playing); V.playing = null; } }; + const tick = () => { V.playing = null; goStep(V.k + 1); V.playing = V.k >= order().length ? null : timers.set(tick, 1200); drawBar(state()); }; + const keepEnd = (fn) => { const atEnd = V.k >= order().length; fn(); V.k = atEnd ? order().length : Math.min(V.k, order().length); draw(); }; + const pressed = (ev) => (ev.key === 'Enter' || ev.key === ' ') && ev.target.closest('[data-sel]'); + + $('m-lanes').innerHTML = core.MODES.map(([k, t]) => option(k, t, k === V.mode)).join(''); + $('m-order').innerHTML = core.ORDERS.map(([k, t]) => option(k, t, k === V.order)).join(''); + $('m-dim').innerHTML = core.DIMS.map(([k, t]) => option(k, t, k === V.dim)).join(''); + $('m-lanes').addEventListener('change', (ev) => { V.mode = ev.target.value; draw(); }); + $('m-order').addEventListener('change', (ev) => { stop(); keepEnd(() => { V.order = ev.target.value; }); }); + $('m-dim').addEventListener('change', (ev) => { V.dim = ev.target.value; draw(); }); + $('pb').addEventListener('click', (ev) => { + const b = ev.target.closest('[data-pb]'); + if (!b) return; + const a = b.dataset.pb; + if (a === 'play') { + if (V.playing !== null) { stop(); drawBar(state()); return; } + if (V.k >= order().length) V.k = 0; + draw(); + V.playing = timers.set(tick, 1200); + drawBar(state()); + return; + } + stop(); + goStep(a === 'first' ? 0 : a === 'prev' ? V.k - 1 : a === 'next' ? V.k + 1 : order().length); + }); + $('pb-scrub').addEventListener('input', (ev) => { stop(); goStep(ev.target.value); }); + $('rail').addEventListener('change', (ev) => { + const t = ev.target; + if (!t.dataset) return; + stop(); + if (t.dataset.patch !== undefined) keepEnd(() => { if (t.checked) V.active.add(t.dataset.patch); else V.active.delete(t.dataset.patch); }); + else if (t.dataset.group !== undefined) { const g = core.groupsOf(V.dim, V.mode)[Number(t.dataset.group)]; if (g) keepEnd(() => { for (const id of g.ids) if (t.checked) V.active.add(id); else V.active.delete(id); }); } + }); + $('rail').addEventListener('click', (ev) => { + const all = ev.target.closest('[data-all]'); + if (all) { stop(); keepEnd(() => { V.active = new Set(all.dataset.all === '1' ? core.orders.sets.map((k) => k.id) : []); }); return; } + const s = ev.target.closest('[data-step]'); + if (s) { stop(); goStep(s.dataset.step); return; } + const b = ev.target.closest('[data-sel]'); + if (b) pick(b.dataset.sel, b.dataset.id); + }); + for (const id of ['grid', 'account', 'sel', 'table']) { + $(id).addEventListener('click', (ev) => { const b = ev.target.closest('[data-sel]'); if (b) pick(b.dataset.sel, b.dataset.id); else if (id === 'grid') pick(null); }); + $(id).addEventListener('keydown', (ev) => { const b = pressed(ev); if (b) { if (ev.preventDefault) ev.preventDefault(); pick(b.dataset.sel, b.dataset.id); } }); + } + $('tabs').addEventListener('click', (ev) => { const b = ev.target.closest('[data-tab]'); if (b) { V.tab = b.dataset.tab; drawTables(state()); } }); + drawLegend(); + draw(); + return { core, V }; +} diff --git a/lib/dfd-record-core.mjs b/lib/dfd-record-core.mjs new file mode 100644 index 00000000..81de0dfd --- /dev/null +++ b/lib/dfd-record-core.mjs @@ -0,0 +1,493 @@ +// lib/dfd-record-core.mjs — record view rules: lanes, hop columns, orthogonal routes, patch replay; imports nothing. + +export function createRecordCore(M) { + const GEO = Object.freeze({ laneHead: 150, col: 236, chipW: 160, rowW: 148, gap: 12, pad: 12, headH: 34, rowH: 18, rowGap: 3, indent: 12, corridorBase: 10, trackY: 6, trackX: 7, r: 5, arrow: 7 }); + const SEV = ['critical', 'high', 'medium', 'low', 'undetermined']; + const STATES = ['open', 'fixed', 'proven', 'dismissed']; + const STATE_WORD = { open: 'open', fixed: 'fixed, untested', proven: 'fixed, tested', dismissed: 'dismissed' }; + const LEVELS = ['tested', 'inspected', 'rescanned', 'asserted', 'none']; + const LEVEL_WORD = { tested: 'test proof', inspected: 'source inspection', rescanned: 'clean rescan', asserted: 'assertion, unverified', none: 'no evidence recorded' }; + const MODES = [['group', 'Groups'], ['layer', 'Layers']]; + const ORDERS = [['sets', 'Change sets'], ['upstream', 'Upstream first'], ['tested', 'Tested first'], ['document', 'Document order']]; + const DIMS = [['changeset', 'Change set'], ['cwe', 'Weakness'], ['lane', 'Lane'], ['evidence', 'Evidence'], ['severity', 'Severity'], ['proof', 'Proof']]; + const r1 = (v) => Math.round(v * 10) / 10; + const natural = (a, b) => String(a).localeCompare(String(b), 'en', { numeric: true }); + const name = (x) => (x ? x.plain || x.label || x.title || x.id : ''); + const push = (map, k, v) => { if (!map.has(k)) map.set(k, []); map.get(k).push(v); }; + + const nodes = M.nodes || []; + const byId = new Map(nodes.map((n) => [n.id, n])); + const flows = (M.flows || []).map((f, i) => ({ ...f, id: `f${i}` })).filter((f) => byId.has(f.from) && byId.has(f.to) && f.from !== f.to); + const fById = new Map(flows.map((f) => [f.id, f])); + const findings = M.findings || []; + const patches = M.patches || []; + const routes = M.routes || []; + const layers = Array.isArray(M.layers) ? M.layers : []; + const gById = new Map((M.groups || []).map((g) => [g.id, g])); + const gOrder = new Map((M.groups || []).map((g, i) => [g.id, i])); + const chain = (gid) => { const out = []; for (let g = gById.get(gid); g && out.length < 32 && !out.includes(g.id); g = gById.get(g.parent)) out.unshift(g.id); return out; }; + const outs = new Map(); const ins = new Map(); + for (const f of flows) { push(outs, f.from, f); push(ins, f.to, f); } + const between = (e) => (e ? flows.filter((f) => f.from === e.from && f.to === e.to) : []); + const existence = (f) => f.existence || (f.evidence && f.evidence.existence) || 'confirmed'; + const names = (k, f) => (k.findings || []).some((id) => id === f.id || id === String(f.id).split('@')[0]); + const sevOf = (f) => (SEV.includes(f.severity) ? f.severity : 'undetermined'); + const levelOf = (k) => (k.evidence && LEVELS.includes(k.evidence.level) ? k.evidence.level : 'none'); + const proves = (k) => !!k.evidence && (k.evidence.level === 'tested' || [k.evidence.control, ...(k.evidence.controls || [])].some((c) => c && c.failsWithout && c.passesWith)); + const guardsOf = new Map(findings.map((f) => [f, patches.filter((k) => names(k, f))])); + const findingsOf = new Map(patches.map((k) => [k, findings.filter((f) => names(k, f))])); + const atFlow = (f) => (f.at && f.at.flow ? between(f.at.flow)[0] || null : null); + const atNode = (f) => (f.at && f.at.node !== undefined && byId.has(f.at.node) ? f.at.node : null); + const guardFlow = (k) => between(k.guard)[0] || null; + + const isSource = (n) => !ins.has(n.id) && outs.has(n.id); + let sources = new Set(nodes.filter((n) => n.kind === 'external' && (n.subtype === 'actor' || n.subtype === 'endpoint') && isSource(n)).map((n) => n.id)); + if (!sources.size) sources = new Set(nodes.filter((n) => n.kind === 'external' && isSource(n)).map((n) => n.id)); + if (!sources.size) sources = new Set(nodes.filter(isSource).map((n) => n.id)); + if (!sources.size && nodes.length) sources = new Set([nodes[0].id]); + const rejectTo = new Set(patches.flatMap((k) => (k.rejects || []).map((e) => e.to))); + let outcomes = new Set(nodes.filter((n) => n.impact !== undefined || rejectTo.has(n.id)).map((n) => n.id)); + const outcomeRule = outcomes.size ? 'declared' : 'sinks'; + if (!outcomes.size) outcomes = new Set(nodes.filter((n) => n.kind !== 'process' && ins.has(n.id) && !outs.has(n.id)).map((n) => n.id)); + for (const id of outcomes) sources.delete(id); + + const hop = new Map([...sources].map((id) => [id, 0])); + for (const q = [...sources]; q.length;) { const id = q.shift(); for (const f of outs.get(id) || []) if (!hop.has(f.to)) { hop.set(f.to, hop.get(id) + 1); q.push(f.to); } } + const deepest = Math.max(0, ...hop.values()); + const unreached = nodes.some((n) => !hop.has(n.id)); + const nCols = deepest + 1 + (unreached ? 1 : 0); + const colOf = (id) => (hop.has(id) ? hop.get(id) : deepest + 1); + const homeOf = (f) => { + const n = atNode(f); + if (n) return n; + const e = f.at && f.at.flow; + if (!e) return null; + if (byId.has(e.from) && !sources.has(e.from)) return e.from; + return byId.has(e.to) ? e.to : byId.has(e.from) ? e.from : null; + }; + + const refKey = (r) => String(r || '').trim().split(/\s+/)[0].replace(/^\.\//, '').replace(/:.*$/, ''); + const declared = new Set((M.prs || []).map((p) => p.id)); + const sets = (M.prs || []).map((p) => ({ id: p.id, title: name(p), kind: 'pull request', patches: patches.filter((k) => k.pr === p.id) })); + const rest = patches.filter((k) => !declared.has(k.pr)); + const up = rest.map((_, i) => i); + const find = (i) => { while (up[i] !== i) i = up[i]; return i; }; + const link = (seen, key, i) => { if (!key) return; if (seen.has(key)) up[find(i)] = find(seen.get(key)); else seen.set(key, i); }; + const byCommit = new Map(); const byRef = new Map(); + rest.forEach((k, i) => { for (const c of k.commits || []) link(byCommit, String(c).slice(0, 12), i); }); + rest.forEach((k, i) => { if (!(k.commits || []).length) for (const r of (k.evidence && k.evidence.refs) || []) link(byRef, refKey(r), i); }); + const restSets = new Map(); + rest.forEach((k, i) => push(restSets, find(i), k)); + for (const list of restSets.values()) { + const commits = [...new Set(list.flatMap((k) => (k.commits || []).map((c) => String(c).slice(0, 12))))]; + const refs = [...new Set(list.flatMap((k) => ((k.evidence && k.evidence.refs) || []).map(refKey)))].filter(Boolean); + const id = commits.length ? `commits ${commits.join(', ')}` : refs.length ? refs.join(', ') : `patch ${list[0].id}`; + const title = list.length === 1 ? name(list[0]) : commits.length ? id : refs[0].split('/').pop(); + sets.push({ id, title, kind: 'change set', patches: list }); + } + const setAt = new Map(); + sets.forEach((s, i) => { for (const k of s.patches) setAt.set(k, i); }); + + const hopOf = (k) => (k.guard && byId.has(k.guard.from) ? colOf(k.guard.from) : nCols); + const orders = { + sets: sets.flatMap((s) => s.patches), + upstream: patches.slice().sort((a, b) => hopOf(a) - hopOf(b) || natural(a.id, b.id)), + tested: patches.slice().sort((a, b) => Number(proves(b)) - Number(proves(a)) || natural(a.id, b.id)), + document: patches.slice(), + }; + const closers = new Map(patches.map((k) => [k, [...(k.closes || []), ...(k.rejects || [])].flatMap(between)])); + const stateOf = (f, landed) => { + if (f.status === 'dismissed') return 'dismissed'; + const gs = guardsOf.get(f); + if (!gs.length) return f.status === 'mitigated' ? 'fixed' : 'open'; + const by = gs.filter((k) => landed.has(k)); + return !by.length ? 'open' : by.some(proves) ? 'proven' : 'fixed'; + }; + const stepCache = new Map(); + const step = (orderKey = 'sets', active = null, k = 0) => { + const order = (orders[orderKey] || orders.sets).filter((p) => !active || active.has(p.id)); + const n = Math.max(0, Math.min(Number(k) || 0, order.length)); + const key = `${orderKey}|${order.map((p) => p.id).join(',')}|${n}`; + if (stepCache.has(key)) return stepCache.get(key); + if (stepCache.size > 500) stepCache.clear(); + const landed = new Set(order.slice(0, n)); + const closed = new Set(); + for (const p of landed) for (const f of closers.get(p)) closed.add(f.id); + const open = (f) => !closed.has(f.id); + const state = new Map(findings.map((f) => [f.id, stateOf(f, landed)])); + const toOut = new Set(outcomes); + for (let ch = true; ch;) { ch = false; for (const f of flows) if (open(f) && toOut.has(f.to) && !toOut.has(f.from)) { toOut.add(f.from); ch = true; } } + const red = new Set(); + const exposed = new Set(); + const walk = (start) => { + const seen = new Set([start]); + for (const q = [start]; q.length;) { + const id = q.shift(); + for (const f of outs.get(id) || []) if (open(f) && toOut.has(f.to)) { red.add(f.id); if (!seen.has(f.to) && !outcomes.has(f.to)) { seen.add(f.to); q.push(f.to); } } + } + }; + for (const f of findings) { + if (state.get(f.id) !== 'open') continue; + const e = atFlow(f); const at = atNode(f); + if (e) { if (open(e) && toOut.has(e.to)) { red.add(e.id); if (!outcomes.has(e.to)) walk(e.to); } } + else if (at) { if (outcomes.has(at)) exposed.add(at); else walk(at); } + } + for (const id of red) if (outcomes.has(fById.get(id).to)) exposed.add(fById.get(id).to); + const out = { k: n, total: order.length, order: order.map((p) => p.id), patch: n ? order[n - 1].id : null, landed: new Set([...landed].map((p) => p.id)), closed, state, red, exposed, open: findings.filter((f) => state.get(f.id) === 'open').length }; + stepCache.set(key, out); + return out; + }; + + const wrap = (text) => { + const out = []; + for (const w of String(text).split(/\s+/).filter(Boolean)) { + for (let i = 0; i < w.length; i += 20) { + const part = w.slice(i, i + 20); const last = out.length - 1; + if (i === 0 && last >= 0 && out[last].length + 1 + part.length <= 20) out[last] += ` ${part}`; else out.push(part); + } + } + return out.length ? out : ['']; + }; + const primOf = (n) => (n.subtype === 'actor' ? 'actor' : outcomes.has(n.id) ? 'outcome' : n.kind === 'process' ? 'process' : n.kind === 'store' ? (n.subtype === 'log' ? 'log' : 'store') : 'external'); + const laneMeta = (k) => { + if (k === 'harness') return { name: 'Harness', sub: 'routes without a node, log drain', boundary: '' }; + if (k === 'l:') return { name: 'No layer', sub: 'outside every layer', boundary: '' }; + if (k.startsWith('l:')) return { name: k.slice(2), sub: 'layer', boundary: '' }; + if (k === 'g:') return { name: 'Ungrouped', sub: 'outside every group', boundary: '' }; + const g = gById.get(k.slice(2)); + return { name: name(g), sub: g.boundary ? `${g.boundary} boundary` : 'group', boundary: g.boundary || '' }; + }; + + function build(mode) { + const laneKey = mode === 'layer' ? (n) => (layers.includes(n.layer) ? `l:${n.layer}` : 'l:') : (n) => { const top = chain(n.group)[0]; return top ? `g:${top}` : 'g:'; }; + const U = new Map(); const units = []; + const unit = (o) => ({ tray: [], tests: [], w: GEO.chipW, ...o }); + for (const n of nodes) { + const lines = wrap(name(n)); + const u = unit({ type: 'node', id: n.id, node: n, prim: primOf(n), lines, h: Math.max(38, lines.length * 13 + 14), lk: laneKey(n), col: colOf(n.id) }); + U.set(n.id, u); units.push(u); + } + for (const f of findings) { const h = homeOf(f); if (h) U.get(h).tray.push({ id: f.id, finding: f }); } + for (const u of units) u.tray.sort((a, b) => natural(a.id, b.id)); + const tests = routes.map((r) => { + const host = U.get(r.node) || null; + const t = unit({ type: 'route', id: r.id, route: r, prim: 'route', lines: [r.id], h: GEO.rowH, w: host ? GEO.rowW : GEO.chipW, lk: host ? host.lk : 'harness', col: host ? host.col : 0, host, stacked: !!host }); + if (host) host.tests.push(t); else units.push(t); + return t; + }); + const drained = [...new Set([...flows.filter((f) => f.role === 'error').map((f) => f.to), ...nodes.filter((n) => n.subtype === 'log').map((n) => n.id)])]; + const drain = drained.length ? unit({ type: 'drain', id: '', prim: 'drain', lines: ['Log drain'], h: 38, lk: 'harness', col: deepest + (unreached ? 1 : 0) }) : null; + if (drain) units.push(drain); + + const keys = [...new Set(units.map((u) => u.lk))]; + const mean = (k) => { const cs = units.filter((u) => u.lk === k && u.type === 'node').map((u) => u.col); return cs.length ? cs.reduce((a, b) => a + b, 0) / cs.length : 0; }; + const rank = (k) => (k === 'harness' ? [2, 0, 0] : mode === 'layer' ? (k === 'l:' ? [1, 0, 0] : [0, layers.indexOf(k.slice(2)), 0]) : [0, mean(k), k === 'g:' ? 1e6 : gOrder.get(k.slice(2))]); + const ranks = new Map(keys.map((k) => [k, rank(k)])); + keys.sort((a, b) => { const x = ranks.get(a); const y = ranks.get(b); return x[0] - y[0] || x[1] - y[1] || x[2] - y[2]; }); + const lanes = keys.map((k) => ({ key: k, ...laneMeta(k) })); + const laneIndex = new Map(keys.map((k, i) => [k, i])); + for (const u of units) u.lane = laneIndex.get(u.lk); + for (const t of tests) if (t.stacked) t.lane = t.host.lane; + + const edges = flows.map((f) => ({ id: f.id, flow: f, from: U.get(f.from), to: U.get(f.to), existence: existence(f), label: f.label || '' })); + if (drain) for (const id of drained) edges.push({ id: `d:${id}`, flow: null, from: U.get(id), to: drain, existence: 'confirmed', label: 'error or log output' }); + for (const e of edges) { + e.crossing = !!e.flow && e.from.lane !== e.to.lane; + e.kind = !e.flow ? 'drain' : e.flow.role === 'error' ? 'error' : e.flow.role === 'feedback' || e.flow.role === 'retry' ? 'return' : e.crossing ? 'cross' : 'in'; + } + + const cells = new Map(); + for (const u of units) push(cells, `${u.lane}:${u.col}`, u); + const trayN = (u) => u.tray.length + u.tests.length; + const unitH = (u) => u.h + (trayN(u) ? GEO.rowGap + trayN(u) * (GEO.rowH + GEO.rowGap) : 0); + const cellH = (list) => list.reduce((a, u) => a + unitH(u), 0) + (list.length - 1) * GEO.gap; + const colX = (c) => GEO.laneHead + c * GEO.col + (GEO.col - GEO.chipW) / 2; + const gutterX = (c) => GEO.laneHead + c * GEO.col; + let corridorH = lanes.map(() => GEO.corridorBase); + let laneTop = []; let laneH = []; let gridH = 0; + const place = () => { + laneH = lanes.map((_, li) => corridorH[li] + GEO.pad * 2 + Math.max(38, ...[...cells].filter(([k]) => k.startsWith(`${li}:`)).map(([, l]) => cellH(l)))); + laneTop = []; let y = GEO.headH; + for (const h of laneH) { laneTop.push(y); y += h; } + gridH = y; + for (const [k, list] of cells) { + const [li, col] = k.split(':').map(Number); + const bodyTop = laneTop[li] + corridorH[li] + GEO.pad; const bodyH = laneH[li] - corridorH[li] - GEO.pad * 2; + let top = bodyTop + (bodyH - cellH(list)) / 2; + for (const u of list) { + u.x = colX(col); u.y = top; + let ry = u.y + u.h + GEO.rowGap; + for (const row of u.tray) { row.x = u.x + GEO.indent; row.y = ry; ry += GEO.rowH + GEO.rowGap; } + for (const t of u.tests) { t.x = u.x + GEO.indent; t.y = ry; t.col = col; ry += GEO.rowH + GEO.rowGap; } + top += unitH(u) + GEO.gap; + } + } + }; + const nb = new Map(units.map((u) => [u, new Set()])); + for (const e of edges) { nb.get(e.from).add(e.to); nb.get(e.to).add(e.from); } + place(); + const byColumn = [...cells.values()].sort((a, b) => a[0].col - b[0].col); + const yMid = (u) => u.y + u.h / 2; + for (let s = 0; s < 6; s++) { + for (const list of s % 2 ? byColumn.slice().reverse() : byColumn) { + const bary = new Map(list.map((u) => { const ys = [...nb.get(u)].filter((m) => m.col !== u.col).map(yMid); return [u, ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : yMid(u)]; })); + list.sort((a, b) => bary.get(a) - bary.get(b) || natural(a.id, b.id)); + place(); + } + } + + const W = GEO.chipW; + const route = () => { + const sides = new Map(); + const addPort = (u, side, e, end) => { let m = sides.get(u); if (!m) { m = { L: [], R: [] }; sides.set(u, m); } m[side].push({ e, end }); }; + for (const e of edges) { + e.shape = e.from.col < e.to.col ? 'fwd' : e.from.col === e.to.col ? 'same' : 'back'; + addPort(e.from, e.shape === 'back' ? 'L' : 'R', e, 'from'); + addPort(e.to, e.shape === 'fwd' ? 'L' : 'R', e, 'to'); + } + const far = (p) => (p.end === 'from' ? p.e.to : p.e.from); + for (const [u, m] of sides) { + for (const list of [m.L, m.R]) { + list.sort((p, q) => yMid(far(p)) - yMid(far(q))); + const span = Math.max(0, u.h - 14); const stepY = list.length > 1 ? Math.min(9, span / (list.length - 1)) : 0; + const y0 = yMid(u) - (stepY * (list.length - 1)) / 2; + list.forEach((p, i) => { p.e[p.end === 'from' ? 'ya' : 'yb'] = y0 + i * stepY; }); + } + } + const vsegs = new Map(); const hsegs = new Map(); + const addV = (g, e, i, y1, y2) => push(vsegs, g, { e, i, lo: Math.min(y1, y2), hi: Math.max(y1, y2) }); + const addH = (li, e, i, x1, x2) => push(hsegs, li, { e, i, lo: Math.min(x1, x2), hi: Math.max(x1, x2) }); + for (const e of edges) { + const a = e.from; const b = e.to; const { ya, yb } = e; + const corridor = yb >= ya ? b.lane : a.lane; + e.cl = undefined; + if (e.shape === 'fwd' && b.col === a.col + 1) { e.plan = [['p', a.x + W, ya], ['g', b.col], ['p', b.x, yb]]; addV(b.col, e, 1, ya, yb); } + else if (e.shape === 'fwd') { e.plan = [['p', a.x + W, ya], ['g', a.col + 1], ['c', corridor], ['g', b.col], ['p', b.x, yb]]; e.cl = corridor; } + else if (e.shape === 'same') { e.plan = [['p', a.x + W, ya], ['g', a.col + 1], ['p', b.x + W, yb]]; addV(a.col + 1, e, 1, ya, yb); } + else if (b.col + 1 === a.col) { e.plan = [['p', a.x, ya], ['g', a.col], ['p', b.x + W, yb]]; addV(a.col, e, 1, ya, yb); } + else { e.plan = [['p', a.x, ya], ['g', a.col], ['c', corridor], ['g', b.col + 1], ['p', b.x + W, yb]]; e.cl = corridor; } + } + for (const e of edges) if (e.cl !== undefined) { const xs = e.plan.filter((s) => s[0] === 'g').map((s) => gutterX(s[1])); addH(e.cl, e, 2, xs[0], xs[1]); } + const assign = (segs, gapBetween) => { + segs.sort((p, q) => p.lo - q.lo || p.hi - q.hi); + const ends = []; + for (const s of segs) { let t = ends.findIndex((x) => x < s.lo - gapBetween); if (t < 0) { t = ends.length; ends.push(0); } ends[t] = s.hi; s.t = t; } + return ends.length; + }; + const need = lanes.map(() => 0); + for (const [li, segs] of hsegs) { need[li] = assign(segs, 10); for (const s of segs) s.e.cy = laneTop[li] + 6 + s.t * GEO.trackY; } + for (const e of edges) if (e.cl !== undefined) { addV(e.plan[1][1], e, 1, e.ya, e.cy); addV(e.plan[3][1], e, 3, e.cy, e.yb); } + for (const e of edges) e.gx = {}; + for (const [g, segs] of vsegs) { + const n = assign(segs, 6); + // a crowded gutter narrows its track spacing instead of spilling tracks into the chip columns + const stepX = Math.min(GEO.trackX, (GEO.col - GEO.chipW - 8) / Math.max(1, n)); + const slot = (t) => (t % 2 ? -1 : 1) * Math.ceil(t / 2) * stepX; + const centre = g === 0 ? gutterX(0) + 14 : gutterX(g); + for (const s of segs) s.e.gx[s.i] = centre + slot(s.t) - (n % 2 ? 0 : stepX / 2); + } + return need; + }; + const want = route().map((n) => GEO.corridorBase + Math.max(0, n) * GEO.trackY); + if (want.some((w, i) => w !== corridorH[i])) { corridorH = want; place(); route(); } + + const onFlow = new Map(); const guardOn = new Map(); + for (const f of findings.slice().sort((a, b) => natural(a.id, b.id))) { const e = atFlow(f); if (e) push(onFlow, e.id, f); } + for (const k of patches) { const e = guardFlow(k); if (e) push(guardOn, e.id, k); } + const markers = []; + let maxX = 0; + for (const e of edges) { + const p = e.plan; const pts = []; + if (p.length === 3) { const x = e.gx[1]; pts.push([p[0][1], p[0][2]], [x, p[0][2]], [x, p[2][2]], [p[2][1], p[2][2]]); } + else { const x1 = e.gx[1]; const x2 = e.gx[3]; pts.push([p[0][1], p[0][2]], [x1, p[0][2]], [x1, e.cy], [x2, e.cy], [x2, p[4][2]], [p[4][1], p[4][2]]); } + const P = pts.filter((q, i) => i === 0 || Math.abs(q[0] - pts[i - 1][0]) > 0.01 || Math.abs(q[1] - pts[i - 1][1]) > 0.01); + e.pts = P; + for (const q of P) maxX = Math.max(maxX, q[0]); + const end = P[P.length - 1]; const prev = P[P.length - 2]; const dir = Math.sign(end[0] - prev[0]) || 1; + const base = [end[0] - dir * GEO.arrow, end[1]]; + const Q = P.slice(0, -1).concat([base]); + let d = `M${r1(Q[0][0])} ${r1(Q[0][1])}`; + for (let i = 1; i < Q.length - 1; i++) { + const a = Q[i - 1]; const c = Q[i]; const b = Q[i + 1]; + const l1 = Math.hypot(c[0] - a[0], c[1] - a[1]); const l2 = Math.hypot(b[0] - c[0], b[1] - c[1]); + const rr = Math.min(GEO.r, l1 / 2, l2 / 2); + const p1 = [c[0] - ((c[0] - a[0]) / (l1 || 1)) * rr, c[1] - ((c[1] - a[1]) / (l1 || 1)) * rr]; + const p2 = [c[0] + ((b[0] - c[0]) / (l2 || 1)) * rr, c[1] + ((b[1] - c[1]) / (l2 || 1)) * rr]; + d += ` L${r1(p1[0])} ${r1(p1[1])} Q${r1(c[0])} ${r1(c[1])} ${r1(p2[0])} ${r1(p2[1])}`; + } + e.d = `${d} L${r1(base[0])} ${r1(base[1])}`; + e.arrow = `M${r1(end[0])} ${r1(end[1])} L${r1(base[0])} ${r1(base[1] - 3.5)} L${r1(base[0])} ${r1(base[1] + 3.5)} Z`; + e.gate = ''; + if (e.crossing) { + const dl = e.to.lane; const by = dl > e.from.lane ? laneTop[dl] : laneTop[dl] + laneH[dl]; + for (let i = 1; i < P.length; i++) { + const a = P[i - 1]; const b = P[i]; + if (Math.abs(a[0] - b[0]) < 0.01 && (by - a[1]) * (by - b[1]) < 0) { e.gate = `M${r1(a[0] - 5)} ${r1(by - 2)} H${r1(a[0] + 5)} M${r1(a[0] - 5)} ${r1(by + 2)} H${r1(a[0] + 5)}`; break; } + } + } + const segL = []; let total = 0; + for (let i = 1; i < P.length; i++) { const l = Math.hypot(P[i][0] - P[i - 1][0], P[i][1] - P[i - 1][1]); segL.push(l); total += l; } + const at = (t) => { let s = t * total; for (let i = 0; i < segL.length; i++) { if (s <= segL[i]) { const u = segL[i] ? s / segL[i] : 0; return [P[i][0] + (P[i + 1][0] - P[i][0]) * u, P[i][1] + (P[i + 1][1] - P[i][1]) * u]; } s -= segL[i]; } return P[P.length - 1]; }; + (onFlow.get(e.id) || []).forEach((f, i) => { const q = at(Math.min(0.9, 0.6 + 0.08 * i)); markers.push({ kind: 'finding', id: f.id, edge: e.id, x: r1(q[0]), y: r1(q[1]) }); }); + (guardOn.get(e.id) || []).forEach((k, i) => { const q = at(Math.max(0.08, 0.3 - 0.06 * i)); markers.push({ kind: 'patch', id: k.id, edge: e.id, x: r1(q[0]), y: r1(q[1]) }); }); + } + const stems = []; + for (const u of units) { + const rows = [...u.tray, ...u.tests]; + if (!rows.length) continue; + const last = rows[rows.length - 1]; + stems.push(`M${r1(u.x + 6)} ${r1(u.y + u.h)} V${r1(last.y + GEO.rowH / 2)}${rows.map((r) => ` M${r1(u.x + 6)} ${r1(r.y + GEO.rowH / 2)} H${r1(r.x)}`).join('')}`); + } + const cols = Array.from({ length: nCols }, (_, c) => ({ + x: GEO.laneHead + c * GEO.col + GEO.col / 2, + text: c === 0 ? 'Sources' : c > deepest ? 'Not reached' : `Hop ${c}`, + sub: c === 0 ? 'hop 0' : c > deepest ? 'from any source' : c === 1 ? 'first contact' : '', + })); + const laneName = new Map(nodes.map((n) => [n.id, lanes[U.get(n.id).lane].name])); + return { + mode, geo: GEO, cols, units, tests, drain, edges, markers, stems, laneName, + lanes: lanes.map((l, i) => ({ ...l, top: laneTop[i], h: laneH[i], corridor: corridorH[i] })), + width: Math.ceil(Math.max(GEO.laneHead + nCols * GEO.col + 12, maxX + 12)), height: Math.ceil(gridH + 8), + }; + } + const layoutCache = new Map(); + const layout = (mode) => { + const m = MODES.some(([k]) => k === mode) ? mode : 'group'; + if (!layoutCache.has(m)) layoutCache.set(m, build(m)); + return layoutCache.get(m); + }; + + const audit = (mode) => { + const L = layout(mode); + const rects = []; + for (const u of L.units) rects.push({ u, x: u.x, y: u.y, w: u.w, h: u.h }); + for (const t of L.tests) if (t.stacked) rects.push({ u: t, x: t.x, y: t.y, w: GEO.rowW, h: GEO.rowH }); + for (const u of L.units) for (const r of u.tray) rects.push({ u, x: r.x, y: r.y, w: GEO.rowW, h: GEO.rowH }); + let nan = 0; const through = []; const segs = []; + for (const e of L.edges) { + if (/NaN|undefined/.test(e.d + e.arrow + e.gate)) nan += 1; + for (let i = 1; i < e.pts.length; i++) { + const a = e.pts[i - 1]; const b = e.pts[i]; + segs.push({ e, a, b }); + const minx = Math.min(a[0], b[0]); const maxx = Math.max(a[0], b[0]); const miny = Math.min(a[1], b[1]); const maxy = Math.max(a[1], b[1]); + for (const r of rects) if (r.u !== e.from && r.u !== e.to && maxx > r.x + 1 && minx < r.x + r.w - 1 && maxy > r.y + 1 && miny < r.y + r.h - 1) through.push(`${e.id} through ${r.u.type}:${r.u.id}`); + } + } + let overlap = 0; + const span = (p, q, k) => Math.min(Math.max(p.a[k], p.b[k]), Math.max(q.a[k], q.b[k])) - Math.max(Math.min(p.a[k], p.b[k]), Math.min(q.a[k], q.b[k])); + for (let i = 0; i < segs.length; i++) { + for (let j = i + 1; j < segs.length; j++) { + const s = segs[i]; const t = segs[j]; + if (s.e === t.e) continue; + const sv = Math.abs(s.a[0] - s.b[0]) < 0.01; const tv = Math.abs(t.a[0] - t.b[0]) < 0.01; + if (sv && tv && Math.abs(s.a[0] - t.a[0]) < 0.5 && span(s, t, 1) > 2) overlap += 1; + if (!sv && !tv && Math.abs(s.a[1] - t.a[1]) < 0.5 && span(s, t, 0) > 2 && s.e.from !== t.e.from && s.e.to !== t.e.to) overlap += 1; + } + } + return { nan, through: through.length, overlap, hits: [...new Set(through)] }; + }; + + const dimOf = (k, dim, mode) => { + const fs = findingsOf.get(k); + if (dim === 'cwe') return String((fs.find((f) => f.cwe) || {}).cwe || 'no CWE'); + if (dim === 'lane') return k.guard && byId.has(k.guard.to) ? layout(mode).laneName.get(k.guard.to) : 'no guarded flow'; + if (dim === 'evidence') return LEVEL_WORD[levelOf(k)]; + if (dim === 'severity') return SEV.find((s) => fs.some((f) => sevOf(f) === s)) || 'no finding'; + if (dim === 'proof') return proves(k) ? 'fails without, passes with' : 'no load-bearing test'; + return sets[setAt.get(k)].title; + }; + const groupsOf = (dim, mode) => { + const out = new Map(); + for (const k of orders.sets) push(out, dimOf(k, dim, mode), k.id); + return [...out].map(([value, ids]) => ({ value, ids })); + }; + + const nodeName = (id) => (byId.has(id) ? name(byId.get(id)) : String(id)); + const edgeText = (e) => (e ? `${nodeName(e.from)} → ${nodeName(e.to)}` : ''); + const ref = (kind, id, text) => ({ kind, id, text }); + const fRef = (f) => ref('finding', f.id, `${f.id} ${f.title || ''}`.trim()); + const kRef = (k) => ref('patch', k.id, `${k.id} ${name(k) === k.id ? '' : name(k)}`.trim()); + const flowRef = (f, side) => ref('flow', f.id, side === 'in' ? `${nodeName(f.from)} — ${f.label || 'flow'}` : side === 'out' ? `${f.label || 'flow'} — ${nodeName(f.to)}` : edgeText(f)); + const sel = (kind, id) => { + if (kind === 'node') return byId.get(id) || null; + if (kind === 'flow') return fById.get(id) || null; + if (kind === 'finding') return findings.find((f) => f.id === id) || null; + if (kind === 'patch') return patches.find((k) => k.id === id) || null; + if (kind === 'route') return routes.find((r) => r.id === id) || null; + return null; + }; + const detail = (kind, id, st) => { + const x = sel(kind, id); + if (!x) return null; + const rows = (list) => list.filter((r) => r[1] !== undefined && r[1] !== null && r[1] !== '').map(([k, v]) => [k, String(v)]); + if (kind === 'node') { + return { + kicker: [x.kind, x.subtype].filter(Boolean).join(' · '), title: name(x), + rows: rows([['id', x.id], ['groups', chain(x.group).map((g) => name(gById.get(g))).join(' › ') || 'none'], ['layer', x.layer], ['hop', hop.has(x.id) ? hop.get(x.id) : 'not reached'], ['place', sources.has(x.id) ? 'source' : outcomes.has(x.id) ? 'outcome' : ''], ['impact', x.impact], ['note', x.note]]), + links: [['Findings', findings.filter((f) => homeOf(f) === x.id).map(fRef)], ['Flows in', (ins.get(x.id) || []).map((f) => flowRef(f, 'in'))], ['Flows out', (outs.get(x.id) || []).map((f) => flowRef(f, 'out'))], ['Routes', routes.filter((r) => r.node === x.id).map((r) => ref('route', r.id, r.id))]], + }; + } + if (kind === 'flow') { + const ev = x.evidence || {}; + return { + kicker: `flow · ${x.role || 'data'}`, title: x.label || edgeText(x), + rows: rows([['from', nodeName(x.from)], ['to', nodeName(x.to)], ['existence', existence(x)], ['witness', ev.witness], ['method', ev.method], ['state', st && st.closed.has(x.id) ? 'closed at this step' : st && st.red.has(x.id) ? 'on an open path to an outcome' : '']]), + links: [['Ends', [ref('node', x.from, nodeName(x.from)), ref('node', x.to, nodeName(x.to))]], ['Findings', findings.filter((f) => atFlow(f) === x).map(fRef)], ['Guarded by', patches.filter((k) => guardFlow(k) === x).map(kRef)], ['Closed by', patches.filter((k) => closers.get(k).includes(x)).map(kRef)]], + }; + } + if (kind === 'finding') { + const home = homeOf(x); + return { + kicker: `finding · ${sevOf(x)}`, title: `${x.id} ${x.title || ''}`.trim(), + rows: rows([['cwe', x.cwe], ['status', x.status], ['state', st ? STATE_WORD[st.state.get(x.id)] : ''], ['where', atFlow(x) ? edgeText(atFlow(x)) : home ? nodeName(home) : 'not placed'], ['note', x.note]]), + links: [['Sits on', home ? [ref('node', home, nodeName(home))] : []], ['Flow', atFlow(x) ? [flowRef(atFlow(x))] : []], ['Patches', guardsOf.get(x).map(kRef)]], + }; + } + if (kind === 'patch') { + const ev = x.evidence || {}; const c = ev.control || (ev.controls || [])[0] || {}; + return { + kicker: `patch · ${LEVEL_WORD[levelOf(x)]}`, title: name(x), + rows: rows([['id', x.id], ['change set', sets[setAt.get(x)].title], ['guard', guardFlow(x) ? edgeText(guardFlow(x)) : x.guard ? `${x.guard.from} → ${x.guard.to}` : ''], ['proof', proves(x) ? 'fails without, passes with' : ''], ['test', c.test], ['landed', st ? (st.landed.has(x.id) ? 'yes, at this step' : 'not yet') : ''], ['caveat', x.caveat], ['note', x.note]]), + links: [['Findings', findingsOf.get(x).map(fRef)], ['Guards', guardFlow(x) ? [flowRef(guardFlow(x))] : []], ['Closes', closers.get(x).map((f) => flowRef(f))]], + }; + } + return { + kicker: `route · ${x.status || 'no status'}`, title: x.id, + rows: rows([['claim', x.claim], ['node', x.node ? nodeName(x.node) : 'none (harness)'], ['test', x.test], ['harness', x.harness], ['would flip', x.would_flip], ['note', x.note]]), + links: [['Node', byId.has(x.node) ? [ref('node', x.node, nodeName(x.node))] : []]], + }; + }; + + const focus = (kind, id) => { + const edges = new Set(); const units = new Set(); + const addFlow = (f) => { if (f) { edges.add(f.id); units.add(f.from); units.add(f.to); } }; + const x = sel(kind, id); + if (!x) return { edges, units }; + if (kind === 'node') { units.add(x.id); for (const f of [...(ins.get(x.id) || []), ...(outs.get(x.id) || [])]) addFlow(f); } + else if (kind === 'flow') addFlow(x); + else if (kind === 'finding') { addFlow(atFlow(x)); if (homeOf(x)) units.add(homeOf(x)); } + else if (kind === 'patch') { addFlow(guardFlow(x)); for (const f of closers.get(x)) addFlow(f); for (const f of findingsOf.get(x)) if (homeOf(f)) units.add(homeOf(f)); } + else if (byId.has(x.node)) units.add(x.node); + return { edges, units }; + }; + + const tables = (st) => ({ + flows: { head: ['From', 'To', 'Label', 'Role', 'Existence', 'Findings', 'Guards'], rows: flows.map((f) => ({ kind: 'flow', id: f.id, cls: st && st.red.has(f.id) ? 'red' : st && st.closed.has(f.id) ? 'closed' : '', cells: [nodeName(f.from), nodeName(f.to), f.label || '', f.role || 'data', existence(f), findings.filter((x) => atFlow(x) === f).map((x) => x.id).join(' '), patches.filter((k) => guardFlow(k) === f).map((k) => k.id).join(' ')] })) }, + findings: { head: ['Id', 'Title', 'Severity', 'CWE', 'Status', 'State', 'Where'], rows: findings.map((f) => ({ kind: 'finding', id: f.id, cls: st ? `st-${st.state.get(f.id)}` : '', cells: [f.id, f.title || '', sevOf(f), f.cwe || '', f.status || '', st ? STATE_WORD[st.state.get(f.id)] : '', atFlow(f) ? edgeText(atFlow(f)) : homeOf(f) ? nodeName(homeOf(f)) : 'not placed'] })) }, + patches: { head: ['Id', 'Title', 'Change set', 'Findings', 'Evidence', 'Proof', 'Guard'], rows: orders.sets.map((k) => ({ kind: 'patch', id: k.id, cls: st && st.landed.has(k.id) ? 'landed' : '', cells: [k.id, name(k), sets[setAt.get(k)].title, findingsOf.get(k).map((f) => f.id).join(' '), LEVEL_WORD[levelOf(k)], proves(k) ? 'yes' : 'no', guardFlow(k) ? edgeText(guardFlow(k)) : ''] })) }, + routes: { head: ['Id', 'Status', 'Claim', 'Node', 'Test'], rows: routes.map((r) => ({ kind: 'route', id: r.id, cls: `rs-${r.status || 'none'}`, cells: [r.id, r.status || '', r.claim || '', byId.has(r.node) ? nodeName(r.node) : 'harness', r.test || ''] })) }, + }); + + const stats = () => ({ + elements: nodes.length, flows: flows.length, findings: findings.length, patches: patches.length, routes: routes.length, sets: sets.length, + lanes: { group: layout('group').lanes.length, layer: layout('layer').lanes.length }, + sources: sources.size, outcomes: outcomes.size, outcomeRule, unplaced: findings.filter((f) => !homeOf(f)).length, + }); + + return { + GEO, SEV, STATES, STATE_WORD, LEVELS, LEVEL_WORD, MODES, ORDERS, DIMS, title: M.title || '', + sets, orders, sources, outcomes, outcomeRule, hop, nCols, + layout, step, audit, groupsOf, dimOf, detail, focus, tables, stats, proves, homeOf, sevOf, levelOf, name, nodeName, + finding: (id) => sel('finding', id), patch: (id) => sel('patch', id), + }; +} diff --git a/lib/dfd-record-render.mjs b/lib/dfd-record-render.mjs new file mode 100644 index 00000000..dbf9b33d --- /dev/null +++ b/lib/dfd-record-render.mjs @@ -0,0 +1,71 @@ +// lib/dfd-record-render.mjs — the record view as one page: rules in dfd-record-core, drawing in dfd-record-client. + +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { esc } from './html-escape.mjs'; +import { createRecordCore } from './dfd-record-core.mjs'; +import { houseTokens } from './house-css.mjs'; +import { MARK_ICON } from './brand-tokens.mjs'; +import { embedJson, stamp } from './dfd-replay-render.mjs'; + +const HERE = dirname(fileURLToPath(import.meta.url)); +const sha256b64 = (s) => createHash('sha256').update(s, 'utf8').digest('base64'); +const inlined = (file) => readFileSync(join(HERE, file), 'utf8').replace(/^export /gm, ''); +export const recordClientJs = () => `${inlined('dfd-record-core.mjs')}\n${inlined('dfd-record-client.js')}\nmountRecordView(document, createRecordCore);\n`; +export const recordCss = () => `${houseTokens()}\n${readFileSync(join(HERE, 'dfd-record.css'), 'utf8')}`; + +/** -> { html, csp, stats }. opts: { label, chip, asOf (Date or string), title }. */ +export function renderRecordHtml(model, opts = {}) { + const title = opts.title || model.title || 'data flow diagram'; + const css = recordCss(); + const client = recordClientJs(); + const core = createRecordCore(model); + const stats = core.stats(); + const audit = { group: core.audit('group'), layer: core.audit('layer') }; + const asOf = opts.asOf instanceof Date ? stamp(opts.asOf) : String(opts.asOf || stamp(new Date())); + const chip = opts.chip || `${stats.findings} findings · ${stats.sets} change sets`; + const policy = (extra) => ["default-src 'none'", `style-src 'sha256-${sha256b64(css)}'`, `script-src 'sha256-${sha256b64(client)}'`, 'img-src data:', "font-src 'none'", "connect-src 'none'", "base-uri 'none'", "form-action 'none'", ...extra].join('; '); + const sel = (id, label) => ``; + const html = ` + +${MARK_ICON} +${esc(title)} — record + +
+
+

${esc(opts.label || 'Data flow record')}

+

${esc(chip)}

+

${esc(title)}

+

Correct as of

+
+ +
+${sel('m-lanes', 'Lanes')} +${sel('m-order', 'Replay order')} +${sel('m-dim', 'Group patches by')} +
+
+ + + + + + + +
+
+ +
+ +
+

Tables

+
+

Layout check: ${audit.group.nan + audit.layer.nan} broken coordinates, ${audit.group.through + audit.layer.through} flows through a chip, ${audit.group.overlap + audit.layer.overlap} overlapping runs.

+ + +
+`; + return { html, csp: policy(["frame-ancestors 'self'"]), stats: { ...stats, audit, bytes: Buffer.byteLength(html, 'utf8') } }; +} diff --git a/lib/dfd-record.css b/lib/dfd-record.css new file mode 100644 index 00000000..758358a0 --- /dev/null +++ b/lib/dfd-record.css @@ -0,0 +1,157 @@ +/* lib/dfd-record.css — record view layout; palette and font stacks come from houseTokens(). */ +:root{--display:'Inter Display',Inter,-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif} +*{box-sizing:border-box} +html,body{margin:0;background:var(--panel);color:var(--ink);font:14px/1.45 var(--sans)} +main{padding:1rem 1.25rem 2rem} +.sub{color:var(--mut);font-size:.8125rem} +.n{font-family:var(--mono);color:var(--mut);font-size:.75rem} +.hd{display:grid;grid-template-columns:auto auto 1fr auto;align-items:center;gap:1.25rem;border-bottom:2px solid var(--ink);padding:.4rem 0 .7rem} +.hd-label{margin:0;font:600 .75rem var(--display);letter-spacing:.16em;text-transform:uppercase} +.hd-chip{margin:0} +.chip{display:inline-block;background:var(--acc);color:var(--on-acc);font:600 .75rem var(--mono);padding:.15rem .5rem;border-radius:2px} +.hd-title{margin:0;font:400 21px/1.2 var(--display)} +.asof{margin:0;font-size:.75rem;color:var(--mut);text-align:right} +.ctl{display:flex;flex-wrap:wrap;gap:.5rem 1rem;align-items:flex-end;padding:.6rem 0;border-bottom:1px solid var(--line)} +.ctl label.mode{display:flex;flex-direction:column;font:600 .6875rem var(--sans);letter-spacing:.04em;text-transform:uppercase;color:var(--mut);gap:.15rem} +.ctl select{font:.8125rem var(--sans);color:var(--ink);background:var(--panel);border:1px solid var(--ink);border-radius:2px;padding:.2rem .35rem} +.pb{display:flex;flex-wrap:wrap;align-items:center;gap:.4rem .6rem;padding:.5rem 0;border-bottom:1px solid var(--line)} +.pb button{font:600 .8125rem var(--sans);background:var(--panel);color:var(--ink);border:1px solid var(--ink);border-radius:2px;padding:.2rem .55rem;cursor:pointer} +.pb button[aria-pressed=true]{background:var(--ink);color:var(--panel)} +.pb input[type=range]{width:16rem} +#pb-out{font-size:.8125rem} +button:focus-visible,select:focus-visible,input:focus-visible,[tabindex]:focus-visible{outline:2px solid var(--ink);outline-offset:1px} +.regions{display:grid;grid-template-columns:17rem minmax(0,1fr) 22rem;gap:1rem;align-items:start;margin-top:.75rem} +@media (max-width:80rem){.regions{grid-template-columns:15rem minmax(0,1fr)}#detail{grid-column:1/-1;position:static;max-height:none}} +.regions h2,#below h2{font:600 .6875rem var(--display);letter-spacing:.16em;text-transform:uppercase;margin:0 0 .35rem} +#railpane,#detail{border:1px solid var(--line);padding:.5rem .6rem;max-height:84vh;overflow:auto;position:sticky;top:.5rem} +#grid{overflow:auto;max-height:84vh;border:1px solid var(--line)} +.rail-n{display:flex;justify-content:space-between;margin:0;font:600 .6875rem var(--sans);letter-spacing:.04em;text-transform:uppercase;color:var(--mut)} +.rail-all{margin:.2rem 0 .4rem;font-size:.8125rem} +.rg{display:flex;justify-content:space-between;align-items:center;gap:.4rem;border-top:1px solid var(--line);margin-top:.35rem;padding-top:.3rem;font-size:.78rem;font-weight:600} +.rg label{display:flex;align-items:center;gap:.3rem;min-width:0} +.gv{overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.rr{display:grid;grid-template-columns:auto auto minmax(0,1fr) auto;align-items:center;gap:.3rem;padding:.08rem 0 .08rem .8rem;font-size:.78rem;border-left:3px solid transparent} +.rr.landed{border-left-color:var(--acc)} +.rr.landed .lk{font-weight:600} +.rr.on{background:var(--wash)} +.rr .lk{font-family:var(--mono)} +.pt{color:var(--mut);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.sn{font:600 .6875rem var(--mono);min-width:1.6rem;background:var(--panel);color:var(--ink);border:1px solid var(--line2);border-radius:2px;padding:0 .2rem;cursor:pointer} +.sn.off{border:0;color:var(--dim);text-align:center;cursor:default} +.lk{font:inherit;color:var(--ink);background:none;border:0;padding:0;cursor:pointer;text-align:left;text-decoration:underline;text-underline-offset:2px} +#detail h2{margin:0} +#detail h3{font:600 .875rem var(--display);margin:.8rem 0 .3rem} +#detail h4{font:600 .6875rem var(--sans);letter-spacing:.04em;text-transform:uppercase;color:var(--mut);margin:.6rem 0 .2rem} +#detail p{margin:.2rem 0;overflow-wrap:anywhere} +.set{font-weight:600} +.lks{margin:0;padding:0;list-style:none} +.lks li{padding:.1rem 0;overflow-wrap:anywhere;font-size:.8125rem} +.tally{display:grid;grid-template-columns:repeat(2,1fr);gap:.4rem;margin:.4rem 0} +.tally div{border:1px solid var(--line);padding:.25rem .4rem} +.tally dt{font:600 .625rem var(--sans);letter-spacing:.04em;text-transform:uppercase;color:var(--mut)} +.tally dd{margin:0;font:400 1.25rem var(--display)} +.tally .ok{color:var(--live)}.tally .bad{color:var(--crit)} +#sel{border-top:1px solid var(--line);margin-top:.6rem;padding-top:.2rem} +.kick{font:600 .6875rem var(--mono);letter-spacing:.04em;text-transform:uppercase;color:var(--mut);margin:.6rem 0 0} +.kv{display:grid;grid-template-columns:5.5rem 1fr;gap:.05rem .4rem;margin:.2rem 0;font-size:.8rem} +.kv div{display:contents} +.kv dt{color:var(--mut)} +.kv dd{margin:0;overflow-wrap:anywhere} +#below{margin-top:1rem} +#tabs{display:flex;gap:.3rem;border-bottom:1px solid var(--ink)} +#tabs button{font:600 .8125rem var(--sans);background:var(--panel);color:var(--ink);border:1px solid var(--line2);border-bottom:0;border-radius:2px 2px 0 0;padding:.25rem .6rem;cursor:pointer} +#tabs button[aria-selected=true]{background:var(--ink);color:var(--panel)} +#tabs button[aria-selected=true] .n{color:var(--panel)} +#table{overflow:auto;max-height:60vh} +.tb{border-collapse:collapse;width:100%;font-size:12px} +.tb th{text-align:left;font-weight:600;border-bottom:1px solid var(--ink);padding:4px 8px 4px 6px;text-transform:uppercase;letter-spacing:.06em;font-size:10.5px;position:sticky;top:0;background:var(--panel)} +.tb td{border-bottom:1px solid var(--line);padding:4px 8px 4px 6px;vertical-align:top;overflow-wrap:anywhere} +.tb tr{cursor:pointer} +.tb tr td:first-child{font-family:var(--mono);border-left:3px solid transparent} +.tb tr.on td{background:var(--wash)} +.tb tr.red td:first-child,.tb tr.st-open td:first-child{border-left-color:var(--crit)} +.tb tr.closed td:first-child,.tb tr.st-fixed td:first-child,.tb tr.st-proven td:first-child{border-left-color:var(--live)} +.tb tr.st-dismissed td:first-child{border-left-color:var(--dim)} +.tb tr.landed td:first-child{border-left-color:var(--acc)} +#legend{margin-top:1rem} +.key{display:flex;flex-wrap:wrap;gap:.3rem 1.1rem;margin:.3rem 0;padding:0;list-style:none;font-size:.8125rem} +.key li{display:flex;align-items:center;gap:.35rem} +.sw{display:inline-block;width:.75rem;height:.75rem;border:1px solid var(--ink);border-radius:50%} +.sw.st-open{background:var(--crit);border-color:var(--crit)} +.sw.st-fixed{border:2px solid var(--live)} +.sw.st-proven{background:var(--live);border-color:var(--live)} +.sw.st-dismissed{background:var(--dim);border-color:var(--dim)} +.sw.mp{border-radius:1px;background:var(--acc)} +.banner{border:2px solid var(--ink);padding:.5rem .75rem} +svg.rec{display:block;background:var(--panel);font-family:var(--sans)} +.band.b0{fill:var(--panel)} +.band.b1{fill:var(--panel2)} +.band.bd{stroke:var(--ink);stroke-width:1;stroke-dasharray:6 4} +.lh{font:600 10.5px var(--display);letter-spacing:.12em;text-transform:uppercase;fill:var(--ink)} +.ls{font:9.5px var(--mono);fill:var(--mut)} +.chd{font:600 10px var(--display);letter-spacing:.12em;text-transform:uppercase;fill:var(--ink);text-anchor:middle} +.csb{font:9px var(--mono);fill:var(--mut);text-anchor:middle} +.stem{fill:none;stroke:var(--line2);stroke-width:1} +.e .ln{fill:none;stroke:var(--mut);stroke-width:1.3} +.e .ah{fill:var(--mut)} +.e .gt{fill:none;stroke:var(--ink);stroke-width:1.2} +.e.k-cross .ln{stroke:var(--ink)} +.e.k-cross .ah{fill:var(--ink)} +.e.k-error .ln{stroke:var(--high);stroke-dasharray:5 3} +.e.k-error .ah{fill:var(--high)} +.e.k-return .ln{stroke-dasharray:2 3} +.e.k-drain .ln{stroke:var(--dim);stroke-dasharray:1 3} +.e.k-drain .ah{fill:var(--dim)} +.e.ex-unknown .ln{stroke-dasharray:7 3} +.e.ex-contradicted .ln{stroke:var(--dim);stroke-dasharray:2 2} +.e.ex-contradicted .ah{fill:var(--dim)} +.e.red .ln{stroke:var(--crit);stroke-width:2.2} +.e.red .ah{fill:var(--crit)} +.e.closed .ln{stroke:var(--live);stroke-width:3} +.e.closed .ah{fill:var(--live)} +.e[data-sel]{cursor:pointer} +.e.em .ln{stroke-width:3} +.e.on .ln{stroke-width:4} +.mk{cursor:pointer;stroke:var(--ink);stroke-width:1.2;fill:var(--panel)} +.mf.st-open{fill:var(--crit);stroke:var(--crit)} +.mf.st-fixed{stroke:var(--live);stroke-width:2.2} +.mf.st-proven{fill:var(--live);stroke:var(--live)} +.mf.st-dismissed{fill:var(--dim);stroke:var(--dim)} +.mp.landed{fill:var(--acc)} +.gl{stroke:none} +.gl.p-actor{fill:var(--sev)} +.gl.p-process{fill:var(--ink)} +.gl.p-store{fill:var(--plan)} +.gl.p-log{fill:var(--mut)} +.gl.p-external{fill:var(--machine)} +.gl.p-outcome{fill:var(--crit)} +.gl.p-route{fill:var(--attest)} +.gl.p-drain{fill:var(--dim)} +.u .cp{fill:var(--panel);stroke:var(--ink);stroke-width:1.2} +.u[data-sel]{cursor:pointer} +.u.p-drain .cp,.u.rt .cp{stroke-dasharray:3 2} +.u.outcome .cp{stroke:var(--crit)} +.u.exposed .cp{fill:var(--crit);stroke:var(--crit)} +.u.exposed .lb{fill:var(--panel)} +.u.exposed .gl{fill:var(--panel)} +.u:focus{outline:none} +.u:focus .cp,.u.on .cp{stroke-width:3} +.u.on .lb{font-weight:700} +.lb{font:500 11px var(--sans);fill:var(--ink)} +.row{cursor:pointer} +.row .rb{fill:var(--panel);stroke:var(--line2);stroke-width:1} +.row .rs{fill:var(--dim)} +.row.st-open .rs{fill:var(--crit)} +.row.st-fixed .rb{stroke:var(--live)} +.row.st-fixed .rs{fill:var(--live)} +.row.st-proven .rs,.row.st-proven .rb{fill:var(--live)} +.row.st-proven .rw{fill:var(--panel)} +.row.st-open .rb{stroke:var(--crit)} +.row.rt .rb{stroke:var(--attest);stroke-dasharray:3 2} +.row:focus{outline:none} +.row:focus .rb,.row.on .rb{stroke:var(--ink);stroke-width:2.2} +.rw{font:9.5px var(--mono);fill:var(--ink)} +.rid{font-weight:600} +.rec.has-em .u:not(.em):not(.on),.rec.has-em .row:not(.on),.rec.has-em .stem{opacity:.3} +.rec.has-em .e:not(.em):not(.on),.rec.has-em .mk{opacity:.2} +svg.lg{flex:none;overflow:visible} diff --git a/lib/dfd.mjs b/lib/dfd.mjs index f6b8f39d..66e3c701 100644 --- a/lib/dfd.mjs +++ b/lib/dfd.mjs @@ -131,6 +131,12 @@ export function validateDfd(doc, { path = schemaPath() } = {}) { } }); } + // routes (open questions) carry an optional node anchor; mirror the finding-anchor referential check + if (doc.routes) { + doc.routes.forEach((rt, i) => { + if (rt.node !== undefined && !ids.has(rt.node)) errors.push(`dfd: routes[${i}] (${JSON.stringify(rt.id)}) names node ${JSON.stringify(rt.node)}, which is not a node`); + }); + } const pairs = new Set(doc.flows.map((f) => `${f.from}\u0000${f.to}`)); const findingIds = doc.findings ? new Set(doc.findings.map((fd) => fd.id)) : null; doc.flows.forEach((f, i) => { diff --git a/lib/test/dfd-record-client.test.mjs b/lib/test/dfd-record-client.test.mjs new file mode 100644 index 00000000..6a0a0ff9 --- /dev/null +++ b/lib/test/dfd-record-client.test.mjs @@ -0,0 +1,310 @@ +// lib/dfd-record-client.js in a stand-in document that keeps what the script writes and fires what a reader would. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createRecordCore } from '../dfd-record-core.mjs'; +import { mountRecordView } from '../dfd-record-client.js'; +import { RECORD, SINKS } from './fixtures/dfd-record-model.mjs'; + +const count = (text, part) => text.split(part).length - 1; +const hits = (text, re) => (text.match(re) || []).length; +function fakeDocument(model) { + const make = (id) => { + const on = {}; + return { id, innerHTML: '', textContent: '', hidden: false, value: '', checked: false, max: '', attrs: {}, + setAttribute(k, v) { this.attrs[k] = v; }, addEventListener(t, fn) { (on[t] = on[t] || []).push(fn); }, fire(t, ev = {}) { for (const fn of on[t] || []) fn(ev); } }; + }; + const els = new Map(); + return { getElementById(id) { if (id === 'dfd-data') return { textContent: JSON.stringify(model) }; if (!els.has(id)) els.set(id, make(id)); return els.get(id); } }; +} +/** An event whose target answers `closest` for one selector with an element carrying `dataset`. */ +const on = (selector, dataset = {}, extra = {}) => ({ target: { dataset, closest: (s) => (s === selector ? { dataset } : null) }, ...extra }); +const miss = { target: { closest: () => null } }; +const mount = (model = RECORD()) => { + const doc = fakeDocument(model); + const timers = { fns: [], ms: [], cleared: 0, set(fn, ms) { this.fns.push(fn); this.ms.push(ms); return this.fns.length; }, clear() { this.cleared += 1; } }; + const view = mountRecordView(doc, createRecordCore, { timers }); + return { timers, V: view.V, $: (id) => doc.getElementById(id) }; +}; +const grid = (v) => v.$('grid').innerHTML; +const out = (v) => v.$('pb-out').textContent; +const press = (v, pb) => v.$('pb').fire('click', on('[data-pb]', { pb })); +const tab = (v, name) => v.$('tabs').fire('click', on('[data-tab]', { tab: name })); +const texts = (html, re) => [...html.matchAll(re)].map((m) => m[1]); + +test('mounting draws every region at the last step: menus, playback, grid, rail, account, empty selection, tables, key', () => { + // Arrange + const model = RECORD(); + // Act + const v = mount(model); + // Assert + assert.equal(v.$('m-lanes').innerHTML, ''); + assert.equal(v.$('m-order').innerHTML, ''); + assert.match(v.$('m-dim').innerHTML, /^