Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47f5e77699 | ||
|
|
99e2f1ed86 | ||
|
|
7d6e910994 | ||
|
|
766fce5da6 |
@@ -76,9 +76,6 @@ explicit path or endpoint and do not need it.
|
||||
Facts retain all-recorded-events-before-selection scope. Other qlog layouts
|
||||
and PCAP correlation are unsupported.
|
||||
- User-owned Electron runtime already open: `list_electron_targets`.
|
||||
- Packet-field discovery: `inspect_packet_fields` searches installed protocols
|
||||
and field names/types before choosing fields for `inspect_packet_capture`.
|
||||
Query/page the relevant records; registrations do not establish observed traffic.
|
||||
- Recorded packet captures: `inspect_packet_capture` with selected TShark fields,
|
||||
display filters and decode-as rules. Requires Linux, util-linux prlimit and `REA_TSHARK_COMMAND`; see
|
||||
[capture guide](https://github.com/morluto/rea/blob/main/docs/packet-captures.md).
|
||||
@@ -92,9 +89,6 @@ explicit path or endpoint and do not need it.
|
||||
[packet summaries](https://github.com/morluto/rea/blob/main/docs/pcap-analysis.md).
|
||||
Select an exact DNS question for address pages; page exhaustion does not prove
|
||||
network completeness. This reads recordings and does not acquire traffic.
|
||||
- Decoder discovery: `inspect_signal_decoders` searches installed decoder IDs
|
||||
or selected decoder help, including channels and options. Query and page the
|
||||
relevant details before choosing settings; this does not scan hardware.
|
||||
- Recorded logic/signal traces: `decode_signal_recording` with explicit decoder,
|
||||
channel and protocol settings. On Linux with util-linux prlimit, supply sigrok-cli 0.7.2 through
|
||||
`REA_SIGROK_COMMAND`; see [recording guide](https://github.com/morluto/rea/blob/main/docs/signal-recordings.md).
|
||||
|
||||
@@ -83,14 +83,6 @@ names, the native API record, and value-flow summaries. Pseudocode offsets and l
|
||||
code units; use the returned `next_offset` for continuation. Provider limitations
|
||||
and unavailable facts remain explicit; the complete parent Evidence is retained.
|
||||
|
||||
`inspect_macho` on a large framework returns megabytes of imports and exports.
|
||||
Select `detail: "summary"` for slice identity, UUID and per-collection counts,
|
||||
then page rows with `view: {kind: "macho", facet: "exports", offset: 0, limit: 64}`
|
||||
and `normalized_result.parent_evidence_id`. Facets are entrypoints,
|
||||
architectures, build_metadata, load_commands, dependencies, imports, exports,
|
||||
segments and provenance. `source_exhaustive: false` means unreturned symbols
|
||||
may exist.
|
||||
|
||||
To see which functions or Objective-C methods a Mach-O actually calls in one
|
||||
run, use `observe_native_calls` with explicit breakpoints and a bounded
|
||||
`duration_ms`/`max_events`. It launches a new process under LLDB, so the target
|
||||
|
||||
@@ -51,7 +51,7 @@ jobs:
|
||||
- run: sudo apt-get update && sudo DEBIAN_FRONTEND=noninteractive apt-get install -y tshark util-linux python3
|
||||
- run: npm ci
|
||||
- run: npm run build:cached
|
||||
- run: npm run test:focused -- tests/boundary/captures/fieldDiscovery.test.ts src/process/LinuxResourceLimits.test.ts tests/boundary/captures/captureProvider.test.ts tests/boundary/captures/captureDescriptorCleanup.test.ts tests/boundary/captures/resourceLimits.test.ts tests/boundary/captures/packetOutput.test.ts tests/boundary/mcp/packetCaptureMcp.test.ts tests/boundary/cli/captureCleanup.test.ts
|
||||
- run: npm run test:focused -- src/process/LinuxResourceLimits.test.ts tests/boundary/captures/captureProvider.test.ts tests/boundary/captures/captureDescriptorCleanup.test.ts tests/boundary/captures/resourceLimits.test.ts tests/boundary/captures/packetOutput.test.ts tests/boundary/mcp/packetCaptureMcp.test.ts tests/boundary/cli/captureCleanup.test.ts
|
||||
- run: node scripts/verify-packet-capture.mjs
|
||||
env:
|
||||
REA_TSHARK_COMMAND: /usr/bin/tshark
|
||||
|
||||
@@ -44,7 +44,7 @@ jobs:
|
||||
- run: sudo apt-get update && sudo apt-get install -y sigrok-cli util-linux python3
|
||||
- run: npm ci
|
||||
- run: npm run build:cached
|
||||
- run: npm run test:focused -- tests/boundary/signals/decoderDiscovery.test.ts src/process/LinuxResourceLimits.test.ts src/domain/signals/annotationTextWindow.test.ts tests/boundary/signals/recordingProvider.test.ts tests/boundary/signals/recordingDescriptorCleanup.test.ts tests/boundary/signals/resourceLimits.test.ts tests/boundary/mcp/signalRecordingMcp.test.ts tests/boundary/cli/signalCleanup.test.ts
|
||||
- run: npm run test:focused -- src/process/LinuxResourceLimits.test.ts src/domain/signals/annotationTextWindow.test.ts tests/boundary/signals/recordingProvider.test.ts tests/boundary/signals/recordingDescriptorCleanup.test.ts tests/boundary/signals/resourceLimits.test.ts tests/boundary/mcp/signalRecordingMcp.test.ts tests/boundary/cli/signalCleanup.test.ts
|
||||
- run: node scripts/verify-signal-recording.mjs
|
||||
env:
|
||||
REA_SIGROK_COMMAND: /usr/bin/sigrok-cli
|
||||
|
||||
@@ -93,7 +93,7 @@ def project_record(state, secrets):
|
||||
safe_bytes, credential_url = transport_value(value, path, transport_url)
|
||||
content_base64 = base64.b64encode(value).decode("ascii")
|
||||
digest = hashlib.sha256(value).hexdigest()
|
||||
hidden = any(secret in value or secret in safe_bytes for secret in byte_secrets) or any(secret in content_base64 or secret in digest or secret in str(len(value)) for secret in secrets)
|
||||
hidden = any(secret in value or secret in safe_bytes for secret in byte_secrets) or any(secret in content_base64 or secret in digest for secret in secrets)
|
||||
safe_text = None
|
||||
try:
|
||||
safe_text = safe_bytes.decode("utf-8", errors="strict")
|
||||
|
||||
@@ -174,7 +174,7 @@ Resolution follows dyld:
|
||||
- `@rpath` tries each `LC_RPATH` of the loading image first, then those of the
|
||||
image that loaded it, up to the process root.
|
||||
- Dependencies load dependents-first in load-command order, and each image
|
||||
loads once per process. A later @rpath request whose install name matches an
|
||||
loads once per process. A later request whose install name matches an
|
||||
already loaded image reuses it.
|
||||
- Symlinks such as `Versions/Current` are followed inside the analyzed root.
|
||||
An escape through `..` or an absolute link is `escapes-target`.
|
||||
|
||||
@@ -298,42 +298,13 @@ subsequent wire recovery and clean shutdown. Caller timeout does not interrupt
|
||||
Hopper's synchronous native operation. Socket boundary tests deterministically
|
||||
cover active and queued expiry, late replies and timer cleanup.
|
||||
|
||||
The Linux demo lane remains a separate `verify:hopper:linux` command. Hopper
|
||||
6.4.2's ELF loader did not recognize the original 4,119-byte literal or three
|
||||
non-ASCII byte strings in the measured fixtures. The lane retains complete raw
|
||||
byte checks for those literals through source-owned symbols. Recognition of the
|
||||
original full-length literal is bound to its exact source address; its decoded
|
||||
object coverage remains explicitly unverified on Linux even when recognized.
|
||||
Absent non-ASCII recognition also reports decoded-object coverage as unverified.
|
||||
Recognized non-ASCII and control-text objects must still match their source
|
||||
bytes, encoding, filters and searches.
|
||||
A separate 548-byte ASCII literal requires native fragmentation, shortened
|
||||
provider display, complete decoded fragments and dossier provenance on Linux;
|
||||
the macOS lane retains the original full-length recognition requirement. These
|
||||
are observed fixture/build capabilities, not universal Hopper length limits.
|
||||
Its lifecycle checks attempt competing CLI launches for the active target and a
|
||||
The Linux demo lane remains a separate `verify:hopper:linux` command. Its
|
||||
lifecycle checks attempt competing CLI launches for the active target and a
|
||||
different target, requiring rejection before either can change the owning
|
||||
MCP session's documents or procedures. Lease boundary tests also preserve
|
||||
unresponsive or malformed live endpoints while allowing confirmed stale
|
||||
sockets to recover.
|
||||
|
||||
`verify:setup:linux` exercises installation on a clean supported Linux runner as
|
||||
root. Use a disposable VM: this lane installs Hopper and its Linux runtime
|
||||
dependencies through the system package manager. Set `REA_VERIFY_SERVER_COMMAND`
|
||||
to the CLI entrypoint being verified. The command builds and checks source-owned
|
||||
ELF fixtures before testing the read-only Hopper setup plan, approved
|
||||
installation, scoped doctor, real CLI/MCP analysis, rejection of a modified
|
||||
launcher, idempotent setup without requesting a reinstall, and owned child
|
||||
cleanup. Before installation and after teardown, a clean-runner process scan
|
||||
also rejects surviving Hopper demo helpers or Xvfb groups, including orphans
|
||||
whose launcher exited. This scan observes processes without signaling them.
|
||||
Hopper detection compares executable file identity through `/proc`, covering
|
||||
alternate or configured launcher paths even after an invoked symlink is removed.
|
||||
The dedicated runner must have no unrelated Hopper/Xvfb sessions. It requires
|
||||
the repository's pinned development toolchain and an
|
||||
existing host C compiler, `file`, `nm`, and `strings`. Use `verify:hopper:linux`
|
||||
instead when Hopper is already installed.
|
||||
|
||||
`verify:hopper:fat` is a separate macOS lane requiring installed Hopper and the
|
||||
existing Xcode clang/lipo toolchain. It compiles arm64/x86-64 thin executables and
|
||||
one- and two-slice FAT32 containers, verifies exact/interior address mappings
|
||||
|
||||
@@ -57,10 +57,6 @@ Hopper installation or any file write. Declining or pressing Ctrl-C makes no
|
||||
changes. Agent configuration writes preserve unrelated entries and comments,
|
||||
create backups, use atomic replacement, and verify their result. Setup and
|
||||
uninstall retain an existing `.rea.backup` rather than replacing the first snapshot.
|
||||
If that snapshot differs from the current configuration, setup previews and
|
||||
preserves a verified `.rea.backup.<sha256>.recovery` copy of the current bytes.
|
||||
Both snapshots remain available; a failed rollback reports the current recovery
|
||||
copy's path and the restore failure.
|
||||
Setup also retains valid environment overrides in REA's existing server entry,
|
||||
such as `REA_MCP_INPUT_SCHEMA_PROFILE` and `REA_MCP_MAX_RESPONSE_BYTES`.
|
||||
Detected provider settings replace only matching environment keys.
|
||||
|
||||
@@ -23,14 +23,6 @@ artifact digest and structural graph ID. Semantic tracing requires the semantic
|
||||
relation graph and reports when it is unavailable rather than treating missing
|
||||
data as an empty graph.
|
||||
|
||||
Explicit TypeScript `import type` and `export type` declarations remain source
|
||||
facts and do not create runtime import or export relationships. Type export names
|
||||
are reported separately from value export names. Inline `type` specifiers can
|
||||
leave an empty import or re-export with side effects under
|
||||
[`verbatimModuleSyntax`](https://www.typescriptlang.org/tsconfig/verbatimModuleSyntax.html);
|
||||
REA retains those dependency candidates and reports the unavailable compiler
|
||||
options rather than assuming the dependency is erased.
|
||||
|
||||
The semantic graph wire format stores shared non-location provenance once in
|
||||
its required `evidence_contexts` table. Each node, relation, fingerprint, and
|
||||
unknown retains its exact `evidence.location` and names the owning context with
|
||||
|
||||
+2
-15
@@ -147,8 +147,8 @@ after target content was read.
|
||||
|
||||
## Retained application Evidence inputs
|
||||
|
||||
`analyze_javascript_application`, `inspect_binary_layout`, `inspect_artifact`,
|
||||
`inspect_wasm_artifact`, and `inspect_macho` accept `detail`:
|
||||
`analyze_javascript_application`, `inspect_binary_layout`, `inspect_artifact`, and
|
||||
`inspect_wasm_artifact` accept `detail`:
|
||||
`complete` (default) returns the complete analysis Evidence; `summary` records
|
||||
that complete Evidence in the session and returns the derived
|
||||
`inspect_analysis_view` summary Evidence instead. Its
|
||||
@@ -218,19 +218,6 @@ attempting oversized delivery, and returns the same summary with an exact
|
||||
`parent_evidence_id` for later export or facet reads. Delivery detail does not
|
||||
reach WABT or change the original source Evidence ID.
|
||||
|
||||
Completed `inspect_macho` Evidence supports a summary and
|
||||
`view: {kind: "macho", facet: "exports", offset: 0, limit: 64}`. Facets are
|
||||
`entrypoints`, `architectures`, `build_metadata`, `load_commands`,
|
||||
`dependencies`, `imports`, `exports`, `segments`, and `provenance`; pages return
|
||||
the original rows. The summary keeps the selected slice, header fields and UUID,
|
||||
and replaces each collection with its returned count, reported total and
|
||||
`exhaustive` flag. Each page repeats the paged collection's `source_total` and
|
||||
`source_exhaustive`; exhausting a non-exhaustive collection does not establish
|
||||
that unreturned symbols are absent. Large frameworks return megabytes of
|
||||
symbols (Electron Framework: 2.5 MB of imports and exports, 3.3 KB as a
|
||||
summary), so select `detail: "summary"` on the first call. Delivery detail
|
||||
never reaches the native tools or changes the source Evidence ID.
|
||||
|
||||
`trace_application_feature`, `trace_javascript_semantics`,
|
||||
`compare_application_versions`, `compare_source_to_bundle`, and
|
||||
`compare_javascript_export_shapes` accept complete inline application Evidence
|
||||
|
||||
@@ -128,49 +128,3 @@ Each provider admits one inspection at a time, including acquisition and cleanup
|
||||
An occupied provider returns a retryable capacity error before acquiring another
|
||||
file or worker. Closing the provider stops new admission and drains accepted work;
|
||||
failed cleanup remains owned and can be retried.
|
||||
|
||||
## Discover protocols and field names
|
||||
|
||||
`inspect_packet_fields` / `inspect-packet-fields` queries the installed TShark
|
||||
registration glossary before selecting fields for capture inspection:
|
||||
|
||||
```sh
|
||||
rea inspect-packet-fields --query usb
|
||||
rea inspect-packet-fields --kind fields --protocol usb --query idVendor
|
||||
rea inspect-packet-fields --kind fields --protocol udp --all
|
||||
```
|
||||
|
||||
`kind` defaults to `protocols`; `fields` selects field definitions. `protocol`
|
||||
selects an exact protocol abbreviation (the protocol itself or its child fields).
|
||||
`query` is a case-insensitive literal substring in name, abbreviation or field
|
||||
description. `offset` skips matching records; `limit` defaults to 50. MCP
|
||||
`limit: null` or CLI `--all` requests all remaining matches within the resource
|
||||
budget. `--all` and `--limit` conflict. The window reports examined records of
|
||||
the selected kind before filters, matching records, returned records and
|
||||
`has_more`; it never counts capture packets.
|
||||
|
||||
Returned records preserve field type, parent protocol, display base, bitmask,
|
||||
description and original glossary line number. Empty producer strings remain
|
||||
empty; protocol records have null field-only properties. Repeated abbreviations
|
||||
remain separate registrations. A listed field is an installation capability, not
|
||||
proof that the field appears in a selected recording.
|
||||
|
||||
The adapter uses the documented `tshark -G fields` grammar under its existing
|
||||
private empty profile and Linux process limits. TShark 4.6.9's full glossary was
|
||||
measured at 22,303,197 bytes; discovery admits at most **32 MiB** combined command
|
||||
output (capture inspection remains at **4 MiB**). Parsing walks lines once and
|
||||
constructs objects only for the selected page. Returned strings are copied so
|
||||
retained pages do not retain the complete glossary string. Before constructing a selected
|
||||
record it charges six times the source UTF-8 bytes plus 512 bytes against an
|
||||
**8 MiB** representation budget, covering JSON escaping and record bookkeeping.
|
||||
If that budget would be exceeded, narrow the query or page size; results are not
|
||||
silently truncated. This is a conservative admission budget, not measured heap
|
||||
usage. Parent pipe buffers and producer per-process limits remain distinct.
|
||||
|
||||
Tool/limiter identity, version, stderr and selected arguments are retained in
|
||||
Evidence. No capture, interface or device is opened. Discovery shares capture
|
||||
analysis's admission slot and cleanup owner. Each call rereads the glossary;
|
||||
installed plugins, libraries and global configuration remain trusted and are not
|
||||
fully fingerprinted. There is no cache or snapshot-consistent pagination claim.
|
||||
The real Linux lane checks public CLI/MCP queries against the direct glossary,
|
||||
including USB vendor-ID typing, negative queries and paging.
|
||||
|
||||
@@ -106,37 +106,3 @@ One decode is admitted at a time, including acquisition and cleanup. Excess
|
||||
requests receive a retryable capacity error before acquiring another file or
|
||||
worker. Shutdown closes admission and drains accepted work; failed cleanup
|
||||
remains owned and retryable.
|
||||
|
||||
## Discover decoders before choosing settings
|
||||
|
||||
`inspect_signal_decoders` / `inspect-signal-decoders` queries the **installed**
|
||||
sigrok catalog without opening a recording or scanning devices:
|
||||
|
||||
```sh
|
||||
rea inspect-signal-decoders --query uart
|
||||
rea inspect-signal-decoders --decoder uart --query baud
|
||||
rea inspect-signal-decoders --decoder i2c --offset 0 --limit 50
|
||||
```
|
||||
|
||||
Omit `decoder` to search decoder IDs and names. Supply one exact decoder ID to
|
||||
read its literal help, including required/optional channels, options, annotation
|
||||
classes and documentation. `query` is a case-insensitive literal substring;
|
||||
matching help retains original one-based line numbers. Empty query selects all.
|
||||
`offset` skips matches; `limit` defaults to 50. MCP `limit: null` or CLI `--all`
|
||||
returns all remaining matches; CLI `--all` and `--limit` conflict.
|
||||
The window reports examined, matching and returned records and `has_more`.
|
||||
A filtered empty page is not evidence that the installation has no decoders.
|
||||
|
||||
Discovery refuses more than 65,535 line separators before constructing record
|
||||
objects (65,536-line representation budget), in addition to the 4 MiB output cap.
|
||||
Exceeding that budget is a resource failure with captured output. Returned text
|
||||
is copied so a retained page does not keep the complete producer output alive.
|
||||
|
||||
Discovery shares decoding's owned process, admission slot, resource limits,
|
||||
cleanup retries and Evidence delivery. It records the executable and limiter
|
||||
identities, version banner and warnings. Failed version checks and malformed
|
||||
producer output preserve diagnostics. Help is producer text, not an independently
|
||||
validated parameter schema. Each request probes again; it does not cache or claim
|
||||
stable pages across installation changes. Libraries/decoder modules remain
|
||||
trusted and are not fully fingerprinted. Catalog output includes a SHA-256 of
|
||||
its executable, not a digest of the complete installation.
|
||||
|
||||
@@ -153,12 +153,8 @@ the private runtime, isolating Ghidra preferences, logs, and caches.
|
||||
Process creation assigns a suspended child atomically to an owned Job Object.
|
||||
Membership and kill-on-owner-close policy are verified before resume.
|
||||
Breakaway is disabled. Only the child's default file owner is normalized;
|
||||
the caller token stays unchanged. Caller priority is preserved, and caller CPU
|
||||
affinity whenever the caller and the child share a processor group. A child that
|
||||
Windows places in another group keeps that group's default when the caller asked
|
||||
for no bound of its own; a caller pinned to fewer processors than its group
|
||||
holds is refused there rather than widened.
|
||||
Close, cancellation, timeout, startup failure, and provider failure
|
||||
the caller token stays unchanged. Caller CPU affinity and priority are
|
||||
preserved. Close, cancellation, timeout, startup failure, and provider failure
|
||||
terminate the job and verify all members have settled before runtime cleanup.
|
||||
Cleanup removes admitted objects by handle and unlinks reparse entries without
|
||||
following their targets. Abrupt owner death kills the job but can leave
|
||||
|
||||
@@ -19,6 +19,10 @@ Follow-up: [SQLite existing-control measurements](sqlite-existing-controls.md)
|
||||
tests QGIS's shipped GeoPackage through the existing column selection, preserving
|
||||
full selected-table schema and typed cells before considering another API.
|
||||
|
||||
Follow-up: [small real PCAP recordings](pcap-small-captures.md) compares existing
|
||||
complete delivery with summary/pages. Preserve the negative SDK/model input
|
||||
results: compact captures do not justify another production mechanism.
|
||||
|
||||
Follow-up: [native PE/DOS entry views and real model verification](native-entry-views.md)
|
||||
records the post-merge native continuation, including a small-function case where
|
||||
four selected replies cost more bytes than the complete dossier.
|
||||
|
||||
@@ -178,7 +178,7 @@ def main():
|
||||
'inspect_android_package', 'search_android_classes',
|
||||
'inspect_android_class', 'inspect_android_method',
|
||||
'inspect_firmware_regions', 'inspect_managed_artifact',
|
||||
'inspect_sqlite_database',
|
||||
'inspect_sqlite_database', 'inspect_pcap_capture',
|
||||
'inspect_managed_members', 'inspect_managed_native_boundaries',
|
||||
'inspect_artifact', 'inspect_wasm_artifact',
|
||||
'inspect_evm_interface', 'get_evidence_bundle', 'export_evidence_bundle',
|
||||
|
||||
@@ -70,6 +70,32 @@ for (const [side, answer] of [
|
||||
value: answer.evidence_ids,
|
||||
});
|
||||
}
|
||||
// PCAP delivery observations preserve each actual receipt's identity, limitations
|
||||
// and view coverage. Summary/page scopes differ from complete source scope;
|
||||
// retain them as run-specific facts rather than equating page exhaustion with
|
||||
// capture coverage. The common capture facts and URI prefix still must match.
|
||||
if (
|
||||
["wireshark-http.cap", "wireshark-http_redirects.pcapng"].includes(
|
||||
left.artifact,
|
||||
)
|
||||
) {
|
||||
for (const [side, answer] of [
|
||||
["left", a],
|
||||
["right", b],
|
||||
]) {
|
||||
if (
|
||||
!Array.isArray(answer.delivery_observations) ||
|
||||
!answer.delivery_observations.length
|
||||
)
|
||||
throw new Error("Missing original PCAP delivery observations");
|
||||
runSpecific.push({
|
||||
side,
|
||||
path: ["delivery_observations"],
|
||||
value: answer.delivery_observations,
|
||||
});
|
||||
delete answer.delivery_observations;
|
||||
}
|
||||
}
|
||||
// Binwalk assigns a new opaque region UUID in each invocation. Preserve both
|
||||
// original lookup values in this report; compare the observed region facts
|
||||
// separately. The product and original replies retain those IDs unchanged.
|
||||
|
||||
@@ -263,6 +263,34 @@
|
||||
"url": "https://raw.githubusercontent.com/qgis/QGIS/e1223b8e9e71fc50ee995ed556f711c54ccc101b/resources/data/world_map.gpkg",
|
||||
"derivation": "unmodified official resource file; streaming Git blob and SHA-256 verification"
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "wireshark-http.cap",
|
||||
"file": "http.cap",
|
||||
"bytes": 25803,
|
||||
"sha256": "25a72bdf10339f2c29916920c8b9501d294923108de8f29b19aba7cc001ab60d",
|
||||
"provenance": {
|
||||
"project": "Wireshark public sample captures",
|
||||
"source_page": "https://wiki.wireshark.org/SampleCaptures",
|
||||
"url": "https://wiki.wireshark.org/uploads/27707187aeb30df68e70c8fb9d614981/http.cap",
|
||||
"resolved_url": "https://gitlab.com/wireshark/wireshark/-/wikis/uploads/27707187aeb30df68e70c8fb9d614981/http.cap",
|
||||
"upstream_expected_digest": null,
|
||||
"derivation": "Unmodified capture published by official Wireshark wiki. Local digest pins downloaded bytes; no independently published upstream digest is claimed."
|
||||
}
|
||||
},
|
||||
{
|
||||
"id": "wireshark-http_redirects.pcapng",
|
||||
"file": "http_redirects.pcapng",
|
||||
"bytes": 47804,
|
||||
"sha256": "ff432a6b71d06cd20720f7763e584014edd0a43c3b55981c682d1b7640207abc",
|
||||
"provenance": {
|
||||
"project": "Wireshark public sample captures",
|
||||
"source_page": "https://wiki.wireshark.org/SampleCaptures",
|
||||
"url": "https://wiki.wireshark.org/uploads/__moin_import__/attachments/SampleCaptures/http_redirects.pcapng",
|
||||
"resolved_url": "https://gitlab.com/wireshark/wireshark/-/wikis/uploads/__moin_import__/attachments/SampleCaptures/http_redirects.pcapng",
|
||||
"upstream_expected_digest": null,
|
||||
"derivation": "Unmodified capture published by official Wireshark wiki. Local digest pins downloaded bytes; no independently published upstream digest is claimed."
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -523,7 +523,115 @@ const inspectEvmTarget = async () => {
|
||||
};
|
||||
};
|
||||
|
||||
const pcapObservation = (evidence) => {
|
||||
const value = normalized(evidence);
|
||||
return {
|
||||
evidence_id: evidence.evidence_id,
|
||||
limitations: evidence.limitations,
|
||||
...Object.fromEntries(
|
||||
[
|
||||
"kind",
|
||||
"view",
|
||||
"parent_evidence_id",
|
||||
"coverage",
|
||||
"limitations",
|
||||
"unknowns",
|
||||
]
|
||||
.filter((key) => Object.hasOwn(value, key) && key !== "limitations")
|
||||
.map((key) => [key, value[key]]),
|
||||
),
|
||||
...(Object.hasOwn(value, "limitations")
|
||||
? { normalized_limitations: value.limitations }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
const inspectPcapTarget = async () => {
|
||||
const input = {
|
||||
path: values.path,
|
||||
...(values.delivery === "summary" ? { detail: "summary" } : {}),
|
||||
};
|
||||
const definition = catalogDefinitions.get("inspect_pcap_capture");
|
||||
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
||||
if (
|
||||
!definition ||
|
||||
!ajv.validateSchema(definition.inputSchema) ||
|
||||
!ajv.validate(definition.inputSchema, input)
|
||||
)
|
||||
throw new Error("Selected PCAP request is not advertised by this runtime");
|
||||
const inspected = await call("inspect_pcap_capture", input);
|
||||
const n = normalized(inspected);
|
||||
const observations = [pcapObservation(inspected)];
|
||||
let capture, uris;
|
||||
if (values.delivery === "summary") {
|
||||
if (n.kind !== "summary" || n.parent_operation !== "inspect_pcap_capture")
|
||||
throw new Error("Runtime returned no requested PCAP summary");
|
||||
capture = n.summary;
|
||||
const selected = await call("inspect_analysis_view", {
|
||||
source: { kind: "retained-evidence", evidence_id: n.parent_evidence_id },
|
||||
view: { kind: "pcap", facet: "http-uris", offset: 0, limit: 2 },
|
||||
});
|
||||
const page = normalized(selected);
|
||||
if (
|
||||
page.parent_evidence_id !== n.parent_evidence_id ||
|
||||
page.parent_operation !== "inspect_pcap_capture" ||
|
||||
page.kind !== "pcap" ||
|
||||
page.page.facet !== "http-uris" ||
|
||||
page.source_coverage !== capture.coverage ||
|
||||
page.coverage.total !== capture.retained_counts.http_request_uris ||
|
||||
page.coverage.examined !== page.page.items.length ||
|
||||
page.artifact.path !== capture.target.path ||
|
||||
page.artifact.sha256 !== capture.target.sha256
|
||||
)
|
||||
throw new Error(
|
||||
"PCAP page identity, scope or coverage differs from its parent",
|
||||
);
|
||||
uris = page.page.items;
|
||||
observations.push(pcapObservation(selected));
|
||||
} else {
|
||||
const {
|
||||
endpoints,
|
||||
dns_queries,
|
||||
tls_sni_values,
|
||||
protocol_distribution,
|
||||
http_request_uris,
|
||||
unattributed_dns_addresses,
|
||||
diagnostics,
|
||||
...metadata
|
||||
} = n;
|
||||
capture = {
|
||||
...metadata,
|
||||
retained_counts: {
|
||||
endpoints: endpoints.length,
|
||||
dns_queries: dns_queries.length,
|
||||
tls_sni_values: tls_sni_values.length,
|
||||
protocol_distribution: protocol_distribution.length,
|
||||
http_request_uris: http_request_uris.length,
|
||||
unattributed_dns_addresses: unattributed_dns_addresses.length,
|
||||
},
|
||||
diagnostics_code_units:
|
||||
diagnostics === undefined
|
||||
? null
|
||||
: {
|
||||
tshark: diagnostics.tshark_stderr.length,
|
||||
capinfos: diagnostics.capinfos_stderr.length,
|
||||
},
|
||||
};
|
||||
uris = http_request_uris.slice(0, 2);
|
||||
}
|
||||
if (uris.length !== Math.min(2, capture.retained_counts.http_request_uris))
|
||||
throw new Error("Runtime did not return the requested retained URI prefix");
|
||||
return {
|
||||
artifact_sha256: targetSha(inspected),
|
||||
capture,
|
||||
http_request_uris_first2: uris,
|
||||
delivery_observations: observations,
|
||||
evidence_ids: observations.map((item) => item.evidence_id),
|
||||
};
|
||||
};
|
||||
|
||||
const workflows = {
|
||||
"wireshark-http.cap": inspectPcapTarget,
|
||||
"wireshark-http_redirects.pcapng": inspectPcapTarget,
|
||||
"qgis-world-map.gpkg": async () => {
|
||||
const columns = ["fid", "NAME", "ISO_A3"];
|
||||
const input = {
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
# Small real PCAP recordings: keep complete delivery
|
||||
|
||||
Continues [#2016](https://github.com/morluto/rea/issues/2016) after the QGIS
|
||||
SQLite round. Measured main is pinned to
|
||||
`3ae826ceba6f25b08bce50bcb51001209bc16b57`, with 23 intervening commits.
|
||||
These include bounded PCAP summaries/pages, authenticated artifact subjects,
|
||||
unknown-snapshot reuse and shared transcript grading. This round measures existing
|
||||
PCAP delivery choices; it adds no production, API, default, cache or skill change.
|
||||
|
||||
## Corpus and question
|
||||
|
||||
Use two unmodified recordings published on the official
|
||||
[Wireshark sample-capture page](https://wiki.wireshark.org/SampleCaptures):
|
||||
|
||||
| Recording | Bytes | SHA-256 |
|
||||
| --------------------------------------- | -----: | ------------------------------------------------------------------ |
|
||||
| HTTP request/response, `http.cap` | 25,803 | `25a72bdf10339f2c29916920c8b9501d294923108de8f29b19aba7cc001ab60d` |
|
||||
| HTTP redirects, `http_redirects.pcapng` | 47,804 | `ff432a6b71d06cd20720f7763e584014edd0a43c3b55981c682d1b7640207abc` |
|
||||
|
||||
`corpus.json` preserves original/resolved URLs. Local digests pin downloaded
|
||||
bytes; no independently published upstream digest or immutable source commit is
|
||||
claimed. These are upstream saved application-protocol recordings, not generated
|
||||
REA fixtures. Recorded clients and current deployments are unknown. No new
|
||||
traffic is captured and no recorded target/URL is executed or fetched.
|
||||
|
||||
The question asks for complete returned identity/client/scalar metadata, every
|
||||
observed count and source coverage, six retained inventory counts, explicit nulls,
|
||||
diagnostic UTF-16 lengths, and the first two retained HTTP URIs in original order.
|
||||
Preserve each used receipt's limitations and identity. Summary/page scope and
|
||||
unknowns remain distinct from source coverage; exhaustion does not establish
|
||||
network completeness. Other inventory lists and diagnostic text are unrequested.
|
||||
|
||||
Compare default `{path}` with existing `{path, detail: "summary"}` plus a retained
|
||||
`http-uris` page, offset 0, limit 2. Ordinary selected-field
|
||||
`inspect_packet_capture` remains a separate boundary, not a substitute claim
|
||||
about complete inventories. `questions/pcap-http.txt` contains the fixed question.
|
||||
|
||||
## SDK measurements
|
||||
|
||||
Frozen dist/bridge file-table SHA-256:
|
||||
`db050545e94dc305a48042e06df96ac6c64b21ee6c5c4707c787d5e46df79e47`.
|
||||
Linux x64, Node 24.18.0, SDK client/server 2.3.1, installed Wireshark 4.0.17.
|
||||
Explicit commands are `/usr/bin/tshark`, `/usr/bin/capinfos`, `/usr/bin/prlimit`;
|
||||
private receipts retain executable hashes. Each workflow starts a fresh server
|
||||
and uses actual named advertised definitions/schema validation. Host page caches
|
||||
are not flushed. Both tools read the owned snapshot.
|
||||
|
||||
Eight trials run complete/summary/summary/complete per recording. Both pairs
|
||||
match selected capture facts, URI prefixes, settings and original source bytes.
|
||||
Each delivery's exact limitations, identities and coverage remain separately
|
||||
recorded, rather than equating source coverage with page exhaustion.
|
||||
|
||||
| Trial | Reply bytes | SDK seconds | Payload CPU seconds | Kernel peak bytes |
|
||||
| -------------------- | ----------: | ----------: | ------------------: | ----------------: |
|
||||
| HTTP complete-1 | 7,601 | 4.349 | 5.336 | 611,778,560 |
|
||||
| HTTP summary-1 | 17,540 | 4.972 | 5.973 | 601,661,440 |
|
||||
| HTTP summary-2 | 17,540 | 5.101 | 6.092 | 611,438,592 |
|
||||
| HTTP complete-2 | 7,601 | 4.463 | 5.503 | 617,148,416 |
|
||||
| Redirects complete-1 | 7,535 | 4.670 | 5.641 | 610,627,584 |
|
||||
| Redirects summary-1 | 17,240 | 5.099 | 6.104 | 615,522,304 |
|
||||
| Redirects summary-2 | 17,240 | 5.060 | 6.056 | 610,385,920 |
|
||||
| Redirects complete-2 | 7,535 | 4.466 | 5.458 | 608,141,312 |
|
||||
|
||||
Bytes are compact client-result JSON summed over one complete or two summary/page
|
||||
calls, not model tokens or raw wire bytes. Summary/page expands replies to more
|
||||
than twice the complete result on both recordings. All four SDK pairs are slower
|
||||
and use more payload CPU; memory differences are small/inconsistent. CPU includes
|
||||
driver/catalog work outside the SDK workflow timer.
|
||||
|
||||
Reproduce with `measure.mjs --artifact wireshark-http.cap` or
|
||||
`wireshark-http_redirects.pcapng`, pinned path/runtime/revision, explicit provider
|
||||
JSON, `--schemas selected`, and `--delivery complete|summary`. Use `compare.mjs`
|
||||
on completed output directories. Original replies, catalogs, comparison receipts
|
||||
and exact measured driver source stay private.
|
||||
|
||||
## Actual model tasks
|
||||
|
||||
Four actual Codex CLI 0.161.0 tasks use requested `gpt-5.6-terra` high, the same
|
||||
redirects question/runtime/artifact/provider settings, direct mode, two exact
|
||||
enabled tools and equal context/discovery capture flags. The requested alias is
|
||||
not verified server-resolved model identity. Equal cohort instructions select
|
||||
complete or summary plus one URI page. The experiment driver applies its existing
|
||||
private per-tool approval policy to `inspect_pcap_capture`; global configuration
|
||||
and REA authority are unchanged.
|
||||
|
||||
| Trial | Input | Cached | Uncached | Output | CLI wall seconds | MCP calls | Facts |
|
||||
| ---------- | -----: | -----: | -------: | -----: | ---------------: | --------: | ----- |
|
||||
| complete-1 | 38,947 | 9,984 | 28,963 | 2,119 | 69.469 | 1 | pass |
|
||||
| summary-1 | 58,779 | 38,144 | 20,635 | 3,241 | 141.304 | 2 | pass |
|
||||
| summary-2 | 58,584 | 38,144 | 20,440 | 4,261 | 50.916 | 2 | pass |
|
||||
| complete-2 | 38,917 | 23,040 | 15,877 | 2,813 | 106.896 | 1 | pass |
|
||||
|
||||
Summary/page total input **increases 50.92% / 50.54%** and output increases
|
||||
52.95% / 51.48%. Uncached input is mixed: 28.75% lower / 28.74% higher. Time is
|
||||
mixed: 103.41% slower / 52.37% faster. No cause is inferred for caching or timing
|
||||
variation. Cached input is included in total; each CLI reports one final aggregate
|
||||
usage. Output includes 1,149 / 1,162 / 2,196 / 1,837 reasoning tokens.
|
||||
|
||||
All calls succeed without extras/retries. Events contain only the selected MCP
|
||||
tools and agent messages. All source-digest and private-profile cleanup checks
|
||||
pass. Model payload CPU seconds/kernel peaks: 7.818/791,060,480;
|
||||
9.793/752,705,536; 7.685/757,891,072; 7.999/750,993,408. These do not establish
|
||||
a general CPU/memory gain.
|
||||
|
||||
The first summary initially fails the grader because it uses explicit equivalent
|
||||
labels and a URI object retaining page/source coverage. Its facts are correct.
|
||||
The grading boundary accepts these known forms while checking exact types,
|
||||
null presence, original limitations and extra scopes against actual receipts.
|
||||
Conflicting duplicates and unsupported claims remain failures. Each cited
|
||||
receipt's own ID must be reported; its parent lookup ID is checked separately.
|
||||
Original answers/reviews/grader source remain intact. No model is rerun. A grader
|
||||
review pause separates the pairs; it is not task time or a cold-cache claim.
|
||||
|
||||
## Verification and decision
|
||||
|
||||
An independent stdlib raw PCAP/PCAPNG/Ethernet/IP/TCP/complete-HTTP-header parser
|
||||
agrees on 43/271 packets, per-packet endpoint counts, first URI prefixes and 2/23
|
||||
distinct HTTP URIs. It invokes no Wireshark. DNS associations, protocol-stack
|
||||
dissection, nullable timestamps and live-network semantics are not independently
|
||||
validated.
|
||||
|
||||
Both real CLI complete results match full MCP normalized results, subjects,
|
||||
parameters, IDs and limitations. Portable CLI summary/URI views match MCP retained
|
||||
normalized facts and subjects; source forms/caller parameters remain distinct.
|
||||
Source bytes stay unchanged. Twelve context/grading regressions pass. Five real-answer
|
||||
mutations—omitted null, false page exhaustion, contradictory source scope,
|
||||
unsupported absence claim and non-string receipt identity—fail correctly.
|
||||
Malformed identities produce failed facts rather than crashing the grader.
|
||||
JS syntax, Python compilation and
|
||||
relevant standard lint pass.
|
||||
|
||||
**Decision: keep existing complete defaults; add no production optimization.**
|
||||
For these compact recordings and this question, summary/page costs more total
|
||||
input in both real-model pairs. No stable speed or CPU/memory benefit justifies
|
||||
another API, automatic delivery switch, cache or plugin layer. Existing pages
|
||||
remain available; their benefit needs evidence for the actual question/inventory.
|
||||
Large captures, other protocols, Windows/macOS/Bun Wireshark and other model
|
||||
workloads remain unverified here.
|
||||
|
||||
Heavy work stays serial with one CPU, 3 GiB early stop/4 GiB hard memory and no
|
||||
swap. Build kernel peak: 2,575,732,736 bytes. Payload cleanup and zero phase limit
|
||||
events are verified; missing terminal whole-scope counters remain unknown, so
|
||||
strict whole-resource grades stay false. No raw capture, trace, credential,
|
||||
runtime or result JSON is committed. No unrelated REA product bug is identified
|
||||
or fixed, and no release is performed.
|
||||
|
||||
Review follow-up binds the cited URI page to its exact requested facet/range,
|
||||
reported values and the summary retained parent. Small synthetic trial receipts
|
||||
exercise the entire grading entrypoint, including faithful but wrong-page/range/
|
||||
parent citations, missing nulls, false scope and malformed identities. These are
|
||||
grader regressions, not real-provider evidence. All four stored actual model
|
||||
answers still pass; no model reruns are required. Transcript readers close their
|
||||
owned file handles after grading.
|
||||
@@ -0,0 +1 @@
|
||||
Statically inspect the supplied saved Wireshark capture at {{artifact_path}} using only registered REA inspect_pcap_capture and inspect_analysis_view. Report its original client/target identity and every returned scalar metadata/count/coverage field exactly, preserving explicit nulls. Include retained_counts for endpoints, dns_queries, tls_sni_values, protocol_distribution, http_request_uris and unattributed_dns_addresses; derive array lengths only when reading complete Evidence. Include diagnostics_code_units as exact UTF-16 lengths of retained capinfos/tshark stderr, or null if diagnostics are unrecorded. In capture, omit inventory arrays and diagnostic text; do not omit their observed counts or change source coverage. Report the first two retained HTTP URIs in original order, or all if fewer; do not request other inventory pages. Report delivery_observations in dependency order for the Evidence used: evidence_id, outer limitations, and each present normalized kind, view, parent_evidence_id, coverage, unknowns and normalized_limitations. Preserve presence, explicit nulls, scalar types and original limitation order. Distinguish source coverage from URI-page exhaustion. Final JSON fields: artifact_sha256, capture, http_request_uris_first2, delivery_observations, evidence_ids. Include only actual response IDs. Saved packet/URI observations do not establish current deployment, process identity, missing traffic, decrypted payloads or current DNS resolution. Do not use shell, host file tools, network, other agents, traffic acquisition or execute recorded targets. Stop once these selected facts are supported.
|
||||
@@ -67,9 +67,28 @@ def scope_with_verified_counts(value, expected_scope, returned_counts):
|
||||
return scope, checks
|
||||
|
||||
|
||||
def pcap_observation_fields(value):
|
||||
"""Equivalent explicit labels are accepted; conflicting duplicates remain failures."""
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
result = dict(value)
|
||||
for label, canonical in {
|
||||
'outer_limitations': 'limitations', 'normalized_kind': 'kind',
|
||||
'normalized_view': 'view', 'normalized_parent_evidence_id': 'parent_evidence_id',
|
||||
'normalized_coverage': 'coverage', 'normalized_unknowns': 'unknowns',
|
||||
'normalized_source_coverage': 'source_coverage',
|
||||
}.items():
|
||||
if label not in result:
|
||||
continue
|
||||
if canonical in result and json.dumps(result[label], sort_keys=True) != json.dumps(result[canonical], sort_keys=True):
|
||||
return {**result, 'conflicting_fields': [label, canonical]}
|
||||
result[canonical] = result.pop(label)
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--domain', choices=['wasm', 'evm', 'android', 'flutter-aot', 'sqlite', 'managed', 'managed-nonempty', 'firmware', 'inventory', 'javascript', 'native', 'browser'], required=True)
|
||||
parser.add_argument('--domain', choices=['wasm', 'evm', 'android', 'flutter-aot', 'sqlite', 'pcap', 'managed', 'managed-nonempty', 'firmware', 'inventory', 'javascript', 'native', 'browser'], required=True)
|
||||
parser.add_argument('--trial', type=Path, required=True)
|
||||
parser.add_argument('--reference', type=Path)
|
||||
parser.add_argument('--resource-log', type=Path, required=True)
|
||||
@@ -84,24 +103,25 @@ def main():
|
||||
observed_ids = set()
|
||||
producer_results = {}
|
||||
tool_errors = []
|
||||
for line in (args.trial / 'events.jsonl').open():
|
||||
event = json.loads(line)
|
||||
item = event.get('item', {})
|
||||
if event.get('type') != 'item.completed' or item.get('type') != 'mcp_tool_call':
|
||||
continue
|
||||
result = item.get('result') or {}
|
||||
parsed = decode(result)
|
||||
if item['status'] == 'completed':
|
||||
# Only response text contributes observed IDs, never model arguments.
|
||||
for text in strings(result):
|
||||
observed_ids.update(re.findall(r'ev_[a-f0-9]{64}', text))
|
||||
if parsed is not None:
|
||||
producer_results.setdefault(item['tool'], []).append(parsed)
|
||||
else:
|
||||
tool_errors.append({'tool': item['tool'], 'arguments': item['arguments'], 'response': parsed if parsed is not None else result})
|
||||
if parsed is not None and parsed.get('error', {}).get('code') == 'resource_constraint':
|
||||
reference_value = parsed['error'].get('details', {}).get('reported_limits', {}).get('evidence_reference')
|
||||
observed_ids.update(evidence_ids(reference_value))
|
||||
with (args.trial / 'events.jsonl').open() as event_lines:
|
||||
for line in event_lines:
|
||||
event = json.loads(line)
|
||||
item = event.get('item', {})
|
||||
if event.get('type') != 'item.completed' or item.get('type') != 'mcp_tool_call':
|
||||
continue
|
||||
result = item.get('result') or {}
|
||||
parsed = decode(result)
|
||||
if item['status'] == 'completed':
|
||||
# Only response text contributes observed IDs, never model arguments.
|
||||
for text in strings(result):
|
||||
observed_ids.update(re.findall(r'ev_[a-f0-9]{64}', text))
|
||||
if parsed is not None:
|
||||
producer_results.setdefault(item['tool'], []).append(parsed)
|
||||
else:
|
||||
tool_errors.append({'tool': item['tool'], 'arguments': item['arguments'], 'response': parsed if parsed is not None else result})
|
||||
if parsed is not None and parsed.get('error', {}).get('code') == 'resource_constraint':
|
||||
reference_value = parsed['error'].get('details', {}).get('reported_limits', {}).get('evidence_reference')
|
||||
observed_ids.update(evidence_ids(reference_value))
|
||||
reported_ids = evidence_ids(answer.get('evidence_ids'))
|
||||
checks = {
|
||||
'reported_evidence_ids_observed_in_responses': bool(reported_ids) and reported_ids <= observed_ids,
|
||||
@@ -138,6 +158,87 @@ def main():
|
||||
# Missing is not SQL/JSON null; booleans are not numeric counters.
|
||||
check(key, (key in answer, json.dumps(answer.get(key), sort_keys=True)),
|
||||
(True, json.dumps(reference[key], sort_keys=True)))
|
||||
elif domain == 'pcap':
|
||||
check('capture', ('capture' in answer, json.dumps(answer.get('capture'), sort_keys=True)),
|
||||
(True, json.dumps(reference['capture'], sort_keys=True)))
|
||||
prefix = answer.get('http_request_uris_first2')
|
||||
records = {value['evidence_id']: value for values in producer_results.values()
|
||||
for value in values if isinstance(value, dict) and 'evidence_id' in value}
|
||||
if isinstance(prefix, dict):
|
||||
checks['pcap_prefix_fields_supported'] = set(prefix) <= {'items', 'coverage', 'source_coverage'} and 'items' in prefix
|
||||
if 'source_coverage' in prefix:
|
||||
check('pcap_prefix_source_coverage', prefix['source_coverage'], reference['capture']['coverage'])
|
||||
if 'coverage' in prefix:
|
||||
page_coverages = [value['normalized_result']['coverage'] for value in records.values()
|
||||
if value['normalized_result'].get('kind') == 'pcap'
|
||||
and value['normalized_result']['page'].get('facet') == 'http-uris'
|
||||
and value['normalized_result']['page'].get('items') == prefix.get('items')]
|
||||
checks['pcap_prefix_coverage_observed'] = any(json.dumps(prefix['coverage'], sort_keys=True) == json.dumps(value, sort_keys=True) for value in page_coverages)
|
||||
prefix = prefix.get('items')
|
||||
check('http_request_uris_first2', ('http_request_uris_first2' in answer, json.dumps(prefix, sort_keys=True)),
|
||||
(True, json.dumps(reference['http_request_uris_first2'], sort_keys=True)))
|
||||
observations = answer.get('delivery_observations')
|
||||
canonical_observations = [pcap_observation_fields(value) for value in observations] if isinstance(observations, list) else observations
|
||||
expected_observations = []
|
||||
if isinstance(canonical_observations, list):
|
||||
for observation in canonical_observations:
|
||||
identity = observation.get('evidence_id') if isinstance(observation, dict) else None
|
||||
record = records.get(identity) if isinstance(identity, str) else None
|
||||
if record is None:
|
||||
expected_observations.append(None)
|
||||
continue
|
||||
value = record['normalized_result']
|
||||
expected = {'evidence_id': record['evidence_id'], 'limitations': record['limitations']}
|
||||
for key in ['kind', 'view', 'parent_evidence_id', 'coverage', 'unknowns']:
|
||||
if key in value:
|
||||
expected[key] = value[key]
|
||||
if 'limitations' in value:
|
||||
expected['normalized_limitations'] = value['limitations']
|
||||
if 'source_coverage' in observation and 'source_coverage' in value:
|
||||
expected['source_coverage'] = value['source_coverage']
|
||||
expected_observations.append(expected)
|
||||
checks['pcap_delivery_observations_nonempty'] = isinstance(observations, list) and bool(observations)
|
||||
check('pcap_original_delivery_observations', json.dumps(canonical_observations, sort_keys=True),
|
||||
json.dumps(expected_observations, sort_keys=True))
|
||||
if isinstance(canonical_observations, list) and all(isinstance(x, dict) for x in canonical_observations):
|
||||
check('pcap_requested_delivery_chain', [x.get('kind', 'complete') for x in canonical_observations],
|
||||
[x.get('kind', 'complete') for x in reference['delivery_observations']])
|
||||
check('pcap_requested_views', [x.get('view') for x in canonical_observations],
|
||||
[x.get('view') for x in reference['delivery_observations']])
|
||||
identities = [x.get('evidence_id') for x in canonical_observations]
|
||||
checks['pcap_observations_have_reported_ids'] = all(isinstance(value, str) for value in identities) and set(identities) <= reported_ids
|
||||
cited = [records.get(identity) if isinstance(identity, str) else None for identity in identities]
|
||||
checks['pcap_cited_source_supports_uri_prefix'] = False
|
||||
if all(isinstance(record, dict) for record in cited):
|
||||
if len(cited) == 1:
|
||||
source = cited[0]['normalized_result']
|
||||
checks['pcap_cited_source_supports_uri_prefix'] = (
|
||||
source.get('target') == reference['capture']['target']
|
||||
and isinstance(source.get('http_request_uris'), list)
|
||||
and json.dumps(source['http_request_uris'][:2], sort_keys=True) == json.dumps(prefix, sort_keys=True)
|
||||
)
|
||||
elif len(cited) == 2:
|
||||
source, page = [record['normalized_result'] for record in cited]
|
||||
capture = source.get('summary', {})
|
||||
selected_page = page.get('page', {})
|
||||
checks['pcap_cited_source_supports_uri_prefix'] = (
|
||||
source.get('kind') == 'summary'
|
||||
and source.get('parent_operation') == 'inspect_pcap_capture'
|
||||
and capture == reference['capture']
|
||||
and isinstance(source.get('parent_evidence_id'), str)
|
||||
and page.get('parent_evidence_id') == source['parent_evidence_id']
|
||||
and page.get('parent_operation') == 'inspect_pcap_capture'
|
||||
and page.get('view') == {'kind': 'pcap', 'facet': 'http-uris', 'offset': 0, 'limit': 2}
|
||||
and selected_page.get('facet') == 'http-uris'
|
||||
and json.dumps(selected_page.get('items'), sort_keys=True) == json.dumps(prefix, sort_keys=True)
|
||||
and page.get('source_coverage') == capture.get('coverage')
|
||||
and page.get('artifact') == {key: capture['target'][key] for key in ['path', 'sha256']}
|
||||
)
|
||||
else:
|
||||
checks['pcap_requested_delivery_chain'] = False
|
||||
checks['pcap_observations_have_reported_ids'] = False
|
||||
checks['pcap_requested_views'] = False
|
||||
checks['pcap_cited_source_supports_uri_prefix'] = False
|
||||
elif domain == 'flutter-aot':
|
||||
for key in ['target', 'abi', 'libapp', 'string_pool', 'coverage', 'limitations']:
|
||||
check(key, answer.get(key), reference[key])
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Distinct capture/cleanup failures; simulated CLI is not real-model evidence."""
|
||||
|
||||
import importlib.util
|
||||
import copy
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
@@ -38,6 +39,140 @@ class ManagedCoverageTests(unittest.TestCase):
|
||||
self.assertNotEqual(scope, expected)
|
||||
|
||||
|
||||
class PcapCoverageTests(unittest.TestCase):
|
||||
def test_explicit_labels_preserve_original_nulls_and_source_scope(self):
|
||||
canonical = runpy.run_path(str(Path(__file__).with_name('review-model.py')))['pcap_observation_fields']
|
||||
original = {'outer_limitations': [], 'normalized_kind': 'pcap',
|
||||
'normalized_coverage': {'examined': 2, 'total': 23, 'next_offset': 2, 'exhausted': False},
|
||||
'normalized_source_coverage': 'partial', 'normalized_parent_evidence_id': None}
|
||||
result = canonical(original)
|
||||
self.assertEqual(result['limitations'], [])
|
||||
self.assertEqual(result['source_coverage'], 'partial')
|
||||
self.assertEqual(result['coverage']['total'], 23)
|
||||
self.assertIsNone(result['parent_evidence_id'])
|
||||
self.assertIn('outer_limitations', original)
|
||||
self.assertNotIn('parent_evidence_id', canonical({}))
|
||||
|
||||
def test_conflicting_duplicates_and_json_type_substitutions_stay_failures(self):
|
||||
canonical = runpy.run_path(str(Path(__file__).with_name('review-model.py')))['pcap_observation_fields']
|
||||
for wrong in ['partial', None]:
|
||||
result = canonical({'normalized_source_coverage': 'complete', 'source_coverage': wrong})
|
||||
self.assertIn('conflicting_fields', result)
|
||||
self.assertEqual(result['normalized_source_coverage'], 'complete')
|
||||
self.assertEqual(result['source_coverage'], wrong)
|
||||
result = canonical({'normalized_coverage': {'examined': 1}, 'coverage': {'examined': True}})
|
||||
self.assertIn('conflicting_fields', result)
|
||||
self.assertEqual(canonical({'outer_limitations': [], 'limitations': []}), {'limitations': []})
|
||||
|
||||
def test_unsupported_claims_are_retained_for_exact_producer_checking(self):
|
||||
canonical = runpy.run_path(str(Path(__file__).with_name('review-model.py')))['pcap_observation_fields']
|
||||
original = {'normalized_kind': 'pcap', 'unrecorded_traffic_absent': True}
|
||||
self.assertIn('unrecorded_traffic_absent', canonical(original))
|
||||
self.assertIsNone(canonical(None))
|
||||
|
||||
|
||||
class PcapGraderWorkflowTests(unittest.TestCase):
|
||||
"""Synthetic receipts test the grader boundary, not Wireshark or real models."""
|
||||
|
||||
def fixture(self):
|
||||
parent, summary_id, page_id = ['ev_' + value * 64 for value in ['a', 'b', 'c']]
|
||||
capture = {'target': {'path': '/fixture/http.pcapng', 'sha256': 'd' * 64},
|
||||
'capture_start': None, 'coverage': 'complete',
|
||||
'retained_counts': {'http_request_uris': 3}}
|
||||
prefix = ['http://example.test/one', 'http://example.test/two']
|
||||
coverage = {'status': 'page', 'examined': 2, 'total': 3, 'next_offset': 2, 'exhausted': False}
|
||||
summary = {'evidence_id': summary_id, 'limitations': ['source', 'view'],
|
||||
'normalized_result': {'kind': 'summary', 'view': {'kind': 'summary'},
|
||||
'parent_operation': 'inspect_pcap_capture', 'parent_evidence_id': parent,
|
||||
'summary': capture, 'coverage': {'status': 'complete-within-view', 'examined': 1, 'total': 1, 'next_offset': None, 'exhausted': True},
|
||||
'limitations': ['source', 'view'], 'unknowns': ['unrecorded traffic']}}
|
||||
page = {'evidence_id': page_id, 'limitations': ['source', 'view'],
|
||||
'normalized_result': {'kind': 'pcap',
|
||||
'view': {'kind': 'pcap', 'facet': 'http-uris', 'offset': 0, 'limit': 2},
|
||||
'parent_operation': 'inspect_pcap_capture', 'parent_evidence_id': parent,
|
||||
'page': {'facet': 'http-uris', 'items': prefix}, 'coverage': coverage,
|
||||
'source_coverage': 'complete', 'artifact': capture['target'],
|
||||
'limitations': ['source', 'view'], 'unknowns': ['unrecorded traffic']}}
|
||||
observations = [self.observation(value) for value in [summary, page]]
|
||||
reference = {'artifact_sha256': 'd' * 64, 'capture': capture,
|
||||
'http_request_uris_first2': prefix, 'delivery_observations': observations}
|
||||
answer = copy.deepcopy({**reference, 'http_request_uris_first2': {
|
||||
'items': prefix, 'coverage': coverage, 'source_coverage': 'complete'},
|
||||
'evidence_ids': [summary_id, page_id]})
|
||||
return answer, [summary, page], copy.deepcopy(reference)
|
||||
|
||||
def observation(self, record):
|
||||
value = record['normalized_result']
|
||||
return {'evidence_id': record['evidence_id'], 'limitations': record['limitations'],
|
||||
'kind': value['kind'], 'view': value['view'],
|
||||
'parent_evidence_id': value['parent_evidence_id'], 'coverage': value['coverage'],
|
||||
'unknowns': value['unknowns'], 'normalized_limitations': value['limitations']}
|
||||
|
||||
def grade(self, answer, records, reference):
|
||||
review = runpy.run_path(str(Path(__file__).with_name('review-model.py')))
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory);trial = root / 'trial';trial.mkdir()
|
||||
for name, value in [('summary.json', {'completed_mcp_calls': []}),
|
||||
('trial-settings.json', {}), ('cleanup.json', {'profile_removed': True})]:
|
||||
(trial / name).write_text(json.dumps(value))
|
||||
(trial / 'answer.txt').write_text(json.dumps(answer))
|
||||
events = [{'type': 'item.completed', 'item': {'type': 'mcp_tool_call',
|
||||
'tool': 'inspect_pcap_capture' if value['normalized_result']['kind'] == 'summary' else 'inspect_analysis_view',
|
||||
'status': 'completed', 'result': {'structuredContent': value}}} for value in records]
|
||||
(trial / 'events.jsonl').write_text(''.join(json.dumps(value) + '\n' for value in events))
|
||||
source = root / 'reference';source.mkdir();(source / 'answer.json').write_text(json.dumps(reference))
|
||||
resource = root / 'resource.log'
|
||||
resource.write_text(json.dumps({'resource_scope': 'simulated-grader-only', 'abort': None,
|
||||
'resource_counters_verified': False, 'resource_events_final': None}) + '\n')
|
||||
output = root / 'review.json'
|
||||
argv = ['review-model.py', '--domain', 'pcap', '--trial', str(trial), '--reference', str(source),
|
||||
'--resource-log', str(resource), '--output', str(output)]
|
||||
with patch.object(sys, 'argv', argv), patch('sys.stdout', io.StringIO()), self.assertRaises(SystemExit) as stopped:
|
||||
review['main']()
|
||||
self.assertEqual(stopped.exception.code, 1) # Unknown resource counters stay false.
|
||||
return json.loads(output.read_text())
|
||||
|
||||
def test_complete_grader_accepts_supported_receipts_and_equivalent_labels(self):
|
||||
answer, records, reference = self.fixture()
|
||||
self.assertTrue(self.grade(answer, records, reference)['all_factual_checks_pass'])
|
||||
for observation in answer['delivery_observations']:
|
||||
observation['outer_limitations'] = observation.pop('limitations')
|
||||
observation['normalized_coverage'] = observation.pop('coverage')
|
||||
self.assertTrue(self.grade(answer, records, reference)['all_factual_checks_pass'])
|
||||
|
||||
def test_complete_grader_rejects_missing_nulls_bad_scope_and_malformed_identity(self):
|
||||
mutations = [lambda x: x['capture'].pop('capture_start'),
|
||||
lambda x: x['http_request_uris_first2']['coverage'].__setitem__('exhausted', True),
|
||||
lambda x: x['delivery_observations'][-1].__setitem__('evidence_id', {'unexpected': 'value'}),
|
||||
lambda x: x['delivery_observations'][-1].__setitem__('unrecorded_traffic_absent', True)]
|
||||
for mutate in mutations:
|
||||
with self.subTest(mutation=mutate):
|
||||
answer, records, reference = self.fixture();mutate(answer)
|
||||
self.assertFalse(self.grade(answer, records, reference)['all_factual_checks_pass'])
|
||||
|
||||
def test_faithful_wrong_receipts_do_not_support_the_reported_uri_prefix(self):
|
||||
for wrong in ['facet', 'range', 'parent']:
|
||||
with self.subTest(wrong=wrong):
|
||||
answer, records, reference = self.fixture()
|
||||
page = copy.deepcopy(records[-1]);page['evidence_id'] = 'ev_' + 'e' * 64
|
||||
value = page['normalized_result']
|
||||
if wrong == 'facet':
|
||||
value['view']['facet'] = 'endpoints'
|
||||
value['page'] = {'facet': 'endpoints', 'items': [{'address': '127.0.0.1'}]}
|
||||
elif wrong == 'range':
|
||||
value['view']['offset'] = 1
|
||||
value['page']['items'] = ['http://example.test/two', 'http://example.test/three']
|
||||
else:
|
||||
value['parent_evidence_id'] = 'ev_' + 'f' * 64
|
||||
records.append(page)
|
||||
answer['delivery_observations'][-1] = self.observation(page)
|
||||
answer['evidence_ids'][-1] = page['evidence_id']
|
||||
report = self.grade(answer, records, reference)
|
||||
self.assertTrue(report['factual_checks']['pcap_original_delivery_observations'])
|
||||
self.assertFalse(report['factual_checks']['pcap_cited_source_supports_uri_prefix'])
|
||||
self.assertFalse(report['all_factual_checks_pass'])
|
||||
|
||||
|
||||
class ContextCaptureTests(unittest.TestCase):
|
||||
def test_filters_ambient_account_and_nested_usage_state(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
|
||||
@@ -69,22 +69,10 @@ without this lane reports Windows native controls as unavailable.
|
||||
limits only for its JavaScript helpers when running on Bun, which ignores
|
||||
their V8 heap flags; Node.js launches are unchanged.
|
||||
- Only the suspended child's default file owner is normalized. Caller token
|
||||
privileges and ownership remain unchanged. Caller process priority is
|
||||
preserved in the child, and caller CPU affinity whenever both occupy the same
|
||||
processor group. Windows chooses a new process's group itself and rejects a
|
||||
mask belonging to another group, so a child placed elsewhere keeps that
|
||||
group's default when the caller asked for no bound of its own. A caller
|
||||
deliberately pinned to fewer processors than its group holds is a constraint
|
||||
such a child cannot express, and is refused rather than widened to that
|
||||
group's default. A mask covering its group's whole active set does not
|
||||
distinguish a caller Windows placed in that group from one that selected the
|
||||
group deliberately, so such a child can still be placed elsewhere: its
|
||||
processor count stays bounded, its group placement is not preserved, and
|
||||
neither that case nor the refusal above has a verification lane, because both
|
||||
need a host whose processors span more than one group.
|
||||
Environment names are sorted and deduplicated using Windows
|
||||
ordinal comparison, preserving their native Unicode semantics and
|
||||
caller-selected values.
|
||||
privileges and ownership remain unchanged. Caller CPU affinity and process
|
||||
priority are preserved in the child. Environment names are sorted and
|
||||
deduplicated using Windows ordinal comparison, preserving their native Unicode
|
||||
semantics and caller-selected values.
|
||||
- Cleanup walks locked directory objects, removes files by handle, and unlinks
|
||||
reparse entries without traversing their targets. Failed removal retains the
|
||||
root and ancestor leases for retry; a partially removed runtime accepts only
|
||||
|
||||
@@ -68,18 +68,6 @@ static ULONGLONG jobMemoryLimit(napi_env env, napi_value value) {
|
||||
return limit;
|
||||
}
|
||||
|
||||
// An affinity mask is meaningful only inside one processor group, so only a
|
||||
// process occupying exactly one group has a group a child can inherit. A
|
||||
// process whose threads span groups, or whose membership cannot be read, has no
|
||||
// single group.
|
||||
static bool singleProcessorGroup(HANDLE process, USHORT& group) {
|
||||
USHORT count = 1;
|
||||
std::array<USHORT, 1> groups{};
|
||||
if (!GetProcessGroupAffinity(process, &count, groups.data()) || count != 1) return false;
|
||||
group = groups[0];
|
||||
return true;
|
||||
}
|
||||
|
||||
static void pipe(Handle& read, Handle& write, bool parentReads = true) {
|
||||
SECURITY_ATTRIBUTES attributes{sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
|
||||
HANDLE rawRead, rawWrite;
|
||||
@@ -180,27 +168,11 @@ std::unique_ptr<Process> spawnProcess(const std::wstring& command, const std::ws
|
||||
TOKEN_OWNER owner{reinterpret_cast<TOKEN_USER*>(tokenUser.data())->User.Sid};
|
||||
require(SetTokenInformation(token.get(), TokenOwner, &owner, sizeof(owner)),
|
||||
"Set suspended process file owner failed", command);
|
||||
// A mask names processors inside one processor group, and Windows assigns a
|
||||
// new process to a group of its own choosing, so a mask belonging to another
|
||||
// group is rejected (ERROR_INVALID_PARAMETER). An unconstrained caller, whose
|
||||
// mask is its group's whole active set, asks for no bound the child's own
|
||||
// group cannot give, so such a child keeps that group's default and the spawn
|
||||
// proceeds. A narrower mask is a deliberate CPU constraint that a child in
|
||||
// another group cannot express, and silently widening it would hand the
|
||||
// provider tree the whole group, so that spawn fails naming the constraint.
|
||||
DWORD_PTR affinity = 0, systemAffinity = 0;
|
||||
require(GetProcessAffinityMask(GetCurrentProcess(), &affinity, &systemAffinity),
|
||||
"Read caller process affinity failed", command);
|
||||
USHORT callerGroup = 0, childGroup = 0;
|
||||
const bool sharedGroup = singleProcessorGroup(GetCurrentProcess(), callerGroup) &&
|
||||
singleProcessorGroup(result->process.get(), childGroup) &&
|
||||
callerGroup == childGroup;
|
||||
if (affinity != 0 && sharedGroup)
|
||||
if (affinity != 0)
|
||||
require(SetProcessAffinityMask(result->process.get(), affinity), "Preserve caller process affinity failed", command);
|
||||
else
|
||||
require(affinity == 0 || affinity == systemAffinity,
|
||||
"Caller CPU affinity cannot bound an owned process in another processor group", command,
|
||||
ERROR_INVALID_PARAMETER);
|
||||
const DWORD priority = GetPriorityClass(GetCurrentProcess());
|
||||
require(priority != 0 && SetPriorityClass(result->process.get(), priority),
|
||||
"Preserve caller process priority failed", command);
|
||||
|
||||
+1
-1
@@ -207,7 +207,7 @@
|
||||
"fixtures:harmony": "node scripts/fixtures/harmony/fetch.mjs",
|
||||
"verify:agent": "npm run build:cached && node scripts/verify-agent-experience.mjs",
|
||||
"verify:hopper:linux": "npm run verify:fixtures && npm run build:cached && node scripts/verify-real-hopper-linux.mjs",
|
||||
"verify:setup:linux": "npm run verify:fixtures && npm run build:cached && node scripts/verify-linux-setup-e2e.mjs",
|
||||
"verify:setup:linux": "npm run build:cached && node scripts/verify-linux-setup-e2e.mjs",
|
||||
"build:fixtures": "node scripts/build-conformance-fixtures.mjs",
|
||||
"build:ghidra-windows-fixture": "node scripts/create-ghidra-windows-fixture.mjs",
|
||||
"verify:fixtures": "npm run build:fixtures && node scripts/verify-conformance-fixtures.mjs",
|
||||
|
||||
@@ -45,20 +45,6 @@ class Generator:
|
||||
assert "ows-secret" not in json.dumps(projected), projected
|
||||
if isinstance(value, bytes):
|
||||
assert projected["binary_fields"][-1]["state"] == "redacted", projected
|
||||
body = b"A" * 12345
|
||||
state = {"response": {"content": body}}
|
||||
control = adapter.project_record(state, [])
|
||||
field = control["binary_fields"][0]
|
||||
assert field["state"] == "retained" and field["bytes"] == len(body), control
|
||||
for literal in ["12345", "2345"]:
|
||||
# Only the generated byte count matches this exclusion.
|
||||
assert literal not in control["reported"]["response"]["content"]
|
||||
assert literal not in field["content_base64"] and literal not in field["sha256"]
|
||||
projected = adapter.project_record(state, [literal])
|
||||
assert projected["reported"]["response"]["content"] is None, projected
|
||||
assert projected["binary_fields"] == [{"pointer": "/response/content", "representation": "producer-bytes", "state": "redacted", "content_base64": None, "bytes": None, "sha256": None}], projected
|
||||
assert {"pointer": "/response/content", "reason": "explicit-sensitive-value"} in projected["redactions"], projected
|
||||
assert literal not in json.dumps(projected), projected
|
||||
(root / "native-error-classifications.json").write_text(json.dumps({"passed": len(classifications) + 2}))
|
||||
first = http.HTTPFlow(connection.Client(peername=("127.0.0.1", 1), sockname=("127.0.0.1", 2)), connection.Server(address=("example.test", 80)))
|
||||
first.id = "original-producer-id"
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export function assertCleanLinuxHopperRuntime(
|
||||
launcherPaths?: readonly string[],
|
||||
): Promise<void>;
|
||||
@@ -1,64 +0,0 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { readdir, stat } from "node:fs/promises";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Observe leftover demo processes on a dedicated clean Linux runner, including
|
||||
* groups reparented after their launcher exits. This is not ownership proof and
|
||||
* never authorizes signaling; unrelated runtime processes also block this lane.
|
||||
*/
|
||||
export const assertCleanLinuxHopperRuntime = async (
|
||||
launcherPaths = [
|
||||
"/opt/hopper/bin/Hopper",
|
||||
...(process.env.HOPPER_LAUNCHER_PATH === undefined
|
||||
? []
|
||||
: [process.env.HOPPER_LAUNCHER_PATH]),
|
||||
],
|
||||
) => {
|
||||
const { stdout } = await execFileAsync("ps", ["-ax", "-o", "command="]);
|
||||
if (/\/opt\/hopper\/bin\/Hopper|\bXvfb\b|hopper-demo-x11\.py/u.test(stdout))
|
||||
throw new Error("Clean Linux runner retained a Hopper demo process");
|
||||
const launchers = [];
|
||||
for (const path of launcherPaths) {
|
||||
try {
|
||||
launchers.push(await stat(path, { bigint: true }));
|
||||
} catch (error) {
|
||||
if (error?.code !== "ENOENT") throw error;
|
||||
}
|
||||
}
|
||||
if (launchers.length === 0) return;
|
||||
// /proc exposes the executed file even when argv[0] names a removed symlink.
|
||||
// Compare file identity, not a display path or a process name.
|
||||
let inspectionError;
|
||||
for (const entry of await readdir("/proc", { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !/^\d+$/u.test(entry.name)) continue;
|
||||
let executable;
|
||||
try {
|
||||
executable = await stat(`/proc/${entry.name}/exe`, { bigint: true });
|
||||
} catch (error) {
|
||||
if (error?.code === "ENOENT" || error?.code === "ESRCH") continue;
|
||||
// Other users' executables may be unreadable. The setup lane launches
|
||||
// providers as the caller; unreadable caller-owned processes fail closed.
|
||||
if (error?.code === "EACCES") {
|
||||
const owner = await stat(`/proc/${entry.name}`).catch((cause) => {
|
||||
if (cause?.code === "ENOENT") return undefined;
|
||||
throw cause;
|
||||
});
|
||||
if (owner === undefined || owner.uid !== process.getuid()) continue;
|
||||
}
|
||||
// Finish the inventory so an unrelated restricted process cannot mask a
|
||||
// positively identified leak. Unknown caller processes still fail closed.
|
||||
inspectionError ??= error;
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
launchers.some(
|
||||
({ dev, ino }) => dev === executable.dev && ino === executable.ino,
|
||||
)
|
||||
)
|
||||
throw new Error("Clean Linux runner retained a Hopper demo process");
|
||||
}
|
||||
if (inspectionError !== undefined) throw inspectionError;
|
||||
};
|
||||
@@ -1,30 +0,0 @@
|
||||
type VerifierCall = (
|
||||
name: string,
|
||||
arguments_?: Record<string, unknown>,
|
||||
) => Promise<unknown>;
|
||||
|
||||
interface StringExpectation {
|
||||
readonly value: string;
|
||||
readonly encoding: string;
|
||||
readonly symbol?: string;
|
||||
readonly recognitionOptional?: boolean;
|
||||
}
|
||||
|
||||
/** Verify source bytes, observed decoding, address filters and literal searches. */
|
||||
export function verifyHopperStringObjects(
|
||||
call: VerifierCall,
|
||||
expectations: readonly StringExpectation[],
|
||||
inventory?: readonly z.output<typeof analysisStringSchema>[] | null,
|
||||
): Promise<{
|
||||
readonly sourceBytesVerified: true;
|
||||
readonly recognition: readonly {
|
||||
readonly value: string;
|
||||
readonly address: string;
|
||||
readonly state: "observed" | "not_observed";
|
||||
readonly decodedObject: "verified" | "unverified";
|
||||
}[];
|
||||
readonly displayEscapesExcludedFromMatching: true;
|
||||
}>;
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { analysisStringSchema } from "../../src/domain/hopperValues.js";
|
||||
@@ -1,16 +1,13 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mcpTextValue } from "./mcp-verifier-results.mjs";
|
||||
|
||||
const fixtureSymbolPrefix = process.platform === "darwin" ? "_" : "";
|
||||
|
||||
/** Exercise literal/regex search, Unicode identities and cache invalidation in Hopper. */
|
||||
export async function verifyHopperSearch(call, invalid, procedure) {
|
||||
const address = procedure.address;
|
||||
const original = await call("address_name", { address });
|
||||
let stringCoverage;
|
||||
try {
|
||||
await verifySymbolNames(call, invalid, address);
|
||||
stringCoverage = await verifySearchModes(call, address);
|
||||
await verifySearchModes(call, address);
|
||||
} finally {
|
||||
await call("set_address_name", { address, name: original });
|
||||
}
|
||||
@@ -29,7 +26,7 @@ export async function verifyHopperSearch(call, invalid, procedure) {
|
||||
symbolUtf16LimitValidatedBeforeMutation: true,
|
||||
regexAndCaseModes: true,
|
||||
annotationCacheInvalidation: true,
|
||||
stringCoverage,
|
||||
escapedUtf8AndByteStrings: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -106,26 +103,11 @@ async function verifySearchModes(call, address) {
|
||||
[{ address, value: "REA_Search_Upper" }],
|
||||
);
|
||||
const strings = await call("list_strings");
|
||||
const linux = process.platform === "linux";
|
||||
const fullLiteral = "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle";
|
||||
// Recognition is a provider/loader capability, not an adapter guarantee.
|
||||
// Always retain the original size in raw-byte coverage; Linux additionally
|
||||
// requires an extent observed to produce native fragmented string objects.
|
||||
const fullBytes = Buffer.from(fullLiteral + "\0");
|
||||
const raw = await call("read_bytes", {
|
||||
address: `${fixtureSymbolPrefix}rea_long_literal`,
|
||||
length: fullBytes.length,
|
||||
});
|
||||
assert.equal(raw.complete, true);
|
||||
assert.equal(raw.bytes_hex, fullBytes.toString("hex"));
|
||||
const long = linux
|
||||
? "REA_FRAGMENTED_LITERAL_" + "x".repeat(512) + "fragment_tail"
|
||||
: fullLiteral;
|
||||
const longItem = strings.find(
|
||||
(item) => long.startsWith(item.value) && item.value.startsWith("REA_"),
|
||||
const long = "REA_LONG_LITERAL_" + "x".repeat(4096) + "needle";
|
||||
const longItem = strings.find((item) =>
|
||||
item.value.startsWith("REA_LONG_LITERAL_"),
|
||||
);
|
||||
assert.ok(longItem, "fixture omitted its real long literal");
|
||||
if (!linux) assert.equal(longItem.address, raw.address);
|
||||
assert.ok(long.startsWith(longItem.value));
|
||||
assert.ok(longItem.provider_value.endsWith("…"));
|
||||
assert.equal(longItem.string.termination, "missing");
|
||||
@@ -176,7 +158,7 @@ async function verifySearchModes(call, address) {
|
||||
}
|
||||
assert.deepEqual(
|
||||
await call("search_strings", {
|
||||
pattern: linux ? "fragment_tail" : "needle",
|
||||
pattern: "needle",
|
||||
mode: "literal",
|
||||
case_sensitive: true,
|
||||
}),
|
||||
@@ -194,122 +176,36 @@ async function verifySearchModes(call, address) {
|
||||
}),
|
||||
expected,
|
||||
);
|
||||
const objects = await verifyHopperStringObjects(
|
||||
call,
|
||||
[
|
||||
{
|
||||
value: "REA_UTF8_é_😀",
|
||||
encoding: "utf-8",
|
||||
symbol: `${fixtureSymbolPrefix}rea_utf8_literal`,
|
||||
recognitionOptional: linux,
|
||||
},
|
||||
{ value: 'REA_ESCAPED_"\\line\nend\t\r', encoding: "utf-8" },
|
||||
{ value: "REA_LITERAL_BACKSLASH_\\n", encoding: "utf-8" },
|
||||
{
|
||||
value: "REA_LITERAL_…",
|
||||
encoding: "utf-8",
|
||||
symbol: `${fixtureSymbolPrefix}rea_ellipsis_literal`,
|
||||
recognitionOptional: linux,
|
||||
},
|
||||
{
|
||||
value: "REA_LATIN1_ÿ",
|
||||
encoding: "latin-1",
|
||||
symbol: `${fixtureSymbolPrefix}rea_latin1_literal`,
|
||||
recognitionOptional: linux,
|
||||
},
|
||||
],
|
||||
strings,
|
||||
);
|
||||
return {
|
||||
fullLiteralSourceBytes: fullBytes.length,
|
||||
fragmentedLiteralSourceBytes: Buffer.byteLength(long),
|
||||
fullLiteralRecognition: {
|
||||
address: raw.address,
|
||||
state: strings.some((item) => item.address === raw.address)
|
||||
? "observed"
|
||||
: "not_observed",
|
||||
// Linux validates the original through raw bytes; its required decoded
|
||||
// fragment/dossier checks exercise the separate supported-size literal.
|
||||
decodedObject: linux ? "unverified" : "verified",
|
||||
},
|
||||
...objects,
|
||||
};
|
||||
await verifyHopperStringObjects(call, [
|
||||
{ value: "REA_UTF8_é_😀", encoding: "utf-8" },
|
||||
{ value: 'REA_ESCAPED_"\\line\nend\t\r', encoding: "utf-8" },
|
||||
{ value: "REA_LITERAL_BACKSLASH_\\n", encoding: "utf-8" },
|
||||
{ value: "REA_LITERAL_…", encoding: "utf-8" },
|
||||
{ value: "REA_LATIN1_ÿ", encoding: "latin-1" },
|
||||
]);
|
||||
}
|
||||
|
||||
/** Compare native string identities and values with the source fixture's bytes. */
|
||||
export async function verifyHopperStringObjects(
|
||||
call,
|
||||
expectations,
|
||||
inventory = null,
|
||||
) {
|
||||
// Reuse only the caller's inventory for this unchanged document, never live
|
||||
// state from an earlier session. Address-filter and search checks remain real.
|
||||
const strings = inventory ?? (await call("list_strings"));
|
||||
const recognition = [];
|
||||
for (const {
|
||||
value,
|
||||
encoding,
|
||||
symbol,
|
||||
recognitionOptional = false,
|
||||
} of expectations) {
|
||||
const expectedBytes = Buffer.from(
|
||||
value + "\0",
|
||||
encoding.replaceAll("-", ""),
|
||||
);
|
||||
let sourceBytes;
|
||||
if (symbol !== undefined) {
|
||||
const raw = await call("read_bytes", {
|
||||
address: symbol,
|
||||
length: expectedBytes.length,
|
||||
});
|
||||
sourceBytes = raw;
|
||||
assert.equal(raw.complete, true);
|
||||
assert.equal(raw.bytes_hex, expectedBytes.toString("hex"));
|
||||
}
|
||||
const item = strings.find((candidate) =>
|
||||
sourceBytes === undefined
|
||||
? candidate.value === value
|
||||
: candidate.address === sourceBytes.address,
|
||||
);
|
||||
if (item === undefined && recognitionOptional) {
|
||||
assert.ok(
|
||||
symbol,
|
||||
"optional recognition requires independent source-byte coverage",
|
||||
);
|
||||
recognition.push({
|
||||
value,
|
||||
address: sourceBytes.address,
|
||||
state: "not_observed",
|
||||
decodedObject: "unverified",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
export async function verifyHopperStringObjects(call, expectations) {
|
||||
const strings = await call("list_strings");
|
||||
for (const { value, encoding } of expectations) {
|
||||
const item = strings.find((candidate) => candidate.value === value);
|
||||
assert.ok(
|
||||
item,
|
||||
`Hopper omitted the decoded string ${JSON.stringify(value)}`,
|
||||
);
|
||||
assert.equal(
|
||||
item.value,
|
||||
value,
|
||||
"native string decoding changed the source value",
|
||||
);
|
||||
recognition.push({
|
||||
value,
|
||||
address: item.address,
|
||||
state: "observed",
|
||||
decodedObject: "verified",
|
||||
});
|
||||
assert.equal(item.string.encoding, encoding);
|
||||
assert.equal(item.string.encoding_status, "inferred");
|
||||
assert.equal(item.string.termination, "present_or_not_required");
|
||||
const expectedBytes = Buffer.from(
|
||||
value + "\0",
|
||||
encoding.replaceAll("-", ""),
|
||||
);
|
||||
assert.equal(item.string.byte_length, expectedBytes.length);
|
||||
const bytes =
|
||||
sourceBytes ??
|
||||
(await call("read_bytes", {
|
||||
address: item.address,
|
||||
length: expectedBytes.length,
|
||||
}));
|
||||
assert.equal(bytes.complete, true);
|
||||
const bytes = await call("read_bytes", {
|
||||
address: item.address,
|
||||
length: expectedBytes.length,
|
||||
});
|
||||
assert.equal(bytes.bytes_hex, expectedBytes.toString("hex"));
|
||||
assert.deepEqual(await call("list_strings", { address: item.address }), [
|
||||
item,
|
||||
@@ -329,7 +225,7 @@ export async function verifyHopperStringObjects(
|
||||
);
|
||||
return {
|
||||
sourceBytesVerified: true,
|
||||
recognition,
|
||||
inferredEncodingReported: true,
|
||||
displayEscapesExcludedFromMatching: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -12,7 +12,6 @@ import { tmpdir } from "node:os";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
||||
import { assertCleanLinuxHopperRuntime } from "./lib/clean-linux-hopper-runtime.mjs";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const verifierRun = createVerifierRun();
|
||||
@@ -20,12 +19,12 @@ const command = process.env.REA_VERIFY_SERVER_COMMAND;
|
||||
if (process.platform !== "linux" || process.getuid?.() !== 0)
|
||||
throw new Error("Linux setup verification requires a root Linux runner");
|
||||
if (!command) throw new Error("REA_VERIFY_SERVER_COMMAND is required");
|
||||
await assertCleanLinuxHopperRuntime();
|
||||
try {
|
||||
await access("/opt/hopper/bin/Hopper");
|
||||
throw new Error("Linux setup verification requires a clean runner");
|
||||
} catch (error) {
|
||||
if (error?.code !== "ENOENT") throw error;
|
||||
if (error instanceof Error && error.message.includes("clean runner"))
|
||||
throw error;
|
||||
}
|
||||
|
||||
const runJson = async (args) => {
|
||||
@@ -36,25 +35,14 @@ const runJson = async (args) => {
|
||||
return JSON.parse(stdout);
|
||||
};
|
||||
|
||||
const plan = await runJson([
|
||||
"setup",
|
||||
"--install-hopper",
|
||||
"--dry-run",
|
||||
"--json",
|
||||
]);
|
||||
if (
|
||||
plan.status !== "planned" ||
|
||||
!plan.plannedActions.some(({ kind }) => kind === "install_hopper") ||
|
||||
plan.appliedActions.length !== 0
|
||||
)
|
||||
throw new Error("setup did not produce a read-only Hopper installation plan");
|
||||
const plan = await runJson(["setup", "--json"]);
|
||||
if (plan.status !== "needs_confirmation")
|
||||
throw new Error("setup did not produce a read-only confirmation plan");
|
||||
await access("/opt/hopper/bin/Hopper").then(
|
||||
() => {
|
||||
throw new Error("setup plan mutated the clean runner");
|
||||
},
|
||||
(error) => {
|
||||
if (error?.code !== "ENOENT") throw error;
|
||||
},
|
||||
() => undefined,
|
||||
);
|
||||
|
||||
const installed = await runJson([
|
||||
@@ -70,7 +58,7 @@ if (
|
||||
throw new Error(
|
||||
`approved setup did not become ready: ${JSON.stringify(installed)}`,
|
||||
);
|
||||
const doctor = await runJson(["doctor", "--provider", "hopper", "--json"]);
|
||||
const doctor = await runJson(["doctor", "--json"]);
|
||||
if (doctor.healthy !== true)
|
||||
throw new Error(`doctor is unhealthy: ${JSON.stringify(doctor)}`);
|
||||
|
||||
@@ -79,6 +67,8 @@ await execFileAsync(command, ["analyze", "/usr/bin/true"], {
|
||||
timeout: 180_000,
|
||||
maxBuffer: 10 * 1024 * 1024,
|
||||
});
|
||||
process.env.HOPPER_TARGET_PATH = "/usr/bin/true";
|
||||
process.env.HOPPER_SECOND_TARGET_PATH = "/usr/bin/false";
|
||||
process.env.REA_VERIFY_SERVER_ARGS_JSON = '["mcp"]';
|
||||
await import("./verify-real-hopper-linux.mjs");
|
||||
|
||||
@@ -105,24 +95,28 @@ try {
|
||||
await rm(modifiedDirectory, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
const repeated = await runJson(["setup", "--yes", "--json"]);
|
||||
const repeated = await runJson([
|
||||
"setup",
|
||||
"--yes",
|
||||
"--install-hopper",
|
||||
"--json",
|
||||
]);
|
||||
if (
|
||||
repeated.status !== "ready" ||
|
||||
repeated.plannedActions.length !== 0 ||
|
||||
repeated.appliedActions.length !== 0
|
||||
repeated.appliedActions.includes("installed_hopper")
|
||||
)
|
||||
throw new Error("a second setup was not idempotent");
|
||||
await assertCleanLinuxHopperRuntime();
|
||||
const completedVerifierRun = await completeVerifierRun(verifierRun);
|
||||
if (
|
||||
completedVerifierRun.process_lineage.status !== "verified" ||
|
||||
completedVerifierRun.process_lineage.descendants.length !== 0
|
||||
)
|
||||
throw new Error("Linux setup verification did not prove owned child cleanup");
|
||||
const { stdout: processes } = await execFileAsync("ps", [
|
||||
"-ax",
|
||||
"-o",
|
||||
"command=",
|
||||
]);
|
||||
if (/\/opt\/hopper\/bin\/Hopper|\bXvfb\b|hopper-demo-x11\.py/u.test(processes))
|
||||
throw new Error("Linux setup verification leaked a Hopper demo session");
|
||||
|
||||
console.log(
|
||||
JSON.stringify({
|
||||
verifier_run: completedVerifierRun,
|
||||
verifier_run: await completeVerifierRun(verifierRun),
|
||||
status: "verified",
|
||||
setup: true,
|
||||
cli: true,
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
import assert from "node:assert/strict";
|
||||
import { estimateTokenCount } from "tokenx";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile, readdir, mkdir, rm } from "node:fs/promises";
|
||||
import { readFile, writeFile, readdir } from "node:fs/promises";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
@@ -92,20 +91,6 @@ const source = pcap(1, [
|
||||
// LINKTYPE_BLUETOOTH_HCI_H4 = 187; H4 command packet, HCI Reset opcode 0x0c03, no parameters.
|
||||
const bluetoothSource = pcap(187, [Buffer.from("01030c00", "hex")]);
|
||||
let cases = 0;
|
||||
const discoveryMeasurements = [];
|
||||
const inheritedAddressSpace = (await readFile("/proc/self/limits", "utf8"))
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith("Max address space "))
|
||||
?.trim()
|
||||
.match(/^Max address space\s+(\S+)\s+(\S+)\s+bytes$/u);
|
||||
assert.ok(inheritedAddressSpace);
|
||||
const expectedAddressSpace = Math.min(
|
||||
1073741824,
|
||||
...inheritedAddressSpace
|
||||
.slice(1)
|
||||
.map((value) => (value === "unlimited" ? Infinity : Number(value))),
|
||||
);
|
||||
|
||||
try {
|
||||
await writeFile(path, source);
|
||||
await writeFile(bluetooth, bluetoothSource);
|
||||
@@ -136,16 +121,14 @@ try {
|
||||
.digest("hex"),
|
||||
);
|
||||
assert.equal(report.hardware_acquisition, "not-performed");
|
||||
assert.equal(report.limits.address_space_bytes, expectedAddressSpace);
|
||||
assert.equal(report.limits.address_space_bytes, 1073741824);
|
||||
assert.equal(report.tool.configured_path, process.env.REA_TSHARK_COMMAND);
|
||||
assert.equal(
|
||||
report.resource_limiter.configured_path,
|
||||
process.env.REA_TSHARK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
|
||||
);
|
||||
assert.ok(
|
||||
report.resource_limiter.arguments.includes(
|
||||
`--as=${expectedAddressSpace}:${expectedAddressSpace}`,
|
||||
),
|
||||
report.resource_limiter.arguments.includes("--as=1073741824:1073741824"),
|
||||
);
|
||||
assert.equal(report.configuration, "private-empty-personal-profile");
|
||||
const flags = Object.entries(input)
|
||||
@@ -330,133 +313,6 @@ try {
|
||||
true,
|
||||
);
|
||||
cases++;
|
||||
const discovery = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "inspect_packet_fields",
|
||||
);
|
||||
assert.ok(discovery?.outputSchema);
|
||||
assert.ok(ajv.validateSchema(discovery.inputSchema));
|
||||
assert.ok(ajv.validateSchema(discovery.outputSchema));
|
||||
const nativeProfile = join(root.path, "native-profile");
|
||||
await mkdir(nativeProfile);
|
||||
const native = (
|
||||
await execute(process.env.REA_TSHARK_COMMAND, ["-G", "fields"], {
|
||||
env: { ...environment, WIRESHARK_CONFIG_DIR: nativeProfile },
|
||||
timeout: 30000,
|
||||
maxBuffer: 32 * 1024 * 1024,
|
||||
})
|
||||
).stdout;
|
||||
await rm(nativeProfile, { recursive: true });
|
||||
const nativeLines = native.split(/\r?\n/);
|
||||
if (nativeLines.at(-1) === "") nativeLines.pop();
|
||||
for (const input of [
|
||||
{ query: "usb" },
|
||||
{ limit: 1 },
|
||||
{ offset: 1, limit: 2 },
|
||||
{ kind: "fields", protocol: "usb", query: "idVendor" },
|
||||
{ kind: "fields", protocol: "udp", limit: null },
|
||||
{ kind: "fields", query: "rea_no_such_field" },
|
||||
]) {
|
||||
const started = performance.now();
|
||||
const response = await client.callTool({
|
||||
name: discovery.name,
|
||||
arguments: input,
|
||||
});
|
||||
assert.notEqual(response.isError, true, JSON.stringify(response));
|
||||
assert.ok(
|
||||
ajv.validate(discovery.outputSchema, response.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
);
|
||||
const evidence = parseEvidence(response.structuredContent);
|
||||
const report = evidence.normalized_result;
|
||||
const kind = input.kind ?? "protocols";
|
||||
const query = (input.query ?? "").toLowerCase();
|
||||
const expectedMatches = nativeLines.flatMap((line, index) => {
|
||||
const columns = line.split("\t");
|
||||
if ((kind === "protocols") !== (columns[0] === "P")) return [];
|
||||
if (
|
||||
input.protocol !== undefined &&
|
||||
(columns[0] === "P" ? columns[2] : columns[4]) !== input.protocol
|
||||
)
|
||||
return [];
|
||||
if (
|
||||
![
|
||||
columns[1],
|
||||
columns[2],
|
||||
...(columns[0] === "F" ? [columns[7]] : []),
|
||||
].some((value) => value.toLowerCase().includes(query))
|
||||
)
|
||||
return [];
|
||||
return [{ sourceLine: index + 1, columns }];
|
||||
});
|
||||
const offset = input.offset ?? 0;
|
||||
const limit = input.limit === null ? undefined : (input.limit ?? 50);
|
||||
const expectedPage = expectedMatches.slice(
|
||||
offset,
|
||||
limit === undefined ? undefined : offset + limit,
|
||||
);
|
||||
assert.deepEqual(
|
||||
report.records.map((record) => record.source_line),
|
||||
expectedPage.map((record) => record.sourceLine),
|
||||
);
|
||||
assert.deepEqual(report.output_window, {
|
||||
examined: nativeLines.filter((line) =>
|
||||
line.startsWith(kind === "protocols" ? "P\t" : "F\t"),
|
||||
).length,
|
||||
matching: expectedMatches.length,
|
||||
returned: expectedPage.length,
|
||||
has_more:
|
||||
Math.max(0, expectedMatches.length - offset) > expectedPage.length,
|
||||
});
|
||||
discoveryMeasurements.push({
|
||||
input,
|
||||
elapsed_ms: +(performance.now() - started).toFixed(2),
|
||||
response_bytes: Buffer.byteLength(JSON.stringify(response)),
|
||||
estimated_tokens_one_tool_request_response: estimateTokenCount(
|
||||
JSON.stringify(discovery) +
|
||||
JSON.stringify(input) +
|
||||
JSON.stringify(response),
|
||||
),
|
||||
});
|
||||
for (const record of report.records) {
|
||||
const columns = nativeLines[record.source_line - 1].split("\t");
|
||||
assert.equal(record.name, columns[1]);
|
||||
assert.equal(record.abbreviation, columns[2]);
|
||||
assert.equal(record.field_type, columns[0] === "F" ? columns[3] : null);
|
||||
assert.equal(
|
||||
record.parent_protocol,
|
||||
columns[0] === "F" ? columns[4] : null,
|
||||
);
|
||||
assert.equal(record.description, columns[0] === "F" ? columns[7] : null);
|
||||
assert.equal(record.display_base, columns[0] === "F" ? columns[5] : null);
|
||||
assert.equal(record.bitmask, columns[0] === "F" ? columns[6] : null);
|
||||
}
|
||||
if (input.query === "idVendor")
|
||||
assert.ok(
|
||||
report.records.some(
|
||||
(row) =>
|
||||
row.abbreviation === "usb.idVendor" &&
|
||||
row.field_type === "FT_UINT16",
|
||||
),
|
||||
);
|
||||
if (input.query === "usb")
|
||||
assert.ok(report.records.some((row) => row.abbreviation === "usb"));
|
||||
if (input.query === "rea_no_such_field")
|
||||
assert.equal(report.output_window.matching, 0);
|
||||
const flags = Object.entries(input).flatMap(([key, value]) =>
|
||||
value === null ? ["--all"] : [`--${key}`, String(value)],
|
||||
);
|
||||
const cli = JSON.parse(
|
||||
(
|
||||
await execute(
|
||||
process.execPath,
|
||||
[entrypoint, "inspect-packet-fields", ...flags, "--format", "json"],
|
||||
{ env: environment, timeout: 60000, maxBuffer: 16 * 1024 * 1024 },
|
||||
)
|
||||
).stdout,
|
||||
);
|
||||
assert.deepEqual(cli.normalized_result, report);
|
||||
cases++;
|
||||
}
|
||||
await client.close();
|
||||
assert.deepEqual((await readdir(root.path)).sort(), [
|
||||
"bluetooth.pcap",
|
||||
@@ -473,9 +329,6 @@ console.log(
|
||||
{
|
||||
status: "passed",
|
||||
cases,
|
||||
discovery_measurements: discoveryMeasurements,
|
||||
measurement_scope:
|
||||
"Warm MCP server, fresh TShark processes; tokenx estimates include one advertised tool/request/response, not billed usage. Model-driven selection, CPU and peak process-family memory are unmeasured; no cache/speedup claim.",
|
||||
host: `${process.platform}/${process.arch}`,
|
||||
scope:
|
||||
"real TShark CLI/MCP; synthetic Ethernet/IPv4/UDP/DNS and Bluetooth HCI PCAP; no hardware acquisition",
|
||||
|
||||
@@ -11,8 +11,7 @@ createVerifierRun();
|
||||
|
||||
if (process.platform !== "linux")
|
||||
throw new Error("Linux real-Hopper verification must run on Linux");
|
||||
const configuredLauncher = process.env.HOPPER_LAUNCHER_PATH;
|
||||
const launcher = configuredLauncher ?? "/opt/hopper/bin/Hopper";
|
||||
const launcher = process.env.HOPPER_LAUNCHER_PATH ?? "/opt/hopper/bin/Hopper";
|
||||
await access(launcher);
|
||||
await access("/usr/bin/Xvfb");
|
||||
await access("/usr/bin/xauth");
|
||||
@@ -29,7 +28,5 @@ try {
|
||||
process.env.HOPPER_LAUNCHER_PATH = alternateLauncher;
|
||||
await import("./verify-real-hopper.mjs");
|
||||
} finally {
|
||||
if (configuredLauncher === undefined) delete process.env.HOPPER_LAUNCHER_PATH;
|
||||
else process.env.HOPPER_LAUNCHER_PATH = configuredLauncher;
|
||||
await rm(alternateDirectory, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#!/usr/bin/env node
|
||||
import assert from "node:assert/strict";
|
||||
import { estimateTokenCount } from "tokenx";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, writeFile, readdir } from "node:fs/promises";
|
||||
@@ -69,20 +68,6 @@ for (const byte of Buffer.from("REA")) {
|
||||
lines.push(`#${tick + 1000}`, "1!");
|
||||
const source = lines.join("\n") + "\n";
|
||||
let cases = 0;
|
||||
const discoveryMeasurements = [];
|
||||
const inheritedAddressSpace = (await readFile("/proc/self/limits", "utf8"))
|
||||
.split("\n")
|
||||
.find((line) => line.startsWith("Max address space "))
|
||||
?.trim()
|
||||
.match(/^Max address space\s+(\S+)\s+(\S+)\s+bytes$/u);
|
||||
assert.ok(inheritedAddressSpace);
|
||||
const expectedAddressSpace = Math.min(
|
||||
1073741824,
|
||||
...inheritedAddressSpace
|
||||
.slice(1)
|
||||
.map((value) => (value === "unlimited" ? Infinity : Number(value))),
|
||||
);
|
||||
|
||||
try {
|
||||
await writeFile(path, source);
|
||||
await client.connect(transport);
|
||||
@@ -119,16 +104,14 @@ try {
|
||||
createHash("sha256").update(source).digest("hex"),
|
||||
);
|
||||
assert.equal(report.hardware_acquisition, "not-performed");
|
||||
assert.equal(report.limits.address_space_bytes, expectedAddressSpace);
|
||||
assert.equal(report.limits.address_space_bytes, 1073741824);
|
||||
assert.equal(report.tool.configured_path, process.env.REA_SIGROK_COMMAND);
|
||||
assert.equal(
|
||||
report.resource_limiter.configured_path,
|
||||
process.env.REA_SIGROK_PRLIMIT_COMMAND ?? "/usr/bin/prlimit",
|
||||
);
|
||||
assert.ok(
|
||||
report.resource_limiter.arguments.includes(
|
||||
`--as=${expectedAddressSpace}:${expectedAddressSpace}`,
|
||||
),
|
||||
report.resource_limiter.arguments.includes("--as=1073741824:1073741824"),
|
||||
);
|
||||
assert.equal(report.diagnostics, "");
|
||||
const flags = Object.entries(input)
|
||||
@@ -262,88 +245,6 @@ try {
|
||||
});
|
||||
assert.equal(invalid.isError, true);
|
||||
cases++;
|
||||
const discoveryTool = (await client.listTools()).tools.find(
|
||||
({ name }) => name === "inspect_signal_decoders",
|
||||
);
|
||||
assert.ok(discoveryTool?.outputSchema);
|
||||
assert.ok(ajv.validateSchema(discoveryTool.inputSchema));
|
||||
assert.ok(ajv.validateSchema(discoveryTool.outputSchema));
|
||||
const nativeHelp = (
|
||||
await execute(
|
||||
process.env.REA_SIGROK_COMMAND,
|
||||
["--dont-scan", "--protocol-decoders=uart", "--show"],
|
||||
{ env: environment, timeout: 30000, maxBuffer: 4 * 1024 * 1024 },
|
||||
)
|
||||
).stdout.split(/\r?\n/);
|
||||
if (nativeHelp.at(-1) === "") nativeHelp.pop();
|
||||
for (const input of [
|
||||
{ query: "uart" },
|
||||
{ limit: 1 },
|
||||
{ offset: 1, limit: 2 },
|
||||
{ decoder: "uart", query: "BaUd" },
|
||||
{ decoder: "uart", offset: 50, limit: null },
|
||||
{ query: "rea_no_such_decoder" },
|
||||
]) {
|
||||
const started = performance.now();
|
||||
const response = await client.callTool({
|
||||
name: discoveryTool.name,
|
||||
arguments: input,
|
||||
});
|
||||
assert.notEqual(response.isError, true, JSON.stringify(response));
|
||||
assert.ok(
|
||||
ajv.validate(discoveryTool.outputSchema, response.structuredContent),
|
||||
JSON.stringify(ajv.errors),
|
||||
);
|
||||
const evidence = parseEvidence(response.structuredContent);
|
||||
const report = evidence.normalized_result;
|
||||
discoveryMeasurements.push({
|
||||
input,
|
||||
elapsed_ms: +(performance.now() - started).toFixed(2),
|
||||
response_bytes: Buffer.byteLength(JSON.stringify(response)),
|
||||
estimated_tokens_one_tool_request_response: estimateTokenCount(
|
||||
JSON.stringify(discoveryTool) +
|
||||
JSON.stringify(input) +
|
||||
JSON.stringify(response),
|
||||
),
|
||||
});
|
||||
if (input.decoder) {
|
||||
const matched = nativeHelp
|
||||
.map((text, i) => ({ line_number: i + 1, text }))
|
||||
.filter(({ text }) =>
|
||||
text.toLowerCase().includes((input.query ?? "").toLowerCase()),
|
||||
);
|
||||
assert.deepEqual(
|
||||
report.help_lines,
|
||||
matched.slice(
|
||||
input.offset ?? 0,
|
||||
input.limit === null
|
||||
? undefined
|
||||
: (input.offset ?? 0) + (input.limit ?? 50),
|
||||
),
|
||||
);
|
||||
} else if (input.query === "uart")
|
||||
assert.ok(report.decoders.some(({ id }) => id === "uart"));
|
||||
const flags = Object.entries(input).flatMap(([key, value]) =>
|
||||
value === null ? ["--all"] : [`--${key}`, String(value)],
|
||||
);
|
||||
const cli = JSON.parse(
|
||||
(
|
||||
await execute(
|
||||
process.execPath,
|
||||
[entrypoint, "inspect-signal-decoders", ...flags, "--format", "json"],
|
||||
{ env: environment, timeout: 60000, maxBuffer: 8 * 1024 * 1024 },
|
||||
)
|
||||
).stdout,
|
||||
);
|
||||
assert.deepEqual(cli.normalized_result, report);
|
||||
cases++;
|
||||
}
|
||||
const unavailable = await client.callTool({
|
||||
name: discoveryTool.name,
|
||||
arguments: { decoder: "rea_no_such_decoder" },
|
||||
});
|
||||
assert.equal(unavailable.isError, true);
|
||||
cases++;
|
||||
await client.close();
|
||||
assert.deepEqual((await readdir(root.path)).sort(), [
|
||||
"paged.vcd",
|
||||
@@ -359,9 +260,6 @@ console.log(
|
||||
{
|
||||
status: "passed",
|
||||
cases,
|
||||
discovery_measurements: discoveryMeasurements,
|
||||
measurement_scope:
|
||||
"Warm MCP server, fresh sigrok processes; tokenx estimates include one advertised tool/request/response, not billed model usage. No model-driven selection benchmark, CPU or peak process-family memory measurement; no cache or speedup claim.",
|
||||
host: `${process.platform}/${process.arch}`,
|
||||
scope:
|
||||
"real sigrok UART VCD through compiled CLI/MCP; no physical acquisition",
|
||||
|
||||
@@ -662,42 +662,6 @@ setInterval(()=>{},1000);\n`,
|
||||
unicodeNamesPreserved: true,
|
||||
});
|
||||
report.processes.windowsEnvironmentSemantics = true;
|
||||
// Observed through this process's own id: a separate probe process would
|
||||
// get its own processor group, so it cannot stand in for the process that
|
||||
// spawns the child.
|
||||
const callerAffinity = JSON.parse(
|
||||
execFileSync(boundaryFixture, ["affinity", String(process.pid)], {
|
||||
encoding: "utf8",
|
||||
}),
|
||||
);
|
||||
const affinityChild = native.call("process_spawn", [
|
||||
boundaryFixture,
|
||||
`${quote(boundaryFixture)} affinity`,
|
||||
workspace,
|
||||
environment,
|
||||
]);
|
||||
const observedAffinity = await wait(affinityChild);
|
||||
native.call("process_close", [affinityChild.handle]);
|
||||
assert.equal(observedAffinity.exitCode, 0);
|
||||
const childAffinity = JSON.parse(observedAffinity.output);
|
||||
// Masks cross as hexadecimal strings because a mask can exceed the
|
||||
// safe-integer range. Sharing one processor group makes the caller's mask
|
||||
// applicable, so it must be inherited exactly. Windows placing the child in
|
||||
// another group is only permitted when the caller asked for no bound of its
|
||||
// own, which its group's whole active set establishes; a narrower mask has
|
||||
// to fail the spawn rather than widen to that group's default.
|
||||
const sharedGroup =
|
||||
callerAffinity.singleProcessorGroup &&
|
||||
childAffinity.singleProcessorGroup &&
|
||||
callerAffinity.processorGroup === childAffinity.processorGroup;
|
||||
if (sharedGroup)
|
||||
assert.equal(childAffinity.affinityMask, callerAffinity.affinityMask);
|
||||
else assert.equal(callerAffinity.affinityMask, callerAffinity.systemMask);
|
||||
report.processes.callerAffinityBoundsOwnedProcessOrRefusesToWiden = true;
|
||||
report.callerAffinity = {
|
||||
...callerAffinity,
|
||||
sharedGroupWithChild: sharedGroup,
|
||||
};
|
||||
}
|
||||
const ownerFixture = join(workspace, "owner.mjs");
|
||||
const ownerPidFile = join(workspace, "crash-child.pid");
|
||||
|
||||
@@ -84,24 +84,6 @@ describe("parseAdbDevicesOutput", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("accepts complete multiword states and rejects state prefixes", () => {
|
||||
const output = [
|
||||
"serial-no-permission no permissions usb:1-1",
|
||||
"serial-bad-device deviceXYZ ",
|
||||
"serial-bad-offline offline-ish",
|
||||
"serial-bad-auth unauthorizedXYZ",
|
||||
].join("\n");
|
||||
const { devices, unparsedLines } = parseAdbDevicesOutput(output);
|
||||
expect(devices.map(({ serial, state }) => [serial, state])).toEqual([
|
||||
["serial-no-permission", "no permissions"],
|
||||
]);
|
||||
expect(unparsedLines).toEqual([
|
||||
"serial-bad-device deviceXYZ ",
|
||||
"serial-bad-offline offline-ish",
|
||||
"serial-bad-auth unauthorizedXYZ",
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns unrecognized lines instead of dropping them", () => {
|
||||
const output = [
|
||||
"List of devices attached",
|
||||
@@ -212,10 +194,10 @@ describe("parsePackageListOutput", () => {
|
||||
|
||||
it("keeps unrecognized lines for partial coverage reporting", () => {
|
||||
const { packages, unparsedLines } = parsePackageListOutput(
|
||||
"package:/data/app/x/base.apk=com.ok\n garbage line \n",
|
||||
"package:/data/app/x/base.apk=com.ok\ngarbage line\n",
|
||||
);
|
||||
expect(packages).toHaveLength(1);
|
||||
expect(unparsedLines).toEqual([" garbage line "]);
|
||||
expect(unparsedLines).toEqual(["garbage line"]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+25
-14
@@ -10,15 +10,11 @@ import {
|
||||
adbHostFileName,
|
||||
type AdbHostFileNameReason,
|
||||
} from "./AdbHostFileName.js";
|
||||
import {
|
||||
ADB_DEVICE_STATES,
|
||||
type AdbDeviceState,
|
||||
} from "../domain/adb/adbDeviceAnalysis.js";
|
||||
|
||||
/** One device exactly as `adb devices -l` reports it. */
|
||||
export interface AdbDeviceEntry {
|
||||
readonly serial: string;
|
||||
readonly state: AdbDeviceState;
|
||||
readonly state: string;
|
||||
readonly transport: "usb" | "tcp" | "unknown";
|
||||
readonly product: string | null;
|
||||
readonly model: string | null;
|
||||
@@ -28,6 +24,25 @@ export interface AdbDeviceEntry {
|
||||
readonly kind_basis: "emulator_serial_prefix" | "usb_transport" | "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* Device states adb prints after the serial, longest first so two-word
|
||||
* states match before their single-word prefixes. A line whose remainder
|
||||
* starts with none of them is not a device line.
|
||||
*/
|
||||
const DEVICE_STATES = [
|
||||
"no permissions",
|
||||
"unauthorized",
|
||||
"authorizing",
|
||||
"offline",
|
||||
"recovery",
|
||||
"sideload",
|
||||
"connecting",
|
||||
"bootloader",
|
||||
"device",
|
||||
"unknown",
|
||||
"host",
|
||||
] as const;
|
||||
|
||||
const DEVICE_LINE = /^(\S+)\s+(.*)$/u;
|
||||
|
||||
const metadataValue = (remainder: string, key: string): string | null => {
|
||||
@@ -58,15 +73,11 @@ export const parseAdbDevicesOutput = (
|
||||
continue;
|
||||
}
|
||||
const match = DEVICE_LINE.exec(line);
|
||||
const state = ADB_DEVICE_STATES.find((candidate) => {
|
||||
const remainder = match?.[2];
|
||||
if (remainder === undefined || !remainder.startsWith(candidate))
|
||||
return false;
|
||||
const next = remainder[candidate.length];
|
||||
return next === undefined || /\s/u.test(next);
|
||||
});
|
||||
const state = DEVICE_STATES.find((candidate) =>
|
||||
match?.[2]?.startsWith(candidate),
|
||||
);
|
||||
if (match === null || state === undefined) {
|
||||
if (rawLine.trim() !== "") unparsedLines.push(rawLine);
|
||||
if (line.trim() !== "") unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
const serial = match[1]!;
|
||||
@@ -181,7 +192,7 @@ export const parsePackageListOutput = (
|
||||
if (line === "") continue;
|
||||
const match = PACKAGE_LINE.exec(line);
|
||||
if (match === null) {
|
||||
unparsedLines.push(rawLine);
|
||||
unparsedLines.push(line);
|
||||
continue;
|
||||
}
|
||||
packages.push({
|
||||
|
||||
@@ -121,52 +121,6 @@ fi`,
|
||||
]);
|
||||
});
|
||||
|
||||
it("refuses device listings with an invalid state token", async () => {
|
||||
const malformedLine = "serial deviceXYZ ";
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "devices" ]; then
|
||||
printf 'List of devices attached\\n${malformedLine}\\n'
|
||||
exit 0
|
||||
fi`,
|
||||
);
|
||||
const result = await providerOver(binary).execute({
|
||||
operation: "list_adb_devices",
|
||||
input: {},
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error._tag).toBe("AnalysisProtocolError");
|
||||
expect(result.error.message).toContain(malformedLine);
|
||||
});
|
||||
|
||||
it("lists rescue and detached transports alongside online devices", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
if [ "$1" = "devices" ]; then
|
||||
printf 'List of devices attached\\n'
|
||||
printf 'serial-online device transport_id:1\\n'
|
||||
printf 'serial-rescue rescue transport_id:2\\n'
|
||||
printf 'serial-detached detached transport_id:3\\n'
|
||||
exit 0
|
||||
fi`,
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "list_adb_devices",
|
||||
input: {},
|
||||
});
|
||||
expect(result.devices).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ serial: "serial-online", state: "device" }),
|
||||
expect.objectContaining({ serial: "serial-rescue", state: "rescue" }),
|
||||
expect.objectContaining({
|
||||
serial: "serial-detached",
|
||||
state: "detached",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("inspects a device through the getprop whitelist", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
() => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi
|
||||
@@ -626,34 +580,6 @@ it("projects package details from dumpsys package output", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Android 10 and 11 append ": restricted=true" to hard- and soft-restricted
|
||||
// entries of the requested-permissions list (Settings.dumpPackageLPr).
|
||||
it("counts requested permissions that the device marks as restricted", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({
|
||||
"dumpsys:package": `Packages:
|
||||
Package [com.example] (abcdef):
|
||||
userId=10234
|
||||
versionName=1.2.3
|
||||
requested permissions:
|
||||
android.permission.INTERNET
|
||||
android.permission.WRITE_EXTERNAL_STORAGE: restricted=true
|
||||
android.permission.CAMERA
|
||||
install permissions:
|
||||
android.permission.INTERNET: granted=true
|
||||
`,
|
||||
}),
|
||||
);
|
||||
const result = await evidenceResult(providerOver(binary), {
|
||||
operation: "inspect_adb_package",
|
||||
input: { serial: "emulator-5554", package: "com.example" },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
requested_permissions_count: 3,
|
||||
coverage: "complete",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports an uninstalled package from dumpsys refusal output", async () => {
|
||||
const { binary } = await writeAdbStub(
|
||||
shellStub({ "dumpsys:package": "Unable to find package: com.absent\n" }),
|
||||
|
||||
@@ -236,11 +236,7 @@ export const parseDumpsysPackageOutput = (
|
||||
inPermissions = true;
|
||||
continue;
|
||||
}
|
||||
// Android 10 and 11 mark restricted entries as "NAME: restricted=true".
|
||||
if (
|
||||
inPermissions &&
|
||||
/^\s{2,}[A-Za-z0-9._]+(?:: restricted=true)?$/u.test(line)
|
||||
) {
|
||||
if (inPermissions && /^\s{2,}[A-Za-z0-9._]+$/.test(line)) {
|
||||
permissions += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -199,11 +199,9 @@ export class JadxMcpTransport implements Transport {
|
||||
throw new Error(`JADX MCP frame exceeds ${MAX_FRAME_BYTES} bytes`);
|
||||
this.#appendFrame(fragment, frameBytes);
|
||||
if (newline === -1) return;
|
||||
const line = new TextDecoder("utf-8", {
|
||||
fatal: true,
|
||||
// Preserve a leading BOM so the JSON-RPC parser can reject it.
|
||||
ignoreBOM: true,
|
||||
}).decode(this.#frameBuffer.subarray(0, this.#frameLength));
|
||||
const line = this.#frameBuffer
|
||||
.subarray(0, this.#frameLength)
|
||||
.toString("utf8");
|
||||
this.#frameBuffer = Buffer.alloc(0);
|
||||
this.#frameLength = 0;
|
||||
this.onmessage?.(deserializeMessage(line));
|
||||
|
||||
@@ -397,7 +397,7 @@ const workflowAvailabilityFor = ({
|
||||
remediation:
|
||||
"On Linux x64, set absolute REA_PWNTOOLS_PYTHON to caller-supplied Python with pwntools 4.15.0. No active binary target is required.",
|
||||
};
|
||||
if (name === "inspect_packet_capture" || name === "inspect_packet_fields")
|
||||
if (name === "inspect_packet_capture")
|
||||
return policy.packetCaptureEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
@@ -405,7 +405,7 @@ const workflowAvailabilityFor = ({
|
||||
remediation:
|
||||
"On Linux, supply TShark 4.x via absolute REA_TSHARK_COMMAND and util-linux prlimit (REA_TSHARK_PRLIMIT_COMMAND, default /usr/bin/prlimit). No active binary target or hardware is required; the tool is checked at execution.",
|
||||
};
|
||||
if (name === "decode_signal_recording" || name === "inspect_signal_decoders")
|
||||
if (name === "decode_signal_recording")
|
||||
return policy.signalRecordingEnabled === true
|
||||
? { reason: "available", remediation: null }
|
||||
: {
|
||||
|
||||
@@ -2,16 +2,12 @@ import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
installMacHopper,
|
||||
type MacHopperBundleVerification,
|
||||
type MacHopperInstallHost,
|
||||
} from "./MacHopper.js";
|
||||
import { installMacHopper, type MacHopperInstallHost } from "./MacHopper.js";
|
||||
|
||||
class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
readonly archive = new TextEncoder().encode("hopper-dmg");
|
||||
archiveOk = true;
|
||||
verification: MacHopperBundleVerification = "verified";
|
||||
valid = true;
|
||||
existing = false;
|
||||
mountSucceeds = true;
|
||||
copySucceeds = true;
|
||||
@@ -19,7 +15,6 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
badHash = false;
|
||||
unmounts = 0;
|
||||
cleanups = 0;
|
||||
installs = 0;
|
||||
opens = 0;
|
||||
replaces = false;
|
||||
|
||||
@@ -52,7 +47,7 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
return Promise.resolve();
|
||||
};
|
||||
appBundle = () => Promise.resolve("/mounted/Hopper Disassembler.app");
|
||||
validBundle = () => Promise.resolve(this.verification);
|
||||
validBundle = () => Promise.resolve(this.valid);
|
||||
destinationExists = () => Promise.resolve(this.existing);
|
||||
installBundle = (
|
||||
_source: string,
|
||||
@@ -60,7 +55,6 @@ class FakeMacHopperHost implements MacHopperInstallHost {
|
||||
_stage: string,
|
||||
replaceExisting: boolean,
|
||||
) => {
|
||||
this.installs += 1;
|
||||
this.replaces = replaceExisting;
|
||||
return Promise.resolve(this.copySucceeds);
|
||||
};
|
||||
@@ -121,7 +115,7 @@ describe("macOS Hopper installation", () => {
|
||||
|
||||
it("cleans and detaches after bundle validation fails", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.verification = "invalid_signature";
|
||||
host.valid = false;
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "bundle",
|
||||
@@ -129,17 +123,4 @@ describe("macOS Hopper installation", () => {
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
|
||||
it("reports a publisher mismatch without copying or launching the bundle", async () => {
|
||||
const host = new FakeMacHopperHost();
|
||||
host.verification = "unverified_publisher";
|
||||
await expect(installMacHopper({}, host)).resolves.toEqual({
|
||||
status: "failed",
|
||||
reason: "publisher_verification_failed",
|
||||
});
|
||||
expect(host.installs).toBe(0);
|
||||
expect(host.opens).toBe(0);
|
||||
expect(host.unmounts).toBe(1);
|
||||
expect(host.cleanups).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -24,35 +24,7 @@ const execFileAsync = promisify(execFile);
|
||||
const RELEASES_URL =
|
||||
"https://www.hopperapp.com/include/files-api.php?request=releases&public=true";
|
||||
const DOWNLOAD_PREFIX = "https://www.hopperapp.com:443/downloader/public/";
|
||||
|
||||
/**
|
||||
* Apple publisher identity pinned for the official Hopper macOS bundle. The
|
||||
* team identifier was captured from `Hopper-6.6.0-demo.dmg` at
|
||||
* `https://www.hopperapp.com:443/downloader/public/Hopper-6.6.0-demo.dmg`
|
||||
* (34846271 bytes, SHA-1 0be530f038249742590992199c7b042ea20ca955) with
|
||||
* `codesign -dvvv`, which reported
|
||||
* `Authority=Developer ID Application: Cryptic Apps (2AMA2753NF)`.
|
||||
*/
|
||||
export const HOPPER_PUBLISHER = Object.freeze({
|
||||
bundleIdentifier: "com.cryptic-apps.hopper-web-4",
|
||||
teamIdentifier: "2AMA2753NF",
|
||||
});
|
||||
|
||||
/**
|
||||
* Code requirement enforcing the bundle identifier and signing team together.
|
||||
* The identifier is read from the sealed CodeDirectory, so it cannot be changed
|
||||
* by editing `Info.plist` the way the previous string comparison could.
|
||||
*/
|
||||
const HOPPER_PUBLISHER_REQUIREMENT =
|
||||
`= identifier "${HOPPER_PUBLISHER.bundleIdentifier}"` +
|
||||
` and anchor apple generic` +
|
||||
` and certificate leaf[subject.OU] = "${HOPPER_PUBLISHER.teamIdentifier}"`;
|
||||
|
||||
/** Outcome of reading a mounted bundle's signature and publisher identity. */
|
||||
export type MacHopperBundleVerification =
|
||||
| "verified"
|
||||
| "invalid_signature"
|
||||
| "unverified_publisher";
|
||||
const BUNDLE_IDENTIFIER = "com.cryptic-apps.hopper-web-4";
|
||||
|
||||
/** Stable network and command effects disclosed before macOS Hopper setup. */
|
||||
export const macHopperInstallDisclosure = {
|
||||
@@ -60,7 +32,6 @@ export const macHopperInstallDisclosure = {
|
||||
commands: [
|
||||
"hdiutil attach -readonly -nobrowse -mountpoint <private-mount> <verified-hopper.dmg>",
|
||||
"codesign --verify --deep --strict <mounted-hopper.app>",
|
||||
`codesign --verify --strict '-R${HOPPER_PUBLISHER_REQUIREMENT}' <mounted-hopper.app>`,
|
||||
"ditto <mounted-hopper.app> <user-Applications-stage>",
|
||||
"open <installed-hopper.app>",
|
||||
] as const,
|
||||
@@ -81,7 +52,6 @@ export type MacHopperInstallResult =
|
||||
| "integrity"
|
||||
| "mount"
|
||||
| "bundle"
|
||||
| "publisher_verification_failed"
|
||||
| "destination_exists"
|
||||
| "copy"
|
||||
| "launcher_missing";
|
||||
@@ -99,7 +69,7 @@ export interface MacHopperInstallHost {
|
||||
mount(packagePath: string, mountPath: string): Promise<boolean>;
|
||||
unmount(mountPath: string): Promise<void>;
|
||||
appBundle(mountPath: string): Promise<string | undefined>;
|
||||
validBundle(appPath: string): Promise<MacHopperBundleVerification>;
|
||||
validBundle(appPath: string): Promise<boolean>;
|
||||
destinationExists(path: string): Promise<boolean>;
|
||||
installBundle(
|
||||
source: string,
|
||||
@@ -154,12 +124,8 @@ export const installMacHopper = async (
|
||||
return { status: "failed", reason: "mount" };
|
||||
mounted = true;
|
||||
const source = await host.appBundle(mountPath);
|
||||
if (source === undefined) return { status: "failed", reason: "bundle" };
|
||||
const verification = await host.validBundle(source);
|
||||
if (verification === "invalid_signature")
|
||||
if (source === undefined || !(await host.validBundle(source)))
|
||||
return { status: "failed", reason: "bundle" };
|
||||
if (verification === "unverified_publisher")
|
||||
return { status: "failed", reason: "publisher_verification_failed" };
|
||||
const stage = `${destination}.rea-stage`;
|
||||
if (
|
||||
!(await host.installBundle(
|
||||
@@ -256,21 +222,25 @@ export const systemMacHopperInstallHost = (
|
||||
environment,
|
||||
))
|
||||
)
|
||||
return "invalid_signature";
|
||||
if (
|
||||
!(await commandSucceeds(
|
||||
"codesign",
|
||||
[
|
||||
"--verify",
|
||||
"--strict",
|
||||
`-R${HOPPER_PUBLISHER_REQUIREMENT}`,
|
||||
appPath,
|
||||
],
|
||||
environment,
|
||||
))
|
||||
)
|
||||
return "unverified_publisher";
|
||||
return "verified";
|
||||
return false;
|
||||
try {
|
||||
const identifier = (
|
||||
await execFileAsync(
|
||||
"/usr/libexec/PlistBuddy",
|
||||
[
|
||||
"-c",
|
||||
"Print :CFBundleIdentifier",
|
||||
join(appPath, "Contents/Info.plist"),
|
||||
],
|
||||
{ env: environment },
|
||||
)
|
||||
).stdout.trim();
|
||||
return identifier === BUNDLE_IDENTIFIER;
|
||||
} catch (cause: unknown) {
|
||||
// best-effort cleanup: optional bundle probing; unreadable means invalid.
|
||||
void cause;
|
||||
return false;
|
||||
}
|
||||
},
|
||||
async destinationExists(path) {
|
||||
try {
|
||||
|
||||
@@ -12,14 +12,12 @@ import {
|
||||
detectReferenceSourceLanguage,
|
||||
} from "../domain/referenceSourceClassification.js";
|
||||
import type { HistoricalSourceGraphInput } from "../domain/referenceSourceGraph.js";
|
||||
import {
|
||||
parseReferenceSourceImports,
|
||||
PARSEABLE_REFERENCE_SOURCE_LANGUAGES,
|
||||
} from "../domain/referenceSourceImportParsing.js";
|
||||
import { parseReferenceSourceImports } from "../domain/referenceSourceImportParsing.js";
|
||||
import type {
|
||||
ReferenceSourceEntry,
|
||||
ReferenceSourceRead,
|
||||
} from "../reference/ReferenceSourceReaderTypes.js";
|
||||
import { PARSEABLE_REFERENCE_SOURCE_LANGUAGES } from "./ReferenceSourceImportTypes.js";
|
||||
import { typescriptEmittedSourceCandidates } from "./TypeScriptEmittedSourceCandidates.js";
|
||||
|
||||
export interface ParsedReferenceSourceEntries {
|
||||
|
||||
@@ -87,3 +87,6 @@ export const DEFAULT_REFERENCE_SOURCE_IGNORE_PATTERNS = [
|
||||
".coverage",
|
||||
"*.log",
|
||||
] as const;
|
||||
|
||||
export const PARSEABLE_REFERENCE_SOURCE_LANGUAGES: ReadonlySet<string> =
|
||||
new Set(["JavaScript", "TypeScript", "JSX", "TSX"]);
|
||||
|
||||
@@ -19,17 +19,6 @@ export interface RegularFileReadOptions {
|
||||
readonly resources?: ArtifactResourceScope;
|
||||
}
|
||||
|
||||
export class InvalidUtf8FileError extends TypeError {
|
||||
readonly _tag = "InvalidUtf8FileError";
|
||||
constructor(
|
||||
readonly path: string,
|
||||
cause: unknown,
|
||||
) {
|
||||
super(`File is not valid UTF-8: ${path}`, { cause });
|
||||
this.name = this._tag;
|
||||
}
|
||||
}
|
||||
|
||||
export type RegularFileReadOutcome<Value> =
|
||||
| { readonly kind: "completed"; readonly value: Value }
|
||||
| { readonly kind: "failed"; readonly cause: unknown };
|
||||
@@ -153,34 +142,7 @@ const withRegularFileOwned = async <Value>(
|
||||
export const readRegularFile = (
|
||||
path: string,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<Buffer> => readRegularFileContent(path, (bytes) => bytes, options);
|
||||
|
||||
/** Read valid UTF-8 without replacing source bytes or stripping an initial BOM. */
|
||||
export const readRegularFileText = (
|
||||
path: string,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<string> =>
|
||||
readRegularFileContent(
|
||||
path,
|
||||
(bytes) => {
|
||||
try {
|
||||
return new TextDecoder("utf-8", {
|
||||
fatal: true,
|
||||
ignoreBOM: true,
|
||||
}).decode(bytes);
|
||||
} catch (cause: unknown) {
|
||||
if (!(cause instanceof TypeError)) throw cause;
|
||||
throw new InvalidUtf8FileError(path, cause);
|
||||
}
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
const readRegularFileContent = <Value>(
|
||||
path: string,
|
||||
decode: (bytes: Buffer) => Value,
|
||||
options: RegularFileReadOptions,
|
||||
): Promise<Value> =>
|
||||
): Promise<Buffer> =>
|
||||
withRegularFile(
|
||||
path,
|
||||
async (handle, stats) => {
|
||||
@@ -191,7 +153,30 @@ const readRegularFileContent = <Value>(
|
||||
);
|
||||
if (bytes === undefined || bytes.length !== stats.size)
|
||||
throw new RegularFileChangedError(path);
|
||||
return decode(bytes);
|
||||
return bytes;
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
/** Read one admitted regular file as UTF-8 without waiting on a pipe. */
|
||||
export const readRegularFileText = async (
|
||||
path: string,
|
||||
options: RegularFileReadOptions = {},
|
||||
): Promise<string> => {
|
||||
try {
|
||||
return (await readRegularFile(path, options)).toString("utf8");
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof RegularFileCleanupFailure &&
|
||||
cause.outcome.kind === "completed" &&
|
||||
Buffer.isBuffer(cause.outcome.value)
|
||||
)
|
||||
throw new RegularFileCleanupFailure(
|
||||
cause.path,
|
||||
cause.owner,
|
||||
{ kind: "completed", value: cause.outcome.value.toString("utf8") },
|
||||
cause.cleanupCause,
|
||||
);
|
||||
throw cause;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -54,40 +54,6 @@ describe("setup workflow", () => {
|
||||
expect(result.remediation).toContain("could not be updated");
|
||||
});
|
||||
|
||||
it("reports a failed config rollback with its destination and recovery backup", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [{ name: "codex", configPath: "/fixture/codex.json" }];
|
||||
host.clientResults.set("codex", {
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: "/fixture/codex.json.rea.backup",
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path: "/fixture/codex.json",
|
||||
detail: "permission denied",
|
||||
},
|
||||
});
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(true), clientIds: ["codex"] },
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result.clients.codex).toEqual({
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
backupPath: "/fixture/codex.json.rea.backup",
|
||||
failure: {
|
||||
kind: "restore",
|
||||
path: "/fixture/codex.json",
|
||||
detail: "permission denied",
|
||||
},
|
||||
});
|
||||
expect(result.remediation).toContain("permission denied");
|
||||
expect(result.remediation).toContain("/fixture/codex.json.rea.backup");
|
||||
});
|
||||
|
||||
it("explains skill installation recovery", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import { dshDocument, DshCordisDocument } from "./DshCordisPatch.js";
|
||||
import { constants as fsConstants } from "node:fs";
|
||||
import { createHash } from "node:crypto";
|
||||
import { copyFile, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { dirname } from "node:path";
|
||||
import writeFileAtomic from "write-file-atomic";
|
||||
@@ -30,7 +29,6 @@ import { npxRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import {
|
||||
readRegularFile,
|
||||
readRegularFileText,
|
||||
RegularFileCleanupFailure,
|
||||
} from "./RegularFileRead.js";
|
||||
@@ -42,26 +40,6 @@ import type {
|
||||
} from "./SetupTypes.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
export class ClientConfigurationCleanupRollbackFailure extends RegularFileCleanupFailure<string> {
|
||||
constructor(
|
||||
failure: RegularFileCleanupFailure<string>,
|
||||
readonly configurationFailure: Extract<
|
||||
ClientConfigurationResult,
|
||||
{ readonly status: "failed"; readonly reason: "rollback" }
|
||||
>,
|
||||
) {
|
||||
super(
|
||||
failure.path,
|
||||
failure.owner,
|
||||
failure.outcome,
|
||||
new AggregateError(
|
||||
[failure.cleanupCause, new Error(configurationFailure.failure.detail)],
|
||||
`Configuration readback cleanup and rollback failed: ${configurationFailure.failure.path}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Configure one supported client's native stdio MCP registration shape. */
|
||||
export const configureClientConfiguration = (
|
||||
client: SetupClient,
|
||||
@@ -189,23 +167,11 @@ const persistClientConfiguration = async ({
|
||||
}: ClientConfigurationUpdate): Promise<ClientConfigurationResult> => {
|
||||
const backupPath =
|
||||
original === undefined ? undefined : `${client.configPath}.rea.backup`;
|
||||
let recoveryBackupPath: string | undefined;
|
||||
if (backupPath !== undefined && original !== undefined) {
|
||||
const selection = await selectCurrentRecoveryBackup(backupPath, original);
|
||||
if (!selection.ok) return { status: "failed", reason: "backup" };
|
||||
if (
|
||||
!(await preserveConfigBackup(transactionPath, selection.value.backupPath))
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
const verified = await selectCurrentRecoveryBackup(backupPath, original);
|
||||
if (
|
||||
!verified.ok ||
|
||||
verified.value.backupPath !== selection.value.backupPath ||
|
||||
!verified.value.present
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
recoveryBackupPath = verified.value.backupPath;
|
||||
}
|
||||
if (
|
||||
backupPath !== undefined &&
|
||||
!(await preserveConfigBackup(transactionPath, backupPath))
|
||||
)
|
||||
return { status: "failed", reason: "backup" };
|
||||
// A native OpenCode V2 entry replaces REA's legacy V1 entry, which would
|
||||
// otherwise conflict with it.
|
||||
const legacyPath = legacyClientServerPath(
|
||||
@@ -273,39 +239,19 @@ const persistClientConfiguration = async ({
|
||||
!clientConfigurationValuesEqual(readback.servers[name], entry),
|
||||
)
|
||||
) {
|
||||
return rollbackOrReadbackFailure(
|
||||
transactionPath,
|
||||
original,
|
||||
recoveryBackupPath,
|
||||
);
|
||||
await restoreConfig(transactionPath, original);
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) {
|
||||
const rollback = await restoreConfig(transactionPath, original);
|
||||
if (!rollback.ok)
|
||||
throw new ClientConfigurationCleanupRollbackFailure(cause, {
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
...(recoveryBackupPath === undefined
|
||||
? {}
|
||||
: { backupPath: recoveryBackupPath }),
|
||||
failure: rollback.error,
|
||||
});
|
||||
throw cause;
|
||||
}
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
// Readback failure restores the transaction before reporting.
|
||||
void cause;
|
||||
return rollbackOrReadbackFailure(
|
||||
transactionPath,
|
||||
original,
|
||||
recoveryBackupPath,
|
||||
);
|
||||
await restoreConfig(transactionPath, original);
|
||||
return { status: "failed", reason: "readback" };
|
||||
}
|
||||
return {
|
||||
status: "configured",
|
||||
...(recoveryBackupPath === undefined
|
||||
? {}
|
||||
: { backupPath: recoveryBackupPath }),
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -460,18 +406,9 @@ export const inspectClientConfiguration = async (
|
||||
"The existing configuration is malformed. Repair it before setup applies any other changes.",
|
||||
};
|
||||
}
|
||||
const backupSelection = await selectCurrentRecoveryBackup(
|
||||
`${client.configPath}.rea.backup`,
|
||||
original,
|
||||
);
|
||||
if (!backupSelection.ok)
|
||||
return {
|
||||
status: "invalid",
|
||||
remediation: backupSelection.error.detail,
|
||||
};
|
||||
return {
|
||||
status: "update",
|
||||
backupPath: backupSelection.value.backupPath,
|
||||
backupPath: `${client.configPath}.rea.backup`,
|
||||
};
|
||||
};
|
||||
|
||||
@@ -536,101 +473,19 @@ const preserveConfigBackup = async (
|
||||
}
|
||||
};
|
||||
|
||||
interface RecoveryBackupSelection {
|
||||
readonly backupPath: string;
|
||||
readonly present: boolean;
|
||||
}
|
||||
|
||||
interface RecoveryBackupSelectionFailure {
|
||||
readonly kind: "unreadable" | "occupied";
|
||||
readonly path: string;
|
||||
readonly detail: string;
|
||||
}
|
||||
|
||||
const selectCurrentRecoveryBackup = async (
|
||||
firstBackupPath: string,
|
||||
original: string,
|
||||
): Promise<Result<RecoveryBackupSelection, RecoveryBackupSelectionFailure>> => {
|
||||
const expected = Buffer.from(original, "utf8");
|
||||
let firstBackup: Buffer | undefined;
|
||||
try {
|
||||
firstBackup = await readRegularFile(firstBackupPath, {
|
||||
symlinks: "reject",
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (!isMissing(cause))
|
||||
return err({
|
||||
kind: "unreadable",
|
||||
path: firstBackupPath,
|
||||
detail: `The recovery backup could not be checked: ${errorDetail(cause)}`,
|
||||
});
|
||||
}
|
||||
if (firstBackup === undefined)
|
||||
return ok({ backupPath: firstBackupPath, present: false });
|
||||
if (firstBackup.equals(expected))
|
||||
return ok({ backupPath: firstBackupPath, present: true });
|
||||
|
||||
const digest = createHash("sha256").update(original, "utf8").digest("hex");
|
||||
const recoveryPath = `${firstBackupPath}.${digest}.recovery`;
|
||||
let recovery: Buffer | undefined;
|
||||
try {
|
||||
recovery = await readRegularFile(recoveryPath, { symlinks: "reject" });
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof RegularFileCleanupFailure) throw cause;
|
||||
if (!isMissing(cause))
|
||||
return err({
|
||||
kind: "unreadable",
|
||||
path: recoveryPath,
|
||||
detail: `The recovery backup could not be checked: ${errorDetail(cause)}`,
|
||||
});
|
||||
}
|
||||
if (recovery !== undefined && !recovery.equals(expected))
|
||||
return err({
|
||||
kind: "occupied",
|
||||
path: recoveryPath,
|
||||
detail: `The recovery path already contains different data: ${recoveryPath}`,
|
||||
});
|
||||
return ok({ backupPath: recoveryPath, present: recovery !== undefined });
|
||||
};
|
||||
|
||||
const restoreConfig = async (
|
||||
path: string,
|
||||
original: string | undefined,
|
||||
): Promise<
|
||||
Result<
|
||||
void,
|
||||
{ readonly kind: "restore"; readonly path: string; readonly detail: string }
|
||||
>
|
||||
> => {
|
||||
): Promise<void> => {
|
||||
try {
|
||||
if (original === undefined) await rm(path, { force: true });
|
||||
else await writeFile(path, original, { encoding: "utf8", mode: 0o600 });
|
||||
return ok(undefined);
|
||||
} catch (cause: unknown) {
|
||||
return err({ kind: "restore", path, detail: errorDetail(cause) });
|
||||
// The backup remains available for the remediation reported by setup.
|
||||
void cause;
|
||||
}
|
||||
};
|
||||
|
||||
const rollbackOrReadbackFailure = async (
|
||||
targetPath: string,
|
||||
original: string | undefined,
|
||||
backupPath: string | undefined,
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
const rollback = await restoreConfig(targetPath, original);
|
||||
return rollback.ok
|
||||
? { status: "failed", reason: "readback" }
|
||||
: {
|
||||
status: "failed",
|
||||
reason: "rollback",
|
||||
...(backupPath === undefined ? {} : { backupPath }),
|
||||
failure: rollback.error,
|
||||
};
|
||||
};
|
||||
|
||||
const errorDetail = (cause: unknown): string =>
|
||||
cause instanceof Error ? cause.message : String(cause);
|
||||
|
||||
/** Whether REA's entry matches, no legacy entry remains, and no client disable list suppresses it. */
|
||||
const registrationCurrent = (
|
||||
parsed: ClientConfigurationDocument,
|
||||
|
||||
@@ -6,19 +6,15 @@ import type {
|
||||
} from "./SetupTypes.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
|
||||
export const failedConfigurationMessage = (
|
||||
result: Extract<ClientConfigurationResult, { readonly status: "failed" }>,
|
||||
const failedConfigurationMessage = (
|
||||
reason: "path" | "backup" | "write" | "readback",
|
||||
): string => {
|
||||
if (result.reason === "path")
|
||||
if (reason === "path")
|
||||
return "Agent configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun setup.";
|
||||
if (result.reason === "backup")
|
||||
if (reason === "backup")
|
||||
return "Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.";
|
||||
if (result.reason === "write")
|
||||
if (reason === "write")
|
||||
return "Agent configuration could not be updated. Check file permissions, then rerun setup.";
|
||||
if (result.reason === "rollback")
|
||||
return result.backupPath === undefined
|
||||
? `Agent configuration rollback failed at ${result.failure.path}: ${result.failure.detail}; the failed first-run file may remain. Remove or repair it before rerunning setup.`
|
||||
: `Agent configuration rollback failed at ${result.failure.path}: ${result.failure.detail}. Inspect the preserved backup at ${result.backupPath} and restore the intended configuration, then rerun setup.`;
|
||||
return "Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.";
|
||||
};
|
||||
|
||||
@@ -44,12 +40,12 @@ export const configureDetectedClients = async (options: {
|
||||
);
|
||||
options.clients[client.name] = result;
|
||||
if (result.status === "failed") {
|
||||
failure ??= failedConfigurationMessage(result);
|
||||
failure ??= failedConfigurationMessage(result.reason);
|
||||
options.onProgress?.({
|
||||
actionId,
|
||||
label,
|
||||
state: "failed",
|
||||
detail: failedConfigurationMessage(result),
|
||||
detail: failedConfigurationMessage(result.reason),
|
||||
});
|
||||
} else if (result.status === "configured") {
|
||||
options.appliedActions.push(`configured_${client.name}`);
|
||||
|
||||
@@ -33,11 +33,9 @@ import {
|
||||
} from "./SetupSkill.js";
|
||||
import {
|
||||
clientConfigurationAligned,
|
||||
ClientConfigurationCleanupRollbackFailure,
|
||||
configureClientConfiguration,
|
||||
inspectClientConfiguration,
|
||||
} from "./SetupClientConfiguration.js";
|
||||
import { failedConfigurationMessage } from "./SetupClients.js";
|
||||
import { setupInstallFailure } from "./SetupInstallFailure.js";
|
||||
import {
|
||||
RegularFileCleanupFailure,
|
||||
@@ -277,12 +275,8 @@ const runClientConfigurationOperation = async <Value>(
|
||||
cleanup.outcome.kind === "failed"
|
||||
? cleanup.outcome.cause
|
||||
: cause.cleanupCause;
|
||||
const rollbackMessage =
|
||||
cause instanceof ClientConfigurationCleanupRollbackFailure
|
||||
? ` ${failedConfigurationMessage(cause.configurationFailure)}`
|
||||
: "";
|
||||
throw configurationCleanupError(
|
||||
`Could not safely access client configuration at ${cause.path}: ${errorMessage(primary)}.${rollbackMessage}`,
|
||||
`Could not safely access client configuration at ${cause.path}: ${errorMessage(primary)}`,
|
||||
cause,
|
||||
cleanup.cleanup,
|
||||
);
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { HOPPER_PUBLISHER } from "./MacHopper.js";
|
||||
import { setupInstallFailure } from "./SetupInstallFailure.js";
|
||||
|
||||
describe("macOS Hopper setup failure projection", () => {
|
||||
it("projects a publisher mismatch onto its own code and recovery", () => {
|
||||
expect(setupInstallFailure("publisher_verification_failed")).toEqual({
|
||||
status: "failed",
|
||||
code: "publisher_verification_failed",
|
||||
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a broken bundle distinct from a publisher mismatch", () => {
|
||||
expect(setupInstallFailure("bundle")).toEqual({
|
||||
status: "failed",
|
||||
code: "bundle_invalid",
|
||||
remediation:
|
||||
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import { HOPPER_PUBLISHER } from "./MacHopper.js";
|
||||
|
||||
export type SetupFailureCode =
|
||||
| "unsupported_host"
|
||||
| "download_failed"
|
||||
@@ -12,7 +10,6 @@ export type SetupFailureCode =
|
||||
| "destination_exists"
|
||||
| "mount_failed"
|
||||
| "bundle_invalid"
|
||||
| "publisher_verification_failed"
|
||||
| "copy_failed"
|
||||
| "skill_install_failed"
|
||||
| "cleanup_failed";
|
||||
@@ -42,7 +39,6 @@ export type HopperInstallFailureReason =
|
||||
| "destination_exists"
|
||||
| "mount"
|
||||
| "bundle"
|
||||
| "publisher_verification_failed"
|
||||
| "copy";
|
||||
|
||||
/** Map provider installer failures to stable setup codes and safe recovery. */
|
||||
@@ -119,12 +115,6 @@ export const setupInstallFailure = (
|
||||
remediation:
|
||||
"The mounted package did not contain the expected Hopper application bundle. Retry setup; if it repeats, update REA before installing.",
|
||||
};
|
||||
case "publisher_verification_failed":
|
||||
return {
|
||||
status: "failed",
|
||||
code: "publisher_verification_failed",
|
||||
remediation: `The mounted Hopper application is not signed by the publisher REA pins (${HOPPER_PUBLISHER.bundleIdentifier}, Apple team ${HOPPER_PUBLISHER.teamIdentifier}); nothing was copied or launched. Install Hopper yourself and set HOPPER_LAUNCHER_PATH to its launcher, then rerun rea setup.`,
|
||||
};
|
||||
case "copy":
|
||||
return {
|
||||
status: "failed",
|
||||
|
||||
@@ -320,5 +320,5 @@ const clientConfigurationDetail = (
|
||||
? " If this plan installs Hopper, REA will add HOPPER_LAUNCHER_PATH using the launcher path reported by that installation."
|
||||
: " The HOPPER_LAUNCHER_PATH value shown above is the current fallback; if this plan installs Hopper, REA will replace it with the launcher path reported by that installation."
|
||||
: "";
|
||||
return `Add the REA MCP registration for ${client}; preserve unrelated configuration. The backup path reflects the configuration inspected for this plan; if that file changes before execution, setup will select a recovery path for its current contents. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}`;
|
||||
return `Add the REA MCP registration for ${client}; preserve unrelated configuration. Command: ${command.map((part) => JSON.stringify(part)).join(" ")}.${environmentDetail}${hopperDetail}`;
|
||||
};
|
||||
|
||||
@@ -26,16 +26,6 @@ export type ClientConfigurationResult =
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly reason: "path" | "backup" | "write" | "readback";
|
||||
}
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly reason: "rollback";
|
||||
readonly backupPath?: string;
|
||||
readonly failure: {
|
||||
readonly kind: "restore";
|
||||
readonly path: string;
|
||||
readonly detail: string;
|
||||
};
|
||||
};
|
||||
|
||||
/** Read-only state used to block unsafe setup plans before any mutation. */
|
||||
|
||||
@@ -25,11 +25,7 @@ import {
|
||||
import { isOwnedClientRegistrationCommand } from "./ClientRegistrationIdentity.js";
|
||||
import { dshDocument } from "./DshCordisPatch.js";
|
||||
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
||||
import {
|
||||
InvalidUtf8FileError,
|
||||
RegularFileCleanupFailure,
|
||||
readRegularFileText,
|
||||
} from "./RegularFileRead.js";
|
||||
import { readRegularFileText } from "./RegularFileRead.js";
|
||||
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
|
||||
import {
|
||||
manualRegistrationRemediation,
|
||||
@@ -273,17 +269,13 @@ const readClientConfiguration = async (
|
||||
try {
|
||||
original = await fileSystem.readText(transactionPath);
|
||||
} catch (cause: unknown) {
|
||||
const readFailure =
|
||||
cause instanceof RegularFileCleanupFailure ? cause.cause : cause;
|
||||
return itemRead(
|
||||
isMissing(cause)
|
||||
? item(client.name, "skipped", "Configuration does not exist.")
|
||||
: item(
|
||||
client.name,
|
||||
"failed",
|
||||
readFailure instanceof InvalidUtf8FileError
|
||||
? "Configuration is not valid UTF-8 and was not changed. Repair it, then rerun uninstall."
|
||||
: "Configuration could not be read. Check file permissions, then rerun uninstall.",
|
||||
"Configuration could not be read. Check file permissions, then rerun uninstall.",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
import {
|
||||
inspectPacketFieldsInputSchema,
|
||||
packetFieldsCatalogSchema,
|
||||
type InspectPacketFieldsInput,
|
||||
} from "../../domain/captures/packetFields.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
@@ -30,10 +24,6 @@ export interface PacketCapturePort {
|
||||
input: InspectPacketCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
inspectFields(
|
||||
input: InspectPacketFieldsInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -84,58 +74,14 @@ export class PacketCaptureService {
|
||||
"Capture analyzer returned malformed data or changed the selected artifact identity/options.",
|
||||
),
|
||||
);
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
async inspectFields(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "inspect_packet_fields";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = inspectPacketFieldsInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
const decoded = await this.provider.inspectFields(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = packetFieldsCatalogSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data) ||
|
||||
execution.subject?.path !== report.data.tool.path ||
|
||||
execution.subject.sha256 !== report.data.tool.sha256
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Field discovery returned malformed data or changed the selected installation/options.",
|
||||
),
|
||||
);
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
#evidence(
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
options?: ExecutionOptions,
|
||||
): Result<Evidence, AnalysisError> {
|
||||
const evidence = createEvidence(
|
||||
execution.subject ?? undefined,
|
||||
execution.provider,
|
||||
{
|
||||
operation,
|
||||
parameters,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
},
|
||||
);
|
||||
const evidence = createEvidence(execution.subject, execution.provider, {
|
||||
operation,
|
||||
parameters: input.data,
|
||||
result: report.data,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
});
|
||||
return options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
|
||||
@@ -809,42 +809,6 @@ it("keeps an active script message bucket after its last message is evicted", as
|
||||
await manager.closeAll();
|
||||
});
|
||||
|
||||
it("retains the newest contiguous messages across repeated budget evictions", async () => {
|
||||
const { bindings, manager, started } = await startLocalAttachedSession();
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
bindings.device.session.nextPayload = { index: -1 };
|
||||
const loaded = await manager.loadScript(started.value.sessionId, {
|
||||
sourceKind: "inline",
|
||||
source: "send({index: -1});",
|
||||
});
|
||||
expect(loaded.ok).toBe(true);
|
||||
const script = bindings.device.session.scripts[0];
|
||||
expect(script).toBeDefined();
|
||||
if (script === undefined) return;
|
||||
|
||||
// About 500 of these fit the 16 MiB budget, so 2,000 sends evict and
|
||||
// compact the queue several times.
|
||||
const filler = "x".repeat(32_000);
|
||||
for (let index = 0; index < 2_000; index += 1)
|
||||
script.message.emit({ type: "send", payload: { index, filler } }, null);
|
||||
|
||||
const status = manager.status(started.value.sessionId);
|
||||
expect(status?.messagesTruncated).toBe(true);
|
||||
const indexes = (status?.messages ?? []).map(
|
||||
(message) => (message as { payload: { index: number } }).payload.index,
|
||||
);
|
||||
expect(indexes.length).toBeGreaterThan(400);
|
||||
expect(indexes.at(-1)).toBe(1_999);
|
||||
expect(indexes).toEqual(
|
||||
Array.from(
|
||||
{ length: indexes.length },
|
||||
(_, offset) => 2_000 - indexes.length + offset,
|
||||
),
|
||||
);
|
||||
await manager.closeAll();
|
||||
});
|
||||
|
||||
it("serializes a final remote release against a new same-endpoint session", async () => {
|
||||
const bindings = new FakeDeviceManager();
|
||||
let enteredRemoval: (() => void) | undefined;
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
lookupExactPackageImport,
|
||||
} from "../../domain/javascript/javascriptPackageImportAliases.js";
|
||||
import { typescriptEmittedSourceCandidates } from "../TypeScriptEmittedSourceCandidates.js";
|
||||
import { isRelativeJavaScriptModuleSpecifier } from "../../domain/javascript/javascriptModuleSpecifier.js";
|
||||
|
||||
type ArtifactPathResolutionContext =
|
||||
| "package-entrypoint"
|
||||
@@ -167,7 +166,7 @@ const resolvePath = (input: ResolveArtifactPathInput): CandidateResolution => {
|
||||
);
|
||||
const isModuleUrlPath =
|
||||
input.context === "module-specifier" &&
|
||||
(isRelativeJavaScriptModuleSpecifier(input.declaredPath) ||
|
||||
(input.declaredPath.startsWith(".") ||
|
||||
input.declaredPath.startsWith("/") ||
|
||||
fileUrlPath(input.declaredPath) !== undefined);
|
||||
const emittedSourceCandidates =
|
||||
@@ -230,10 +229,7 @@ const contextualCandidate = (
|
||||
return unresolvedCandidate("external", [
|
||||
"URL and Node builtin schemes are outside static artifact module resolution.",
|
||||
]);
|
||||
if (
|
||||
!isRelativeJavaScriptModuleSpecifier(declared) &&
|
||||
!declared.startsWith("/")
|
||||
)
|
||||
if (!declared.startsWith(".") && !declared.startsWith("/"))
|
||||
return bareModuleCandidate(input);
|
||||
if (input.moduleKind !== "require") {
|
||||
const decoded = decodeModuleUrlPath(stripQueryAndFragment(declared));
|
||||
@@ -279,10 +275,7 @@ const contextualCandidate = (
|
||||
"URL",
|
||||
);
|
||||
}
|
||||
const candidate = relativeCandidate(input.sourcePath, declared);
|
||||
return context === "module-specifier" && input.moduleKind === "import"
|
||||
? exactUrlPathCandidate(declared, candidate, "module URL")
|
||||
: candidate;
|
||||
return relativeCandidate(input.sourcePath, declared);
|
||||
};
|
||||
|
||||
const decodeModuleUrlPath = (
|
||||
@@ -317,12 +310,9 @@ const bareModuleCandidate = (
|
||||
return unresolvedCandidate("external", [
|
||||
"The bare specifier is a Node builtin or invalid package name.",
|
||||
]);
|
||||
if (
|
||||
input.moduleKind === "import" &&
|
||||
(request.packageName.startsWith(".") || request.packageName.includes("%"))
|
||||
)
|
||||
if (input.moduleKind === "import" && request.packageName.includes("%"))
|
||||
return unresolvedCandidate("rejected", [
|
||||
"ES module package names cannot start with a dot or contain percent signs.",
|
||||
"Percent signs are not admitted in ES module package names.",
|
||||
]);
|
||||
const self = packageSelfCandidate(input, request);
|
||||
if (self !== null) return self;
|
||||
@@ -745,7 +735,7 @@ const htmlCandidate = (
|
||||
const exactUrlPathCandidate = (
|
||||
declared: string,
|
||||
candidate: string,
|
||||
kind: "HTML" | "URL" | "module URL",
|
||||
kind: "HTML" | "URL",
|
||||
): string | CandidateResolution => {
|
||||
if (!urlPathIsDirectory(declared)) return candidate;
|
||||
const confined = confineCandidate(candidate);
|
||||
|
||||
@@ -81,13 +81,8 @@ export const addJavaScriptSourceModules = (
|
||||
if (asset === undefined || semantic === null || program === undefined)
|
||||
continue;
|
||||
const exports = semantic.ir.moduleLinks
|
||||
.flatMap(({ exportedName, kind }) =>
|
||||
exportedName === null || kind === "type-import" ? [] : [exportedName],
|
||||
)
|
||||
.sort(compareUnicodeCodePoints);
|
||||
const typeExports = semantic.ir.moduleLinks
|
||||
.flatMap(({ exportedName, kind }) =>
|
||||
exportedName === null || kind !== "type-import" ? [] : [exportedName],
|
||||
.flatMap(({ exportedName }) =>
|
||||
exportedName === null ? [] : [exportedName],
|
||||
)
|
||||
.sort(compareUnicodeCodePoints);
|
||||
const retainedExports = [...new Set(exports)];
|
||||
@@ -110,12 +105,8 @@ export const addJavaScriptSourceModules = (
|
||||
import_relationships: semantic.ir.moduleLinks.filter(
|
||||
({ kind }) => kind === "import" || kind === "require",
|
||||
).length,
|
||||
type_relationships: semantic.ir.moduleLinks.filter(
|
||||
({ kind }) => kind === "type-import",
|
||||
).length,
|
||||
export_relationships: exports.length,
|
||||
export_names: retainedExports,
|
||||
type_export_names: [...new Set(typeExports)],
|
||||
omitted_export_names: 0,
|
||||
},
|
||||
evidence: astObservationEvidence({
|
||||
@@ -161,7 +152,6 @@ export function* addJavaScriptModuleRelationshipsSteps(
|
||||
for (const link of semantic.ir.moduleLinks) {
|
||||
// One module can export thousands of bindings, each with return shapes.
|
||||
yield;
|
||||
if (link.kind === "type-import") continue;
|
||||
const input = { context, file, semantic, source, link };
|
||||
if (isExportLink(link)) addExportRelationship(input, omissions);
|
||||
else if (link.specifier !== null)
|
||||
|
||||
@@ -1,9 +1,3 @@
|
||||
import {
|
||||
inspectSignalDecodersInputSchema,
|
||||
signalDecodersSchema,
|
||||
type InspectSignalDecodersInput,
|
||||
} from "../../domain/signals/signalDecoders.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import { isAbsolute } from "node:path";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
@@ -30,10 +24,6 @@ export interface SignalRecordingPort {
|
||||
input: DecodeSignalRecordingInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
inspectDecoders(
|
||||
input: InspectSignalDecodersInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -84,58 +74,14 @@ export class SignalRecordingService {
|
||||
"Decoder returned malformed data or changed the selected recording identity/options.",
|
||||
),
|
||||
);
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
async inspectDecoders(
|
||||
raw: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const operation = "inspect_signal_decoders";
|
||||
if (options?.signal?.aborted)
|
||||
return err(new AnalysisCancelledError(operation));
|
||||
const input = inspectSignalDecodersInputSchema.safeParse(raw);
|
||||
if (!input.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(operation, input.error.issues, raw, {
|
||||
cause: input.error,
|
||||
}),
|
||||
);
|
||||
const decoded = await this.provider.inspectDecoders(input.data, options);
|
||||
if (!decoded.ok) return decoded;
|
||||
const execution = decoded.value;
|
||||
const report = signalDecodersSchema.safeParse(execution.result);
|
||||
if (
|
||||
!report.success ||
|
||||
JSON.stringify(report.data.selection) !== JSON.stringify(input.data) ||
|
||||
execution.subject?.path !== report.data.tool.path ||
|
||||
execution.subject.sha256 !== report.data.tool.sha256
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
operation,
|
||||
"Decoder discovery returned malformed data or changed the selected installation/options.",
|
||||
),
|
||||
);
|
||||
return this.#evidence(operation, input.data, execution, options);
|
||||
}
|
||||
#evidence(
|
||||
operation: string,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
execution: AnalysisExecution,
|
||||
options?: ExecutionOptions,
|
||||
): Result<Evidence, AnalysisError> {
|
||||
const evidence = createEvidence(
|
||||
execution.subject ?? undefined,
|
||||
execution.provider,
|
||||
{
|
||||
operation,
|
||||
parameters,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
},
|
||||
);
|
||||
const evidence = createEvidence(execution.subject, execution.provider, {
|
||||
operation,
|
||||
parameters: input.data,
|
||||
result: report.data,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
});
|
||||
return options?.signal?.aborted
|
||||
? err(
|
||||
new AnalysisCancelledError(operation, {
|
||||
|
||||
@@ -81,9 +81,7 @@ export class MachOSliceArtifactReader implements ArtifactReader {
|
||||
if (!captured.ok)
|
||||
throw new ArtifactReaderFailure(
|
||||
captured.error.reason === "cancelled" ? "cancelled" : "unavailable",
|
||||
captured.error.detail === null
|
||||
? "lipo could not enumerate universal Mach-O slices"
|
||||
: `lipo could not enumerate universal Mach-O slices: ${captured.error.detail}`,
|
||||
"lipo could not enumerate universal Mach-O slices",
|
||||
{
|
||||
cause: captured.error,
|
||||
...(captured.error.cleanupFailure === null &&
|
||||
|
||||
@@ -280,11 +280,9 @@ export class SafeOutputTree {
|
||||
}
|
||||
|
||||
/** Sync the owned output tree and prevent further writes through this instance. */
|
||||
async commit(signal?: AbortSignal): Promise<void> {
|
||||
async commit(): Promise<void> {
|
||||
this.#assertWritable();
|
||||
abortIfNeeded(signal);
|
||||
await this.#assertOwnedDirectories();
|
||||
abortIfNeeded(signal);
|
||||
// Windows has no directory fsync; file contents are already synced in write().
|
||||
if (this.platform === "win32") {
|
||||
this.#published = true;
|
||||
@@ -317,7 +315,6 @@ export class SafeOutputTree {
|
||||
);
|
||||
await output.handle.sync();
|
||||
await parent.handle.sync();
|
||||
abortIfNeeded(signal);
|
||||
this.#published = true;
|
||||
} catch (cause: unknown) {
|
||||
sync = { kind: "failed", cause };
|
||||
@@ -339,26 +336,23 @@ export class SafeOutputTree {
|
||||
closeFailure,
|
||||
this.#outputRoot,
|
||||
);
|
||||
if (sync.kind === "failed") {
|
||||
const primary = isCancellationFailure(sync.cause)
|
||||
? sync.cause
|
||||
: new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Could not durably sync extraction output",
|
||||
{ cause: sync.cause },
|
||||
);
|
||||
throw ArtifactReaderFailure.withCleanup(primary, cleanup);
|
||||
}
|
||||
if (sync.kind === "failed")
|
||||
throw ArtifactReaderFailure.withCleanup(
|
||||
new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Could not durably sync extraction output",
|
||||
{ cause: sync.cause },
|
||||
),
|
||||
cleanup,
|
||||
);
|
||||
throw ArtifactReaderFailure.withCleanup(closeFailure, cleanup);
|
||||
}
|
||||
if (sync.kind === "failed") {
|
||||
if (isCancellationFailure(sync.cause)) throw sync.cause;
|
||||
if (sync.kind === "failed")
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Could not durably sync extraction output",
|
||||
{ cause: sync.cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove only this operation's unsealed tree and verify absence. */
|
||||
@@ -596,11 +590,6 @@ const abortIfNeeded = (signal?: AbortSignal): void => {
|
||||
);
|
||||
};
|
||||
|
||||
const isCancellationFailure = (
|
||||
cause: unknown,
|
||||
): cause is ArtifactReaderFailure =>
|
||||
cause instanceof ArtifactReaderFailure && cause.reason === "cancelled";
|
||||
|
||||
const isAlreadyExists = (cause: unknown): boolean =>
|
||||
cause instanceof Error && "code" in cause && cause.code === "EEXIST";
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
|
||||
import { SafeOutputTree } from "../SafeOutputTree.js";
|
||||
import { SafeOutputTreeCreationFailure } from "../SafeOutputTreeCreationFailure.js";
|
||||
import { ZipArtifactReader } from "../ZipArtifactReader.js";
|
||||
import { isZipPackageFormat } from "../../domain/zipPackageFormat.js";
|
||||
import { MachOSliceArtifactReader } from "../MachOSliceArtifactReader.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
@@ -249,7 +248,7 @@ const materializeSelection = async ({
|
||||
compareUnicodeCodePoints(left.relative_path, right.relative_path),
|
||||
);
|
||||
completed = createExtractionResult(input, inventory, selected, extracted);
|
||||
await output.commit(signal);
|
||||
await output.commit();
|
||||
return completed;
|
||||
} catch (cause: unknown) {
|
||||
const cleanupFailures = await releaseExtractionOwners(
|
||||
@@ -401,6 +400,13 @@ interface ExtractionInventory {
|
||||
readonly integrityContradictions: readonly IntegrityContradiction[];
|
||||
}
|
||||
|
||||
const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const;
|
||||
|
||||
const isZipFormat = (
|
||||
format: BinaryTarget["format"],
|
||||
): format is (typeof ZIP_FORMATS)[number] =>
|
||||
(ZIP_FORMATS as readonly string[]).includes(format);
|
||||
|
||||
/**
|
||||
* Refuse a format without an extraction reader before inventory work starts.
|
||||
* The target kind, not the host, is unsupported by extraction. The error keeps
|
||||
@@ -416,7 +422,7 @@ const requireExtractableFormat = async (
|
||||
!directory &&
|
||||
format !== "asar" &&
|
||||
!isMachOFormat(format) &&
|
||||
!isZipPackageFormat(format)
|
||||
!isZipFormat(format)
|
||||
)
|
||||
throw new AnalysisUnsupportedTargetError(
|
||||
"extract_artifact",
|
||||
@@ -437,7 +443,7 @@ const createReader = async (
|
||||
if (await requireExtractableFormat(path, input))
|
||||
return new DirectoryArtifactReader(path);
|
||||
if (format === "asar") return new AsarArtifactReader(path);
|
||||
if (isZipPackageFormat(format)) return new ZipArtifactReader(path, format);
|
||||
if (isZipFormat(format)) return new ZipArtifactReader(path, format);
|
||||
return new MachOSliceArtifactReader(path, input.environment);
|
||||
};
|
||||
|
||||
|
||||
@@ -91,7 +91,7 @@ export const browserScenarioCaptureData = (input: {
|
||||
network_content: input.scenario.capture.network,
|
||||
event_families: [...new Set(input.scenario.capture.events)].sort(),
|
||||
},
|
||||
duration_ms: Math.max(0, Math.round(performance.now() - input.startedAt)),
|
||||
duration_ms: Date.now() - input.startedAt,
|
||||
steps: [...input.steps],
|
||||
events,
|
||||
limitations: [
|
||||
|
||||
@@ -303,7 +303,6 @@ describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
});
|
||||
expect(result.value.limitations).toContain(session.eventGaps[0]);
|
||||
});
|
||||
|
||||
it("returns an initial state and every step beyond the former action ceiling", async () => {
|
||||
const session = new FakeSession("launch");
|
||||
const provider = new PlaywrightBrowserScenarioProvider(() =>
|
||||
@@ -377,35 +376,6 @@ describe("PlaywrightBrowserScenarioProvider", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider timing", () => {
|
||||
it("keeps capture elapsed values valid across a backward wall-clock jump", async () => {
|
||||
let wallClock = 10_000;
|
||||
vi.spyOn(Date, "now").mockImplementation(() => wallClock);
|
||||
const session = new FakeSession("launch");
|
||||
session.onPerform = () => {
|
||||
wallClock = 1;
|
||||
};
|
||||
const provider = new PlaywrightBrowserScenarioProvider(() =>
|
||||
Promise.resolve(session),
|
||||
);
|
||||
|
||||
try {
|
||||
const result = await provider.captureScenario(scenario());
|
||||
if (!result.ok) throw result.error;
|
||||
expect(wallClock).toBe(1);
|
||||
expect(Number.isInteger(result.value.duration_ms)).toBe(true);
|
||||
expect(result.value.duration_ms).toBeGreaterThanOrEqual(0);
|
||||
expect(
|
||||
result.value.steps.every(
|
||||
({ elapsed_ms }) => Number.isInteger(elapsed_ms) && elapsed_ms >= 0,
|
||||
),
|
||||
).toBe(true);
|
||||
} finally {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("PlaywrightBrowserScenarioProvider comparison coverage", () => {
|
||||
it("keeps quiet captures with different event families from comparing unchanged", async () => {
|
||||
const capture = async (events: readonly BrowserScenarioEventFamily[]) => {
|
||||
|
||||
@@ -172,7 +172,7 @@ const executeStep = async (input: {
|
||||
),
|
||||
});
|
||||
|
||||
const actionStartedAt = performance.now();
|
||||
const actionStartedAt = Date.now();
|
||||
session.setStep(stepIndex);
|
||||
const requestCancelled = (): boolean => signal?.aborted === true;
|
||||
let outcome: BrowserScenarioStepOutcome = {
|
||||
@@ -200,7 +200,7 @@ const executeStep = async (input: {
|
||||
stepId: action.step_id,
|
||||
action: action.action,
|
||||
...outcome,
|
||||
elapsedMs: Math.max(0, Math.round(performance.now() - actionStartedAt)),
|
||||
elapsedMs: Date.now() - actionStartedAt,
|
||||
beforeUrl,
|
||||
afterUrl: session.sanitizeUrl(session.currentUrl()),
|
||||
eventStart,
|
||||
@@ -233,7 +233,7 @@ const runScenario = async (
|
||||
): Promise<BrowserScenarioCapture> => {
|
||||
if (options.signal?.aborted === true)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
const startedAt = performance.now();
|
||||
const startedAt = Date.now();
|
||||
const session = await openSession(scenario, {
|
||||
...(options.signal === undefined ? {} : { signal: options.signal }),
|
||||
retainCleanup,
|
||||
@@ -250,7 +250,7 @@ const runScenario = async (
|
||||
await initialStep({
|
||||
session,
|
||||
scenario,
|
||||
elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
signal: options.signal,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -72,7 +72,7 @@ export const runElectronActions = async (
|
||||
): Promise<ElectronActions> => {
|
||||
const actions: ElectronActions = [];
|
||||
for (const action of input.actions) {
|
||||
const actionStartedAt = performance.now();
|
||||
const actionStartedAt = Date.now();
|
||||
const windowIndex = actionWindowIndex(action);
|
||||
let selectedWindow: Page | undefined;
|
||||
try {
|
||||
@@ -107,10 +107,7 @@ export const runElectronActions = async (
|
||||
target:
|
||||
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
|
||||
status: "completed",
|
||||
elapsed_ms: Math.max(
|
||||
0,
|
||||
Math.round(performance.now() - actionStartedAt),
|
||||
),
|
||||
elapsed_ms: Date.now() - actionStartedAt,
|
||||
error: null,
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
@@ -121,10 +118,7 @@ export const runElectronActions = async (
|
||||
target:
|
||||
selectedWindow === undefined ? null : `window:${String(windowIndex)}`,
|
||||
status: options.signal?.aborted ? "cancelled" : "failed",
|
||||
elapsed_ms: Math.max(
|
||||
0,
|
||||
Math.round(performance.now() - actionStartedAt),
|
||||
),
|
||||
elapsed_ms: Date.now() - actionStartedAt,
|
||||
error: safeActionErrorMessage(cause),
|
||||
});
|
||||
break;
|
||||
@@ -372,7 +366,7 @@ export const runWithExecutionLimits = async <Value>(
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() => reject(new BrowserObservationError(OPERATION, "timeout")),
|
||||
Math.max(1, deadline - performance.now()),
|
||||
Math.max(1, deadline - Date.now()),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -86,7 +86,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
if (options.signal?.aborted === true)
|
||||
throw new BrowserObservationError(OPERATION, "cancelled");
|
||||
await prepareProcessOwnershipInspection(options.signal);
|
||||
const startupDeadline = performance.now() + STARTUP_TIMEOUT_MS;
|
||||
const startupDeadline = Date.now() + STARTUP_TIMEOUT_MS;
|
||||
paths = {
|
||||
executable: input.executable_path,
|
||||
application: input.application_path,
|
||||
@@ -101,7 +101,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
cwd: paths.root,
|
||||
env: safeElectronEnvironment(this.environment, runId),
|
||||
args: ["-r", hookPath, paths.application, ...input.args],
|
||||
timeout: Math.max(1, startupDeadline - performance.now()),
|
||||
timeout: Math.max(1, startupDeadline - Date.now()),
|
||||
});
|
||||
const leaderPid = application.process().pid;
|
||||
if (
|
||||
@@ -128,7 +128,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
const state = await runWithExecutionLimits(
|
||||
readApplicationState(application),
|
||||
undefined,
|
||||
options.signal?.aborted ? performance.now() + 5_000 : undefined,
|
||||
options.signal?.aborted ? Date.now() + 5_000 : undefined,
|
||||
);
|
||||
capture = projectElectronActiveCapture(paths, actions, state);
|
||||
outcome = options.signal?.aborted
|
||||
@@ -187,7 +187,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati
|
||||
await runWithExecutionLimits(
|
||||
application.close(),
|
||||
undefined,
|
||||
performance.now() + 5_000,
|
||||
Date.now() + 5_000,
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
closeError = cause;
|
||||
|
||||
@@ -7,10 +7,7 @@ import {
|
||||
} from "../domain/analysisErrorCore.js";
|
||||
|
||||
describe("withPlaywrightExecutionBoundary", () => {
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("rejects work that exceeds its absolute remaining duration", async () => {
|
||||
vi.useFakeTimers();
|
||||
@@ -34,20 +31,4 @@ describe("withPlaywrightExecutionBoundary", () => {
|
||||
controller.abort();
|
||||
await expect(result).rejects.toBeInstanceOf(AnalysisCancelledError);
|
||||
});
|
||||
|
||||
it("keeps its timeout stable across a wall-clock jump", async () => {
|
||||
vi.spyOn(Date, "now")
|
||||
.mockReturnValueOnce(1_000)
|
||||
.mockReturnValue(10_000_000);
|
||||
|
||||
await expect(
|
||||
withPlaywrightExecutionBoundary(
|
||||
() =>
|
||||
new Promise<string>((resolve) =>
|
||||
setTimeout(() => resolve("done"), 5),
|
||||
),
|
||||
1_000,
|
||||
),
|
||||
).resolves.toBe("done");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -19,10 +19,10 @@ export const withPlaywrightExecutionBoundary = <Value>(
|
||||
let settled = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const deadline =
|
||||
timeoutMs === undefined ? undefined : performance.now() + timeoutMs;
|
||||
timeoutMs === undefined ? undefined : Date.now() + timeoutMs;
|
||||
const scheduleTimeout = (): void => {
|
||||
if (deadline === undefined) return;
|
||||
const remaining = deadline - performance.now();
|
||||
const remaining = deadline - Date.now();
|
||||
if (remaining <= 0) {
|
||||
fail(new AnalysisTimeoutError(OPERATION, timeoutMs ?? 0));
|
||||
return;
|
||||
|
||||
@@ -133,7 +133,7 @@ export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
|
||||
const secrets = BrowserScenarioSecrets.resolve(scenario, environment);
|
||||
if (secrets === undefined)
|
||||
throw new BrowserObservationError(OPERATION, "secret_unavailable");
|
||||
const startedAt = performance.now();
|
||||
const startedAt = Date.now();
|
||||
const opening = openPlaywrightScenarioBrowser(scenario, environment, {
|
||||
signal: options.signal,
|
||||
...(options.retainCleanup === undefined
|
||||
|
||||
@@ -86,7 +86,7 @@ export const fetchWebSourceMaps = async (
|
||||
signal?.addEventListener("abort", abortFromCaller, { once: true });
|
||||
const operationSignal = operationController.signal;
|
||||
const deadlineAt =
|
||||
performance.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
|
||||
Date.now() + (host.timeoutMs ?? SOURCE_MAP_FETCH_TIMEOUT_MS);
|
||||
const budget = {
|
||||
retainedBytes: 0,
|
||||
deadlineAt,
|
||||
@@ -110,7 +110,7 @@ export const fetchWebSourceMaps = async (
|
||||
}
|
||||
const expandedBytesBeforeItem = budget.decodedRecords.expandedBytes;
|
||||
budget.decodedRecords.expandedBytes += reservation;
|
||||
if (operationSignal.aborted || performance.now() >= deadlineAt) {
|
||||
if (operationSignal.aborted || Date.now() >= deadlineAt) {
|
||||
items.push(
|
||||
emptySourceMapItem(
|
||||
request,
|
||||
@@ -789,7 +789,7 @@ const checkOperation = (
|
||||
): void => {
|
||||
if (callerSignal?.aborted === true) throw callerSignal.reason;
|
||||
if (operationSignal?.aborted === true) throw operationSignal.reason;
|
||||
if (performance.now() >= deadlineAt) throw new SourceMapDeadlineError();
|
||||
if (Date.now() >= deadlineAt) throw new SourceMapDeadlineError();
|
||||
};
|
||||
|
||||
const approvedUrl = (
|
||||
|
||||
@@ -113,7 +113,7 @@ export const publishWebScripts = async (
|
||||
options.signal,
|
||||
);
|
||||
options.signal?.throwIfAborted();
|
||||
await tree.commit(options.signal);
|
||||
await tree.commit();
|
||||
return result;
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof SafeOutputTreeCreationFailure) tree = cause.tree;
|
||||
|
||||
@@ -144,8 +144,7 @@ const projectHar = (
|
||||
(literal) =>
|
||||
item.includes(literal) ||
|
||||
contentBase64.includes(literal) ||
|
||||
sha256.includes(literal) ||
|
||||
String(bytes.length).includes(literal),
|
||||
sha256.includes(literal),
|
||||
);
|
||||
binary_fields.push(
|
||||
hidden
|
||||
|
||||
@@ -1,12 +1,3 @@
|
||||
import {
|
||||
type InspectPacketFieldsInput,
|
||||
packetFieldsCatalogSchema,
|
||||
} from "../domain/captures/packetFields.js";
|
||||
import {
|
||||
parseFieldDiscovery,
|
||||
FieldDiscoveryBudgetError,
|
||||
FIELD_RECORD_BUDGET,
|
||||
} from "./parseFieldDiscovery.js";
|
||||
import {
|
||||
readLinuxResourceLimits,
|
||||
type LinuxResourceLimits,
|
||||
@@ -100,31 +91,17 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
return this.#resources.run(
|
||||
() => this.#executeRequest(input, options),
|
||||
() => this.#inspect(input, options),
|
||||
options?.signal,
|
||||
);
|
||||
}
|
||||
inspectFields(
|
||||
input: InspectPacketFieldsInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
return this.#resources.run(
|
||||
() => this.#executeRequest(input, options),
|
||||
options?.signal,
|
||||
"inspect_packet_fields",
|
||||
);
|
||||
}
|
||||
close(): Promise<void> {
|
||||
return this.#resources.close();
|
||||
}
|
||||
async #executeRequest(
|
||||
input: InspectPacketCaptureInput | InspectPacketFieldsInput,
|
||||
async #inspect(
|
||||
input: InspectPacketCaptureInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<AnalysisExecution, AnalysisError>> {
|
||||
const operation = "path" in input ? OPERATION : "inspect_packet_fields";
|
||||
// TShark 4.6.9 emits a 22.3 MB glossary; keep capture output capped at 4 MiB.
|
||||
const limits =
|
||||
"path" in input ? LIMITS : { ...LIMITS, output_bytes: 32 * 1024 * 1024 };
|
||||
let phase:
|
||||
| "configuration"
|
||||
| "artifact"
|
||||
@@ -132,12 +109,12 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
| "producer"
|
||||
| "integrity" = "configuration";
|
||||
let capturedOutput: AnalysisCapturedOutput | undefined;
|
||||
let resourcePath = "path" in input ? input.path : "TShark field glossary";
|
||||
let resourcePath = input.path;
|
||||
let effectiveLimits: LinuxResourceLimits | undefined;
|
||||
let root: ArtifactAnalysisRuntime | undefined;
|
||||
let result: Result<AnalysisExecution, AnalysisError>;
|
||||
try {
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(operation);
|
||||
if (options?.signal?.aborted) throw new AnalysisCancelledError(OPERATION);
|
||||
await this.#resources.release();
|
||||
if (this.platform !== "linux")
|
||||
throw new Error(
|
||||
@@ -164,7 +141,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
64 * 1024 * 1024,
|
||||
options?.signal,
|
||||
);
|
||||
effectiveLimits = await this.#resources.readLimits(limits);
|
||||
effectiveLimits = await this.#resources.readLimits(LIMITS);
|
||||
const limitArguments = [
|
||||
`--as=${effectiveLimits.address_space_bytes}:${effectiveLimits.address_space_bytes}`,
|
||||
`--fsize=${effectiveLimits.file_bytes}:${effectiveLimits.file_bytes}`,
|
||||
@@ -175,7 +152,7 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
];
|
||||
phase = "workspace";
|
||||
root = await this.createRuntime();
|
||||
this.#resources.retain(root, undefined, operation);
|
||||
this.#resources.retain(root, undefined);
|
||||
const snapshotPath = join(root.path, "capture");
|
||||
const configurationPath = join(root.path, "configuration");
|
||||
await mkdir(configurationPath, { mode: 0o700 });
|
||||
@@ -193,8 +170,8 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
},
|
||||
},
|
||||
{
|
||||
timeoutMs: limits.command_timeout_ms,
|
||||
diagnosticBytes: limits.output_bytes,
|
||||
timeoutMs: LIMITS.command_timeout_ms,
|
||||
diagnosticBytes: LIMITS.output_bytes,
|
||||
acceptNonZeroExit: true,
|
||||
},
|
||||
{
|
||||
@@ -223,24 +200,24 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
);
|
||||
if (currentLimiter.sha256 !== limiterIdentity.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
operation,
|
||||
OPERATION,
|
||||
limiter,
|
||||
"Configured resource limiter changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
if (current.sha256 !== tool.sha256)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
operation,
|
||||
OPERATION,
|
||||
command,
|
||||
"Configured TShark executable changed during analysis.",
|
||||
{ capturedOutput },
|
||||
);
|
||||
phase = previousPhase;
|
||||
resourcePath = "path" in input ? input.path : command;
|
||||
resourcePath = input.path;
|
||||
if (output.exitCode !== 0)
|
||||
throw new ProviderAdapterError(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
operation,
|
||||
OPERATION,
|
||||
{
|
||||
diagnostics: {
|
||||
exit_code: output.exitCode ?? null,
|
||||
@@ -261,15 +238,86 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
throw new Error(
|
||||
"Expected TShark 4.x; inspect the selected installation.",
|
||||
);
|
||||
const metadata = (args: readonly string[], diagnostics: string) => ({
|
||||
diagnostics,
|
||||
phase = "artifact";
|
||||
const selected = await this.#resources.read(
|
||||
input.path,
|
||||
LIMITS.input_bytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "workspace";
|
||||
await writeFile(snapshotPath, selected.bytes, {
|
||||
flag: "wx",
|
||||
mode: 0o400,
|
||||
});
|
||||
phase = "producer";
|
||||
const args = [
|
||||
"-n",
|
||||
"-r",
|
||||
"capture",
|
||||
"-T",
|
||||
"json",
|
||||
"--no-duplicate-keys",
|
||||
"--temp-dir=.",
|
||||
...(input.two_pass ? ["-2"] : []),
|
||||
...(input.packet_limit === null
|
||||
? []
|
||||
: ["-c", String(input.packet_limit)]),
|
||||
...(input.display_filter === null ? [] : ["-Y", input.display_filter]),
|
||||
...input.decode_as.flatMap((value) => ["-d", value]),
|
||||
...[...new Set(["frame.number", ...input.fields])].flatMap((field) => [
|
||||
"-e",
|
||||
field,
|
||||
]),
|
||||
];
|
||||
const output = await execute(args);
|
||||
phase = "integrity";
|
||||
resourcePath = snapshotPath;
|
||||
if (
|
||||
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
|
||||
.sha256 !== selected.sha256
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
OPERATION,
|
||||
snapshotPath,
|
||||
"TShark changed the private capture copy.",
|
||||
capturedOutput === undefined ? {} : { capturedOutput },
|
||||
);
|
||||
phase = "producer";
|
||||
resourcePath = input.path;
|
||||
const matchingPackets = parsePacketOutput(
|
||||
output.stdout.text,
|
||||
input.fields,
|
||||
);
|
||||
const start = Math.min(input.match_offset, matchingPackets.length);
|
||||
const end =
|
||||
input.match_limit === null
|
||||
? matchingPackets.length
|
||||
: start + Math.min(input.match_limit, matchingPackets.length - start);
|
||||
const packets = matchingPackets.slice(start, end);
|
||||
const report = packetCaptureSchema.parse({
|
||||
artifact: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
bytes: selected.bytes.length,
|
||||
},
|
||||
selection: input,
|
||||
packets,
|
||||
output_window: {
|
||||
matching_packets: matchingPackets.length,
|
||||
returned_packets: packets.length,
|
||||
has_more: end < matchingPackets.length,
|
||||
},
|
||||
read_scope:
|
||||
input.packet_limit === null ? "to-eof" : "up-to-input-packet-limit",
|
||||
configuration: "private-empty-personal-profile",
|
||||
diagnostics: output.stderr.text,
|
||||
tool: {
|
||||
configured_path: configured,
|
||||
path: command,
|
||||
sha256: tool.sha256,
|
||||
version_banner: version.stdout.text,
|
||||
version_diagnostics: version.stderr.text,
|
||||
arguments: [...args],
|
||||
arguments: args,
|
||||
},
|
||||
resource_limiter: {
|
||||
configured_path: configuredLimiter,
|
||||
@@ -277,136 +325,33 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
sha256: limiterIdentity.sha256,
|
||||
arguments: limitArguments,
|
||||
},
|
||||
limits: { ...limits, ...effectiveLimits },
|
||||
hardware_acquisition: "not-performed" as const,
|
||||
limits: { ...LIMITS, ...effectiveLimits },
|
||||
hardware_acquisition: "not-performed",
|
||||
});
|
||||
if (!("path" in input)) {
|
||||
phase = "producer";
|
||||
const args = ["-G", "fields"];
|
||||
const output = await execute(args);
|
||||
const report = packetFieldsCatalogSchema.parse({
|
||||
selection: input,
|
||||
...parseFieldDiscovery(output.stdout.text, input),
|
||||
...metadata(args, output.stderr.text),
|
||||
limits: {
|
||||
...limits,
|
||||
...effectiveLimits,
|
||||
record_budget_bytes: FIELD_RECORD_BUDGET,
|
||||
},
|
||||
configuration: "private-empty-personal-profile",
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(report, TSHARK_PROVIDER_IDENTITY, {
|
||||
subject: { path: command, sha256: tool.sha256, format: "file" },
|
||||
limitations: [
|
||||
"Protocol and field registrations describe the selected installation, not traffic observed in a capture. Duplicate abbreviations remain distinct producer records with source line numbers.",
|
||||
"Each request probes again without caching. The private empty personal profile does not fingerprint or isolate installed libraries, global configuration or plugins; they remain trusted.",
|
||||
"No capture file, interface or device is opened. Resource ceilings do not constitute an OS sandbox. Glossary output is capped at 32 MiB and selected record representation at 8 MiB before expansion.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
phase = "artifact";
|
||||
const selected = await this.#resources.read(
|
||||
input.path,
|
||||
LIMITS.input_bytes,
|
||||
options?.signal,
|
||||
);
|
||||
phase = "workspace";
|
||||
await writeFile(snapshotPath, selected.bytes, {
|
||||
flag: "wx",
|
||||
mode: 0o400,
|
||||
});
|
||||
phase = "producer";
|
||||
const args = [
|
||||
"-n",
|
||||
"-r",
|
||||
"capture",
|
||||
"-T",
|
||||
"json",
|
||||
"--no-duplicate-keys",
|
||||
"--temp-dir=.",
|
||||
...(input.two_pass ? ["-2"] : []),
|
||||
...(input.packet_limit === null
|
||||
? []
|
||||
: ["-c", String(input.packet_limit)]),
|
||||
...(input.display_filter === null
|
||||
? []
|
||||
: ["-Y", input.display_filter]),
|
||||
...input.decode_as.flatMap((value) => ["-d", value]),
|
||||
...[...new Set(["frame.number", ...input.fields])].flatMap(
|
||||
(field) => ["-e", field],
|
||||
),
|
||||
];
|
||||
const output = await execute(args);
|
||||
phase = "integrity";
|
||||
resourcePath = snapshotPath;
|
||||
if (
|
||||
(await this.#resources.read(snapshotPath, LIMITS.input_bytes))
|
||||
.sha256 !== selected.sha256
|
||||
)
|
||||
throw new AnalysisArtifactChangedError(
|
||||
operation,
|
||||
snapshotPath,
|
||||
"TShark changed the private capture copy.",
|
||||
capturedOutput === undefined ? {} : { capturedOutput },
|
||||
);
|
||||
phase = "producer";
|
||||
resourcePath = "path" in input ? input.path : command;
|
||||
const matchingPackets = parsePacketOutput(
|
||||
output.stdout.text,
|
||||
input.fields,
|
||||
);
|
||||
const start = Math.min(input.match_offset, matchingPackets.length);
|
||||
const end =
|
||||
input.match_limit === null
|
||||
? matchingPackets.length
|
||||
: start +
|
||||
Math.min(input.match_limit, matchingPackets.length - start);
|
||||
const packets = matchingPackets.slice(start, end);
|
||||
const report = packetCaptureSchema.parse({
|
||||
artifact: {
|
||||
result = ok(
|
||||
createAnalysisExecution(report, TSHARK_PROVIDER_IDENTITY, {
|
||||
subject: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
bytes: selected.bytes.length,
|
||||
format: "file",
|
||||
},
|
||||
selection: input,
|
||||
packets,
|
||||
output_window: {
|
||||
matching_packets: matchingPackets.length,
|
||||
returned_packets: packets.length,
|
||||
has_more: end < matchingPackets.length,
|
||||
},
|
||||
read_scope:
|
||||
input.packet_limit === null ? "to-eof" : "up-to-input-packet-limit",
|
||||
configuration: "private-empty-personal-profile",
|
||||
...metadata(args, output.stderr.text),
|
||||
});
|
||||
result = ok(
|
||||
createAnalysisExecution(report, TSHARK_PROVIDER_IDENTITY, {
|
||||
subject: {
|
||||
path: input.path,
|
||||
sha256: selected.sha256,
|
||||
format: "file",
|
||||
},
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations: [
|
||||
"Fields are TShark dissector observations under the selected filter/decode-as/pass settings, not independently verified protocol semantics. Missing fields are absent from the producer output, not known zero or empty values.",
|
||||
"Packet limits count input packets before display filtering. Filtered results do not establish whole-capture or device traffic absence. Two-pass reassembly cannot recover bytes missing from the recording or beyond the read limit.",
|
||||
"Repeated field values remain ordered string arrays; raw packet bytes are included only when explicitly selected as a supported field. Export index/score metadata are omitted. All stderr, including warnings on exit zero, is retained.",
|
||||
"A private empty personal configuration is used. Installed libraries, global configuration and dissector plugins are trusted and not fully fingerprinted. File-only analysis and disabled name resolution do not constitute an OS sandbox.",
|
||||
"Linux prlimit enforces soft and hard ceilings before execution, preserving stricter inherited limits: at most 1 GiB address space per process, 64 MiB per file, 30 CPU seconds and no core dumps. Effective limits are reported. Resident input is capped at 32 MiB, each command at 30 wall-clock seconds and combined output at 4 MiB. Output overflow fails. These are per-process/per-file limits, not aggregate memory or filesystem quotas; caller-supplied tools and the limiter are trusted.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
}
|
||||
locations: [{ kind: "artifact-path", path: input.path }],
|
||||
limitations: [
|
||||
"Fields are TShark dissector observations under the selected filter/decode-as/pass settings, not independently verified protocol semantics. Missing fields are absent from the producer output, not known zero or empty values.",
|
||||
"Packet limits count input packets before display filtering. Filtered results do not establish whole-capture or device traffic absence. Two-pass reassembly cannot recover bytes missing from the recording or beyond the read limit.",
|
||||
"Repeated field values remain ordered string arrays; raw packet bytes are included only when explicitly selected as a supported field. Export index/score metadata are omitted. All stderr, including warnings on exit zero, is retained.",
|
||||
"A private empty personal configuration is used. Installed libraries, global configuration and dissector plugins are trusted and not fully fingerprinted. File-only analysis and disabled name resolution do not constitute an OS sandbox.",
|
||||
"Linux prlimit enforces soft and hard ceilings before execution, preserving stricter inherited limits: at most 1 GiB address space per process, 64 MiB per file, 30 CPU seconds and no core dumps. Effective limits are reported. Resident input is capped at 32 MiB, each command at 30 wall-clock seconds and combined output at 4 MiB. Output overflow fails. These are per-process/per-file limits, not aggregate memory or filesystem quotas; caller-supplied tools and the limiter are trusted.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (
|
||||
root !== undefined &&
|
||||
cause instanceof OwnedCommandFailure &&
|
||||
cause.cleanupOwner !== undefined
|
||||
)
|
||||
this.#resources.retain(root, cause.cleanupOwner, operation);
|
||||
this.#resources.retain(root, cause.cleanupOwner);
|
||||
result = err(
|
||||
this.#failure(
|
||||
cause,
|
||||
@@ -415,23 +360,18 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
root?.path ?? null,
|
||||
effectiveLimits,
|
||||
capturedOutput,
|
||||
operation,
|
||||
limits,
|
||||
),
|
||||
);
|
||||
}
|
||||
return this.#resources.finish(
|
||||
result,
|
||||
(execution) =>
|
||||
createEvidence(execution.subject ?? undefined, execution.provider, {
|
||||
operation,
|
||||
parameters: input,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
}),
|
||||
operation,
|
||||
return this.#resources.finish(result, (execution) =>
|
||||
createEvidence(execution.subject ?? undefined, execution.provider, {
|
||||
operation: OPERATION,
|
||||
parameters: input,
|
||||
result: execution.result,
|
||||
confidence: "observed",
|
||||
locations: execution.locations,
|
||||
limitations: execution.limitations,
|
||||
}),
|
||||
);
|
||||
}
|
||||
#failure(
|
||||
@@ -446,11 +386,6 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
workspacePath: string | null,
|
||||
effectiveLimits: LinuxResourceLimits | undefined,
|
||||
observedOutput: AnalysisCapturedOutput | undefined,
|
||||
operation = OPERATION,
|
||||
limits: {
|
||||
readonly output_bytes: number;
|
||||
readonly command_timeout_ms: number;
|
||||
} = LIMITS,
|
||||
): AnalysisError {
|
||||
if (cause instanceof AnalysisError) return cause;
|
||||
if (cause instanceof ArtifactReaderFailure && cause.cleanup !== undefined)
|
||||
@@ -458,34 +393,15 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
cause.cleanup,
|
||||
cause,
|
||||
observedOutput,
|
||||
operation,
|
||||
);
|
||||
if (
|
||||
(cause instanceof Error && cause.name === "AbortError") ||
|
||||
(cause instanceof ArtifactReaderFailure && cause.reason === "cancelled")
|
||||
)
|
||||
return new AnalysisCancelledError(operation, { cause });
|
||||
if (cause instanceof FieldDiscoveryBudgetError)
|
||||
return new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
"memory",
|
||||
cause.message,
|
||||
{ record_budget_bytes: FIELD_RECORD_BUDGET },
|
||||
{
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
},
|
||||
);
|
||||
return new AnalysisCancelledError(OPERATION, { cause });
|
||||
const reason = cause instanceof Error ? cause.message : String(cause);
|
||||
if (cause instanceof OwnedCommandFailure)
|
||||
return this.#resources.commandFailure(
|
||||
cause,
|
||||
limits,
|
||||
effectiveLimits,
|
||||
operation,
|
||||
);
|
||||
return this.#resources.commandFailure(cause, LIMITS, effectiveLimits);
|
||||
if (phase === "workspace") {
|
||||
const code =
|
||||
cause instanceof Error &&
|
||||
@@ -495,13 +411,13 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
: null;
|
||||
if (code === "ENOSPC" || code === "EDQUOT" || code === "EFBIG")
|
||||
return new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
OPERATION,
|
||||
"file-size",
|
||||
`Private analysis workspace failed (${code}): ${reason}`,
|
||||
{ workspace_path: workspacePath, system_code: code },
|
||||
{ cause },
|
||||
);
|
||||
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, operation, {
|
||||
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
cause,
|
||||
userMessage: `Cannot prepare the private analysis workspace: ${reason}`,
|
||||
diagnostics: {
|
||||
@@ -524,12 +440,12 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
["limit", "integrity", "path"].includes(cause.reason)
|
||||
)
|
||||
return new AnalysisArtifactChangedError(
|
||||
operation,
|
||||
OPERATION,
|
||||
path,
|
||||
`Post-run identity verification failed for ${path}: ${reason}`,
|
||||
detail,
|
||||
);
|
||||
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, operation, {
|
||||
return new ProviderAdapterError(TSHARK_PROVIDER_IDENTITY.id, OPERATION, {
|
||||
...detail,
|
||||
diagnostics: { stage: "integrity", resource_path: path, reason },
|
||||
});
|
||||
@@ -537,13 +453,10 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
if (phase === "configuration")
|
||||
return new AnalysisCapabilityUnavailableError(
|
||||
TSHARK_PROVIDER_IDENTITY.id,
|
||||
operation,
|
||||
OPERATION,
|
||||
reason,
|
||||
{
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
userMessage: `${reason} On Linux, configure TShark 4.x through REA_TSHARK_COMMAND and util-linux prlimit through REA_TSHARK_PRLIMIT_COMMAND (default /usr/bin/prlimit).`,
|
||||
},
|
||||
);
|
||||
@@ -553,14 +466,14 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
cause.reason === "limit"
|
||||
)
|
||||
return new AnalysisResourceConstraintError(
|
||||
operation,
|
||||
OPERATION,
|
||||
"file-size",
|
||||
reason,
|
||||
{ input_bytes: LIMITS.input_bytes },
|
||||
{ cause },
|
||||
);
|
||||
if (cause instanceof ArtifactReaderFailure && cause.reason === "integrity")
|
||||
return new AnalysisArtifactChangedError(operation, path, reason, {
|
||||
return new AnalysisArtifactChangedError(OPERATION, path, reason, {
|
||||
cause,
|
||||
});
|
||||
if (
|
||||
@@ -569,18 +482,13 @@ export class TsharkCaptureProvider implements PacketCapturePort {
|
||||
"code" in cause &&
|
||||
(cause.code === "EACCES" || cause.code === "EPERM")
|
||||
)
|
||||
return new AnalysisAccessDeniedError(operation, path, cause.code, {
|
||||
return new AnalysisAccessDeniedError(OPERATION, path, cause.code, {
|
||||
cause,
|
||||
});
|
||||
if (phase === "artifact")
|
||||
return new AnalysisInputError(operation, { cause }, [
|
||||
return new AnalysisInputError(OPERATION, { cause }, [
|
||||
{ path: ["path"], reason: "invalid_value", message: reason },
|
||||
]);
|
||||
return new AnalysisOutputError(operation, reason, {
|
||||
cause,
|
||||
...(observedOutput === undefined
|
||||
? {}
|
||||
: { capturedOutput: observedOutput }),
|
||||
});
|
||||
return new AnalysisOutputError(OPERATION, reason, { cause });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
import type {
|
||||
InspectPacketFieldsInput,
|
||||
PacketFieldRecord,
|
||||
} from "../domain/captures/packetFields.js";
|
||||
|
||||
export class FieldDiscoveryBudgetError extends Error {}
|
||||
export const FIELD_RECORD_BUDGET = 8 * 1024 * 1024;
|
||||
|
||||
/** TShark -G fields: P/name/abbreviation or F/name/abbreviation/type/parent/base/mask/blurb. */
|
||||
export const parseFieldDiscovery = (
|
||||
text: string,
|
||||
input: InspectPacketFieldsInput,
|
||||
) => {
|
||||
const copy = (value: string) =>
|
||||
Buffer.from(value, "utf16le").toString("utf16le");
|
||||
const query = input.query.toLowerCase();
|
||||
const records: PacketFieldRecord[] = [];
|
||||
let examined = 0,
|
||||
matching = 0,
|
||||
sourceLine = 0,
|
||||
budget = 0;
|
||||
// Walk the bounded text once; allocate record objects only for the requested page.
|
||||
for (let start = 0; start < text.length;) {
|
||||
const end = text.indexOf("\n", start);
|
||||
let line = text.slice(start, end < 0 ? text.length : end);
|
||||
start = end < 0 ? text.length : end + 1;
|
||||
sourceLine++;
|
||||
if (line.endsWith("\r")) line = line.slice(0, -1);
|
||||
const columns = line.split("\t", 9);
|
||||
const [tag, name, abbreviation] = columns;
|
||||
if (
|
||||
!(
|
||||
(tag === "P" && columns.length === 3) ||
|
||||
(tag === "F" && columns.length === 8)
|
||||
) ||
|
||||
name === undefined ||
|
||||
abbreviation === undefined ||
|
||||
abbreviation === ""
|
||||
)
|
||||
throw new Error(
|
||||
`Malformed TShark field glossary record at line ${sourceLine}`,
|
||||
);
|
||||
if ((input.kind === "protocols") !== (tag === "P")) continue;
|
||||
examined++;
|
||||
if (
|
||||
input.protocol !== null &&
|
||||
(tag === "P" ? abbreviation : columns[4]) !== input.protocol
|
||||
)
|
||||
continue;
|
||||
if (
|
||||
![name, abbreviation, ...(tag === "F" ? [columns[7] ?? ""] : [])].some(
|
||||
(value) => value.toLowerCase().includes(query),
|
||||
)
|
||||
)
|
||||
continue;
|
||||
matching++;
|
||||
if (
|
||||
matching <= input.offset ||
|
||||
records.length >= (input.limit ?? Number.MAX_SAFE_INTEGER)
|
||||
)
|
||||
continue;
|
||||
// Six bytes per source byte covers worst-case JSON escaping, plus record bookkeeping.
|
||||
budget += Buffer.byteLength(line, "utf8") * 6 + 512;
|
||||
if (budget > FIELD_RECORD_BUDGET)
|
||||
throw new FieldDiscoveryBudgetError(
|
||||
"Selected glossary records exceed the 8 MiB representation budget; narrow the query or page size",
|
||||
);
|
||||
// Detach retained fields from the much larger producer string.
|
||||
records.push({
|
||||
source_line: sourceLine,
|
||||
kind: tag === "P" ? "protocol" : "field",
|
||||
name: copy(name),
|
||||
abbreviation: copy(abbreviation),
|
||||
field_type: tag === "F" ? copy(columns[3] ?? "") : null,
|
||||
parent_protocol: tag === "F" ? copy(columns[4] ?? "") : null,
|
||||
display_base: tag === "F" ? copy(columns[5] ?? "") : null,
|
||||
bitmask: tag === "F" ? copy(columns[6] ?? "") : null,
|
||||
description: tag === "F" ? copy(columns[7] ?? "") : null,
|
||||
});
|
||||
}
|
||||
if (sourceLine === 0)
|
||||
throw new Error("TShark returned an empty field glossary");
|
||||
return {
|
||||
records,
|
||||
output_window: {
|
||||
examined,
|
||||
matching,
|
||||
returned: records.length,
|
||||
has_more: Math.max(0, matching - input.offset) > records.length,
|
||||
},
|
||||
};
|
||||
};
|
||||
+26
-67
@@ -1,4 +1,3 @@
|
||||
import { inspectPacketFieldsInputSchema } from "../domain/captures/packetFields.js";
|
||||
import { z } from "incur";
|
||||
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
@@ -23,73 +22,9 @@ export const registerCaptureCommands = (
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
service: Pick<
|
||||
PacketCaptureService,
|
||||
"inspect" | "inspectFields" | "close"
|
||||
"inspect" | "close"
|
||||
> = createPacketCaptureService(environment),
|
||||
): void => {
|
||||
const finish = async (
|
||||
result: Awaited<ReturnType<PacketCaptureService["inspect"]>>,
|
||||
operation: string,
|
||||
) => {
|
||||
// A one-shot command must retry retained cleanup before discarding its owner.
|
||||
try {
|
||||
await service.close();
|
||||
} catch (cause) {
|
||||
const cleanup =
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
[],
|
||||
{ reason: String(cause) },
|
||||
{ cause, operation: operation },
|
||||
);
|
||||
if (result.ok) cleanup.retainPartialObservation(result.value);
|
||||
return projectAnalysisError(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(result.error, cleanup, operation),
|
||||
);
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
};
|
||||
cli.command(CLI_COMMANDS.inspectPacketFields, {
|
||||
description: "Search installed TShark protocol and field definitions",
|
||||
options: z
|
||||
.object({
|
||||
...inspectPacketFieldsInputSchema.shape,
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.optional()
|
||||
.describe("Maximum matching records to return; defaults to 50"),
|
||||
all: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Return all remaining matches within resource limits"),
|
||||
})
|
||||
.superRefine((options, context) => {
|
||||
if (options.all && options.limit !== undefined)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["all"],
|
||||
message: "all and limit are mutually exclusive",
|
||||
});
|
||||
}),
|
||||
run: ({ options: { all, ...options } }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectPacketFields, async () =>
|
||||
finish(
|
||||
await service.inspectFields(
|
||||
{ ...options, ...(all ? { limit: null } : {}) },
|
||||
{ signal },
|
||||
),
|
||||
"inspect_packet_fields",
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.inspectPacketCapture, {
|
||||
description:
|
||||
"Inspect an existing packet capture with caller-supplied TShark",
|
||||
@@ -133,7 +68,31 @@ export const registerCaptureCommands = (
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return finish(result, "inspect_packet_capture");
|
||||
// A one-shot command must retry retained cleanup before discarding its owner.
|
||||
try {
|
||||
await service.close();
|
||||
} catch (cause) {
|
||||
const cleanup =
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
"tshark-capture",
|
||||
[],
|
||||
{ reason: String(cause) },
|
||||
{ cause, operation: "inspect_packet_capture" },
|
||||
);
|
||||
if (result.ok) cleanup.retainPartialObservation(result.value);
|
||||
return projectAnalysisError(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(
|
||||
result.error,
|
||||
cleanup,
|
||||
"inspect_packet_capture",
|
||||
),
|
||||
);
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
+26
-69
@@ -1,4 +1,3 @@
|
||||
import { inspectSignalDecodersInputSchema } from "../domain/signals/signalDecoders.js";
|
||||
import { z } from "incur";
|
||||
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
|
||||
import { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
@@ -23,75 +22,9 @@ export const registerSignalCommands = (
|
||||
environment: Readonly<NodeJS.ProcessEnv>,
|
||||
service: Pick<
|
||||
SignalRecordingService,
|
||||
"decode" | "inspectDecoders" | "close"
|
||||
"decode" | "close"
|
||||
> = createSignalRecordingService(environment),
|
||||
): void => {
|
||||
const finish = async (
|
||||
result: Awaited<ReturnType<SignalRecordingService["decode"]>>,
|
||||
operation: string,
|
||||
) => {
|
||||
// A one-shot command must retry retained cleanup before discarding its owner.
|
||||
try {
|
||||
await service.close();
|
||||
} catch (cause) {
|
||||
const cleanup =
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
[],
|
||||
{ reason: String(cause) },
|
||||
{ cause, operation: operation },
|
||||
);
|
||||
if (result.ok) cleanup.retainPartialObservation(result.value);
|
||||
return projectAnalysisError(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(result.error, cleanup, operation),
|
||||
);
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
};
|
||||
cli.command(CLI_COMMANDS.inspectSignalDecoders, {
|
||||
description: "Search installed sigrok decoders or selected decoder help",
|
||||
options: z
|
||||
.object({
|
||||
...inspectSignalDecodersInputSchema.shape,
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.optional()
|
||||
.describe(
|
||||
"Maximum matching decoders or help lines to return; defaults to 50",
|
||||
),
|
||||
all: z
|
||||
.boolean()
|
||||
.default(false)
|
||||
.describe("Return all remaining matches"),
|
||||
})
|
||||
.superRefine((options, context) => {
|
||||
if (options.all && options.limit !== undefined)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["all"],
|
||||
message: "all and limit are mutually exclusive",
|
||||
});
|
||||
}),
|
||||
run: ({ options: { all, ...options } }) =>
|
||||
withCommandCancellation((signal) =>
|
||||
logCliCommand(logger, CLI_COMMANDS.inspectSignalDecoders, async () =>
|
||||
finish(
|
||||
await service.inspectDecoders(
|
||||
{ ...options, ...(all ? { limit: null } : {}) },
|
||||
{ signal },
|
||||
),
|
||||
"inspect_signal_decoders",
|
||||
),
|
||||
),
|
||||
),
|
||||
});
|
||||
cli.command(CLI_COMMANDS.decodeSignalRecording, {
|
||||
description:
|
||||
"Decode an existing signal recording with caller-supplied sigrok",
|
||||
@@ -135,7 +68,31 @@ export const registerSignalCommands = (
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return finish(result, "decode_signal_recording");
|
||||
// A one-shot command must retry retained cleanup before discarding its owner.
|
||||
try {
|
||||
await service.close();
|
||||
} catch (cause) {
|
||||
const cleanup =
|
||||
cause instanceof AnalysisError
|
||||
? cause
|
||||
: new ProviderCleanupError(
|
||||
"sigrok-recording",
|
||||
[],
|
||||
{ reason: String(cause) },
|
||||
{ cause, operation: "decode_signal_recording" },
|
||||
);
|
||||
if (result.ok) cleanup.retainPartialObservation(result.value);
|
||||
return projectAnalysisError(
|
||||
result.ok
|
||||
? cleanup
|
||||
: analysisErrorWithCleanupFailure(
|
||||
result.error,
|
||||
cleanup,
|
||||
"decode_signal_recording",
|
||||
),
|
||||
);
|
||||
}
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
/** Canonical names used by every one-shot CLI command registration. */
|
||||
export const CLI_COMMANDS = Object.freeze({
|
||||
inspectPacketFields: "inspect-packet-fields",
|
||||
inspectPacketCapture: "inspect-packet-capture",
|
||||
inspectSignalDecoders: "inspect-signal-decoders",
|
||||
decodeSignalRecording: "decode-signal-recording",
|
||||
inspectWasmArtifact: "inspect-wasm-artifact",
|
||||
inspectSqliteDatabase: "inspect-sqlite-database",
|
||||
|
||||
@@ -3,18 +3,6 @@ import { describe, expect, it } from "vitest";
|
||||
import { parseConfig } from "./config/parseConfig.js";
|
||||
import { projectAnalysisError } from "./domain/analysisErrorProjection.js";
|
||||
|
||||
it("reports a configuration failure for a NUL in Hopper loader arguments", () => {
|
||||
const result = parseConfig({
|
||||
HOPPER_LOADER_ARGS_JSON: JSON.stringify(["--option", "value\0suffix"]),
|
||||
});
|
||||
if (result.ok)
|
||||
throw new Error("NUL argv cannot be passed to a child process");
|
||||
expect(result.error).toMatchObject({
|
||||
settings: [{ setting: "HOPPER_LOADER_ARGS_JSON" }],
|
||||
});
|
||||
expect(result.error.message).toContain("NUL");
|
||||
});
|
||||
|
||||
describe("runtime configuration", () => {
|
||||
it("allows target-free startup and applies runtime defaults", () => {
|
||||
const empty = parseConfig({});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ConfigurationError } from "../domain/configurationErrors.js";
|
||||
import { nulFreeStringSchema } from "../domain/localPath.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import { safeParseJson } from "../domain/safeJson.js";
|
||||
|
||||
@@ -21,8 +20,7 @@ export const parseLoaderArgs = (
|
||||
return parseConfiguredStringArray(
|
||||
encoded,
|
||||
"HOPPER_LOADER_ARGS_JSON",
|
||||
nulFreeStringSchema,
|
||||
"must encode an array of strings without NUL bytes",
|
||||
z.string(),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -30,7 +28,6 @@ const parseConfiguredStringArray = (
|
||||
encoded: string,
|
||||
setting: string,
|
||||
itemSchema: z.ZodString,
|
||||
requirement = "must encode an array of strings",
|
||||
): Result<readonly string[], ConfigurationError> => {
|
||||
const decoded = safeParseJson(encoded);
|
||||
if (!decoded.ok)
|
||||
@@ -40,7 +37,13 @@ const parseConfiguredStringArray = (
|
||||
const parsed = z.array(itemSchema).safeParse(decoded.value);
|
||||
return parsed.success
|
||||
? ok(parsed.data)
|
||||
: err(configuredArrayError(setting, requirement, parsed.error));
|
||||
: err(
|
||||
configuredArrayError(
|
||||
setting,
|
||||
"must encode an array of strings",
|
||||
parsed.error,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const configuredArrayError = (
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
inspectPacketFieldsInputSchema,
|
||||
packetFieldsCatalogSchema,
|
||||
} from "../../domain/captures/packetFields.js";
|
||||
import {
|
||||
inspectPacketCaptureInputSchema,
|
||||
packetCaptureSchema,
|
||||
@@ -10,22 +6,6 @@ import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
export const CAPTURE_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_packet_fields",
|
||||
...toolContractMetadata("inspect_packet_fields"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Discover protocols or field names/types registered in the installed TShark 4.x. kind defaults to protocols; use fields and optional exact protocol abbreviation to select field definitions. query searches name/abbreviation/description by case-insensitive literal substring. Return 50 matches by default with offset/limit paging; null requests all remaining within resource limits. Preserve type/base/bitmask/description, duplicate registrations, source line numbers, coverage, tool identity and diagnostics. Linux, REA_TSHARK_COMMAND and prlimit required. No capture file, interface or binary target needed. Registrations describe tool capabilities, not observed traffic. Each call rereads the glossary; use selected fields with inspect_packet_capture.",
|
||||
inputSchema: inspectPacketFieldsInputSchema,
|
||||
outputSchema: evidenceResultOf(packetFieldsCatalogSchema),
|
||||
examples: [
|
||||
{ title: "Find USB protocol registrations", input: { query: "usb" } },
|
||||
{
|
||||
title: "Find the installed USB vendor-ID field",
|
||||
input: { kind: "fields", protocol: "usb", query: "idVendor" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "inspect_packet_capture",
|
||||
...toolContractMetadata("inspect_packet_capture"),
|
||||
|
||||
@@ -11,7 +11,6 @@ import { jsonValueSchema } from "../../domain/jsonValue.js";
|
||||
import { localPathStringSchema } from "../../domain/localPath.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
|
||||
import { analysisDetailSchema } from "../analysisDetail.js";
|
||||
|
||||
const examples: Readonly<Record<string, Readonly<Record<string, unknown>>>> = {
|
||||
inspect_macho: {},
|
||||
@@ -95,15 +94,8 @@ export const NATIVE_TOOL_CONTRACTS = [
|
||||
),
|
||||
native(
|
||||
"inspect_macho",
|
||||
"Inspect Mach-O slices, load commands, imports, exports, dependencies, build metadata, segments, sections, permissions, and exact command provenance without launching Hopper. Large frameworks return megabytes of symbols; detail summary retains the complete Evidence and returns slice identity with per-collection counts, then page rows with inspect_analysis_view kind macho.",
|
||||
z.object({
|
||||
detail: analysisDetailSchema
|
||||
.unwrap()
|
||||
.optional()
|
||||
.describe(
|
||||
"Omitted or complete returns the complete inspection Evidence. summary retains that complete Evidence in this session and returns its inspect_analysis_view summary; use normalized_result.parent_evidence_id for macho pages.",
|
||||
),
|
||||
}),
|
||||
"Inspect Mach-O slices, load commands, imports, exports, dependencies, build metadata, segments, sections, permissions, and exact command provenance without launching Hopper.",
|
||||
z.object({}),
|
||||
),
|
||||
native(
|
||||
"inspect_signature",
|
||||
|
||||
@@ -1,7 +1,3 @@
|
||||
import {
|
||||
inspectSignalDecodersInputSchema,
|
||||
signalDecodersSchema,
|
||||
} from "../../domain/signals/signalDecoders.js";
|
||||
import {
|
||||
decodeSignalRecordingInputSchema,
|
||||
signalRecordingSchema,
|
||||
@@ -10,22 +6,6 @@ import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
export const SIGNAL_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_signal_decoders",
|
||||
...toolContractMetadata("inspect_signal_decoders"),
|
||||
kind: "artifact-provider",
|
||||
description:
|
||||
"Discover installed sigrok protocol decoders or inspect one decoder's channel/option help on Linux. Omit decoder to list ID/name pairs; supply its exact ID for literal help lines with source line numbers. query is a case-insensitive literal substring. Page matches with offset/limit (default 50; null returns all remaining). Reports tool identity, version, diagnostics and examined/matching coverage. Uses configured REA_SIGROK_COMMAND and prlimit; no recording, binary target, hardware scan or acquisition. Each call probes again; decoder modules are trusted, not fully fingerprinted. Use returned IDs/options with decode_signal_recording.",
|
||||
inputSchema: inspectSignalDecodersInputSchema,
|
||||
outputSchema: evidenceResultOf(signalDecodersSchema),
|
||||
examples: [
|
||||
{ title: "Find installed UART decoders", input: { query: "uart" } },
|
||||
{
|
||||
title: "Read the installed UART baud-rate option",
|
||||
input: { decoder: "uart", query: "baud" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "decode_signal_recording",
|
||||
...toolContractMetadata("decode_signal_recording"),
|
||||
|
||||
@@ -59,21 +59,11 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
writesFilesystem: true,
|
||||
launchesProcess: true,
|
||||
}),
|
||||
inspect_packet_fields: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_packet_capture: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
inspect_signal_decoders: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
writesFilesystem: true,
|
||||
}),
|
||||
decode_signal_recording: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { z } from "zod";
|
||||
import {
|
||||
artifactInventorySummaryViewResultSchema,
|
||||
machoSummaryViewResultSchema,
|
||||
managedArtifactSummaryViewResultSchema,
|
||||
} from "../domain/analysisView/analysisView.js";
|
||||
import { evidenceBundleSummarySchema } from "../domain/evidenceRecordSummary.js";
|
||||
@@ -382,9 +381,7 @@ export const nativeOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
observe_native_ui: evidenceResultOf(nativeUiResultSchema),
|
||||
capture_native_ui_scenario: evidenceResultOf(nativeUiResultSchema),
|
||||
observe_native_calls: evidenceResultOf(nativeCallObservationResultSchema),
|
||||
inspect_macho: evidenceResultOf(
|
||||
z.union([inspectMachoSchema, machoSummaryViewResultSchema]),
|
||||
),
|
||||
inspect_macho: evidenceResultOf(inspectMachoSchema),
|
||||
inspect_signature: evidenceResultOf(inspectSignatureSchema),
|
||||
inspect_plist: evidenceResultOf(inspectPlistSchema),
|
||||
list_architectures: evidenceResultOf(listArchitecturesSchema),
|
||||
|
||||
@@ -30,25 +30,6 @@ const packageNameSchema = z
|
||||
"Package name must be dot-separated Java identifiers",
|
||||
);
|
||||
|
||||
/** Text states emitted by adb's ConnectionState formatter. */
|
||||
export const ADB_DEVICE_STATES = [
|
||||
"no permissions",
|
||||
"unauthorized",
|
||||
"authorizing",
|
||||
"offline",
|
||||
"recovery",
|
||||
"sideload",
|
||||
"connecting",
|
||||
"bootloader",
|
||||
"device",
|
||||
"unknown",
|
||||
"host",
|
||||
"rescue",
|
||||
"detached",
|
||||
] as const;
|
||||
export const adbDeviceStateSchema = z.enum(ADB_DEVICE_STATES);
|
||||
export type AdbDeviceState = (typeof ADB_DEVICE_STATES)[number];
|
||||
|
||||
const keyStringSchema = z.string().min(1).max(256);
|
||||
const keyPattern = /^[A-Za-z0-9._\x2d]+$/u;
|
||||
|
||||
@@ -431,7 +412,7 @@ const client = z.strictObject({
|
||||
|
||||
const device = z.strictObject({
|
||||
serial: z.string().min(1),
|
||||
state: adbDeviceStateSchema,
|
||||
state: z.string().min(1),
|
||||
transport: z.enum(["usb", "tcp", "unknown"]),
|
||||
product: z.string().nullable(),
|
||||
model: z.string().nullable(),
|
||||
|
||||
@@ -55,13 +55,6 @@ import {
|
||||
wasmViewItemSchema,
|
||||
wasmSummarySchema,
|
||||
} from "./wasmArtifactView.js";
|
||||
import {
|
||||
machoSummarySchema,
|
||||
machoViewContextSchema,
|
||||
machoViewItemSchema,
|
||||
machoViewRequestSchema,
|
||||
projectMachoView,
|
||||
} from "./machoView.js";
|
||||
import {
|
||||
projectWebNetworkCaptureView,
|
||||
captureViewRequestSchema,
|
||||
@@ -203,7 +196,6 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
|
||||
nativeViewSchema,
|
||||
inventoryViewSchema,
|
||||
wasmViewRequestSchema,
|
||||
machoViewRequestSchema,
|
||||
evmViewRequestSchema,
|
||||
managedViewRequestSchema,
|
||||
androidViewRequestSchema,
|
||||
@@ -323,7 +315,6 @@ const viewResultBase = {
|
||||
"inspect_artifact",
|
||||
"inventory_artifact",
|
||||
"inspect_wasm_artifact",
|
||||
"inspect_macho",
|
||||
"inspect_evm_interface",
|
||||
"inspect_managed_artifact",
|
||||
"inspect_web_network_capture",
|
||||
@@ -373,13 +364,6 @@ export const wasmArtifactSummaryViewResultSchema = z.strictObject({
|
||||
summary: wasmSummarySchema,
|
||||
});
|
||||
|
||||
/** Exact slice identity and collection counts for Mach-O's selected delivery. */
|
||||
export const machoSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
parent_operation: z.literal("inspect_macho"),
|
||||
summary: machoSummarySchema,
|
||||
});
|
||||
|
||||
/** Exact inferred-interface summary for EVM's caller-selected delivery. */
|
||||
export const evmInterfaceSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
@@ -441,7 +425,6 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
javascriptSummarySchema,
|
||||
inventorySummarySchema,
|
||||
wasmSummarySchema,
|
||||
machoSummarySchema,
|
||||
evmSummarySchema,
|
||||
managedSummarySchema,
|
||||
captureSummarySchema,
|
||||
@@ -504,14 +487,6 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
item: wasmViewItemSchema,
|
||||
...viewResultBase,
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("macho"),
|
||||
view: machoViewRequestSchema,
|
||||
item: machoViewItemSchema,
|
||||
...viewResultBase,
|
||||
...machoViewContextSchema.shape,
|
||||
parent_operation: z.literal("inspect_macho"),
|
||||
}),
|
||||
z.strictObject({
|
||||
kind: z.literal("evm"),
|
||||
view: evmViewRequestSchema,
|
||||
@@ -608,7 +583,6 @@ export type UnsignedAnalysisView =
|
||||
"view_digest"
|
||||
>
|
||||
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
|
||||
| Omit<Extract<AnalysisViewResult, { readonly kind: "macho" }>, "view_digest">
|
||||
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
|
||||
| Omit<Extract<AnalysisViewResult, { readonly kind: "qlog" }>, "view_digest">
|
||||
| Omit<Extract<AnalysisViewResult, { readonly kind: "pcap" }>, "view_digest">
|
||||
@@ -672,7 +646,7 @@ const unsupportedParent = (
|
||||
new AnalysisUnsupportedTargetError(
|
||||
INSPECT_ANALYSIS_VIEW_OPERATION,
|
||||
parentArtifactPath(parent),
|
||||
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, Mach-O, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
|
||||
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
|
||||
);
|
||||
|
||||
const parentArtifactPath = (parent: AnalysisViewParent): string => {
|
||||
@@ -699,7 +673,6 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
|
||||
/** Named source owners for views that need no extra decoder or accumulator. */
|
||||
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
|
||||
["inspect_wasm_artifact", projectWasmArtifactView],
|
||||
["inspect_macho", projectMachoView],
|
||||
["inspect_evm_interface", projectEvmInterfaceView],
|
||||
["inspect_managed_artifact", projectManagedArtifactView],
|
||||
["inspect_android_package", projectAndroidPackageView],
|
||||
|
||||
@@ -1,246 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
projectAnalysisView,
|
||||
type AnalysisViewParent,
|
||||
} from "./analysisView.js";
|
||||
|
||||
const symbol = (name: string) => ({
|
||||
name,
|
||||
address: null,
|
||||
weak: null,
|
||||
reexport: null,
|
||||
source: "libSystem",
|
||||
});
|
||||
const coverage = <T>(items: T[], exhaustive = true) => ({
|
||||
items,
|
||||
total: exhaustive ? items.length : null,
|
||||
exhaustive,
|
||||
limitations: exhaustive ? [] : ["nm output may omit stripped symbols."],
|
||||
});
|
||||
const report = {
|
||||
format: "mach-o",
|
||||
selected_architecture: { name: "arm64", container_file_offset: 0 },
|
||||
endian: null,
|
||||
word_size: 64,
|
||||
file_type: "2",
|
||||
flags: ["0x00200085"],
|
||||
uuid: "4C4C44E9-5555-3144-A1E9-D858E24A1CCE",
|
||||
entrypoints: coverage([{ file_offset: 16384 }]),
|
||||
architectures: coverage([
|
||||
{
|
||||
name: "arm64",
|
||||
cpu_type: "16777228",
|
||||
cpu_subtype: "0",
|
||||
file_offset: 0,
|
||||
size: 4096,
|
||||
alignment: 14,
|
||||
},
|
||||
]),
|
||||
build_metadata: coverage([
|
||||
{ platform: "1", minimum_os: "14.0", sdk: "15.0", tools: [] },
|
||||
]),
|
||||
load_commands: coverage([{ index: 0, kind: "LC_MAIN", fields: {} }]),
|
||||
dependencies: coverage([
|
||||
{
|
||||
path: "/usr/lib/libSystem.B.dylib",
|
||||
kind: "LC_LOAD_DYLIB",
|
||||
current_version: "1351.0.0",
|
||||
compatibility_version: "1.0.0",
|
||||
},
|
||||
]),
|
||||
imports: coverage(
|
||||
["_malloc", "_free", "_open"].map((name) => symbol(name)),
|
||||
false,
|
||||
),
|
||||
exports: coverage([symbol("__mh_execute_header")]),
|
||||
segments: coverage([
|
||||
{
|
||||
name: "__TEXT",
|
||||
vm_address: "0x100000000",
|
||||
vm_size: 16384,
|
||||
file_offset: 0,
|
||||
file_size: 16384,
|
||||
maximum_permissions: {
|
||||
read: true,
|
||||
write: false,
|
||||
execute: true,
|
||||
raw: "5",
|
||||
},
|
||||
initial_permissions: {
|
||||
read: true,
|
||||
write: false,
|
||||
execute: true,
|
||||
raw: "5",
|
||||
},
|
||||
sections: coverage([]),
|
||||
},
|
||||
]),
|
||||
provenance: [
|
||||
{
|
||||
tool: "nm",
|
||||
command: ["/usr/bin/nm", "$ARTIFACT"],
|
||||
tool_version: null,
|
||||
version_reason: "fixture",
|
||||
executable_sha256: "a".repeat(64),
|
||||
exit: { code: 0, signal: null },
|
||||
stdout_bytes: 10,
|
||||
stderr_bytes: 0,
|
||||
},
|
||||
],
|
||||
limitations: ["Imports and exports combine dyld_info and nm."],
|
||||
};
|
||||
const parent = (
|
||||
normalizedResult: unknown = report,
|
||||
subject: AnalysisViewParent["subject"] = {
|
||||
name: "tool",
|
||||
digest: { sha256: "b".repeat(64) },
|
||||
format: "mach-o",
|
||||
architecture: "arm64",
|
||||
local_path: "/bin/tool",
|
||||
},
|
||||
): AnalysisViewParent => ({
|
||||
evidenceId: `ev_${"c".repeat(64)}`,
|
||||
operation: "inspect_macho",
|
||||
normalizedResult,
|
||||
subject,
|
||||
limitations: ["Parent limitation."],
|
||||
});
|
||||
|
||||
describe("Mach-O analysis views", () => {
|
||||
it("summarizes slice identity and collection counts without rows", () => {
|
||||
const projected = projectAnalysisView(parent(), { kind: "summary" });
|
||||
if (!projected.ok) throw projected.error;
|
||||
expect(projected.value).toMatchObject({
|
||||
kind: "summary",
|
||||
parent_operation: "inspect_macho",
|
||||
artifact: { path: "/bin/tool", sha256: "b".repeat(64) },
|
||||
summary: {
|
||||
selected_architecture: { name: "arm64", container_file_offset: 0 },
|
||||
uuid: report.uuid,
|
||||
collections: {
|
||||
imports: { returned: 3, total: null, exhaustive: false },
|
||||
exports: { returned: 1, total: 1, exhaustive: true },
|
||||
segments: { returned: 1, total: 1, exhaustive: true },
|
||||
},
|
||||
provenance_count: 1,
|
||||
limitation_count: 3,
|
||||
},
|
||||
coverage: { status: "complete-within-view", examined: 10, total: 10 },
|
||||
limitations: [
|
||||
"Imports and exports combine dyld_info and nm.",
|
||||
"Parent limitation.",
|
||||
"nm output may omit stripped symbols.",
|
||||
],
|
||||
unknowns: [expect.stringContaining("exhaustive imports;")],
|
||||
});
|
||||
expect(JSON.stringify(projected.value)).not.toContain("_malloc");
|
||||
});
|
||||
|
||||
it("pages original rows with the producer's own coverage", () => {
|
||||
const first = projectAnalysisView(parent(), {
|
||||
kind: "macho",
|
||||
facet: "imports",
|
||||
offset: 1,
|
||||
limit: 1,
|
||||
});
|
||||
if (!first.ok) throw first.error;
|
||||
expect(first.value).toMatchObject({
|
||||
kind: "macho",
|
||||
item: [symbol("_free")],
|
||||
source_total: null,
|
||||
source_exhaustive: false,
|
||||
coverage: { status: "page", examined: 1, total: 3, next_offset: 2 },
|
||||
});
|
||||
expect(first.value.limitations).toContain(
|
||||
"nm output may omit stripped symbols.",
|
||||
);
|
||||
// Rows whose keys include an earlier row shape's keys stay whole.
|
||||
for (const facet of ["architectures", "segments"] as const) {
|
||||
const page = projectAnalysisView(parent(), {
|
||||
kind: "macho",
|
||||
facet,
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
});
|
||||
if (!page.ok) throw page.error;
|
||||
expect(page.value.kind === "macho" && page.value.item).toEqual(
|
||||
report[facet].items,
|
||||
);
|
||||
}
|
||||
const provenance = projectAnalysisView(parent(), {
|
||||
kind: "macho",
|
||||
facet: "provenance",
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
});
|
||||
if (!provenance.ok) throw provenance.error;
|
||||
expect(provenance.value).toMatchObject({
|
||||
item: report.provenance,
|
||||
source_total: 1,
|
||||
source_exhaustive: true,
|
||||
coverage: { exhausted: true, next_offset: null },
|
||||
});
|
||||
const past = projectAnalysisView(parent(), {
|
||||
kind: "macho",
|
||||
facet: "exports",
|
||||
offset: 5,
|
||||
limit: 64,
|
||||
});
|
||||
if (!past.ok) throw past.error;
|
||||
expect(past.value.coverage).toMatchObject({
|
||||
status: "empty",
|
||||
exhausted: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a missing subject unknown instead of inventing identity", () => {
|
||||
const projected = projectAnalysisView(parent(report, null), {
|
||||
kind: "summary",
|
||||
});
|
||||
if (!projected.ok) throw projected.error;
|
||||
expect(projected.value.artifact).toEqual({ path: "", sha256: null });
|
||||
expect(projected.value.unknowns).toContain(
|
||||
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects other view kinds and malformed retained results", () => {
|
||||
const wrongKind = projectAnalysisView(parent(), {
|
||||
kind: "wasm",
|
||||
facet: "exports",
|
||||
offset: 0,
|
||||
limit: 64,
|
||||
});
|
||||
if (wrongKind.ok) throw new Error("expected a view-kind refusal");
|
||||
expect(wrongKind.error).toMatchObject({
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [
|
||||
{
|
||||
path: ["view"],
|
||||
message: "Mach-O inspection supports summary and macho views.",
|
||||
},
|
||||
],
|
||||
});
|
||||
const contradictory = projectAnalysisView(
|
||||
parent(report, {
|
||||
name: "tool",
|
||||
digest: { sha256: "b".repeat(64) },
|
||||
format: "elf",
|
||||
architecture: null,
|
||||
local_path: "/bin/tool",
|
||||
}),
|
||||
{ kind: "summary" },
|
||||
);
|
||||
if (contradictory.ok) throw new Error("expected a subject refusal");
|
||||
expect(contradictory.error).toMatchObject({
|
||||
issues: [{ path: ["source", "subject"] }],
|
||||
});
|
||||
const malformed = projectAnalysisView(
|
||||
parent({ ...report, imports: { items: "x" } }),
|
||||
{ kind: "summary" },
|
||||
);
|
||||
expect(malformed.ok).toBe(false);
|
||||
if (!malformed.ok) expect(malformed.error._tag).toBe("AnalysisInputError");
|
||||
});
|
||||
});
|
||||
@@ -1,247 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import type { AnalysisError } from "../analysisErrorBase.js";
|
||||
import { uniqueSorted } from "../canonicalOrdering.js";
|
||||
import { isMachOFormat } from "../binaryTargetTypes.js";
|
||||
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
|
||||
import { inspectMachoSchema } from "../native/nativeInspection.js";
|
||||
import { err, ok, type Result } from "../result.js";
|
||||
import {
|
||||
analysisViewInputError,
|
||||
type AnalysisViewParent,
|
||||
type AnalysisViewRequest,
|
||||
type UnsignedAnalysisView,
|
||||
} from "./analysisView.js";
|
||||
import {
|
||||
completeWithinViewCoverage,
|
||||
pageViewCoverage,
|
||||
} from "./analysisViewCoverage.js";
|
||||
|
||||
const MACHO_COLLECTIONS = [
|
||||
"entrypoints",
|
||||
"architectures",
|
||||
"build_metadata",
|
||||
"load_commands",
|
||||
"dependencies",
|
||||
"imports",
|
||||
"exports",
|
||||
"segments",
|
||||
] as const;
|
||||
type MachoCollection = (typeof MACHO_COLLECTIONS)[number];
|
||||
|
||||
/** Original inspect_macho rows; offsets count rows in the retained collection. */
|
||||
export const machoViewRequestSchema = z.strictObject({
|
||||
kind: z.literal("macho"),
|
||||
facet: z.enum([...MACHO_COLLECTIONS, "provenance"]),
|
||||
offset: z.number().int().nonnegative().default(0),
|
||||
limit: z.number().int().positive().default(64),
|
||||
});
|
||||
|
||||
const { shape } = inspectMachoSchema;
|
||||
/**
|
||||
* Union members are tried in order and plain objects drop unknown keys, so a
|
||||
* segment or architecture row would otherwise match the entrypoint row and
|
||||
* lose every field but file_offset. Exact key sets keep each page's rows whole.
|
||||
*/
|
||||
const exactRows = <Shape extends z.ZodRawShape>(
|
||||
rows: z.ZodArray<z.ZodObject<Shape>>,
|
||||
) => z.array(z.strictObject(rows.element.shape));
|
||||
export const machoViewItemSchema = z.union([
|
||||
exactRows(shape.entrypoints.shape.items),
|
||||
exactRows(shape.architectures.shape.items),
|
||||
exactRows(shape.build_metadata.shape.items),
|
||||
exactRows(shape.load_commands.shape.items),
|
||||
exactRows(shape.dependencies.shape.items),
|
||||
// Imports and exports share one row shape.
|
||||
exactRows(shape.imports.shape.items),
|
||||
exactRows(shape.segments.shape.items),
|
||||
exactRows(shape.provenance),
|
||||
]);
|
||||
|
||||
/** The producer's own coverage of the paged collection, not of this page. */
|
||||
export const machoViewContextSchema = z.strictObject({
|
||||
source_total: z.number().int().nonnegative().nullable(),
|
||||
source_exhaustive: z.boolean(),
|
||||
});
|
||||
|
||||
const collectionCountSchema = z.strictObject({
|
||||
returned: z.number().int().nonnegative(),
|
||||
total: z.number().int().nonnegative().nullable(),
|
||||
exhaustive: z.boolean(),
|
||||
});
|
||||
|
||||
/** Slice identity and per-collection counts without the collections themselves. */
|
||||
export const machoSummarySchema = z.strictObject({
|
||||
format: shape.format,
|
||||
selected_architecture: shape.selected_architecture,
|
||||
endian: shape.endian,
|
||||
word_size: shape.word_size,
|
||||
file_type: shape.file_type,
|
||||
flags: shape.flags,
|
||||
uuid: shape.uuid,
|
||||
collections: z.strictObject(
|
||||
Object.fromEntries(
|
||||
MACHO_COLLECTIONS.map((name) => [name, collectionCountSchema]),
|
||||
) as Record<MachoCollection, typeof collectionCountSchema>,
|
||||
),
|
||||
provenance_count: z.number().int().nonnegative(),
|
||||
limitation_count: z.number().int().nonnegative(),
|
||||
});
|
||||
|
||||
type MachoReport = z.output<typeof inspectMachoSchema>;
|
||||
|
||||
/** Admit a well-formed report whose recorded subject, if any, is a Mach-O. */
|
||||
const parseMachoReport = (
|
||||
parent: AnalysisViewParent,
|
||||
): Result<MachoReport, AnalysisError> => {
|
||||
const parsed = inspectMachoSchema.safeParse(parent.normalizedResult);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
analysisInputErrorFromIssues(
|
||||
"inspect_analysis_view",
|
||||
parsed.error.issues.map((issue) => ({
|
||||
...issue,
|
||||
path: ["source", "normalized_result", ...issue.path],
|
||||
})),
|
||||
{ source: { normalized_result: parent.normalizedResult } },
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
);
|
||||
if (parent.subject != null && !isMachOFormat(parent.subject.format))
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["source", "subject"],
|
||||
reason: "invalid_value",
|
||||
message:
|
||||
"Mach-O parent Evidence subject must identify a thin or universal Mach-O.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
return ok(parsed.data);
|
||||
};
|
||||
|
||||
/** Counts replace rows; every collection caveat stays in the limitations. */
|
||||
const summarizeMacho = (
|
||||
report: MachoReport,
|
||||
parentLimitations: readonly string[],
|
||||
) => {
|
||||
const limitations = uniqueSorted([
|
||||
...parentLimitations,
|
||||
...report.limitations,
|
||||
...MACHO_COLLECTIONS.flatMap((name) => report[name].limitations),
|
||||
]);
|
||||
const collections = Object.fromEntries(
|
||||
MACHO_COLLECTIONS.map((name) => [
|
||||
name,
|
||||
{
|
||||
returned: report[name].items.length,
|
||||
total: report[name].total,
|
||||
exhaustive: report[name].exhaustive,
|
||||
},
|
||||
]),
|
||||
) as Record<MachoCollection, z.output<typeof collectionCountSchema>>;
|
||||
return {
|
||||
limitations,
|
||||
returned: MACHO_COLLECTIONS.reduce(
|
||||
(sum, name) => sum + report[name].items.length,
|
||||
0,
|
||||
),
|
||||
summary: {
|
||||
format: report.format,
|
||||
selected_architecture: report.selected_architecture,
|
||||
endian: report.endian,
|
||||
word_size: report.word_size,
|
||||
file_type: report.file_type,
|
||||
flags: report.flags,
|
||||
uuid: report.uuid,
|
||||
collections,
|
||||
provenance_count: report.provenance.length,
|
||||
limitation_count: limitations.length,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
/** Project retained inspect_macho Evidence without rerunning native tools. */
|
||||
export const projectMachoView = (
|
||||
parent: AnalysisViewParent,
|
||||
view: AnalysisViewRequest,
|
||||
): Result<UnsignedAnalysisView, AnalysisError> => {
|
||||
if (view.kind !== "summary" && view.kind !== "macho")
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["view"],
|
||||
reason: "invalid_value",
|
||||
message: "Mach-O inspection supports summary and macho views.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const parsed = parseMachoReport(parent);
|
||||
if (!parsed.ok) return parsed;
|
||||
const report = parsed.value;
|
||||
const incomplete = MACHO_COLLECTIONS.filter(
|
||||
(name) => !report[name].exhaustive,
|
||||
);
|
||||
const shared = {
|
||||
parent_evidence_id: parent.evidenceId,
|
||||
parent_operation: "inspect_macho" as const,
|
||||
parent_digest: parent.evidenceId.slice(3),
|
||||
artifact:
|
||||
parent.subject == null
|
||||
? { path: "", sha256: null }
|
||||
: {
|
||||
path: parent.subject.local_path,
|
||||
sha256: parent.subject.digest.sha256,
|
||||
},
|
||||
unknowns: [
|
||||
...(incomplete.length === 0
|
||||
? []
|
||||
: [
|
||||
`Native tools did not report exhaustive ${incomplete.join(", ")}; page exhaustion does not establish absence of unreturned rows.`,
|
||||
]),
|
||||
...(parent.subject == null
|
||||
? [
|
||||
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
|
||||
]
|
||||
: []),
|
||||
],
|
||||
};
|
||||
if (view.kind === "summary") {
|
||||
const { summary, limitations, returned } = summarizeMacho(
|
||||
report,
|
||||
parent.limitations,
|
||||
);
|
||||
return ok({
|
||||
kind: "summary",
|
||||
view,
|
||||
...shared,
|
||||
limitations,
|
||||
summary,
|
||||
coverage: completeWithinViewCoverage(returned, returned),
|
||||
});
|
||||
}
|
||||
const source =
|
||||
view.facet === "provenance"
|
||||
? {
|
||||
items: report.provenance,
|
||||
total: report.provenance.length,
|
||||
exhaustive: true,
|
||||
limitations: [],
|
||||
}
|
||||
: report[view.facet];
|
||||
const item = source.items.slice(view.offset, view.offset + view.limit);
|
||||
return ok({
|
||||
kind: "macho",
|
||||
view,
|
||||
item,
|
||||
...shared,
|
||||
limitations: uniqueSorted([
|
||||
...parent.limitations,
|
||||
...report.limitations,
|
||||
...source.limitations,
|
||||
]),
|
||||
source_total: source.total,
|
||||
source_exhaustive: source.exhaustive,
|
||||
coverage: pageViewCoverage(view.offset, item.length, source.items.length),
|
||||
});
|
||||
};
|
||||
@@ -597,136 +597,6 @@ describe("dyld load order", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("loader-relative dylib resolution", () => {
|
||||
it("does not reuse already loaded images by install name for @loader_path dependencies", async () => {
|
||||
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
|
||||
const helperA = "Contents/PlugIns/A/libhelper.dylib";
|
||||
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [
|
||||
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
|
||||
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
|
||||
],
|
||||
}),
|
||||
[pluginA]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
[helperA]: parsed(
|
||||
slice({
|
||||
install_name: "@loader_path/libhelper.dylib",
|
||||
}),
|
||||
),
|
||||
[pluginB]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
|
||||
const edgeA = edgeFor(trace, pluginA, "@loader_path/libhelper.dylib");
|
||||
expect(edgeA.resolution).toEqual({
|
||||
status: "resolved",
|
||||
image: helperA,
|
||||
});
|
||||
expect(edgeA.candidates).toEqual([
|
||||
expect.objectContaining({
|
||||
source: "loader_path",
|
||||
outcome: "resolved",
|
||||
resolved_path: helperA,
|
||||
}),
|
||||
]);
|
||||
|
||||
const edgeB = edgeFor(trace, pluginB, "@loader_path/libhelper.dylib");
|
||||
expect(edgeB.resolution).toEqual({
|
||||
status: "unresolved",
|
||||
image: null,
|
||||
});
|
||||
expect(edgeB.candidates).toEqual([
|
||||
expect.objectContaining({
|
||||
path: "Contents/PlugIns/B/libhelper.dylib",
|
||||
source: "loader_path",
|
||||
outcome: "absent",
|
||||
resolved_path: null,
|
||||
}),
|
||||
]);
|
||||
expect(trace.findings).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "required-load-unresolved",
|
||||
image: pluginB,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves @loader_path dependencies to the loader's own directory when multiple helpers exist", async () => {
|
||||
const pluginA = "Contents/PlugIns/A/pluginA.dylib";
|
||||
const helperA = "Contents/PlugIns/A/libhelper.dylib";
|
||||
const pluginB = "Contents/PlugIns/B/pluginB.dylib";
|
||||
const helperB = "Contents/PlugIns/B/libhelper.dylib";
|
||||
const trace = await traceDylibLoading(
|
||||
memoryView({
|
||||
[MAIN]: executable({
|
||||
dependencies: [
|
||||
dependency("@executable_path/../PlugIns/A/pluginA.dylib"),
|
||||
dependency("@executable_path/../PlugIns/B/pluginB.dylib"),
|
||||
],
|
||||
}),
|
||||
[pluginA]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
[helperA]: parsed(
|
||||
slice({
|
||||
install_name: "@loader_path/libhelper.dylib",
|
||||
}),
|
||||
),
|
||||
[pluginB]: parsed(
|
||||
slice({
|
||||
dependencies: [dependency("@loader_path/libhelper.dylib")],
|
||||
}),
|
||||
),
|
||||
[helperB]: parsed(
|
||||
slice({
|
||||
install_name: "@loader_path/libhelper.dylib",
|
||||
}),
|
||||
),
|
||||
}),
|
||||
{ roots: [MAIN] },
|
||||
);
|
||||
|
||||
expect(
|
||||
edgeFor(trace, pluginA, "@loader_path/libhelper.dylib"),
|
||||
).toMatchObject({
|
||||
resolution: { status: "resolved", image: helperA },
|
||||
candidates: [
|
||||
expect.objectContaining({
|
||||
source: "loader_path",
|
||||
outcome: "resolved",
|
||||
resolved_path: helperA,
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(
|
||||
edgeFor(trace, pluginB, "@loader_path/libhelper.dylib"),
|
||||
).toMatchObject({
|
||||
resolution: { status: "resolved", image: helperB },
|
||||
candidates: [
|
||||
expect.objectContaining({
|
||||
source: "loader_path",
|
||||
outcome: "resolved",
|
||||
resolved_path: helperB,
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("dyld slice compatibility and coverage", () => {
|
||||
it("lets an x86_64h process load generic x86_64 but not arm64e load arm64", async () => {
|
||||
const files = {
|
||||
|
||||
@@ -427,9 +427,7 @@ const resolveDependency = async (
|
||||
): Promise<Edge> => {
|
||||
const current = context.loaded.get(loader);
|
||||
const chain = current?.chain ?? [loader];
|
||||
const loaded = dependency.install_name.startsWith("@rpath/")
|
||||
? context.byInstallName.get(dependency.install_name)
|
||||
: undefined;
|
||||
const loaded = context.byInstallName.get(dependency.install_name);
|
||||
const candidates: Candidate[] = [];
|
||||
if (loaded !== undefined)
|
||||
candidates.push({
|
||||
@@ -508,10 +506,7 @@ const traceProcess = async (
|
||||
chain: [context.root],
|
||||
conditional: false,
|
||||
});
|
||||
if (
|
||||
rootSlice.install_name !== null &&
|
||||
rootSlice.install_name.startsWith("@rpath/")
|
||||
)
|
||||
if (rootSlice.install_name !== null)
|
||||
context.byInstallName.set(rootSlice.install_name, context.root);
|
||||
const pending = [context.root];
|
||||
while (pending.length > 0) {
|
||||
@@ -542,7 +537,6 @@ const traceProcess = async (
|
||||
});
|
||||
if (
|
||||
slice.install_name !== null &&
|
||||
slice.install_name.startsWith("@rpath/") &&
|
||||
!context.byInstallName.has(slice.install_name)
|
||||
)
|
||||
context.byInstallName.set(slice.install_name, image);
|
||||
|
||||
@@ -91,7 +91,7 @@ export const DYLIB_RESOLUTION_LIMITATIONS = [
|
||||
"Slices are matched by dyld's graded architectures (an x86_64h process also loads x86_64). arm64e processes that disable pointer authentication can also load arm64 slices; that fallback is not modeled.",
|
||||
"Absolute install names and rpaths are outside the analyzed root and are not evaluated, including /System and /usr/lib libraries that the dyld shared cache usually provides.",
|
||||
"Leaf and relative install names depend on dyld fallback paths, DYLD_* variables, and the working directory; they are undetermined.",
|
||||
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later @rpath request whose install name matches an already loaded image reuses it.",
|
||||
"Load order follows dyld's dependents-first traversal in load-command order. An image reached through several chains is resolved once per process, with the rpath stack and conditionality of the first chain; a later request whose install name matches an already loaded image reuses it.",
|
||||
"@loader_path uses each image's symlink-resolved path within the analyzed root.",
|
||||
"Code-signing checks that can reject a found image, such as library validation and the hardened runtime, are not evaluated.",
|
||||
"Dylib compatibility versions are not compared. Apple's linker documentation describes a load-time rejection when an image's compatibility version is older than the loader requires, but dyld on macOS 26 was observed to load such an image.",
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import { z } from "zod";
|
||||
import { packetCaptureSchema } from "./packetCapture.js";
|
||||
|
||||
export const inspectPacketFieldsInputSchema = z.strictObject({
|
||||
kind: z
|
||||
.enum(["protocols", "fields"])
|
||||
.default("protocols")
|
||||
.describe(
|
||||
"Return protocol registrations or field definitions; defaults to protocols",
|
||||
),
|
||||
protocol: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(8192)
|
||||
.nullable()
|
||||
.default(null)
|
||||
.describe(
|
||||
"Exact protocol abbreviation; selects that protocol or its registered fields",
|
||||
),
|
||||
query: z
|
||||
.string()
|
||||
.max(8192)
|
||||
.default("")
|
||||
.describe(
|
||||
"Case-insensitive literal substring in name, abbreviation or field description",
|
||||
),
|
||||
offset: z
|
||||
.number()
|
||||
.int()
|
||||
.nonnegative()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.default(0)
|
||||
.describe("Number of matching records to skip; defaults to 0"),
|
||||
limit: z
|
||||
.number()
|
||||
.int()
|
||||
.positive()
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.nullable()
|
||||
.default(50)
|
||||
.describe(
|
||||
"Maximum matches returned; null requests all remaining within the record budget",
|
||||
),
|
||||
});
|
||||
export type InspectPacketFieldsInput = z.infer<
|
||||
typeof inspectPacketFieldsInputSchema
|
||||
>;
|
||||
export const packetFieldRecordSchema = z.strictObject({
|
||||
source_line: z.number().int().positive(),
|
||||
kind: z.enum(["protocol", "field"]),
|
||||
name: z.string(),
|
||||
abbreviation: z.string(),
|
||||
field_type: z.string().nullable(),
|
||||
parent_protocol: z.string().nullable(),
|
||||
display_base: z.string().nullable(),
|
||||
bitmask: z.string().nullable(),
|
||||
description: z.string().nullable(),
|
||||
});
|
||||
export type PacketFieldRecord = z.infer<typeof packetFieldRecordSchema>;
|
||||
export const packetFieldsCatalogSchema = z
|
||||
.strictObject({
|
||||
selection: inspectPacketFieldsInputSchema,
|
||||
records: z.array(packetFieldRecordSchema),
|
||||
output_window: z.strictObject({
|
||||
examined: z.number().int().nonnegative(),
|
||||
matching: z.number().int().nonnegative(),
|
||||
returned: z.number().int().nonnegative(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
diagnostics: z.string(),
|
||||
tool: packetCaptureSchema.shape.tool,
|
||||
resource_limiter: packetCaptureSchema.shape.resource_limiter,
|
||||
limits: packetCaptureSchema.shape.limits.extend({
|
||||
record_budget_bytes: z.literal(8388608),
|
||||
}),
|
||||
configuration: z.literal("private-empty-personal-profile"),
|
||||
hardware_acquisition: z.literal("not-performed"),
|
||||
})
|
||||
.superRefine((report, context) => {
|
||||
const w = report.output_window;
|
||||
const remaining = Math.max(0, w.matching - report.selection.offset);
|
||||
const expected = Math.min(remaining, report.selection.limit ?? remaining);
|
||||
if (
|
||||
w.matching > w.examined ||
|
||||
w.returned !== expected ||
|
||||
report.records.length !== expected ||
|
||||
w.has_more !== remaining > expected ||
|
||||
report.records.some(
|
||||
(row) =>
|
||||
row.kind !==
|
||||
(report.selection.kind === "protocols" ? "protocol" : "field"),
|
||||
)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["output_window"],
|
||||
message:
|
||||
"Field discovery coverage must match the selected page and record kind",
|
||||
});
|
||||
});
|
||||
@@ -22,9 +22,6 @@ const source = (digit: string): Evidence =>
|
||||
const left = source("1");
|
||||
const right = source("2");
|
||||
|
||||
const aggregate = (comparisons: readonly unknown[]) =>
|
||||
findChangedBehavior({ comparisons });
|
||||
|
||||
const comparison = (
|
||||
operation: "compare_process_captures" | "compare_artifacts",
|
||||
result: JsonValue,
|
||||
@@ -139,9 +136,9 @@ const expectInvalidSummary = (result: ChangedBehaviorResult): void => {
|
||||
|
||||
describe("changed behavior", () => {
|
||||
it("accepts process comparison Evidence", () => {
|
||||
const result = aggregate([
|
||||
const result = findChangedBehavior([
|
||||
comparison("compare_process_captures", processResult()),
|
||||
]).result;
|
||||
]);
|
||||
expect(result.behavior_status).toBe("observed_unchanged");
|
||||
});
|
||||
|
||||
@@ -155,7 +152,7 @@ describe("changed behavior", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(aggregate([evidence]).result).toMatchObject({
|
||||
expect(findChangedBehavior([evidence])).toMatchObject({
|
||||
behavior_status: "observed_changed",
|
||||
summary: { observed_changes: 2 },
|
||||
findings: {
|
||||
@@ -175,7 +172,7 @@ describe("changed behavior", () => {
|
||||
"compare_process_captures",
|
||||
processResult({ status: "changed", terminal: "changed" }),
|
||||
);
|
||||
const result = aggregate([evidence]).result;
|
||||
const result = findChangedBehavior([evidence]);
|
||||
expect(changedBehaviorResultSchema.parse(result)).toMatchObject({
|
||||
behavior_status: "observed_changed",
|
||||
summary: { observed_changes: 1, static_candidates: 0 },
|
||||
@@ -196,7 +193,7 @@ describe("changed behavior", () => {
|
||||
|
||||
it("keeps static differences as candidates, never runtime observations", () => {
|
||||
const evidence = comparison("compare_artifacts", artifactResult());
|
||||
const result = aggregate([evidence]).result;
|
||||
const result = findChangedBehavior([evidence]);
|
||||
expect(result).toMatchObject({
|
||||
behavior_status: "unknown",
|
||||
summary: { observed_changes: 0, static_candidates: 1 },
|
||||
@@ -220,17 +217,17 @@ describe("changed behavior", () => {
|
||||
"compare_process_captures",
|
||||
processResult({ status: "unknown", exit: "unknown" }),
|
||||
);
|
||||
const result = aggregate([changed, unknown]).result;
|
||||
const result = findChangedBehavior([changed, unknown]);
|
||||
expect(result).toMatchObject({
|
||||
behavior_status: "unknown",
|
||||
findings: { items: expect.any(Array) },
|
||||
});
|
||||
expect(aggregate([changed, unknown]).result).toEqual(result);
|
||||
expect(findChangedBehavior([changed, unknown])).toEqual(result);
|
||||
});
|
||||
|
||||
it("uses complete inline artifact deltas as static candidates", () => {
|
||||
const complete = comparison("compare_artifacts", artifactResult());
|
||||
expect(aggregate([complete]).result.findings.items).toEqual(
|
||||
expect(findChangedBehavior([complete]).findings.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ dimension: "artifact:main.js" }),
|
||||
]),
|
||||
@@ -239,7 +236,7 @@ describe("changed behavior", () => {
|
||||
|
||||
it("rejects bundles, duplicate comparisons, and malformed exact results", () => {
|
||||
const valid = comparison("compare_process_captures", processResult());
|
||||
expect(() => aggregate([valid, valid])).toThrow(
|
||||
expect(() => findChangedBehavior([valid, valid])).toThrow(
|
||||
/duplicate comparison Evidence/u,
|
||||
);
|
||||
const bundle = createEvidence(
|
||||
@@ -255,25 +252,25 @@ describe("changed behavior", () => {
|
||||
evidenceLinks: [left.evidence_id, right.evidence_id],
|
||||
},
|
||||
);
|
||||
expect(() => aggregate([bundle])).toThrow(
|
||||
expect(() => findChangedBehavior([bundle])).toThrow(
|
||||
/requires process, artifact, or function/u,
|
||||
);
|
||||
const malformed = comparison("compare_process_captures", {
|
||||
status: "unchanged",
|
||||
});
|
||||
expect(() => aggregate([malformed])).toThrow();
|
||||
expect(() => findChangedBehavior([malformed])).toThrow();
|
||||
const contradictory = comparison(
|
||||
"compare_process_captures",
|
||||
processResult({ status: "unchanged", terminal: "changed" }),
|
||||
);
|
||||
expect(() => aggregate([contradictory])).toThrow(
|
||||
expect(() => findChangedBehavior([contradictory])).toThrow(
|
||||
/contradicts its dimensions/u,
|
||||
);
|
||||
const danglingNested = comparison(
|
||||
"compare_artifacts",
|
||||
artifactResult([`ev_${"f".repeat(64)}`, right.evidence_id]),
|
||||
);
|
||||
expect(() => aggregate([danglingNested])).toThrow(
|
||||
expect(() => findChangedBehavior([danglingNested])).toThrow(
|
||||
/outside its top-level closure/u,
|
||||
);
|
||||
});
|
||||
@@ -302,15 +299,10 @@ describe("changed behavior aggregation", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const result = aggregate(comparisons);
|
||||
const result = findChangedBehavior(comparisons);
|
||||
|
||||
expect(result.result.summary.observed_changes).toBe(comparisons.length);
|
||||
expect(result.result.evidence_links).toHaveLength(
|
||||
comparisons.length * 201 + 2,
|
||||
);
|
||||
expect(result.result.findings.items[0]?.evidence_links).toHaveLength(203);
|
||||
expect(result.comparisonEvidenceIds).toEqual(
|
||||
comparisons.map(({ evidence_id }) => evidence_id),
|
||||
);
|
||||
expect(result.summary.observed_changes).toBe(comparisons.length);
|
||||
expect(result.evidence_links).toHaveLength(comparisons.length * 201 + 2);
|
||||
expect(result.findings.items[0]?.evidence_links).toHaveLength(203);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -91,22 +91,6 @@ export const changedBehaviorResultSchema = z
|
||||
export type ChangedBehaviorResult = z.infer<typeof changedBehaviorResultSchema>;
|
||||
type Finding = z.infer<typeof findingSchema>;
|
||||
type RuntimeStatus = z.infer<typeof processCaptureComparisonSchema>["status"];
|
||||
type ParsedComparison =
|
||||
| {
|
||||
readonly operation: "compare_process_captures";
|
||||
readonly evidence: Evidence;
|
||||
readonly result: z.infer<typeof processCaptureComparisonSchema>;
|
||||
}
|
||||
| {
|
||||
readonly operation: "compare_functions";
|
||||
readonly evidence: Evidence;
|
||||
readonly result: z.infer<typeof functionComparisonResultSchema>;
|
||||
}
|
||||
| {
|
||||
readonly operation: "compare_artifacts";
|
||||
readonly evidence: Evidence;
|
||||
readonly result: z.infer<typeof artifactComparisonResultSchema>;
|
||||
};
|
||||
|
||||
const EXPECTED_PROVIDERS = {
|
||||
compare_process_captures: {
|
||||
@@ -133,37 +117,24 @@ const acceptsPredicate = (
|
||||
): boolean => expected.some((predicate) => predicate === actual);
|
||||
|
||||
/** Find observed runtime changes and separately report static change candidates. */
|
||||
interface FoundChangedBehavior {
|
||||
readonly result: ChangedBehaviorResult;
|
||||
/** Authenticated IDs retained from the comparisons used to compute result. */
|
||||
readonly comparisonEvidenceIds: readonly string[];
|
||||
}
|
||||
|
||||
export const findChangedBehavior = (input: unknown): FoundChangedBehavior => {
|
||||
// The public input schema remains available to clients; this internal
|
||||
// admission only checks the list shape because parseEvidence below owns
|
||||
// validation and authentication of each retained Evidence item.
|
||||
const { comparisons } = z
|
||||
.strictObject({ comparisons: z.array(z.unknown()).min(1) })
|
||||
.parse(input);
|
||||
export const findChangedBehavior = (
|
||||
comparisonsInput: unknown,
|
||||
): ChangedBehaviorResult => {
|
||||
const parsedInput = changedBehaviorInputSchema.parse({
|
||||
comparisons: comparisonsInput,
|
||||
});
|
||||
const comparisons = parsedInput.comparisons;
|
||||
const evidence = comparisons.map(parseComparisonEvidence);
|
||||
assertUnique(
|
||||
evidence.map(({ evidence: { evidence_id: id } }) => id),
|
||||
evidence.map(({ evidence_id: id }) => id),
|
||||
"comparison Evidence",
|
||||
);
|
||||
const findings = evidence.flatMap(findingsFor).sort(compareFindings);
|
||||
const runtimeStatuses = evidence.flatMap((comparison) =>
|
||||
comparison.operation === "compare_process_captures"
|
||||
? [comparison.result.status]
|
||||
: [],
|
||||
);
|
||||
const runtimeStatuses = evidence.flatMap(runtimeStatus);
|
||||
const links = uniqueSorted(
|
||||
evidence.flatMap(({ evidence: item }) => [
|
||||
item.evidence_id,
|
||||
...item.evidence_links,
|
||||
]),
|
||||
evidence.flatMap((item) => [item.evidence_id, ...item.evidence_links]),
|
||||
);
|
||||
const result = changedBehaviorResultSchema.parse({
|
||||
return changedBehaviorResultSchema.parse({
|
||||
behavior_status: behaviorStatus(runtimeStatuses),
|
||||
summary: {
|
||||
observed_changes: count(findings, "observed_change"),
|
||||
@@ -176,7 +147,7 @@ export const findChangedBehavior = (input: unknown): FoundChangedBehavior => {
|
||||
},
|
||||
evidence_links: links,
|
||||
limitations: uniqueSorted([
|
||||
...evidence.flatMap(({ evidence: item }) => item.limitations),
|
||||
...evidence.flatMap(({ limitations }) => limitations),
|
||||
...(evidence.some(
|
||||
({ operation }) => operation !== "compare_process_captures",
|
||||
)
|
||||
@@ -189,15 +160,9 @@ export const findChangedBehavior = (input: unknown): FoundChangedBehavior => {
|
||||
: []),
|
||||
]),
|
||||
});
|
||||
return {
|
||||
result,
|
||||
comparisonEvidenceIds: evidence.map(
|
||||
({ evidence: { evidence_id } }) => evidence_id,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const parseComparisonEvidence = (input: unknown): ParsedComparison => {
|
||||
const parseComparisonEvidence = (input: unknown): Evidence => {
|
||||
const evidence = parseEvidence(input);
|
||||
if (!(evidence.operation in EXPECTED_PROVIDERS))
|
||||
throw new TypeError(
|
||||
@@ -233,17 +198,12 @@ const parseComparisonEvidence = (input: unknown): ParsedComparison => {
|
||||
throw new TypeError(
|
||||
"Comparison Evidence must cite both selected source observations",
|
||||
);
|
||||
return parseResult(evidence, operation);
|
||||
parseResult(evidence);
|
||||
return evidence;
|
||||
};
|
||||
|
||||
const parseResult = (
|
||||
evidence: Evidence,
|
||||
operation:
|
||||
| "compare_process_captures"
|
||||
| "compare_artifacts"
|
||||
| "compare_functions",
|
||||
): ParsedComparison => {
|
||||
if (operation === "compare_process_captures") {
|
||||
const parseResult = (evidence: Evidence): void => {
|
||||
if (evidence.operation === "compare_process_captures") {
|
||||
const result = processCaptureComparisonSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
@@ -254,9 +214,9 @@ const parseResult = (
|
||||
throw new TypeError(
|
||||
"Process comparison status contradicts its dimensions",
|
||||
);
|
||||
return { operation, evidence, result };
|
||||
return;
|
||||
}
|
||||
if (operation === "compare_functions") {
|
||||
if (evidence.operation === "compare_functions") {
|
||||
const result = functionComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
@@ -264,7 +224,7 @@ const parseResult = (
|
||||
evidence,
|
||||
result.dimensions.flatMap(({ evidence_links: links }) => links),
|
||||
);
|
||||
return { operation, evidence, result };
|
||||
return;
|
||||
}
|
||||
const result = artifactComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
@@ -273,7 +233,6 @@ const parseResult = (
|
||||
evidence,
|
||||
result.changes.flatMap(({ evidence_links: links }) => links),
|
||||
);
|
||||
return { operation, evidence, result };
|
||||
};
|
||||
|
||||
const assertNestedLinks = (
|
||||
@@ -287,21 +246,18 @@ const assertNestedLinks = (
|
||||
);
|
||||
};
|
||||
|
||||
const findingsFor = (comparison: ParsedComparison): Finding[] => {
|
||||
if (comparison.operation === "compare_process_captures")
|
||||
return processFindings(comparison);
|
||||
if (comparison.operation === "compare_functions")
|
||||
return functionFindings(comparison);
|
||||
return artifactFindings(comparison);
|
||||
const findingsFor = (evidence: Evidence): Finding[] => {
|
||||
if (evidence.operation === "compare_process_captures")
|
||||
return processFindings(evidence);
|
||||
if (evidence.operation === "compare_functions")
|
||||
return functionFindings(evidence);
|
||||
return artifactFindings(evidence);
|
||||
};
|
||||
|
||||
const processFindings = (
|
||||
comparison: Extract<
|
||||
ParsedComparison,
|
||||
{ readonly operation: "compare_process_captures" }
|
||||
>,
|
||||
): Finding[] => {
|
||||
const { evidence, result } = comparison;
|
||||
const processFindings = (evidence: Evidence): Finding[] => {
|
||||
const result = processCaptureComparisonSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
const dimensions = [
|
||||
["terminal", result.terminal, "runtime"],
|
||||
["interaction", result.interaction, "runtime"],
|
||||
@@ -327,13 +283,10 @@ const processFindings = (
|
||||
);
|
||||
};
|
||||
|
||||
const functionFindings = (
|
||||
comparison: Extract<
|
||||
ParsedComparison,
|
||||
{ readonly operation: "compare_functions" }
|
||||
>,
|
||||
): Finding[] => {
|
||||
const { evidence, result } = comparison;
|
||||
const functionFindings = (evidence: Evidence): Finding[] => {
|
||||
const result = functionComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
return result.dimensions.flatMap((dimension) =>
|
||||
dimension.status === "unchanged"
|
||||
? []
|
||||
@@ -354,13 +307,10 @@ const functionFindings = (
|
||||
);
|
||||
};
|
||||
|
||||
const artifactFindings = (
|
||||
comparison: Extract<
|
||||
ParsedComparison,
|
||||
{ readonly operation: "compare_artifacts" }
|
||||
>,
|
||||
): Finding[] => {
|
||||
const { evidence, result } = comparison;
|
||||
const artifactFindings = (evidence: Evidence): Finding[] => {
|
||||
const result = artifactComparisonResultSchema.parse(
|
||||
evidence.normalized_result,
|
||||
);
|
||||
const changes = result.changes.map((change) =>
|
||||
makeFinding({
|
||||
evidence,
|
||||
@@ -417,6 +367,11 @@ const makeFinding = (input: {
|
||||
limitations: uniqueSorted(input.limitations),
|
||||
});
|
||||
|
||||
const runtimeStatus = (evidence: Evidence): RuntimeStatus[] =>
|
||||
evidence.operation === "compare_process_captures"
|
||||
? [processCaptureComparisonSchema.parse(evidence.normalized_result).status]
|
||||
: [];
|
||||
|
||||
const behaviorStatus = (
|
||||
statuses: readonly RuntimeStatus[],
|
||||
): ChangedBehaviorResult["behavior_status"] => {
|
||||
|
||||
@@ -116,24 +116,6 @@ it("keeps unsupported profile reasons distinct from malformed input", () => {
|
||||
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
|
||||
});
|
||||
|
||||
it("preserves a retryable capability failure through explicit-value redaction", () => {
|
||||
// Retryability is a semantic field of the error, not presentation: dropping
|
||||
// it turns a transient admission failure into a permanent one and changes
|
||||
// the remediation the caller is shown.
|
||||
const error = new AnalysisCapabilityUnavailableError(
|
||||
"mitmproxy",
|
||||
"inspect_web_network_capture",
|
||||
"Runtime admission for /targets/private/capture failed transiently",
|
||||
{ retryable: true },
|
||||
);
|
||||
expect(projectAnalysisError(error).retryable).toBe(true);
|
||||
const result = redactExplicitFailure(error, ["private"]);
|
||||
expect(result).toBeInstanceOf(AnalysisCapabilityUnavailableError);
|
||||
expect((result as AnalysisCapabilityUnavailableError).retryable).toBe(true);
|
||||
expect(projectAnalysisError(result).retryable).toBe(true);
|
||||
expect(JSON.stringify(projectAnalysisError(result))).not.toContain("private");
|
||||
});
|
||||
|
||||
it("coarsens format issue pointers without creating replacement coordinates", () => {
|
||||
const error = new AnalysisInputError(
|
||||
"inspect_web_network_capture",
|
||||
|
||||
@@ -154,7 +154,6 @@ export const redactExplicitFailure = (
|
||||
...(error.userMessage === undefined
|
||||
? {}
|
||||
: { userMessage: text(error.userMessage) }),
|
||||
...(error.retryable ? { retryable: true } : {}),
|
||||
},
|
||||
);
|
||||
if (error instanceof AnalysisResourceConstraintError)
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
/** Whether TypeScript explicitly erases this entire import declaration. */
|
||||
export const isTypeOnlyImportDeclaration = (
|
||||
node: t.ImportDeclaration,
|
||||
): boolean => node.importKind === "type" || node.importKind === "typeof";
|
||||
|
||||
/** Whether TypeScript explicitly erases this entire export declaration. */
|
||||
export const isTypeOnlyExportDeclaration = (
|
||||
node: t.ExportNamedDeclaration | t.ExportAllDeclaration,
|
||||
): boolean =>
|
||||
node.exportKind === "type" ||
|
||||
(t.isExportNamedDeclaration(node) &&
|
||||
node.declaration !== null &&
|
||||
(t.isTSInterfaceDeclaration(node.declaration) ||
|
||||
t.isTSTypeAliasDeclaration(node.declaration) ||
|
||||
t.isTSDeclareFunction(node.declaration)));
|
||||
|
||||
/** Whether this import binding is explicitly type-only. */
|
||||
export const isTypeOnlyImportSpecifier = (node: t.ImportSpecifier): boolean =>
|
||||
node.importKind === "type" || node.importKind === "typeof";
|
||||
|
||||
/** Whether this exported binding is explicitly type-only. */
|
||||
export const isTypeOnlyExportSpecifier = (node: t.ExportSpecifier): boolean =>
|
||||
node.exportKind === "type";
|
||||
|
||||
/** A regular import whose bindings are all erased but may retain side effects. */
|
||||
export const hasOnlyInlineTypeImportSpecifiers = (
|
||||
node: t.ImportDeclaration,
|
||||
): boolean =>
|
||||
!isTypeOnlyImportDeclaration(node) &&
|
||||
node.specifiers.length > 0 &&
|
||||
node.specifiers.every(
|
||||
(specifier) =>
|
||||
t.isImportSpecifier(specifier) && isTypeOnlyImportSpecifier(specifier),
|
||||
);
|
||||
|
||||
/** A regular re-export whose bindings are all erased but may retain side effects. */
|
||||
export const hasOnlyInlineTypeExportSpecifiers = (
|
||||
node: t.ExportNamedDeclaration,
|
||||
): boolean =>
|
||||
!isTypeOnlyExportDeclaration(node) &&
|
||||
node.source != null &&
|
||||
node.specifiers.length > 0 &&
|
||||
node.specifiers.every(
|
||||
(specifier) =>
|
||||
t.isExportSpecifier(specifier) && isTypeOnlyExportSpecifier(specifier),
|
||||
);
|
||||
|
||||
/** Whether compiler options leave an inline type-only declaration's side effect unknown. */
|
||||
export const hasUncertainTypeOnlyModuleSideEffect = (
|
||||
program: t.Program,
|
||||
): boolean =>
|
||||
program.body.some(
|
||||
(node) =>
|
||||
(t.isImportDeclaration(node) &&
|
||||
hasOnlyInlineTypeImportSpecifiers(node)) ||
|
||||
(t.isExportNamedDeclaration(node) &&
|
||||
hasOnlyInlineTypeExportSpecifiers(node)),
|
||||
);
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user