mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 04:34:13 +00:00
feat(artifacts): inspect NuGet package metadata and dependencies
Inspect supplied NuGet packages as local Evidence with bounded ZIP parsing, preserved caller choices and credential-safe metadata. Fixes #8144 Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning) Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com>
This commit is contained in:
1 parent
3c71d3528f
commit
43b9fa87fb
78 files changed
+3525
-19
No files matched your search
@@ -416,6 +416,14 @@ explicit path or endpoint and do not need it.
|
||||
Evidence. CLI summary requires `--evidence_output`. Missing table counts stay
|
||||
null; decoded empty tables count zero. Bytecode is not executed. See the
|
||||
[Erlang BEAM guide](https://github.com/morluto/rea/blob/main/docs/erlang-beam.md).
|
||||
- NuGet `.nupkg` package identity, dependency groups and ZIP inventory:
|
||||
`inspect_nuget_nupkg` with the explicit local file. This built-in
|
||||
target-free inspection does not restore the package, execute it, or contact a
|
||||
feed. Preserve identity fields as present, dependency version ranges as
|
||||
spelled, and path-derived member roles. Missing, ambiguous, or malformed
|
||||
`.nuspec` members still return the inventory with limitations. Encrypted
|
||||
members are listed and not extracted. See the
|
||||
[NuGet packages guide](https://github.com/morluto/rea/blob/main/docs/guides/managed/nuget-nupkg.md).
|
||||
|
||||
- Explicit local SQLite database snapshot: `inspect_sqlite_database`. Inspect
|
||||
with Node.js 24.x >=24.15 or 26+ providing native SQLite limits. Read schema
|
||||
|
||||
@@ -371,6 +371,19 @@ exports retain every arity and original atom index. CLI summary delivery require
|
||||
`--evidence_output`. Null table counts remain distinct from decoded empty tables. See
|
||||
[Erlang BEAM files](https://github.com/morluto/rea/blob/main/docs/erlang-beam.md).
|
||||
|
||||
## NuGet packages
|
||||
|
||||
Use `inspect_nuget_nupkg` for an explicit local `.nupkg` when the question
|
||||
concerns package identity, license, repository, dependency groups, or the ZIP
|
||||
contents inventory. No `open_binary`, restore, feed access, or target execution
|
||||
is required. The CLI equivalent is `inspect-nuget-nupkg PATH`. Preserve artifact
|
||||
SHA-256, `.nuspec` fields as present, dependency version ranges as spelled, and
|
||||
path-derived member roles (`lib`, `ref`, `runtimes`, and the other NuGet folder
|
||||
conventions). Missing, ambiguous, or malformed `.nuspec` members succeed with
|
||||
inventory and limitations. Encrypted members are listed and not extracted.
|
||||
Roles are folder conventions, not restore-time asset selection. See
|
||||
[NuGet packages](https://github.com/morluto/rea/blob/main/docs/guides/managed/nuget-nupkg.md).
|
||||
|
||||
## SQLite snapshots
|
||||
|
||||
Use `inspect_sqlite_database` with an explicit local database snapshot for its
|
||||
|
||||
@@ -416,6 +416,14 @@ explicit path or endpoint and do not need it.
|
||||
Evidence. CLI summary requires `--evidence_output`. Missing table counts stay
|
||||
null; decoded empty tables count zero. Bytecode is not executed. See the
|
||||
[Erlang BEAM guide](https://github.com/morluto/rea/blob/main/docs/erlang-beam.md).
|
||||
- NuGet `.nupkg` package identity, dependency groups and ZIP inventory:
|
||||
`inspect_nuget_nupkg` with the explicit local file. This built-in
|
||||
target-free inspection does not restore the package, execute it, or contact a
|
||||
feed. Preserve identity fields as present, dependency version ranges as
|
||||
spelled, and path-derived member roles. Missing, ambiguous, or malformed
|
||||
`.nuspec` members still return the inventory with limitations. Encrypted
|
||||
members are listed and not extracted. See the
|
||||
[NuGet packages guide](https://github.com/morluto/rea/blob/main/docs/guides/managed/nuget-nupkg.md).
|
||||
|
||||
- Explicit local SQLite database snapshot: `inspect_sqlite_database`. Inspect
|
||||
with Node.js 24.x >=24.15 or 26+ providing native SQLite limits. Read schema
|
||||
|
||||
@@ -371,6 +371,19 @@ exports retain every arity and original atom index. CLI summary delivery require
|
||||
`--evidence_output`. Null table counts remain distinct from decoded empty tables. See
|
||||
[Erlang BEAM files](https://github.com/morluto/rea/blob/main/docs/erlang-beam.md).
|
||||
|
||||
## NuGet packages
|
||||
|
||||
Use `inspect_nuget_nupkg` for an explicit local `.nupkg` when the question
|
||||
concerns package identity, license, repository, dependency groups, or the ZIP
|
||||
contents inventory. No `open_binary`, restore, feed access, or target execution
|
||||
is required. The CLI equivalent is `inspect-nuget-nupkg PATH`. Preserve artifact
|
||||
SHA-256, `.nuspec` fields as present, dependency version ranges as spelled, and
|
||||
path-derived member roles (`lib`, `ref`, `runtimes`, and the other NuGet folder
|
||||
conventions). Missing, ambiguous, or malformed `.nuspec` members succeed with
|
||||
inventory and limitations. Encrypted members are listed and not extracted.
|
||||
Roles are folder conventions, not restore-time asset selection. See
|
||||
[NuGet packages](https://github.com/morluto/rea/blob/main/docs/guides/managed/nuget-nupkg.md).
|
||||
|
||||
## SQLite snapshots
|
||||
|
||||
Use `inspect_sqlite_database` with an explicit local database snapshot for its
|
||||
|
||||
@@ -212,6 +212,7 @@ Additional tools and host support depend on the target:
|
||||
| Apple IPS crashes | .ips metadata, threads, images, registers and documented crash classes | Built-in static JSON inspection; [Apple IPS](docs/apple-ips.md) |
|
||||
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](docs/kernel-modules.md) |
|
||||
| Erlang BEAM | IFF chunks, atoms, exports, imports, lambdas and the Code header | Built-in static BEAM inspection; [Erlang BEAM](docs/erlang-beam.md) |
|
||||
| NuGet packages | Package identity, dependency groups, license, repository and ZIP contents | Built-in static .nupkg inspection; [NuGet packages](docs/guides/managed/nuget-nupkg.md) |
|
||||
| WASM artifact | Validation, sections, exact import/export WAT forms and decoded WAT | Caller-supplied WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| EVM bytecode | Dispatch selectors, byte offsets, inferred arguments and mutability | Local raw/hex carrier on Linux x64; [offline EVM guide](docs/guides/evm/evm-bytecode.md) |
|
||||
| SQLite databases | Tables, columns, indexes, views, triggers and selected ordinary-table rows | Local database/WAL snapshot; Node.js 24.x >=24.15 or 26+ with native SQLite limits |
|
||||
|
||||
@@ -213,6 +213,11 @@ export const documentationSections = [
|
||||
source: "guides/managed/managed-code-analysis.md",
|
||||
route: "/managed-code-analysis",
|
||||
},
|
||||
{
|
||||
text: "NuGet packages",
|
||||
source: "guides/managed/nuget-nupkg.md",
|
||||
route: "/nuget-nupkg",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -196,6 +196,7 @@ the exact commit messages and references from the release they describe.
|
||||
- [Model file declarations](model-artifacts.md)
|
||||
- [Match native functions across builds](native-function-matching.md)
|
||||
- [Node.js single executable applications](node-sea.md)
|
||||
- [NuGet packages](guides/managed/nuget-nupkg.md)
|
||||
- [PE Authenticode certificate tables](pe-certificates.md)
|
||||
- [PE import and delay-load tables](pe-imports.md)
|
||||
- [PE TLS callbacks and load configuration](pe-load-config.md)
|
||||
|
||||
@@ -630,6 +630,17 @@ The workflow reports IFF chunk names, atom tables, exports, imports, lambdas,
|
||||
and the Code chunk header. Missing optional tables stay null. See
|
||||
[Erlang BEAM files](../erlang-beam.md).
|
||||
|
||||
Inspect a NuGet `.nupkg` without restoring the package or contacting a feed:
|
||||
|
||||
```bash
|
||||
rea inspect-nuget-nupkg /absolute/path/to/Demo.Package.1.2.3.nupkg --json
|
||||
```
|
||||
|
||||
The workflow reports package identity, license and repository fields as present,
|
||||
dependency groups with version ranges, and a ZIP contents inventory with
|
||||
path-derived folder roles. Missing or malformed `.nuspec` members still return
|
||||
the inventory with limitations. See [NuGet packages](../guides/managed/nuget-nupkg.md).
|
||||
|
||||
Complete `rea decompile --json` Evidence can be saved and inspected through
|
||||
`inspect-analysis-view` with an inline source and
|
||||
`view: {kind: "native", facet: "pseudocode", offset: 0, limit: 20000}`.
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
# NuGet packages
|
||||
|
||||
`inspect_nuget_nupkg` / `inspect-nuget-nupkg` reads one selected local `.nupkg`
|
||||
as a ZIP and reports package identity, dependency groups, and a contents
|
||||
inventory from the `.nuspec` and related package files. It does not restore the
|
||||
package, execute anything in it, or contact a NuGet feed.
|
||||
|
||||
```bash
|
||||
rea inspect-nuget-nupkg /absolute/path/to/Demo.Package.1.2.3.nupkg --json
|
||||
```
|
||||
|
||||
With `--detail summary --evidence_output /absolute/path/nupkg.json`, the CLI
|
||||
saves the complete Evidence as a new bundle and prints a summary view with the
|
||||
package identity, license, repository, selected `.nuspec`, coverage, and counts
|
||||
of dependency groups, dependencies, contents and limitations.
|
||||
|
||||
The CLI resolves relative paths against the caller's working directory. MCP
|
||||
requires an absolute filesystem path and preserves that exact selection:
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "inspect_nuget_nupkg",
|
||||
"arguments": { "path": "/artifacts/Demo.Package.1.2.3.nupkg" }
|
||||
}
|
||||
```
|
||||
|
||||
## Observations
|
||||
|
||||
The inline Evidence result contains the artifact path, SHA-256, and byte length.
|
||||
|
||||
`identity` reports `id`, `version`, `authors`, and `description` as present in
|
||||
the `.nuspec` metadata. Missing fields are `null`. When no `.nuspec` can be
|
||||
selected, `identity` is `null`.
|
||||
|
||||
`license` reports the `.nuspec` license element: `type` is `expression` or
|
||||
`file` when that attribute is present, otherwise `null`, and `value` is the
|
||||
element text. `repository` reports `type`, `url`, `commit`, and `branch`
|
||||
attributes when a repository element is present. Absent elements stay `null`.
|
||||
Transport URL userinfo is excluded, with `url_credentials_redacted` marking
|
||||
that exclusion; a URL whose credential span cannot be located is `null` with
|
||||
that flag set. Other URL spelling and query values are preserved. OPC
|
||||
relationship diagnostics apply the same exclusion.
|
||||
|
||||
`dependency_groups` lists each `.nuspec` dependency group with its
|
||||
`target_framework` and dependencies (`id`, `version` range as spelled,
|
||||
`include`, `exclude`, `development_dependency`). Ungrouped dependencies appear
|
||||
as a group with `target_framework: null`. Version ranges are recorded as text;
|
||||
restore results are unknown.
|
||||
|
||||
`contents` lists file ZIP members with the stored ZIP `name`, a logical `path`
|
||||
(backslashes as `/`, leading `./` removed), uncompressed and compressed sizes,
|
||||
an `encrypted` flag, and a `path`-derived `role` (`lib`, `ref`, `runtimes`,
|
||||
`native`, `analyzers`, `build`, `buildTransitive`, `buildMultiTargeting`,
|
||||
`content`, `contentFiles`, `tools`, `nuspec`, `opc`, or `unknown`). Directory
|
||||
markers are omitted. Encrypted members are listed and not extracted.
|
||||
Unflagged non-ASCII names use the ZIP CP437 fallback unless a valid Unicode Path
|
||||
extra field supplies the name. For fallback names, limitations identify the
|
||||
member, retain the exact raw filename bytes as hex, and mark the source encoding
|
||||
as unverified. ASCII names, flagged UTF-8 names, and valid Unicode Path names do
|
||||
not carry that uncertainty warning.
|
||||
|
||||
`nuspec` names the selected manifest path, decoded byte length, and whether it
|
||||
came from an OPC `_rels/.rels` manifest relationship or a unique root `.nuspec`.
|
||||
When selection is missing or ambiguous, `nuspec` is `null` and the inventory
|
||||
still succeeds with a limitation.
|
||||
|
||||
The `.nuspec` is chosen from a unique OPC relationship whose Type ends in
|
||||
`/manifest` when that target exists in the ZIP. Otherwise a unique `.nuspec` at
|
||||
the package root is used. Multiple conflicting manifests are not decoded.
|
||||
|
||||
## Limits and failures
|
||||
|
||||
The selected file is limited to 64 MiB by default (512 MiB maximum). At most
|
||||
4096 ZIP entries are inventoried by default (65536 maximum), and the selected
|
||||
`.nuspec` is limited to 1 MiB by default (16 MiB maximum). Invalid ZIP input
|
||||
fails without a partial inventory.
|
||||
|
||||
Missing, ambiguous, or malformed `.nuspec` members succeed with the ZIP
|
||||
inventory and explicit limitations. This workflow does not restore packages,
|
||||
verify signatures, or select assets the way `dotnet restore` would. Member
|
||||
roles are folder conventions in ZIP names. Package identity, license,
|
||||
repository, and dependency metadata are publisher-provided and do not establish
|
||||
package safety.
|
||||
|
||||
Evidence parameters retain only caller-selected controls; execution resolves omitted budgets from the documented defaults.
|
||||
+13
-13
@@ -49,19 +49,19 @@ For runtime instrumentation, see the [Frida guide](guides/runtime/frida-instrume
|
||||
|
||||
The [documentation directory](README.md) lists every guide by domain.
|
||||
|
||||
| Task | Guides |
|
||||
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Identify a desktop installation | [Runtime candidates, evidence and follow-up files](desktop-applications.md) |
|
||||
| Inspect native functions, references, or types | [Native binaries](guides/native/native-investigation.md), [Go metadata](guides/native/go-binaries.md), [Rust dependencies](rust-binaries.md), [CPython pyc files](python-pyc.md), [PE certificates](pe-certificates.md), [PE imports](pe-imports.md), [PE TLS/load config](pe-load-config.md), [ELF notes](elf-notes.md), [DWARF compile units](guides/native/dwarf-units.md), [ELF debug files](guides/native/elf-debug-link.md), [ELF dependencies](elf-dependencies.md), [initializer functions](guides/native/native-initializers.md), [ELF unwind ranges](guides/native/elf-unwind-ranges.md), [Linux kernel modules](kernel-modules.md), [Linux kernel build config](guides/native/kernel-build-config.md), [Apple IPS](apple-ips.md), [Erlang BEAM](erlang-beam.md), [offline ELF layout](guides/native/binary-diagnostics.md), [recorded crashes](guides/native/recorded-crashes.md) |
|
||||
| Select a native provider or import format | [Ghidra semantics](providers/ghidra-provider.md), [Windows](providers/windows-ghidra-p0.md), [DOS](providers/ghidra-dos.md), [raw bytes](providers/raw-binary.md), [GameCube DOL](ghidra-dol.md), [MIPS](providers/ghidra-mips.md), [RISC-V](providers/ghidra-riscv.md), [PowerPC](ghidra-ppc.md), [PSP](providers/ghidra-psp.md), [NativeAOT](providers/ghidra-nativeaot.md), [IDA](providers/ida-provider.md), [Kuna](kuna-provider.md), [JEB](providers/jeb-analysis.md) |
|
||||
| Analyze JavaScript or Electron artifacts | [Static analysis](guides/javascript/javascript-artifact-reconstruction.md), [tracing and comparisons](guides/javascript/javascript-application-workflows.md), [application graph](guides/javascript/javascript-application-graph.md), [source recovery](guides/javascript/javascript-recovery.md) |
|
||||
| Compare static JavaScript with runtime observations | [Runtime attribution](guides/javascript/javascript-runtime-observation.md), [reconciliation](guides/javascript/javascript-runtime-reconciliation.md), [Electron observation](guides/javascript/electron-observation.md), [Electron fuses](electron-fuses.md), [Release exposure](release-exposure.md) |
|
||||
| Inspect assemblies, packages, or firmware | [Godot PCK](godot-pck.md), [UnityFS](unityfs.md), [wxapkg](wxapkg.md), [U-Boot uImage](uimage.md), [Android boot images](android-boot-image.md), [.NET](guides/managed/managed-code-analysis.md), [Python packages](python-packaged-applications.md), [Android](guides/android/android-analysis.md), [APK signatures](apk-signature.md), [Apktool resources](guides/android/apktool-resource-analysis.md), [ADB acquisition](guides/android/adb-device-analysis.md), [Apple](guides/apple/apple-application-analysis.md), [Harmony](guides/harmony/harmony-analysis.md), [firmware](guides/firmware/firmware-analysis.md), [Device Tree](devicetree.md), [FIT images](fit-images.md), [UF2/DfuSe](uf2-dfuse.md), [Flutter](guides/android/flutter-analysis.md), [ESP images](esp-image.md), [ESP flash images](esp-flash-image.md), [WASM](guides/wasm/wasm-artifacts.md), [EVM](guides/evm/evm-bytecode.md) |
|
||||
| Observe or compare a browser scenario | [CDP observation](guides/web/browser-observation.md), [scenarios](guides/web/browser-scenario-contract.md), [runtime evidence](guides/web/web-runtime.md), [historical captures](guides/web/web-network-captures.md) |
|
||||
| Serve recorded behavior as an agent environment | [Agent environments](agent-environments.md) |
|
||||
| Trace captured website source | [Source locations](guides/web/web-source-location.md), [module traces](guides/web/website-module-trace.md), [script export](guides/web/website-script-export.md) |
|
||||
| Capture and compare a command | [Process capture](guides/runtime/process-capture.md) |
|
||||
| Use CLI/MCP and retain evidence | [CLI](getting-started/cli.md), [MCP contracts](reference/mcp-contracts.md), [agent prompts](getting-started/mcp-prompts.md), [obligation ledgers](reference/reconstruction-obligation-ledgers.md) |
|
||||
| Task | Guides |
|
||||
| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Identify a desktop installation | [Runtime candidates, evidence and follow-up files](desktop-applications.md) |
|
||||
| Inspect native functions, references, or types | [Native binaries](guides/native/native-investigation.md), [Go metadata](guides/native/go-binaries.md), [Rust dependencies](rust-binaries.md), [CPython pyc files](python-pyc.md), [PE certificates](pe-certificates.md), [PE imports](pe-imports.md), [PE TLS/load config](pe-load-config.md), [ELF notes](elf-notes.md), [DWARF compile units](guides/native/dwarf-units.md), [ELF debug files](guides/native/elf-debug-link.md), [ELF dependencies](elf-dependencies.md), [initializer functions](guides/native/native-initializers.md), [ELF unwind ranges](guides/native/elf-unwind-ranges.md), [Linux kernel modules](kernel-modules.md), [Linux kernel build config](guides/native/kernel-build-config.md), [Apple IPS](apple-ips.md), [Erlang BEAM](erlang-beam.md), [offline ELF layout](guides/native/binary-diagnostics.md), [recorded crashes](guides/native/recorded-crashes.md) |
|
||||
| Select a native provider or import format | [Ghidra semantics](providers/ghidra-provider.md), [Windows](providers/windows-ghidra-p0.md), [DOS](providers/ghidra-dos.md), [raw bytes](providers/raw-binary.md), [GameCube DOL](ghidra-dol.md), [MIPS](providers/ghidra-mips.md), [RISC-V](providers/ghidra-riscv.md), [PowerPC](ghidra-ppc.md), [PSP](providers/ghidra-psp.md), [NativeAOT](providers/ghidra-nativeaot.md), [IDA](providers/ida-provider.md), [Kuna](kuna-provider.md), [JEB](providers/jeb-analysis.md) |
|
||||
| Analyze JavaScript or Electron artifacts | [Static analysis](guides/javascript/javascript-artifact-reconstruction.md), [tracing and comparisons](guides/javascript/javascript-application-workflows.md), [application graph](guides/javascript/javascript-application-graph.md), [source recovery](guides/javascript/javascript-recovery.md) |
|
||||
| Compare static JavaScript with runtime observations | [Runtime attribution](guides/javascript/javascript-runtime-observation.md), [reconciliation](guides/javascript/javascript-runtime-reconciliation.md), [Electron observation](guides/javascript/electron-observation.md), [Electron fuses](electron-fuses.md), [Release exposure](release-exposure.md) |
|
||||
| Inspect assemblies, packages, or firmware | [Godot PCK](godot-pck.md), [UnityFS](unityfs.md), [wxapkg](wxapkg.md), [U-Boot uImage](uimage.md), [Android boot images](android-boot-image.md), [.NET](guides/managed/managed-code-analysis.md), [NuGet packages](guides/managed/nuget-nupkg.md), [Python packages](python-packaged-applications.md), [Android](guides/android/android-analysis.md), [APK signatures](apk-signature.md), [Apktool resources](guides/android/apktool-resource-analysis.md), [ADB acquisition](guides/android/adb-device-analysis.md), [Apple](guides/apple/apple-application-analysis.md), [Harmony](guides/harmony/harmony-analysis.md), [firmware](guides/firmware/firmware-analysis.md), [Device Tree](devicetree.md), [FIT images](fit-images.md), [UF2/DfuSe](uf2-dfuse.md), [Flutter](guides/android/flutter-analysis.md), [ESP images](esp-image.md), [ESP flash images](esp-flash-image.md), [WASM](guides/wasm/wasm-artifacts.md), [EVM](guides/evm/evm-bytecode.md) |
|
||||
| Observe or compare a browser scenario | [CDP observation](guides/web/browser-observation.md), [scenarios](guides/web/browser-scenario-contract.md), [runtime evidence](guides/web/web-runtime.md), [historical captures](guides/web/web-network-captures.md) |
|
||||
| Serve recorded behavior as an agent environment | [Agent environments](agent-environments.md) |
|
||||
| Trace captured website source | [Source locations](guides/web/web-source-location.md), [module traces](guides/web/website-module-trace.md), [script export](guides/web/website-script-export.md) |
|
||||
| Capture and compare a command | [Process capture](guides/runtime/process-capture.md) |
|
||||
| Use CLI/MCP and retain evidence | [CLI](getting-started/cli.md), [MCP contracts](reference/mcp-contracts.md), [agent prompts](getting-started/mcp-prompts.md), [obligation ledgers](reference/reconstruction-obligation-ledgers.md) |
|
||||
|
||||
For development, use [testing](development/testing.md), [client verification](development/client-verification.md),
|
||||
[tool design](development/tool-design.md), [admission limits and recovery](design/limits-and-recovery.md),
|
||||
|
||||
@@ -196,6 +196,7 @@ npx rea-agents@latest setup
|
||||
| ملفات النماذج | بيانات GGUF / safetensors الوصفية وتصريحات الموترات والمجاميع المشتقة | فحص الترويسات؛ بصمة الملف الكامل اختيارية; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| بيانات IL2CPP الوصفية | صور التجميعات وأسماء الأنواع والدوال ونطاقات الفهارس في Unity global-metadata.dat | فك ثابت للإصدارات 24 و27 و29 و31 و39؛ لا يتطلب Unity |
|
||||
| Godot PCK | جرد الأرشيف واستخراجه وحقائق الترويسات والأدلة الأصلية وهوية المحتوى المختار | الصيغ الثابتة 2 و3 و4؛ لا يتطلب Godot |
|
||||
| حزم NuGet | هوية الحزمة ومجموعات التبعيات والترخيص والمستودع ومحتويات ZIP | فحص ثابت مدمج لملفات .nupkg؛ [حزم NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| ملفات WASM | التحقق والأقسام وأشكال WAT الدقيقة للاستيراد والتصدير وWAT المفكوك | يوفّره المستخدم WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| توقيعات APK | الموقّعون v1/v2/v3/v3.1 وبصمات الشهادات وتدوير المفاتيح واتساق الملخصات داخليًا | فحص ثابت مدمج; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -221,6 +221,7 @@ npm. Допълнителните инструменти и поддържани
|
||||
| Сривове на Apple (IPS) | Метаданни от .ips, нишки, образи, регистри и документирани класове сривове | Вградена статична проверка на JSON; [Apple IPS](../apple-ips.md) |
|
||||
| Модули на ядрото на Linux | Ключове от .modinfo, CRC стойности от __versions, наличие на this_module и подпис в края на файла | Вградена статична проверка на ELF; [модули на ядрото](../kernel-modules.md) |
|
||||
| Erlang BEAM | IFF блокове (chunks), атоми, експорти, импорти, ламбди и заглавната част Code | Вградена статична проверка на BEAM; [Erlang BEAM](../erlang-beam.md) |
|
||||
| NuGet пакети | Идентичност на пакета, групи зависимости, лиценз, хранилище и съдържание на ZIP | Вградена статична проверка на .nupkg; [NuGet пакети](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM артефакти | Валидация, секции, точни WAT форми на импортите/експортите и декодиран WAT | Предоставен от вас WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| EVM байткод | Селектори на функции, отмествания в байтове, изведени аргументи и променливост (mutability) | Локален raw/hex носител на Linux x64; [ръководство за офлайн EVM](../guides/evm/evm-bytecode.md) |
|
||||
| SQLite бази данни | Таблици, колони, индекси, изгледи, тригери и избрани редове от обикновени таблици | Локална моментна снимка на базата/WAL; Node.js 24.x >=24.15 или 26+ с нативни ограничения на SQLite |
|
||||
|
||||
@@ -196,6 +196,7 @@ REA benötigt Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) oder 26+ (>=26.12.1) so
|
||||
| Modelldateien | GGUF-/safetensors-Metadaten, Tensordeklarationen und abgeleitete Summen | Headerprüfung; optionaler Hash der gesamten Datei; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| IL2CPP-Metadaten | Unity global-metadata.dat: Assembly-Images, Typ-/Methodennamen und Indexbereiche | Statische Dekodierung der Versionen 24, 27, 29, 31, 39; kein Unity nötig |
|
||||
| Godot PCK | Archivinventar und Extraktion, originale Header-/Verzeichnisdaten und ausgewählte Inhaltsidentitäten | Statische Formate 2, 3, 4; kein Godot nötig |
|
||||
| NuGet-Pakete | Paketidentität, Abhängigkeitsgruppen, Lizenz, Repository und ZIP-Inhalt | Integrierte statische .nupkg-Prüfung; [NuGet-Pakete](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM-Artefakte | Validierung, Sektionen, exakte Import-/Export-WAT-Formen und dekodiertes WAT | Vom Aufrufer bereitgestellt WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| APK-Signaturen | v1/v2/v3/v3.1-Signer, Zertifikatfingerabdrücke, Schlüsselrotation und Digest-Selbstkonsistenz | Integrierte statische Prüfung; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -171,6 +171,7 @@ npx rea-agents@latest setup
|
||||
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
|
||||
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
|
||||
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
|
||||
| Πακέτα NuGet | Ταυτότητα πακέτου, ομάδες εξαρτήσεων, άδεια, αποθετήριο και περιεχόμενα ZIP | Ενσωματωμένος στατικός έλεγχος .nupkg· [Πακέτα NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Αρχείο WASM | Έλεγχο εγκυρότητας, ενότητες, ακριβείς μορφές εισαγωγών/εξαγωγών σε WAT και αποκωδικοποιημένο WAT | WABT 1.0.42 που παρέχει ο χρήστης· `inspect_wasm_artifact` |
|
||||
| Bytecode EVM | Selectors επιλογής συνάρτησης, μετατοπίσεις σε bytes, εκτιμώμενα ορίσματα και δυνατότητα μεταβολής της κατάστασης | Τοπική είσοδος σε ακατέργαστα bytes ή δεκαεξαδική μορφή σε Linux x64· [οδηγός EVM χωρίς εκτέλεση](../guides/evm/evm-bytecode.md) |
|
||||
| Βάσεις δεδομένων SQLite | Πίνακες, στήλες, ευρετήρια, όψεις, triggers και επιλεγμένες γραμμές κανονικών πινάκων | Τοπικό στιγμιότυπο βάσης δεδομένων/WAL· Node.js 24.x >=24.15 ή 26+ με εγγενή όρια SQLite |
|
||||
|
||||
@@ -196,6 +196,7 @@ REA requiere Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) o 26+ (>=26.12.1), adem
|
||||
| Archivos de modelos | Metadatos GGUF / safetensors, declaraciones de tensores y totales derivados | Inspección de cabeceras; hash completo opcional; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| Metadatos IL2CPP | Imágenes de ensamblado Unity global-metadata.dat, nombres de tipos/métodos y rangos de índices | Decodificación estática de versiones 24, 27, 29, 31, 39; sin Unity |
|
||||
| Godot PCK | Inventario y extracción, cabeceras/directorios originales e identidad del contenido seleccionado | Formatos estáticos 2, 3, 4; sin Godot |
|
||||
| Paquetes NuGet | Identidad del paquete, grupos de dependencias, licencia, repositorio y contenido del ZIP | Inspección estática integrada de .nupkg; [Paquetes NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Artefactos WASM | Validación, secciones, formas WAT exactas de importación/exportación y WAT decodificado | Aportado por quien llama WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| Firmas APK | Firmantes v1/v2/v3/v3.1, huellas de certificados, rotación de claves y coherencia interna de resúmenes | Inspección estática integrada; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -188,6 +188,7 @@ REA به Node.js 22.x (>=22.23.4)، 24.x (>=24.22.1) یا 26+ (>=26.12.1)، به
|
||||
| فایلهای مدل | فرادادهٔ GGUF / safetensors، اعلان تانسورها و مجموعهای مشتقشده | بررسی هدر؛ هش کل فایل اختیاری است; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| فرادادهٔ IL2CPP | تصاویر اسمبلی، نام نوعها/متدها و بازهٔ ایندکسها در Unity global-metadata.dat | رمزگشایی ایستای نسخههای 24، 27، 29، 31 و 39؛ بدون نیاز به Unity |
|
||||
| Godot PCK | فهرست و استخراج آرشیو، اطلاعات اصلی هدر/دایرکتوری و هویت محتوای انتخابشده | قالبهای ایستای 2، 3 و 4؛ بدون نیاز به Godot |
|
||||
| بستههای NuGet | هویت بسته، گروههای وابستگی، مجوز، مخزن و محتوای ZIP | بازرسی ایستای داخلی .nupkg؛ [بستههای NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| مصنوعات WASM | اعتبارسنجی، بخشها، فرم دقیق WAT ورودی/خروجی و WAT رمزگشاییشده | تهیهشده توسط کاربر WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| امضاهای APK | امضاکنندگان v1/v2/v3/v3.1، اثر انگشت گواهی، چرخش کلید و سازگاری داخلی digest | بررسی ایستای داخلی; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -161,6 +161,7 @@ REA nécessite Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) ou 26+ (>=26.12.1), ai
|
||||
| PE certificates | Authenticode WIN_CERTIFICATE entries and PKCS#7 signer/X.509 identity fields | Built-in static PE inspection; [PE certificates](../pe-certificates.md) |
|
||||
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
|
||||
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
|
||||
| Paquets NuGet | Identité du paquet, groupes de dépendances, licence, dépôt et contenu ZIP | Inspection statique intégrée des .nupkg ; [Paquets NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Artefact WASM | Validation, sections, formes WAT exactes d'import/export et WAT décodé | WABT 1.0.42 fourni par l'utilisateur ; `inspect_wasm_artifact` |
|
||||
| Bytecode EVM | Sélecteurs de dispatch, offsets en octets, arguments inférés et mutabilité | Fichier local brut ou hexadécimal sous Linux x64 ; [guide EVM hors ligne](../guides/evm/evm-bytecode.md) |
|
||||
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
|
||||
|
||||
@@ -164,6 +164,7 @@ Alat tambahan dan dukungan sistem host bergantung pada target yang dianalisis:
|
||||
| PE certificates | Authenticode WIN_CERTIFICATE entries and PKCS#7 signer/X.509 identity fields | Built-in static PE inspection; [PE certificates](../pe-certificates.md) |
|
||||
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
|
||||
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
|
||||
| Paket NuGet | Identitas paket, grup dependensi, lisensi, repositori, dan isi ZIP | Inspeksi statis .nupkg bawaan; [Paket NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Artefak WASM | Validasi, bagian, bentuk WAT import/ekspor yang tepat, dan WAT yang didekode | WABT 1.0.42 yang disediakan pemanggil; `inspect_wasm_artifact` |
|
||||
| Bytecode EVM | Selector dispatch, offset byte, argumen yang disimpulkan, dan sifat mutabilitas | Pembawa data raw/hex lokal di Linux x64; [panduan EVM offline](../guides/evm/evm-bytecode.md) |
|
||||
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
|
||||
|
||||
@@ -161,6 +161,7 @@ REA richiede Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) o 26+ (>=26.12.1), oltre
|
||||
| PE certificates | Authenticode WIN_CERTIFICATE entries and PKCS#7 signer/X.509 identity fields | Built-in static PE inspection; [PE certificates](../pe-certificates.md) |
|
||||
| PE imports | Import and delay-load DLL names, ordinals, IAT RVAs and pefile import hash | Built-in static PE inspection; [PE imports](../pe-imports.md) |
|
||||
| Windows shortcuts | Shell Link target, arguments, working dir, ExtraData and Tracker droid facts | Built-in static LNK inspection; [Windows shortcuts](../guides/native/windows-shortcut.md) |
|
||||
| Pacchetti NuGet | Identità del pacchetto, gruppi di dipendenze, licenza, repository e contenuto ZIP | Ispezione statica integrata dei .nupkg; [Pacchetti NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Artefatto WASM | Convalida, sezioni, forme WAT di import/export esatte e WAT decodificato | WABT 1.0.42 fornito dal chiamante; `inspect_wasm_artifact` |
|
||||
| Bytecode EVM | Selettori di dispatch, offset dei byte, argomenti inferiti e mutabilità | Carrier raw/hex locale su Linux x64; [guida EVM offline](../guides/evm/evm-bytecode.md) |
|
||||
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
|
||||
|
||||
@@ -196,6 +196,7 @@ REA には Node.js 22.x(>=22.23.4)、24.x(>=24.22.1)、または 26+ (>=
|
||||
| モデルファイル | GGUF / safetensors メタデータ、テンソル宣言、導出した合計 | ヘッダー解析。任意でファイル全体をハッシュ; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| IL2CPP メタデータ | Unity global-metadata.dat のアセンブリ、型・メソッド名、インデックス範囲 | バージョン 24、27、29、31、39 を静的デコード。Unity 不要 |
|
||||
| Godot PCK | アーカイブ一覧と展開、元のヘッダー・ディレクトリ情報、選択内容の識別情報 | 形式 2、3、4 を静的解析。Godot 不要 |
|
||||
| NuGet パッケージ | パッケージ ID、依存関係グループ、ライセンス、リポジトリ、ZIP の内容 | 組み込みの静的 .nupkg 検査; [NuGet パッケージ](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM アーティファクト | 検証、セクション、正確なインポート/エクスポート WAT 形式、デコード済み WAT | 利用者が用意 WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| APK 署名 | v1/v2/v3/v3.1 署名者、証明書指紋、鍵ローテーション、ダイジェストの自己整合性 | 組み込みの静的解析; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -171,6 +171,7 @@ REA에는 Node.js 22.x(>=22.23.4), 24.x(>=24.22.1) 또는 26+ (>=26.12.1)와 npm
|
||||
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
|
||||
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
|
||||
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
|
||||
| NuGet 패키지 | 패키지 ID, 종속성 그룹, 라이선스, 리포지토리, ZIP 내용 | 내장 정적 .nupkg 검사; [NuGet 패키지](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM 아티팩트 | 유효성 검사, 섹션, import/export의 정확한 WAT 형식, 디코딩된 WAT | 호출자 제공 WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| EVM 바이트코드 | 디스패치 선택자, 바이트 오프셋, 추론한 인자와 상태 변경 가능 여부 | Linux x64의 로컬 원시 바이트/16진수 입력 파일; [오프라인 EVM 가이드](../guides/evm/evm-bytecode.md) |
|
||||
| SQLite 데이터베이스 | 테이블, 열, 인덱스, 뷰, 트리거, 선택한 일반 테이블의 행 | 로컬 데이터베이스/WAL 스냅샷; Node.js 24.15 이상의 24.x 또는 26 이상(네이티브 SQLite 한도 적용) |
|
||||
|
||||
@@ -170,6 +170,7 @@ REA-യ്ക്ക് Node.js 22.x (>=22.23.4), 24.x (>=24.22.1), അല്ല
|
||||
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
|
||||
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
|
||||
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
|
||||
| NuGet packages | Package identity, dependency groups, license, repository, ZIP ഉള്ളടക്കം | Built-in static .nupkg പരിശോധന; [NuGet packages](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM artifact | Validation, sections, കൃത്യമായ import/export WAT രൂപങ്ങൾ, decoded WAT | Caller നൽകുന്ന WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| EVM bytecode | Dispatch selectors, byte offsets, അനുമാനിച്ച arguments, mutability | Linux x64-ൽ local raw/hex carrier; [offline EVM guide](../guides/evm/evm-bytecode.md) |
|
||||
| SQLite databases | Tables, columns, indexes, views, triggers, തിരഞ്ഞെടുത്ത സാധാരണ table rows | Local database/WAL snapshot; native SQLite പരിമിതികളോടെ Node.js 24.x >=24.15 അല്ലെങ്കിൽ 26+ |
|
||||
|
||||
@@ -196,6 +196,7 @@ REA wymaga Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) lub 26+ (>=26.12.1) oraz n
|
||||
| Pliki modeli | Metadane GGUF / safetensors, deklaracje tensorów i wyliczone sumy | Odczyt nagłówków; opcjonalny hash całego pliku; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| Metadane IL2CPP | Obrazy zestawów Unity global-metadata.dat, nazwy typów/metod i zakresy indeksów | Statyczne dekodowanie wersji 24, 27, 29, 31, 39; bez Unity |
|
||||
| Godot PCK | Spis i rozpakowanie archiwum, oryginalne nagłówki/katalogi i tożsamość wybranej zawartości | Formaty statyczne 2, 3, 4; bez Godot |
|
||||
| Pakiety NuGet | Tożsamość pakietu, grupy zależności, licencja, repozytorium i zawartość ZIP | Wbudowana statyczna inspekcja .nupkg; [Pakiety NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Artefakty WASM | Walidacja, sekcje, dokładne formy WAT importów/eksportów i zdekodowany WAT | Dostarczone przez użytkownika WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| Podpisy APK | Sygnatariusze v1/v2/v3/v3.1, odciski certyfikatów, rotacja kluczy i wewnętrzna spójność skrótów | Wbudowana analiza statyczna; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -196,6 +196,7 @@ O REA requer Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) ou 26+ (>=26.12.1), alé
|
||||
| Arquivos de modelos | Metadados GGUF / safetensors, declarações de tensores e totais derivados | Inspeção de cabeçalhos; hash completo opcional; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| Metadados IL2CPP | Imagens de assemblies Unity global-metadata.dat, nomes de tipos/métodos e intervalos de índices | Decodificação estática das versões 24, 27, 29, 31, 39; sem Unity |
|
||||
| Godot PCK | Inventário e extração, cabeçalhos/diretórios originais e identidade do conteúdo selecionado | Formatos estáticos 2, 3, 4; sem Godot |
|
||||
| Pacotes NuGet | Identidade do pacote, grupos de dependências, licença, repositório e conteúdo do ZIP | Inspeção estática integrada de .nupkg; [Pacotes NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Artefatos WASM | Validação, seções, formas WAT exatas de importação/exportação e WAT decodificado | Fornecido pelo usuário WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| Assinaturas APK | Signatários v1/v2/v3/v3.1, impressões digitais de certificados, rotação de chaves e consistência interna dos resumos | Inspeção estática integrada; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -209,6 +209,7 @@ Uneltele suplimentare și platformele acceptate depind de ținta analizată:
|
||||
| Rapoarte Apple IPS de eroare fatală | Metadate .ips, fire de execuție, imagini binare, registre și clase documentate de erori fatale | Inspectare statică integrată a datelor JSON; [Apple IPS](../apple-ips.md) |
|
||||
| Module de kernel Linux | Chei .modinfo, CRC-uri din __versions, prezența this_module și structura semnăturii de la sfârșitul fișierului | Inspectare statică integrată a fișierelor ELF; [module de kernel](../kernel-modules.md) |
|
||||
| Erlang BEAM | Blocuri IFF, atomi, exporturi, importuri, funcții lambda și antetul Code | Inspectare statică integrată a fișierelor BEAM; [Erlang BEAM](../erlang-beam.md) |
|
||||
| Pachete NuGet | Identitatea pachetului, grupuri de dependențe, licență, depozit și conținutul ZIP | Inspecție statică integrată a .nupkg; [Pachete NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Fișiere WASM | Validare, secțiuni, forme WAT exacte ale importurilor și exporturilor și cod WAT decodat | WABT 1.0.42 furnizat de utilizator; `inspect_wasm_artifact` |
|
||||
| Bytecode EVM | Selectori de apel, poziții în octeți, argumente și mutabilitate deduse | Fișier local în format brut sau hexazecimal, pe Linux x64; [ghid EVM offline](../guides/evm/evm-bytecode.md) |
|
||||
| Baze de date SQLite | Tabele, coloane, indecși, vizualizări, declanșatoare și rânduri selectate din tabele obișnuite | Instantaneu local al bazei de date/WAL; Node.js 24.x >=24.15 sau 26+, cu limite SQLite native |
|
||||
|
||||
@@ -196,6 +196,7 @@ REA требует Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) или 26+ (>=26.1
|
||||
| Файлы моделей | Метаданные GGUF / safetensors, объявления тензоров и вычисленные итоги | Анализ заголовков; полный хеш файла по выбору; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| Метаданные IL2CPP | Образы сборок Unity global-metadata.dat, имена типов/методов и диапазоны индексов | Статическое декодирование версий 24, 27, 29, 31, 39; Unity не нужен |
|
||||
| Godot PCK | Список и извлечение файлов, исходные заголовки/каталоги и идентификаторы выбранного содержимого | Статические форматы 2, 3, 4; Godot не нужен |
|
||||
| Пакеты NuGet | Идентичность пакета, группы зависимостей, лицензия, репозиторий и содержимое ZIP | Встроенная статическая проверка .nupkg; [Пакеты NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Артефакты WASM | Валидация, секции, точные WAT-формы импорта/экспорта и декодированный WAT | Предоставляется пользователем WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| Подписи APK | Подписанты v1/v2/v3/v3.1, отпечатки сертификатов, ротация ключей и внутренняя согласованность хешей | Встроенный статический анализ; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -196,6 +196,7 @@ REA ต้องใช้ Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) หรื
|
||||
| ไฟล์โมเดล | เมทาดาทา GGUF / safetensors การประกาศเทนเซอร์ และยอดรวมที่คำนวณได้ | ตรวจสอบส่วนหัว; เลือกแฮชทั้งไฟล์ได้; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| เมทาดาทา IL2CPP | อิมเมจแอสเซมบลี Unity global-metadata.dat ชื่อชนิด/เมธอด และช่วงดัชนี | ถอดรหัสสแตติกเวอร์ชัน 24, 27, 29, 31, 39; ไม่ต้องใช้ Unity |
|
||||
| Godot PCK | รายการและการแตกไฟล์ ข้อมูลส่วนหัว/ไดเรกทอรีต้นฉบับ และตัวตนเนื้อหาที่เลือก | รูปแบบสแตติก 2, 3, 4; ไม่ต้องใช้ Godot |
|
||||
| แพ็กเกจ NuGet | ตัวตนของแพ็กเกจ กลุ่ม dependency ใบอนุญาต repository และเนื้อหา ZIP | การตรวจสอบ .nupkg แบบสแตติกในตัว; [แพ็กเกจ NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| อาร์ติแฟกต์ WASM | การตรวจสอบ เซกชัน รูปแบบ WAT นำเข้า/ส่งออกที่ตรงต้นฉบับ และ WAT ที่ถอดรหัส | ผู้เรียกจัดเตรียม WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| ลายเซ็น APK | ผู้ลงนาม v1/v2/v3/v3.1 ลายนิ้วมือใบรับรอง การหมุนเวียนคีย์ และความสอดคล้องภายในของไดเจสต์ | การตรวจสอบสแตติกในตัว; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -169,6 +169,7 @@ REA; Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) veya 26+ (>=26.12.1) ve npm gere
|
||||
| Apple IPS crashes | .ips metadata, threads, images, registers and crash classes | Built-in static JSON inspection; [Apple IPS](../apple-ips.md) |
|
||||
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
|
||||
| Erlang BEAM | IFF chunks, atoms, exports, and tables | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
|
||||
| NuGet paketleri | Paket kimliği, bağımlılık grupları, lisans, depo ve ZIP içeriği | Yerleşik statik .nupkg incelemesi; [NuGet paketleri](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM artefaktı | Doğrulama, bölümler, tam import/export WAT biçimleri ve decode edilmiş WAT | Çağıranın sağladığı WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| EVM bayt kodu | Yönlendirme seçicileri, bayt ofsetleri, çıkarımla belirlenen argümanlar ve durum değiştirilebilirliği | Linux x64 üzerinde yerel ham bayt/onaltılık girdi; [çevrimdışı EVM rehberi](../guides/evm/evm-bytecode.md) |
|
||||
| SQLite veritabanları | Tablolar, sütunlar, index'ler, view'lar, trigger'lar ve seçilen sıradan tablo satırları | Yerel database/WAL snapshot'ı; native SQLite sınırlarıyla Node.js 24.x >=24.15 veya 26+ |
|
||||
|
||||
@@ -196,6 +196,7 @@ REA потребує Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) або 26+ (>=26
|
||||
| Файли моделей | Метадані GGUF / safetensors, оголошення тензорів і обчислені підсумки | Перевірка заголовків; повний хеш файлу за вибором; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| Метадані IL2CPP | Образи збірок Unity global-metadata.dat, імена типів/методів та діапазони індексів | Статичне декодування версій 24, 27, 29, 31, 39; Unity не потрібен |
|
||||
| Godot PCK | Інвентар і видобування, оригінальні заголовки/каталоги та ідентичність вибраного вмісту | Статичні формати 2, 3, 4; Godot не потрібен |
|
||||
| Пакети NuGet | Ідентичність пакета, групи залежностей, ліцензія, репозиторій і вміст ZIP | Вбудована статична перевірка .nupkg; [Пакети NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Артефакти WASM | Валідація, секції, точні WAT-форми імпорту/експорту та декодований WAT | Надає користувач WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| Підписи APK | Підписувачі v1/v2/v3/v3.1, відбитки сертифікатів, ротація ключів і внутрішня узгодженість хешів | Вбудований статичний аналіз; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -209,6 +209,7 @@ Mazeed tools aur host support target par depend karte hain:
|
||||
| Binary hardening | PIE, NX, RELRO, CFG and related header flags for ELF, PE and Mach-O | Built-in static header inspection; [binary hardening](../binary-hardening.md) |
|
||||
| Linux kernel modules | .modinfo keys, __versions CRCs, this_module presence, and signature trailer | Built-in static ELF inspection; [kernel modules](../kernel-modules.md) |
|
||||
| Erlang BEAM | IFF chunks, atoms, exports, imports, lambdas aur Code header | Built-in static BEAM inspection; [Erlang BEAM](../erlang-beam.md) |
|
||||
| NuGet packages | Package identity, dependency groups, license, repository aur ZIP contents | Built-in static .nupkg inspection; [NuGet packages](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM artifact | Validation, sections, exact import/export WAT forms aur decoded WAT | Aapka diya hua WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| EVM bytecode | Dispatch selectors, byte offsets, inferred arguments aur mutability | Linux x64 par local raw/hex carrier; [offline EVM guide](../guides/evm/evm-bytecode.md) |
|
||||
| SQLite databases | Tables, columns, indexes, views, triggers aur selected ordinary-table rows | Local database/WAL snapshot; native SQLite limits ke saath Node.js 24.x >=24.15 ya 26+ |
|
||||
|
||||
@@ -196,6 +196,7 @@ REA yêu cầu Node.js 22.x (>=22.23.4), 24.x (>=24.22.1) hoặc 26+ (>=26.12.1)
|
||||
| Tệp mô hình | Siêu dữ liệu GGUF / safetensors, khai báo tensor và tổng suy ra | Kiểm tra header; tùy chọn băm toàn bộ tệp; [GGUF / safetensors](../model-artifacts.md) |
|
||||
| Siêu dữ liệu IL2CPP | Ảnh assembly Unity global-metadata.dat, tên kiểu/phương thức và phạm vi chỉ mục | Giải mã tĩnh phiên bản 24, 27, 29, 31, 39; không cần Unity |
|
||||
| Godot PCK | Danh mục và trích xuất, header/thư mục gốc và định danh nội dung được chọn | Định dạng tĩnh 2, 3, 4; không cần Godot |
|
||||
| Gói NuGet | Định danh gói, nhóm phụ thuộc, giấy phép, kho mã và nội dung ZIP | Kiểm tra tĩnh .nupkg tích hợp sẵn; [Gói NuGet](../guides/managed/nuget-nupkg.md) |
|
||||
| Hiện vật WASM | Xác thực, section, dạng WAT import/export chính xác và WAT đã giải mã | Do người gọi cung cấp WABT 1.0.42; `inspect_wasm_artifact` |
|
||||
| Chữ ký APK | Bên ký v1/v2/v3/v3.1, dấu vân tay chứng chỉ, xoay vòng khóa và tính nhất quán nội bộ của digest | Kiểm tra tĩnh tích hợp; `inspect_apk_signature` |
|
||||
|
||||
|
||||
@@ -158,6 +158,7 @@ REA 需要 Node.js 22.x(>=22.23.4)、24.x(>=24.22.1)或 26+ (>=26.12.1)
|
||||
| 原生二進位檔案 | 偽程式碼、組合語言、字串、符號、呼叫和引用 | Hopper、Ghidra、IDA 或 Kuna;[原生分析](../guides/native/native-investigation.md) |
|
||||
| 離線 ELF 佈局 | 節、段、原始符號/重定位資訊及靜態防護機制候選項 | Linux x64 上由呼叫方提供的 pwntools;[二進位診斷](../guides/native/binary-diagnostics.md) |
|
||||
| Go 二進位檔案 | 內嵌編譯器版本、模組、替換項和建置設定 | 內建靜態 ELF/PE/thin Mach-O 檢查;無需安裝 Go |
|
||||
| NuGet 套件 | 套件識別、相依性群組、授權、儲存庫及 ZIP 內容 | 內建靜態 .nupkg 檢查;[NuGet 套件](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM 工件 | 驗證、節、精確的匯入/匯出 WAT 形式及解碼後的 WAT | 呼叫方提供的 WABT 1.0.42;`inspect_wasm_artifact` |
|
||||
| EVM 位元組碼 | 分派選擇器、位元組偏移、推斷的參數和狀態可變性 | Linux x64 上的本地原始位元組/十六進位輸入載體;[離線 EVM 指南](../guides/evm/evm-bytecode.md) |
|
||||
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
|
||||
|
||||
@@ -158,6 +158,7 @@ REA 需要 Node.js 22.x(>=22.23.4)、24.x(>=24.22.1)或 26+ (>=26.12.1)
|
||||
| 原生二进制文件 | 伪代码、汇编、字符串、符号、调用和引用 | Hopper、Ghidra、IDA 或 Kuna;[原生分析](../guides/native/native-investigation.md) |
|
||||
| 离线 ELF 布局 | 节、段、原始符号/重定位信息及静态防护机制候选项 | Linux x64 上由调用方提供的 pwntools;[二进制诊断](../guides/native/binary-diagnostics.md) |
|
||||
| Go 二进制文件 | 内嵌编译器版本、模块、替换项和构建设置 | 内置静态 ELF/PE/thin Mach-O 检查;无需安装 Go |
|
||||
| NuGet 包 | 包标识、依赖组、许可证、仓库及 ZIP 内容 | 内置静态 .nupkg 检查;[NuGet 包](../guides/managed/nuget-nupkg.md) |
|
||||
| WASM 工件 | 验证、节、精确的导入/导出 WAT 形式及解码后的 WAT | 调用方提供的 WABT 1.0.42;`inspect_wasm_artifact` |
|
||||
| EVM 字节码 | 分派选择器、字节偏移、推断的参数和状态可变性 | Linux x64 上的本地原始字节/十六进制输入载体;[离线 EVM 指南](../guides/evm/evm-bytecode.md) |
|
||||
| Rust binaries | Embedded cargo-auditable dependency list | [Rust binaries](../rust-binaries.md) |
|
||||
|
||||
@@ -41,3 +41,5 @@ for new work, roadmap granularity and producer-owned contracts.
|
||||
|
||||
- [Release exposure audit](artifacts/release-exposure/spec.md) ([plan](artifacts/release-exposure/plan.md), [tasks](artifacts/release-exposure/tasks.md))
|
||||
- [CycloneDX dependency view](analysis-views/cyclonedx-dependencies/spec.md) ([plan](analysis-views/cyclonedx-dependencies/plan.md), [tasks](analysis-views/cyclonedx-dependencies/tasks.md))
|
||||
|
||||
- [NuGet package inspection](artifacts/nuget-nupkg/spec.md) ([plan](artifacts/nuget-nupkg/plan.md), [tasks](artifacts/nuget-nupkg/tasks.md))
|
||||
@@ -0,0 +1,30 @@
|
||||
# Implementation plan
|
||||
|
||||
## Boundary and contract
|
||||
|
||||
Add the result and input schemas in `src/domain/nuget/nupkg.ts` and the tool
|
||||
contract in `src/contracts/nuget/nupkgToolContracts.ts`, registered with the
|
||||
tool families, effects and capability declarations. The application port and
|
||||
service live in `src/application/nuget/`; the service admits one absolute path
|
||||
and delegates to the parser. The CLI command is `src/cli/nugetNupkgCommands.ts`.
|
||||
|
||||
`src/nuget/NugetNupkgParser.ts` owns ZIP enumeration, `.nuspec` selection and
|
||||
decoding, member roles and limitation wording. Capacity and format failures are
|
||||
typed in `src/nuget/NugetNupkg.errors.ts`.
|
||||
|
||||
## Incremental work and validation
|
||||
|
||||
1. Define the domain schema, tool contract and capability registration.
|
||||
2. Implement bounded ZIP enumeration that stops once the entry allowance is
|
||||
exceeded, then OPC and root `.nuspec` selection.
|
||||
3. Decode identity, license, repository and dependency groups with DOCTYPE
|
||||
rejection.
|
||||
4. Add the service, composition and CLI wiring.
|
||||
5. Add parser, domain and service tests with synthetic fixtures in
|
||||
`src/nuget/NugetNupkg.fixture.ts`.
|
||||
6. Update the usage guide, CLI guide, README and skill references.
|
||||
|
||||
## Effects and compatibility
|
||||
|
||||
The tool reads one existing local file. Nothing is executed, restored or
|
||||
downloaded. The change is additive to the CLI and MCP surfaces.
|
||||
@@ -0,0 +1,41 @@
|
||||
# NuGet package inspection
|
||||
|
||||
## Problem and outcome
|
||||
|
||||
A `.nupkg` is a ZIP with a `.nuspec` manifest, but REA has no owner that reads
|
||||
package identity, dependency groups or NuGet folder roles. Let
|
||||
`inspect_nuget_nupkg` / `inspect-nuget-nupkg` report that metadata and a
|
||||
contents inventory for one selected local file, without restoring the package,
|
||||
executing anything in it or contacting a NuGet feed.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Report the artifact path, SHA-256 and byte length.
|
||||
- Select the `.nuspec` from a unique OPC `_rels/.rels` relationship whose Type
|
||||
ends in `/manifest` when that target exists, otherwise from a unique root
|
||||
`.nuspec`. Missing, ambiguous or malformed manifests succeed with the ZIP
|
||||
inventory, `identity: null` and an explicit limitation.
|
||||
- Report `identity`, `license`, `repository` and `dependency_groups` as spelled
|
||||
in the `.nuspec`. Ungrouped dependencies form a group with
|
||||
`target_framework: null`. Version ranges stay text; restore results are
|
||||
unknown.
|
||||
- List file ZIP members with sizes, an `encrypted` flag and a path-derived
|
||||
NuGet folder `role`. Omit directory markers.
|
||||
- Bound the file size, ZIP entry count and `.nuspec` bytes with named
|
||||
allowances. Enforce the entry allowance while enumerating the ZIP. Refuse a
|
||||
file that is not a valid ZIP without a partial inventory.
|
||||
- Reject a DOCTYPE in the `.nuspec` and report it as a limitation.
|
||||
|
||||
## Acceptance
|
||||
|
||||
Synthetic fixtures cover a complete package, ungrouped dependencies and
|
||||
missing, ambiguous and malformed manifests. Tests cover non-ZIP refusal, the
|
||||
entry, file and `.nuspec` allowances, service path admission, and the domain
|
||||
schema. Limitation delivery is asserted through the parser-owned
|
||||
`NUPKG_LIMITATIONS` wording. The [usage guide](../../../guides/managed/nuget-nupkg.md)
|
||||
documents the result and limits.
|
||||
|
||||
## Out of scope
|
||||
|
||||
Restore-time asset selection, signature verification, feed lookups, extraction
|
||||
of package members and any judgment of package safety.
|
||||
@@ -0,0 +1,9 @@
|
||||
# Tasks
|
||||
|
||||
- [x] Define single-feature scope, contracts and implementation plan (`spec.md`, `plan.md`).
|
||||
- [x] Add the domain schema, tool contract and capability registration.
|
||||
- [x] Implement bounded ZIP enumeration and `.nuspec` selection in `src/nuget/NugetNupkgParser.ts`.
|
||||
- [x] Decode identity, license, repository and dependency groups with DOCTYPE rejection.
|
||||
- [x] Wire the service, composition and CLI command.
|
||||
- [x] Add parser, domain and service tests with synthetic fixtures.
|
||||
- [x] Update the usage guide, CLI guide, README and skill references.
|
||||
@@ -14,6 +14,7 @@ const MIGRATED_PROVIDER_ROOTS = new Set([
|
||||
"model",
|
||||
"gpu",
|
||||
"python",
|
||||
"nuget",
|
||||
"rust",
|
||||
"wasm",
|
||||
"captures",
|
||||
|
||||
@@ -81,6 +81,7 @@ export const UNIT_LAYERS = Object.freeze(
|
||||
"kuna",
|
||||
"model",
|
||||
"native",
|
||||
"nuget",
|
||||
"objdump",
|
||||
"pcap",
|
||||
"python",
|
||||
@@ -353,6 +354,7 @@ export const ENTRY_FILES = Object.freeze(
|
||||
"pwntools/PwntoolsRecordedCrashProvider.ts",
|
||||
"windows/WindowsShortcutProvider.ts",
|
||||
],
|
||||
nuget: ["NugetNupkgProvider.ts", "NugetNupkgProviderIdentity.ts"],
|
||||
objdump: ["ObjdumpCommand.ts", "ObjdumpProviderIdentity.ts"],
|
||||
pcap: [
|
||||
"PcapConfiguration.ts",
|
||||
|
||||
@@ -19,7 +19,7 @@ export const SOURCE_TEST_PROJECTS = [
|
||||
group: "source",
|
||||
include: [
|
||||
"src/*.test.ts",
|
||||
"src/{android,apkSignature,apktool,jeb,adb,artifacts,browser,compression,config,cutter,desktop,dotnet,electron,erlang,evm,firmware,flutter,frida,pcap,ghidra,go,gpu,hopper,hopperPaths,ida,inspector,javascript,kuna,main,native,process,providers,python,reference,resources,rust,server,sqlite,v8,wasm,windows}/**/*.test.ts",
|
||||
"src/{android,apkSignature,apktool,jeb,adb,artifacts,browser,compression,config,cutter,desktop,dotnet,electron,erlang,evm,firmware,flutter,frida,pcap,ghidra,go,gpu,hopper,hopperPaths,ida,inspector,javascript,kuna,main,native,nuget,process,providers,python,reference,resources,rust,server,sqlite,v8,wasm,windows}/**/*.test.ts",
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"schemas": {
|
||||
"input compact": "871987dd85a868bc",
|
||||
"output compact": "4bda7c3651bfc579"
|
||||
},
|
||||
"patterns": {
|
||||
"input": ["^[^\\x00]*$"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { NugetNupkgService } from "./NugetNupkgService.js";
|
||||
import type { NugetNupkg } from "../../domain/nuget/nupkg.js";
|
||||
import { ok } from "../../domain/result.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
} from "../../domain/analysisErrorCore.js";
|
||||
|
||||
const identity = {
|
||||
id: "fixture-nuget-nupkg",
|
||||
name: "Source-owned nupkg reader seam",
|
||||
version: "1",
|
||||
};
|
||||
const report: NugetNupkg = {
|
||||
artifact: {
|
||||
path: "/artifacts/pkg.nupkg",
|
||||
sha256: "a".repeat(64),
|
||||
bytes: 64,
|
||||
},
|
||||
identity: {
|
||||
id: "Demo.Package",
|
||||
version: "1.0.0",
|
||||
authors: "Alice",
|
||||
description: "Demo",
|
||||
},
|
||||
license: { type: "expression", value: "MIT" },
|
||||
repository: {
|
||||
type: "git",
|
||||
url: "https://example.invalid/demo",
|
||||
url_credentials_redacted: false,
|
||||
commit: null,
|
||||
branch: null,
|
||||
},
|
||||
dependency_groups: [],
|
||||
contents: [
|
||||
{
|
||||
name: "Demo.Package.nuspec",
|
||||
path: "Demo.Package.nuspec",
|
||||
uncompressed_size: 12,
|
||||
compressed_size: 12,
|
||||
role: "nuspec",
|
||||
encrypted: false,
|
||||
},
|
||||
],
|
||||
nuspec: {
|
||||
path: "Demo.Package.nuspec",
|
||||
bytes: 12,
|
||||
source: "root-nuspec",
|
||||
},
|
||||
coverage: { status: "complete", entries: 1, examined_nuspec_bytes: 12 },
|
||||
limitations: [
|
||||
"This workflow reads the .nupkg ZIP and .nuspec metadata without restoring, executing, or contacting a NuGet feed.",
|
||||
],
|
||||
};
|
||||
|
||||
it("rejects a relative path and extra arguments before reading", async () => {
|
||||
let calls = 0;
|
||||
const service = new NugetNupkgService({
|
||||
close: async () => {},
|
||||
identity,
|
||||
inspect: () => {
|
||||
calls += 1;
|
||||
return Promise.resolve(ok(report));
|
||||
},
|
||||
});
|
||||
const relative = await service.inspect({ path: "pkg.nupkg" });
|
||||
const extra = await service.inspect({
|
||||
path: report.artifact.path,
|
||||
extra: true,
|
||||
});
|
||||
const nul = await service.inspect({ path: "/artifacts/pkg\0.nupkg" });
|
||||
expect(relative.ok).toBe(false);
|
||||
expect(extra.ok).toBe(false);
|
||||
expect(nul.ok).toBe(false);
|
||||
if (!relative.ok)
|
||||
expect(relative.error).toMatchObject({
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [{ path: ["path"] }],
|
||||
});
|
||||
if (!extra.ok) expect(extra.error).toBeInstanceOf(AnalysisInputError);
|
||||
if (!nul.ok)
|
||||
expect(nul.error).toMatchObject({
|
||||
_tag: "AnalysisInputError",
|
||||
issues: [{ path: ["path"] }],
|
||||
});
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
|
||||
it("retains completed Evidence and caller selections on late cancellation", async () => {
|
||||
const controller = new AbortController();
|
||||
const reason = { source: "caller-request", operation: "cancel" };
|
||||
const service = new NugetNupkgService({
|
||||
close: async () => {},
|
||||
identity,
|
||||
inspect: () => {
|
||||
controller.abort(reason);
|
||||
return Promise.resolve(ok(report));
|
||||
},
|
||||
});
|
||||
const result = await service.inspect(
|
||||
{ path: report.artifact.path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
expect(result.error.cause).toBe(reason);
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
operation: "inspect_nuget_nupkg",
|
||||
parameters: { path: report.artifact.path },
|
||||
normalized_result: report,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it.each([undefined, 67108864, 128])(
|
||||
"preserves the caller's selected file budget %s",
|
||||
async (maximum) => {
|
||||
const input = {
|
||||
path: report.artifact.path,
|
||||
...(maximum === undefined ? {} : { max_file_bytes: maximum }),
|
||||
};
|
||||
const service = new NugetNupkgService({
|
||||
close: async () => {},
|
||||
identity,
|
||||
inspect: async () => ok(report),
|
||||
});
|
||||
const result = await service.inspect(input);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.parameters).toEqual(input);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,101 @@
|
||||
import type { ExecutionOptions } from "../../ports/AnalysisProvider.js";
|
||||
import type { NugetNupkgPort } from "../../ports/nuget/NugetNupkgPort.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import {
|
||||
inspectNugetNupkgInputSchema,
|
||||
nugetNupkgSchema,
|
||||
type NugetNupkg,
|
||||
} from "../../domain/nuget/nupkg.js";
|
||||
import { err, type Result } from "../../domain/result.js";
|
||||
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
|
||||
import {
|
||||
callerAnalysisParameters,
|
||||
parseAnalysisInput,
|
||||
} from "../AnalysisInput.js";
|
||||
|
||||
const OPERATION = "inspect_nuget_nupkg";
|
||||
|
||||
/** Shared caller validation, output parsing and Evidence provenance for CLI/MCP. */
|
||||
export class NugetNupkgService {
|
||||
constructor(readonly provider: NugetNupkgPort) {}
|
||||
|
||||
close(): Promise<void> {
|
||||
return this.provider.close();
|
||||
}
|
||||
|
||||
async inspect(
|
||||
rawInput: unknown,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<Evidence, AnalysisError>> {
|
||||
const selectedParameters = callerAnalysisParameters(rawInput);
|
||||
const input = parseAnalysisInput(
|
||||
OPERATION,
|
||||
rawInput,
|
||||
inspectNugetNupkgInputSchema,
|
||||
options?.signal,
|
||||
);
|
||||
if (!input.ok) return input;
|
||||
const result = await this.provider.inspect(input.value, options);
|
||||
if (!result.ok) return result;
|
||||
const report = nugetNupkgSchema.safeParse(result.value);
|
||||
if (
|
||||
!report.success ||
|
||||
report.data.artifact.path !== input.value.path ||
|
||||
!validReport(report.data, input.value)
|
||||
)
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
OPERATION,
|
||||
"NuGet nupkg provider returned malformed output or changed artifact identity.",
|
||||
),
|
||||
);
|
||||
const value = report.data;
|
||||
return completeProviderEvidence(
|
||||
createEvidence(
|
||||
{
|
||||
path: value.artifact.path,
|
||||
format: "file",
|
||||
sha256: value.artifact.sha256,
|
||||
},
|
||||
this.provider.identity,
|
||||
{
|
||||
operation: OPERATION,
|
||||
parameters: selectedParameters(input.value),
|
||||
result: value,
|
||||
confidence: "observed",
|
||||
limitations: value.limitations,
|
||||
locations: [
|
||||
{ kind: "artifact-path" as const, path: value.artifact.path },
|
||||
],
|
||||
},
|
||||
),
|
||||
options?.signal,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const validReport = (
|
||||
report: NugetNupkg,
|
||||
input: {
|
||||
readonly max_file_bytes: number;
|
||||
readonly max_entries: number;
|
||||
readonly max_nuspec_bytes: number;
|
||||
},
|
||||
): boolean => {
|
||||
if (
|
||||
report.artifact.bytes > input.max_file_bytes ||
|
||||
report.coverage.entries > input.max_entries ||
|
||||
report.contents.length > input.max_entries ||
|
||||
report.coverage.examined_nuspec_bytes > input.max_nuspec_bytes
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
report.nuspec?.bytes !== null &&
|
||||
report.nuspec !== null &&
|
||||
report.nuspec.bytes > input.max_nuspec_bytes
|
||||
)
|
||||
return false;
|
||||
return report.coverage.entries === report.contents.length;
|
||||
};
|
||||
@@ -31,6 +31,7 @@ import * as modelModule from "./cli/modelCommands.js";
|
||||
import * as gpuModule from "./cli/gpuCommands.js";
|
||||
import * as rustModule from "./cli/rustCommands.js";
|
||||
import * as pythonPycModule from "./cli/pythonPycCommands.js";
|
||||
import * as nugetNupkgModule from "./cli/nugetNupkgCommands.js";
|
||||
import * as erlangModule from "./cli/erlangCommands.js";
|
||||
import * as v8CodeCacheModule from "./cli/v8CodeCacheCommands.js";
|
||||
import * as sqliteModule from "./cli/sqliteCommands.js";
|
||||
@@ -87,6 +88,7 @@ const CLI_COMMAND_MODULES: CliCommandModules = {
|
||||
gpu: gpuModule,
|
||||
rust: rustModule,
|
||||
pythonPyc: pythonPycModule,
|
||||
nugetNupkg: nugetNupkgModule,
|
||||
erlang: erlangModule,
|
||||
v8CodeCache: v8CodeCacheModule,
|
||||
sqlite: sqliteModule,
|
||||
|
||||
@@ -150,6 +150,11 @@ export const CLI_COMMAND_REGISTRATIONS = {
|
||||
(module, context) =>
|
||||
module.registerPythonPycCommands(context.cli, context.logger),
|
||||
),
|
||||
nugetNupkg: plain(
|
||||
() => import("./nugetNupkgCommands.js"),
|
||||
(module, context) =>
|
||||
module.registerNugetNupkgCommands(context.cli, context.logger),
|
||||
),
|
||||
erlang: plain(
|
||||
() => import("./erlangCommands.js"),
|
||||
(module, context) =>
|
||||
@@ -442,6 +447,7 @@ const CLI_FAMILY_REGISTRATIONS: {
|
||||
"gpu",
|
||||
"rust",
|
||||
"pythonPyc",
|
||||
"nugetNupkg",
|
||||
"erlang",
|
||||
"v8CodeCache",
|
||||
"sqlite",
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { Logger } from "pino";
|
||||
|
||||
import { createNugetNupkgService } from "../composition/nugetNupkg.js";
|
||||
import { NUGET_NUPKG_TOOL_CONTRACTS } from "../contracts/nuget/nupkgToolContracts.js";
|
||||
import { contractNamed } from "./contractCliDescription.js";
|
||||
import {
|
||||
deliverWithService,
|
||||
registerContractCommand,
|
||||
} from "./contractCommand.js";
|
||||
import type { CliInstance } from "./types.js";
|
||||
|
||||
/** Inspect operator-selected NuGet packages through the same shared workflow as MCP. */
|
||||
export const registerNugetNupkgCommands = (
|
||||
cli: CliInstance,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
registerContractCommand(
|
||||
cli,
|
||||
logger,
|
||||
contractNamed(NUGET_NUPKG_TOOL_CONTRACTS, "inspect_nuget_nupkg"),
|
||||
{
|
||||
description:
|
||||
"Inspect NuGet .nupkg identity, dependency groups and ZIP contents without restore or network",
|
||||
positionals: ["path"],
|
||||
callerPaths: ["path"],
|
||||
evidenceDelivery: true,
|
||||
fields: { path: { description: "Local NuGet .nupkg package" } },
|
||||
},
|
||||
deliverWithService(createNugetNupkgService, "rea-nuget-nupkg"),
|
||||
);
|
||||
};
|
||||
@@ -97,6 +97,7 @@ import { NATIVE_MACOS_PROVIDER_IDENTITY } from "../native/NativeMacosProviderIde
|
||||
import { PWNTOOLS_PROVIDER_IDENTITY } from "../native/pwntools/PwntoolsProviderIdentity.js";
|
||||
import { OBJDUMP_PROVIDER_IDENTITY } from "../objdump/ObjdumpProviderIdentity.js";
|
||||
import { PCAP_PROVIDER_IDENTITY } from "../pcap/PcapProviderIdentity.js";
|
||||
import { NUGET_NUPKG_PROVIDER_IDENTITY } from "../nuget/NugetNupkgProviderIdentity.js";
|
||||
import { PYTHON_PYC_PROVIDER_IDENTITY } from "../python/PythonPycProviderIdentity.js";
|
||||
import { RIZIN_DEBUGGER_PROVIDER_IDENTITY } from "../rizin/RizinDebuggerProviderIdentity.js";
|
||||
import { RIZIN_PROVIDER_IDENTITY } from "../rizin/RizinProviderIdentity.js";
|
||||
@@ -498,6 +499,13 @@ export const CAPABILITY_DECLARATIONS = {
|
||||
}),
|
||||
],
|
||||
},
|
||||
nugetNupkg: {
|
||||
providers: [
|
||||
providerBinding(NUGET_NUPKG_PROVIDER_IDENTITY, {
|
||||
group: "NUGET_NUPKG_TOOL_CONTRACTS",
|
||||
}),
|
||||
],
|
||||
},
|
||||
releaseExposure: {
|
||||
providers: [
|
||||
providerBinding(RELEASE_EXPOSURE_PROVIDER, {
|
||||
|
||||
@@ -35,6 +35,7 @@ import { createIl2cppMetadataService } from "./il2cpp.js";
|
||||
import { createElectronFuseService } from "./electronFuses.js";
|
||||
import { createReleaseExposureService } from "./releaseExposure.js";
|
||||
import { createPythonPycService } from "./pythonPyc.js";
|
||||
import { createNugetNupkgService } from "./nugetNupkg.js";
|
||||
import { createWebNetworkCaptureService } from "./webNetworkCaptures.js";
|
||||
import { createWebSourceLocationService } from "./webSourceLocations.js";
|
||||
import { createWebModuleTraceService } from "./webModules.js";
|
||||
@@ -98,6 +99,7 @@ import type { GoBinaryService } from "../application/go/GoBinaryService.js";
|
||||
import type { ElectronFuseService } from "../application/electron/ElectronFuseService.js";
|
||||
import type { RustBinaryService } from "../application/rust/RustBinaryService.js";
|
||||
import type { PythonPycService } from "../application/python/PythonPycService.js";
|
||||
import type { NugetNupkgService } from "../application/nuget/NugetNupkgService.js";
|
||||
import type { BeamService } from "../application/erlang/BeamService.js";
|
||||
import type { V8CodeCacheService } from "../application/v8CodeCache/V8CodeCacheService.js";
|
||||
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
|
||||
@@ -137,6 +139,7 @@ export interface CapabilityServiceOptions {
|
||||
readonly il2cppMetadata?: Il2cppMetadataService;
|
||||
readonly rustBinary?: RustBinaryService;
|
||||
readonly pythonPyc?: PythonPycService;
|
||||
readonly nugetNupkg?: NugetNupkgService;
|
||||
readonly erlangBeam?: BeamService;
|
||||
readonly v8CodeCache?: V8CodeCacheService;
|
||||
readonly electronFuses?: ElectronFuseService;
|
||||
@@ -398,6 +401,9 @@ const modules = {
|
||||
pythonPyc: service(
|
||||
({ options }) => options.pythonPyc ?? createPythonPycService(),
|
||||
),
|
||||
nugetNupkg: service(
|
||||
({ options }) => options.nugetNupkg ?? createNugetNupkgService(),
|
||||
),
|
||||
webNetworkCapture: service(
|
||||
({ environment, options, settings }) =>
|
||||
options.webNetworkCapture ??
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { NugetNupkgPort } from "../ports/nuget/NugetNupkgPort.js";
|
||||
import { NugetNupkgService } from "../application/nuget/NugetNupkgService.js";
|
||||
import { NugetNupkgProvider } from "../nuget/NugetNupkgProvider.js";
|
||||
|
||||
/** Compose read-only .nupkg inspection without restore, execution, or network. */
|
||||
export const createNugetNupkgService = (): NugetNupkgService => {
|
||||
const provider: NugetNupkgPort = new NugetNupkgProvider();
|
||||
return new NugetNupkgService(provider);
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
inspectNugetNupkgInputSchema,
|
||||
nugetNupkgSchema,
|
||||
} from "../../domain/nuget/nupkg.js";
|
||||
import type { ToolContract } from "../toolContractTypes.js";
|
||||
import { evidenceEffects, toolContractMetadata } from "../toolEffects.js";
|
||||
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
|
||||
|
||||
/** Static NuGet package inspection is independent of restore, feeds, and active native providers. */
|
||||
export const NUGET_NUPKG_TOOL_CONTRACTS = [
|
||||
{
|
||||
name: "inspect_nuget_nupkg",
|
||||
availability: "standalone",
|
||||
cli: true,
|
||||
...toolContractMetadata("inspect_nuget_nupkg", evidenceEffects),
|
||||
kind: "artifact-provider",
|
||||
requiresActiveTarget: true,
|
||||
description:
|
||||
"Inspect a local NuGet .nupkg ZIP without restoring, executing, or contacting a feed. Returns package identity (id, version, authors, description), license and repository fields as present in the .nuspec, dependency groups with target frameworks and version ranges, and a ZIP contents inventory (entry names, sizes, encrypted flag, path-derived folder roles). Missing, ambiguous, or malformed .nuspec members succeed with inventory and explicit limitations. Encrypted members are listed and not extracted. Invalid ZIP input fails without partial success. Member roles are folder conventions, not restore-time asset selection. Complete Evidence is the result.",
|
||||
inputSchema: inspectNugetNupkgInputSchema,
|
||||
outputSchema: evidenceResultOf(nugetNupkgSchema),
|
||||
examples: [
|
||||
{
|
||||
title: "Inspect package identity and dependency groups",
|
||||
input: { path: "/artifacts/Demo.Package.1.2.3.nupkg" },
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
@@ -12,6 +12,7 @@ import { MODEL_TOOL_CONTRACTS } from "./model/modelToolContracts.js";
|
||||
import { IL2CPP_TOOL_CONTRACTS } from "./il2cpp/il2cppToolContracts.js";
|
||||
import { RUST_TOOL_CONTRACTS } from "./rust/rustToolContracts.js";
|
||||
import { PYTHON_PYC_TOOL_CONTRACTS } from "./python/pythonPycToolContracts.js";
|
||||
import { NUGET_NUPKG_TOOL_CONTRACTS } from "./nuget/nupkgToolContracts.js";
|
||||
import { ERLANG_BEAM_TOOL_CONTRACTS } from "./erlang/beamToolContracts.js";
|
||||
import { V8_CODE_CACHE_TOOL_CONTRACTS } from "./v8/v8CodeCacheToolContracts.js";
|
||||
import { SQLITE_TOOL_CONTRACTS } from "./sqlite/sqliteToolContracts.js";
|
||||
@@ -70,6 +71,7 @@ const CATALOG_CONTRACT_GROUPS = {
|
||||
GPU_TOOL_CONTRACTS,
|
||||
RUST_TOOL_CONTRACTS,
|
||||
PYTHON_PYC_TOOL_CONTRACTS,
|
||||
NUGET_NUPKG_TOOL_CONTRACTS,
|
||||
ERLANG_BEAM_TOOL_CONTRACTS,
|
||||
V8_CODE_CACHE_TOOL_CONTRACTS,
|
||||
WASM_TOOL_CONTRACTS,
|
||||
|
||||
@@ -50,6 +50,7 @@ export const TOOL_FAMILY_DEFINITIONS = [
|
||||
...TOOL_CONTRACT_GROUPS.MODEL_TOOL_CONTRACTS,
|
||||
...TOOL_CONTRACT_GROUPS.RUST_TOOL_CONTRACTS,
|
||||
...TOOL_CONTRACT_GROUPS.PYTHON_PYC_TOOL_CONTRACTS,
|
||||
...TOOL_CONTRACT_GROUPS.NUGET_NUPKG_TOOL_CONTRACTS,
|
||||
...TOOL_CONTRACT_GROUPS.ERLANG_BEAM_TOOL_CONTRACTS,
|
||||
...TOOL_CONTRACT_GROUPS.V8_CODE_CACHE_TOOL_CONTRACTS,
|
||||
...TOOL_CONTRACT_GROUPS.WASM_TOOL_CONTRACTS,
|
||||
|
||||
@@ -15,6 +15,7 @@ import { projectApkSignatureView } from "./apkSignatureView.js";
|
||||
import { byteEntropySchema } from "../native/byteEntropy.js";
|
||||
import { projectErlangBeamView } from "./erlangBeamView.js";
|
||||
import { projectPythonPycView } from "./pythonPycView.js";
|
||||
import { projectNugetNupkgView } from "./nugetNupkgView.js";
|
||||
import { projectNativeExportsView } from "./nativeExportsView.js";
|
||||
import { projectElfDependenciesView } from "./elfDependenciesView.js";
|
||||
import { projectByteEntropyView } from "./byteEntropyView.js";
|
||||
@@ -183,6 +184,7 @@ const retainedViewProjectors = new Map<string, RetainedViewProjector>([
|
||||
retain("inspect_elf_dependencies", projectElfDependenciesView),
|
||||
retain("inspect_native_load_image", projectNativeLoadImageView),
|
||||
retain("inspect_python_pyc", projectPythonPycView),
|
||||
retain("inspect_nuget_nupkg", projectNugetNupkgView),
|
||||
retain("frida_session_status", projectFridaSessionStatusView),
|
||||
retain("gdb_console", projectCommandObservationView),
|
||||
retain("inspect_with_objdump", projectCommandObservationView),
|
||||
|
||||
@@ -77,6 +77,7 @@ import {
|
||||
pythonPycViewItemsSchema,
|
||||
pythonPycSummarySchema,
|
||||
} from "./pythonPycView.js";
|
||||
import { nugetNupkgSummarySchema } from "./nugetNupkgView.js";
|
||||
import {
|
||||
nativeExportsViewRequestSchema,
|
||||
nativeExportsViewItemsSchema,
|
||||
@@ -375,6 +376,7 @@ const viewResultBase = {
|
||||
parent_operation: z.enum([
|
||||
"trace_web_source_location",
|
||||
"inspect_python_pyc",
|
||||
"inspect_nuget_nupkg",
|
||||
"inspect_erlang_beam",
|
||||
"inspect_devicetree",
|
||||
"inspect_byte_entropy",
|
||||
@@ -589,6 +591,12 @@ export const pythonPycSummaryViewResultSchema = z.strictObject({
|
||||
summary: pythonPycSummarySchema,
|
||||
});
|
||||
|
||||
export const nugetNupkgSummaryViewResultSchema = z.strictObject({
|
||||
...summaryViewResultBase,
|
||||
parent_operation: z.literal("inspect_nuget_nupkg"),
|
||||
summary: nugetNupkgSummarySchema,
|
||||
});
|
||||
|
||||
export const pythonPycCodeObjectsViewResultSchema = z.strictObject({
|
||||
...viewResultBase,
|
||||
kind: z.literal("python-pyc"),
|
||||
@@ -1443,6 +1451,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
|
||||
featureTraceSummaryViewResultSchema,
|
||||
batchDecompileSummaryViewResultSchema,
|
||||
webBundleSummaryViewResultSchema,
|
||||
nugetNupkgSummaryViewResultSchema,
|
||||
]),
|
||||
z.strictObject({
|
||||
...viewResultBase,
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { createEvidence } from "../evidence.js";
|
||||
import { projectAnalysisView } from "./analysisView.js";
|
||||
import type { AnalysisViewParent } from "./analysisViewParent.js";
|
||||
import { nugetNupkgSummaryViewResultSchema } from "./analysisViewResult.js";
|
||||
import { analysisViewRequestSchema } from "./analysisViewRequest.js";
|
||||
|
||||
const report = {
|
||||
artifact: {
|
||||
path: "/artifacts/Demo.Package.nupkg",
|
||||
sha256: "a".repeat(64),
|
||||
bytes: 100,
|
||||
},
|
||||
identity: {
|
||||
id: "Demo.Package",
|
||||
version: "1.2.3",
|
||||
authors: null,
|
||||
description: null,
|
||||
},
|
||||
license: null,
|
||||
repository: null,
|
||||
dependency_groups: [
|
||||
{
|
||||
target_framework: "net8.0",
|
||||
dependencies: [
|
||||
{
|
||||
id: "Newtonsoft.Json",
|
||||
version: "13.0.1",
|
||||
include: null,
|
||||
exclude: null,
|
||||
development_dependency: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
contents: [
|
||||
{
|
||||
name: "./Demo.Package.nuspec",
|
||||
path: "Demo.Package.nuspec",
|
||||
uncompressed_size: 12,
|
||||
compressed_size: 12,
|
||||
role: "nuspec",
|
||||
encrypted: false,
|
||||
},
|
||||
],
|
||||
nuspec: { path: "Demo.Package.nuspec", bytes: 12, source: "root-nuspec" },
|
||||
coverage: { status: "complete", entries: 1, examined_nuspec_bytes: 12 },
|
||||
limitations: ["Package condition"],
|
||||
};
|
||||
|
||||
const parent = (): AnalysisViewParent => {
|
||||
const evidence = createEvidence(
|
||||
{
|
||||
path: report.artifact.path,
|
||||
sha256: report.artifact.sha256,
|
||||
format: "file",
|
||||
},
|
||||
{ id: "rea-nuget-nupkg", name: "REA NuGet package reader", version: "1" },
|
||||
{
|
||||
operation: "inspect_nuget_nupkg",
|
||||
parameters: {},
|
||||
result: report,
|
||||
limitations: ["Parent condition"],
|
||||
},
|
||||
);
|
||||
return {
|
||||
predicateType: evidence.predicate_type,
|
||||
evidenceId: evidence.evidence_id,
|
||||
operation: evidence.operation,
|
||||
normalizedResult: report,
|
||||
subject: evidence.subject,
|
||||
limitations: evidence.limitations,
|
||||
};
|
||||
};
|
||||
|
||||
it("summarizes NuGet package Evidence with identity and counts", () => {
|
||||
const result = projectAnalysisView(
|
||||
parent(),
|
||||
analysisViewRequestSchema.parse({ kind: "summary" }),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
const view = nugetNupkgSummaryViewResultSchema.parse(result.value);
|
||||
expect(view.summary).toMatchObject({
|
||||
identity: { id: "Demo.Package", version: "1.2.3" },
|
||||
dependency_group_count: 1,
|
||||
dependency_count: 1,
|
||||
content_count: 1,
|
||||
limitation_count: 1,
|
||||
});
|
||||
expect(view.limitations).toEqual(
|
||||
expect.arrayContaining(["Parent condition", "Package condition"]),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
import { z } from "zod";
|
||||
import { nugetNupkgSchema } from "../nuget/nupkg.js";
|
||||
import { err, ok } from "../result.js";
|
||||
import type { AnalysisViewParent } from "./analysisViewParent.js";
|
||||
import {
|
||||
ownedView,
|
||||
type AdmittedView,
|
||||
type SummaryAnalysisView,
|
||||
} from "./analysisViewShape.js";
|
||||
import { analysisViewInputError } from "./analysisViewErrors.js";
|
||||
import { createAnalysisViewResultReader } from "./analysisViewParent.js";
|
||||
import {
|
||||
boundedViewMessages,
|
||||
completeWithinViewCoverage,
|
||||
} from "./analysisViewCoverage.js";
|
||||
|
||||
/** Package identity and counts; member rows and dependencies stay in the complete parent. */
|
||||
export const nugetNupkgSummarySchema = nugetNupkgSchema
|
||||
.pick({
|
||||
artifact: true,
|
||||
identity: true,
|
||||
license: true,
|
||||
repository: true,
|
||||
nuspec: true,
|
||||
coverage: true,
|
||||
})
|
||||
.extend({
|
||||
dependency_group_count: z.int().nonnegative(),
|
||||
dependency_count: z.int().nonnegative(),
|
||||
content_count: z.int().nonnegative(),
|
||||
limitation_count: z.int().nonnegative(),
|
||||
});
|
||||
|
||||
const readReport = createAnalysisViewResultReader(nugetNupkgSchema);
|
||||
|
||||
/** Summarize retained NuGet package facts without reopening the .nupkg. */
|
||||
export const projectNugetNupkgView = (
|
||||
parent: AnalysisViewParent,
|
||||
admitted: AdmittedView,
|
||||
) => {
|
||||
const view = ownedView<SummaryAnalysisView>(admitted, "summary");
|
||||
if (view === undefined)
|
||||
return err(
|
||||
analysisViewInputError([
|
||||
{
|
||||
path: ["view"],
|
||||
reason: "invalid_value",
|
||||
message: "NuGet package Evidence supports the summary view.",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const parsed = readReport(parent);
|
||||
if (!parsed.ok) return parsed;
|
||||
const report = parsed.value;
|
||||
return ok({
|
||||
parent_evidence_id: parent.evidenceId,
|
||||
parent_operation: "inspect_nuget_nupkg" as const,
|
||||
parent_digest: parent.evidenceId.slice(3),
|
||||
artifact: {
|
||||
path: report.artifact.path,
|
||||
sha256: report.artifact.sha256,
|
||||
},
|
||||
limitations: boundedViewMessages(
|
||||
[...parent.limitations, ...report.limitations],
|
||||
parent.evidenceId,
|
||||
"limitations",
|
||||
),
|
||||
unknowns: [],
|
||||
kind: "summary" as const,
|
||||
view,
|
||||
summary: {
|
||||
artifact: report.artifact,
|
||||
identity: report.identity,
|
||||
license: report.license,
|
||||
repository: report.repository,
|
||||
nuspec: report.nuspec,
|
||||
coverage: report.coverage,
|
||||
dependency_group_count: report.dependency_groups.length,
|
||||
dependency_count: report.dependency_groups.reduce(
|
||||
(total, group) => total + group.dependencies.length,
|
||||
0,
|
||||
),
|
||||
content_count: report.contents.length,
|
||||
limitation_count: report.limitations.length,
|
||||
},
|
||||
coverage: completeWithinViewCoverage(report.contents.length),
|
||||
});
|
||||
};
|
||||
@@ -89,6 +89,7 @@ export class ArtifactOperationError extends AnalysisError {
|
||||
| "inspect_elf_dependencies"
|
||||
| "inspect_kernel_build_config"
|
||||
| "inspect_erlang_beam"
|
||||
| "inspect_nuget_nupkg"
|
||||
| "inspect_v8_code_cache"
|
||||
| "extract_artifact"
|
||||
| "decode_interface_builder"
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
inspectNugetNupkgInputSchema,
|
||||
nugetNupkgEntryRole,
|
||||
nugetNupkgSchema,
|
||||
} from "./nupkg.js";
|
||||
import { absoluteLocalPathStringSchema } from "../localPath.js";
|
||||
|
||||
const jsonSchema = (schema: {
|
||||
readonly "~standard": {
|
||||
readonly jsonSchema: {
|
||||
readonly input: (options: {
|
||||
readonly target: "draft-2020-12";
|
||||
}) => unknown;
|
||||
};
|
||||
};
|
||||
}): Record<string, unknown> =>
|
||||
schema["~standard"].jsonSchema.input({
|
||||
target: "draft-2020-12",
|
||||
}) as Record<string, unknown>;
|
||||
|
||||
it("applies the shared absolute local-path policy to the public input", () => {
|
||||
expect(
|
||||
inspectNugetNupkgInputSchema.safeParse({ path: "pkg.nupkg" }).success,
|
||||
).toBe(false);
|
||||
expect(inspectNugetNupkgInputSchema.safeParse({ path: "" }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
inspectNugetNupkgInputSchema.safeParse({
|
||||
path: "/artifacts/pkg\0.nupkg",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
inspectNugetNupkgInputSchema.safeParse({
|
||||
path: "/artifacts/pkg.nupkg",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
|
||||
const shared = jsonSchema(absoluteLocalPathStringSchema);
|
||||
const advertised = jsonSchema(inspectNugetNupkgInputSchema);
|
||||
const path = (
|
||||
advertised.properties as Record<string, Record<string, unknown>>
|
||||
).path;
|
||||
const {
|
||||
$schema: _schema,
|
||||
description: _sharedDescription,
|
||||
...sharedPolicy
|
||||
} = shared;
|
||||
const { description: _pathDescription, ...pathPolicy } = path ?? {};
|
||||
expect(pathPolicy).toEqual(sharedPolicy);
|
||||
expect(path?.description).toBe(
|
||||
"Absolute filesystem path to a NuGet .nupkg package",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects extra caller arguments and admits a package with unknown identity", () => {
|
||||
expect(
|
||||
inspectNugetNupkgInputSchema.safeParse({
|
||||
path: "/artifacts/pkg.nupkg",
|
||||
extra: true,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
const report = nugetNupkgSchema.parse({
|
||||
artifact: {
|
||||
path: "/artifacts/pkg.nupkg",
|
||||
sha256: "a".repeat(64),
|
||||
bytes: 16,
|
||||
},
|
||||
identity: null,
|
||||
license: null,
|
||||
repository: null,
|
||||
dependency_groups: [],
|
||||
contents: [],
|
||||
nuspec: null,
|
||||
coverage: { status: "complete", entries: 0, examined_nuspec_bytes: 0 },
|
||||
limitations: ["No .nuspec was selected."],
|
||||
});
|
||||
expect(report.identity).toBeNull();
|
||||
expect(report.nuspec).toBeNull();
|
||||
});
|
||||
|
||||
it("derives NuGet folder roles from ZIP names", () => {
|
||||
expect(nugetNupkgEntryRole("lib/net8.0/Demo.dll")).toBe("lib");
|
||||
expect(nugetNupkgEntryRole("./ref/netstandard2.0/Demo.dll")).toBe("ref");
|
||||
expect(nugetNupkgEntryRole("runtimes/win-x64/native/demo.dll")).toBe(
|
||||
"runtimes",
|
||||
);
|
||||
expect(nugetNupkgEntryRole("native/demo.a")).toBe("native");
|
||||
expect(nugetNupkgEntryRole("analyzers/dotnet/cs/Demo.dll")).toBe("analyzers");
|
||||
expect(nugetNupkgEntryRole("build/Demo.targets")).toBe("build");
|
||||
expect(nugetNupkgEntryRole("buildTransitive/Demo.props")).toBe(
|
||||
"buildTransitive",
|
||||
);
|
||||
expect(nugetNupkgEntryRole("buildMultiTargeting/Demo.props")).toBe(
|
||||
"buildMultiTargeting",
|
||||
);
|
||||
expect(nugetNupkgEntryRole("content/readme.txt")).toBe("content");
|
||||
expect(nugetNupkgEntryRole("contentFiles/any/net8.0/data.json")).toBe(
|
||||
"contentFiles",
|
||||
);
|
||||
expect(nugetNupkgEntryRole("tools/net8.0/any/tool.dll")).toBe("tools");
|
||||
expect(nugetNupkgEntryRole("Demo.Package.nuspec")).toBe("nuspec");
|
||||
expect(nugetNupkgEntryRole("_rels/.rels")).toBe("opc");
|
||||
expect(nugetNupkgEntryRole("[Content_Types].xml")).toBe("opc");
|
||||
expect(nugetNupkgEntryRole("README.md")).toBe("unknown");
|
||||
});
|
||||
@@ -0,0 +1,193 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { digestSchema } from "../digests.js";
|
||||
import { absoluteLocalPathStringSchema } from "../localPath.js";
|
||||
import { coverageStatusSchema } from "../coverage.js";
|
||||
|
||||
/** Format identity for typed NuGet package parse failures. */
|
||||
export const NUGET_NUPKG_FORMAT = "nuget-nupkg";
|
||||
|
||||
const uint = z.number().int().min(0).max(0xffffffff);
|
||||
|
||||
/** Hard ceiling on the caller-selected input read budget. */
|
||||
export const MAX_INSPECT_NUGET_NUPKG_FILE_BYTES = 536870912;
|
||||
/** Hard ceiling on ZIP members inventoried in one package. */
|
||||
export const MAX_INSPECT_NUGET_NUPKG_ENTRIES = 65536;
|
||||
/** Hard ceiling on decoded .nuspec bytes. */
|
||||
export const MAX_INSPECT_NUGET_NUPKG_NUSPEC_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
export const NUGET_NUPKG_LIMIT_MAXIMA = {
|
||||
max_file_bytes: MAX_INSPECT_NUGET_NUPKG_FILE_BYTES,
|
||||
max_entries: MAX_INSPECT_NUGET_NUPKG_ENTRIES,
|
||||
max_nuspec_bytes: MAX_INSPECT_NUGET_NUPKG_NUSPEC_BYTES,
|
||||
} as const;
|
||||
|
||||
/** Path-derived NuGet folder roles; restore-time asset selection is not observed. */
|
||||
export const NUGET_NUPKG_ENTRY_ROLES = [
|
||||
"lib",
|
||||
"ref",
|
||||
"runtimes",
|
||||
"native",
|
||||
"analyzers",
|
||||
"build",
|
||||
"buildTransitive",
|
||||
"buildMultiTargeting",
|
||||
"content",
|
||||
"contentFiles",
|
||||
"tools",
|
||||
"nuspec",
|
||||
"opc",
|
||||
"unknown",
|
||||
] as const;
|
||||
export type NugetNupkgEntryRole = (typeof NUGET_NUPKG_ENTRY_ROLES)[number];
|
||||
|
||||
// A Map so arbitrary payload folder names never resolve inherited properties.
|
||||
const FOLDER_ROLES: ReadonlyMap<string, NugetNupkgEntryRole> = new Map([
|
||||
["lib", "lib"],
|
||||
["ref", "ref"],
|
||||
["runtimes", "runtimes"],
|
||||
["native", "native"],
|
||||
["analyzers", "analyzers"],
|
||||
["buildtransitive", "buildTransitive"],
|
||||
["buildmultitargeting", "buildMultiTargeting"],
|
||||
["build", "build"],
|
||||
["contentfiles", "contentFiles"],
|
||||
["content", "content"],
|
||||
["tools", "tools"],
|
||||
]);
|
||||
|
||||
/** Logical ZIP path with unified separators and without a leading `./`. */
|
||||
export const nugetNupkgLogicalPath = (name: string): string =>
|
||||
name.replaceAll("\\", "/").replace(/^(?:\.\/)+/u, "");
|
||||
|
||||
/** Folder convention for one ZIP member name; unknown when no convention matches. */
|
||||
export const nugetNupkgEntryRole = (name: string): NugetNupkgEntryRole => {
|
||||
const logical = nugetNupkgLogicalPath(name);
|
||||
const lower = logical.toLowerCase();
|
||||
if (
|
||||
lower === "[content_types].xml" ||
|
||||
lower.startsWith("_rels/") ||
|
||||
lower.endsWith(".rels")
|
||||
)
|
||||
return "opc";
|
||||
if (lower.endsWith(".nuspec")) return "nuspec";
|
||||
const slash = lower.indexOf("/");
|
||||
const head = slash === -1 ? lower : lower.slice(0, slash);
|
||||
return FOLDER_ROLES.get(head) ?? "unknown";
|
||||
};
|
||||
|
||||
/** Complete bounded inspection of one NuGet .nupkg ZIP. */
|
||||
export const inspectNugetNupkgInputSchema = z.strictObject({
|
||||
path: absoluteLocalPathStringSchema.describe(
|
||||
"Absolute filesystem path to a NuGet .nupkg package",
|
||||
),
|
||||
max_file_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(16)
|
||||
.max(MAX_INSPECT_NUGET_NUPKG_FILE_BYTES)
|
||||
.default(67108864)
|
||||
.describe("Maximum stable artifact bytes to read (default 64 MiB)"),
|
||||
max_entries: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(MAX_INSPECT_NUGET_NUPKG_ENTRIES)
|
||||
.default(4096)
|
||||
.describe(
|
||||
"Maximum ZIP entries to inventory; exceeding the budget fails without partial success",
|
||||
),
|
||||
max_nuspec_bytes: z
|
||||
.number()
|
||||
.int()
|
||||
.min(1)
|
||||
.max(MAX_INSPECT_NUGET_NUPKG_NUSPEC_BYTES)
|
||||
.default(1048576)
|
||||
.describe(
|
||||
"Maximum expanded bytes to decode for the .nuspec and the OPC _rels/.rels member; exceeding the budget fails without partial success",
|
||||
),
|
||||
});
|
||||
|
||||
const nullableText = z.string().min(1).nullable();
|
||||
|
||||
const dependencySchema = z.strictObject({
|
||||
id: nullableText,
|
||||
version: nullableText,
|
||||
include: nullableText,
|
||||
exclude: nullableText,
|
||||
development_dependency: z.boolean().nullable(),
|
||||
});
|
||||
|
||||
const dependencyGroupSchema = z.strictObject({
|
||||
target_framework: nullableText,
|
||||
dependencies: z.array(dependencySchema),
|
||||
});
|
||||
|
||||
const contentSchema = z.strictObject({
|
||||
/** ZIP member name as stored in the archive. */
|
||||
name: z.string().min(1),
|
||||
/** Name with separators normalized and leading `./` removed; drives role and lookup. */
|
||||
path: z.string().min(1),
|
||||
uncompressed_size: z.number().int().nonnegative().nullable(),
|
||||
compressed_size: z.number().int().nonnegative().nullable(),
|
||||
role: z.enum(NUGET_NUPKG_ENTRY_ROLES),
|
||||
encrypted: z.boolean(),
|
||||
});
|
||||
|
||||
/** Observed .nupkg identity, dependency groups, and ZIP inventory; unknowns stay null. */
|
||||
export const nugetNupkgSchema = z.strictObject({
|
||||
artifact: z.strictObject({
|
||||
path: z.string().min(1),
|
||||
sha256: digestSchema,
|
||||
bytes: uint,
|
||||
}),
|
||||
identity: z
|
||||
.strictObject({
|
||||
id: nullableText,
|
||||
version: nullableText,
|
||||
authors: nullableText,
|
||||
description: nullableText,
|
||||
})
|
||||
.nullable(),
|
||||
license: z
|
||||
.strictObject({
|
||||
type: z.enum(["expression", "file"]).nullable(),
|
||||
value: nullableText,
|
||||
})
|
||||
.nullable(),
|
||||
repository: z
|
||||
.strictObject({
|
||||
type: nullableText,
|
||||
url: nullableText,
|
||||
url_credentials_redacted: z.boolean(),
|
||||
commit: nullableText,
|
||||
branch: nullableText,
|
||||
})
|
||||
.nullable(),
|
||||
dependency_groups: z.array(dependencyGroupSchema),
|
||||
contents: z.array(contentSchema),
|
||||
nuspec: z
|
||||
.strictObject({
|
||||
path: z.string().min(1),
|
||||
bytes: uint
|
||||
.nullable()
|
||||
.describe(
|
||||
"Decoded manifest bytes; null when the member was not extracted",
|
||||
),
|
||||
source: z.enum(["opc-relationship", "root-nuspec"]),
|
||||
})
|
||||
.nullable(),
|
||||
coverage: z.strictObject({
|
||||
// Unknown when the central directory leaves member-region bytes
|
||||
// unaccounted for: local entries it omits may exist there.
|
||||
status: coverageStatusSchema,
|
||||
entries: uint,
|
||||
examined_nuspec_bytes: uint,
|
||||
}),
|
||||
limitations: z.array(z.string().min(1)).min(1),
|
||||
});
|
||||
|
||||
export type NugetNupkg = z.infer<typeof nugetNupkgSchema>;
|
||||
export type InspectNugetNupkgInput = z.infer<
|
||||
typeof inspectNugetNupkgInputSchema
|
||||
>;
|
||||
@@ -2,6 +2,7 @@ import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
parseRecordedTransportUrl,
|
||||
redactRecordedTransportUrl,
|
||||
parseUrlQueryParameterNames,
|
||||
iterateUrlQueryParameters,
|
||||
recordedPathSegments,
|
||||
@@ -83,3 +84,26 @@ it("reads only requested path coordinates, retaining empty and raw segments", ()
|
||||
),
|
||||
).toBe("wanted");
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"HTTPS://user:password@Example.invalid/a/../b?token=visible#hash",
|
||||
"HTTPS://Example.invalid/a/../b?token=visible#hash",
|
||||
true,
|
||||
],
|
||||
[
|
||||
"https://example.invalid/a?password=public-metadata",
|
||||
"https://example.invalid/a?password=public-metadata",
|
||||
false,
|
||||
],
|
||||
["https:user:password@example.invalid/a", null, true],
|
||||
[null, null, false],
|
||||
] as const)(
|
||||
"redacts only the recorded transport credential span in %s",
|
||||
(source, url, redacted) => {
|
||||
expect(redactRecordedTransportUrl(source)).toEqual({
|
||||
url,
|
||||
url_credentials_redacted: redacted,
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -194,3 +194,22 @@ export const recordedPathSegments = (
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/** Exclude only transport userinfo while retaining the remaining recorded URL spelling. */
|
||||
export const redactRecordedTransportUrl = (
|
||||
value: string | null,
|
||||
): {
|
||||
readonly url: string | null;
|
||||
readonly url_credentials_redacted: boolean;
|
||||
} => {
|
||||
if (value === null) return { url: null, url_credentials_redacted: false };
|
||||
const { credentials } = parseRecordedTransportUrl(value);
|
||||
if (credentials === null)
|
||||
return { url: value, url_credentials_redacted: false };
|
||||
if (credentials === "ambiguous")
|
||||
return { url: null, url_credentials_redacted: true };
|
||||
return {
|
||||
url: value.slice(0, credentials.start) + value.slice(credentials.end),
|
||||
url_credentials_redacted: true,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,208 @@
|
||||
import {
|
||||
TextReader,
|
||||
Uint8ArrayReader,
|
||||
Uint8ArrayWriter,
|
||||
ZipWriter,
|
||||
} from "@zip.js/zip.js";
|
||||
import { crc32 } from "node:zlib";
|
||||
|
||||
/** Real ZIP filename carriers and their independent, format-defined readings. */
|
||||
export const NUPKG_NAME_ENCODING_CASES = [
|
||||
{
|
||||
encoding: "legacy",
|
||||
rawName: Buffer.from("6c69622f6e6574382e302f822e646c6c", "hex"),
|
||||
utf8: false,
|
||||
unicodePath: null,
|
||||
name: "lib/net8.0/é.dll",
|
||||
uncertain: true,
|
||||
},
|
||||
{
|
||||
encoding: "ascii",
|
||||
rawName: Buffer.from("lib/net8.0/demo.dll"),
|
||||
utf8: false,
|
||||
unicodePath: null,
|
||||
name: "lib/net8.0/demo.dll",
|
||||
uncertain: false,
|
||||
},
|
||||
{
|
||||
encoding: "utf8",
|
||||
rawName: Buffer.from("lib/net8.0/é.dll"),
|
||||
utf8: true,
|
||||
unicodePath: null,
|
||||
name: "lib/net8.0/é.dll",
|
||||
uncertain: false,
|
||||
},
|
||||
{
|
||||
encoding: "unicode-path",
|
||||
rawName: Buffer.from("6c69622f6e6574382e302f822e646c6c", "hex"),
|
||||
utf8: false,
|
||||
unicodePath: "lib/net8.0/café.dll",
|
||||
name: "lib/net8.0/café.dll",
|
||||
uncertain: false,
|
||||
},
|
||||
] as const;
|
||||
|
||||
/** Inert package with an independently selected raw filename, EFS flag and Unicode Path claim. */
|
||||
export const nugetNupkgNameEncodingFixture = async (
|
||||
input: (typeof NUPKG_NAME_ENCODING_CASES)[number],
|
||||
): Promise<Uint8Array> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter(), {
|
||||
encodeText: (text, type) =>
|
||||
type === "filename" && text === "asset" ? input.rawName : undefined,
|
||||
});
|
||||
await writer.add("Demo.Package.nuspec", new TextReader(defaultNuspec), {
|
||||
level: 0,
|
||||
});
|
||||
let unicodeField: Buffer | undefined;
|
||||
if (input.unicodePath !== null) {
|
||||
const name = Buffer.from(input.unicodePath);
|
||||
unicodeField = Buffer.alloc(5 + name.length);
|
||||
unicodeField[0] = 1;
|
||||
unicodeField.writeUInt32LE(crc32(input.rawName), 1);
|
||||
name.copy(unicodeField, 5);
|
||||
}
|
||||
await writer.add("asset", new TextReader("benign asset bytes"), {
|
||||
level: 0,
|
||||
useUnicodeFileNames: input.utf8,
|
||||
...(unicodeField === undefined
|
||||
? {}
|
||||
: { extraField: new Map([[0x7075, unicodeField]]) }),
|
||||
});
|
||||
return writer.close();
|
||||
};
|
||||
|
||||
const CONTENT_TYPES = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
|
||||
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />
|
||||
<Default Extension="nuspec" ContentType="application/octet" />
|
||||
<Default Extension="dll" ContentType="application/octet" />
|
||||
</Types>
|
||||
`;
|
||||
|
||||
const relsXml = (
|
||||
target: string,
|
||||
): string => `<?xml version="1.0" encoding="utf-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" Target="${target}" Id="R1" />
|
||||
</Relationships>
|
||||
`;
|
||||
|
||||
const defaultNuspec = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
|
||||
<metadata>
|
||||
<id>Demo.Package</id>
|
||||
<version>1.2.3</version>
|
||||
<authors>Alice, Bob</authors>
|
||||
<description>A tiny fixture package.</description>
|
||||
<license type="expression">MIT</license>
|
||||
<repository type="git" url="https://example.invalid/demo" commit="deadbeef" branch="main" />
|
||||
<dependencies>
|
||||
<group targetFramework="net8.0">
|
||||
<dependency id="Newtonsoft.Json" version="13.0.1" />
|
||||
</group>
|
||||
<group targetFramework="netstandard2.0">
|
||||
<dependency id="Newtonsoft.Json" version="[12.0.3,13.0.0)" exclude="Build,Analyzers" />
|
||||
</group>
|
||||
</dependencies>
|
||||
</metadata>
|
||||
</package>
|
||||
`;
|
||||
|
||||
export const ungroupedNuspec = `<?xml version="1.0" encoding="utf-8"?>
|
||||
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
|
||||
<metadata>
|
||||
<id>Ungrouped.Package</id>
|
||||
<version>0.1.0</version>
|
||||
<authors>Casey</authors>
|
||||
<description>Ungrouped dependencies.</description>
|
||||
<dependencies>
|
||||
<dependency id="Foo" version="1.0.0" include="Compile" developmentDependency="true" />
|
||||
</dependencies>
|
||||
</metadata>
|
||||
</package>
|
||||
`;
|
||||
|
||||
const addText = async (
|
||||
writer: ZipWriter<Uint8Array>,
|
||||
name: string,
|
||||
text: string,
|
||||
): Promise<void> => {
|
||||
await writer.add(name, new TextReader(text), { level: 0 });
|
||||
};
|
||||
|
||||
/** Inert ZIP with OPC relationships, a .nuspec, and conventional folders. */
|
||||
export const nugetNupkgFixture = async (
|
||||
options: {
|
||||
readonly nuspec?: string;
|
||||
/** Exact .nuspec bytes, for encodings other than UTF-8. */
|
||||
readonly nuspecBytes?: Uint8Array;
|
||||
readonly nuspecName?: string;
|
||||
readonly relsTarget?: string;
|
||||
readonly extraMembers?: Readonly<Record<string, string>>;
|
||||
readonly includeRels?: boolean;
|
||||
readonly includeContentTypes?: boolean;
|
||||
} = {},
|
||||
): Promise<Uint8Array> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
const nuspecName = options.nuspecName ?? "Demo.Package.nuspec";
|
||||
if (options.includeContentTypes !== false)
|
||||
await addText(writer, "[Content_Types].xml", CONTENT_TYPES);
|
||||
if (options.includeRels !== false)
|
||||
await addText(
|
||||
writer,
|
||||
"_rels/.rels",
|
||||
relsXml(options.relsTarget ?? `/${nuspecName}`),
|
||||
);
|
||||
if (options.nuspecBytes === undefined)
|
||||
await addText(writer, nuspecName, options.nuspec ?? defaultNuspec);
|
||||
else
|
||||
await writer.add(nuspecName, new Uint8ArrayReader(options.nuspecBytes), {
|
||||
level: 0,
|
||||
});
|
||||
await writer.add(
|
||||
"lib/net8.0/Demo.dll",
|
||||
new Uint8ArrayReader(Uint8Array.from([0x4d, 0x5a])),
|
||||
{ level: 0 },
|
||||
);
|
||||
await writer.add(
|
||||
"runtimes/win-x64/native/demo.dll",
|
||||
new Uint8ArrayReader(Uint8Array.from([0x00])),
|
||||
{ level: 0 },
|
||||
);
|
||||
for (const [name, text] of Object.entries(options.extraMembers ?? {}))
|
||||
await addText(writer, name, text);
|
||||
return writer.close();
|
||||
};
|
||||
|
||||
/** ZIP that is a valid archive but has no .nuspec. */
|
||||
export const nugetNupkgMissingNuspecFixture = async (): Promise<Uint8Array> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await addText(writer, "[Content_Types].xml", CONTENT_TYPES);
|
||||
await writer.add(
|
||||
"lib/net8.0/Demo.dll",
|
||||
new Uint8ArrayReader(Uint8Array.from([0x4d, 0x5a])),
|
||||
{ level: 0 },
|
||||
);
|
||||
return writer.close();
|
||||
};
|
||||
|
||||
/** ZIP with two root .nuspec members and no OPC manifest relationship. */
|
||||
export const nugetNupkgAmbiguousNuspecFixture =
|
||||
async (): Promise<Uint8Array> => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await addText(writer, "First.nuspec", defaultNuspec);
|
||||
await addText(writer, "Second.nuspec", ungroupedNuspec);
|
||||
await writer.add(
|
||||
"lib/net8.0/Demo.dll",
|
||||
new Uint8ArrayReader(Uint8Array.from([0x4d, 0x5a])),
|
||||
{ level: 0 },
|
||||
);
|
||||
return writer.close();
|
||||
};
|
||||
|
||||
/** ZIP whose only .nuspec is not well-formed XML. */
|
||||
export const nugetNupkgMalformedNuspecFixture = async (): Promise<Uint8Array> =>
|
||||
nugetNupkgFixture({
|
||||
nuspec: "<package><metadata><id>Broken</id>",
|
||||
includeRels: false,
|
||||
});
|
||||
@@ -0,0 +1,694 @@
|
||||
import { ParseFailureError } from "../domain/parseFailure.js";
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
TextReader,
|
||||
Uint8ArrayWriter,
|
||||
ZipReader,
|
||||
ZipWriter,
|
||||
} from "@zip.js/zip.js";
|
||||
|
||||
import {
|
||||
inspectNugetNupkgInputSchema,
|
||||
nugetNupkgSchema,
|
||||
} from "../domain/nuget/nupkg.js";
|
||||
import {
|
||||
nugetNupkgAmbiguousNuspecFixture,
|
||||
nugetNupkgFixture,
|
||||
nugetNupkgMalformedNuspecFixture,
|
||||
nugetNupkgMissingNuspecFixture,
|
||||
ungroupedNuspec,
|
||||
NUPKG_NAME_ENCODING_CASES,
|
||||
nugetNupkgNameEncodingFixture,
|
||||
} from "./NugetNupkg.fixture.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
ZipArtifactReader,
|
||||
} from "../resources/index.js";
|
||||
import {
|
||||
NUPKG_LIMITATIONS,
|
||||
distinctTargetMatches,
|
||||
parseNugetNupkg,
|
||||
} from "./NugetNupkgParser.js";
|
||||
|
||||
const defaults = inspectNugetNupkgInputSchema.parse({
|
||||
path: "/artifacts/Demo.Package.nupkg",
|
||||
});
|
||||
|
||||
const artifactOf = (bytes: Uint8Array) => ({
|
||||
path: defaults.path,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.length,
|
||||
});
|
||||
|
||||
it.each(NUPKG_NAME_ENCODING_CASES)(
|
||||
"preserves $encoding filename provenance consistently with the shared ZIP reader",
|
||||
async (input) => {
|
||||
const bytes = await nugetNupkgNameEncodingFixture(input);
|
||||
const result = await parseNugetNupkg(bytes, artifactOf(bytes), defaults);
|
||||
expect(result.contents).toContainEqual(
|
||||
expect.objectContaining({
|
||||
name: input.name,
|
||||
path: input.name,
|
||||
role: "lib",
|
||||
}),
|
||||
);
|
||||
const root = await createTestTempDirectory("rea-nupkg-name-encoding-");
|
||||
const path = join(root, "package.nupkg");
|
||||
await writeFile(path, bytes);
|
||||
const reader = new ZipArtifactReader(path, "zip");
|
||||
try {
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
const shared = entries.find((entry) => entry.path === input.name);
|
||||
expect(shared).toBeDefined();
|
||||
const warnings = result.limitations.filter((value) =>
|
||||
value.includes("CP437"),
|
||||
);
|
||||
if (input.uncertain) {
|
||||
expect(shared?.limitations).toEqual([
|
||||
expect.stringContaining(input.rawName.toString("hex")),
|
||||
]);
|
||||
expect(warnings).toEqual([
|
||||
expect.stringContaining(shared!.limitations[0]!),
|
||||
]);
|
||||
expect(warnings[0]).toContain(JSON.stringify(input.name));
|
||||
} else {
|
||||
expect(shared?.limitations).toEqual([]);
|
||||
expect(warnings).toEqual([]);
|
||||
}
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("redacts an unfollowed authority manifest target before package-path normalization", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
relsTarget: "//user:password@feed.invalid/missing.nuspec?token=visible",
|
||||
});
|
||||
const result = await parseNugetNupkg(bytes, artifactOf(bytes), defaults);
|
||||
expect(JSON.stringify(result)).not.toContain("user:password");
|
||||
expect(result.limitations.join(" ")).toContain(
|
||||
"//feed.invalid/missing.nuspec?token=visible",
|
||||
);
|
||||
expect(result.nuspec?.source).toBe("root-nuspec");
|
||||
});
|
||||
|
||||
it("keeps missing manifest target provenance separate from its normalized lookup", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
relsTarget: "./part/../missing.nuspec",
|
||||
});
|
||||
const result = await parseNugetNupkg(bytes, artifactOf(bytes), defaults);
|
||||
expect(result.limitations).toContain(
|
||||
'OPC manifest relationship Target "./part/../missing.nuspec" is missing from the package; identity was not decoded from that path.',
|
||||
);
|
||||
expect(result.nuspec?.source).toBe("root-nuspec");
|
||||
});
|
||||
|
||||
it.each([
|
||||
new Error("controlled opaque decoder failure"),
|
||||
{ failure: "opaque" },
|
||||
])(
|
||||
"preserves an unclassified ZIP failure without claiming malformed bytes: %j",
|
||||
async (cause) => {
|
||||
const bytes = await nugetNupkgFixture();
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* () {
|
||||
throw cause;
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
).rejects.toBe(cause);
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("reads identity, license, repository, dependency groups and folder roles", async () => {
|
||||
const bytes = await nugetNupkgFixture();
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.identity).toEqual({
|
||||
id: "Demo.Package",
|
||||
version: "1.2.3",
|
||||
authors: "Alice, Bob",
|
||||
description: "A tiny fixture package.",
|
||||
});
|
||||
expect(report.license).toEqual({ type: "expression", value: "MIT" });
|
||||
expect(report.repository).toEqual({
|
||||
type: "git",
|
||||
url: "https://example.invalid/demo",
|
||||
url_credentials_redacted: false,
|
||||
commit: "deadbeef",
|
||||
branch: "main",
|
||||
});
|
||||
expect(report.nuspec).toMatchObject({
|
||||
path: "Demo.Package.nuspec",
|
||||
source: "opc-relationship",
|
||||
});
|
||||
expect(report.dependency_groups).toEqual([
|
||||
{
|
||||
target_framework: "net8.0",
|
||||
dependencies: [
|
||||
{
|
||||
id: "Newtonsoft.Json",
|
||||
version: "13.0.1",
|
||||
include: null,
|
||||
exclude: null,
|
||||
development_dependency: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
target_framework: "netstandard2.0",
|
||||
dependencies: [
|
||||
{
|
||||
id: "Newtonsoft.Json",
|
||||
version: "[12.0.3,13.0.0)",
|
||||
include: null,
|
||||
exclude: "Build,Analyzers",
|
||||
development_dependency: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
expect(report.contents.map((entry) => [entry.name, entry.role])).toEqual(
|
||||
expect.arrayContaining([
|
||||
["[Content_Types].xml", "opc"],
|
||||
["_rels/.rels", "opc"],
|
||||
["Demo.Package.nuspec", "nuspec"],
|
||||
["lib/net8.0/Demo.dll", "lib"],
|
||||
["runtimes/win-x64/native/demo.dll", "runtimes"],
|
||||
]),
|
||||
);
|
||||
expect(report.coverage.status).toBe("complete");
|
||||
expect(report.limitations).toContain(NUPKG_LIMITATIONS.memberRoles);
|
||||
});
|
||||
|
||||
it("keeps the stored ZIP member name beside its logical path", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
extraMembers: { "./lib/net8.0/Extra.txt": "x" },
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(
|
||||
report.contents.find((entry) => entry.path === "lib/net8.0/Extra.txt"),
|
||||
).toMatchObject({
|
||||
name: "./lib/net8.0/Extra.txt",
|
||||
path: "lib/net8.0/Extra.txt",
|
||||
role: "lib",
|
||||
});
|
||||
expect(
|
||||
report.contents.find((entry) => entry.path === "lib/net8.0/Demo.dll"),
|
||||
).toMatchObject({ name: "lib/net8.0/Demo.dll" });
|
||||
});
|
||||
|
||||
it("records ungrouped dependencies as a group with a null target framework", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
nuspec: ungroupedNuspec,
|
||||
includeRels: false,
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.nuspec?.source).toBe("root-nuspec");
|
||||
expect(report.dependency_groups).toEqual([
|
||||
{
|
||||
target_framework: null,
|
||||
dependencies: [
|
||||
{
|
||||
id: "Foo",
|
||||
version: "1.0.0",
|
||||
include: "Compile",
|
||||
exclude: null,
|
||||
development_dependency: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("inventories a package with no .nuspec and leaves identity unknown", async () => {
|
||||
const bytes = await nugetNupkgMissingNuspecFixture();
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.identity).toBeNull();
|
||||
expect(report.nuspec).toBeNull();
|
||||
expect(report.contents.some((entry) => entry.role === "lib")).toBe(true);
|
||||
expect(report.limitations).toContain(NUPKG_LIMITATIONS.noNuspec);
|
||||
});
|
||||
|
||||
it("inventories a package with an ambiguous pair of root .nuspec members", async () => {
|
||||
const bytes = await nugetNupkgAmbiguousNuspecFixture();
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.identity).toBeNull();
|
||||
expect(report.nuspec).toBeNull();
|
||||
expect(
|
||||
report.contents.filter((entry) => entry.role === "nuspec"),
|
||||
).toHaveLength(2);
|
||||
expect(report.limitations).toContain(NUPKG_LIMITATIONS.ambiguousRootNuspec);
|
||||
});
|
||||
|
||||
it("inventories a package whose .nuspec is not well-formed XML", async () => {
|
||||
const bytes = await nugetNupkgMalformedNuspecFixture();
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.identity).toBeNull();
|
||||
expect(report.nuspec?.path).toBe("Demo.Package.nuspec");
|
||||
expect(report.limitations).toContain(NUPKG_LIMITATIONS.malformedNuspec);
|
||||
});
|
||||
|
||||
it("refuses a non-ZIP file without claiming a package inventory", async () => {
|
||||
const bytes = Buffer.from("not a zip");
|
||||
await expect(
|
||||
parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
).rejects.toBeInstanceOf(ParseFailureError);
|
||||
});
|
||||
|
||||
it("stops ZIP enumeration as soon as the entry budget is exceeded", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
extraMembers: Object.fromEntries(
|
||||
Array.from({ length: 20 }, (_, index) => [
|
||||
`content/f${String(index)}.txt`,
|
||||
"x",
|
||||
]),
|
||||
),
|
||||
});
|
||||
const original = ZipReader.prototype.getEntriesGenerator;
|
||||
let yielded = 0;
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* (this: ZipReader<unknown>, options) {
|
||||
for await (const entry of original.call(this, options)) {
|
||||
yielded += 1;
|
||||
yield entry;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
parseNugetNupkg(bytes, artifactOf(bytes), {
|
||||
...defaults,
|
||||
max_entries: 2,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
constructor: ParseFailureError,
|
||||
failure: {
|
||||
kind: "limit",
|
||||
limit: { name: "max_entries", maximum: 2, required: 3 },
|
||||
},
|
||||
});
|
||||
expect(yielded).toBe(3);
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("reports cancellation during a member read with the caller's reason", async () => {
|
||||
const bytes = await nugetNupkgFixture();
|
||||
const controller = new AbortController();
|
||||
const reason = { source: "caller-request", operation: "cancel" };
|
||||
const original = ZipReader.prototype.getEntriesGenerator;
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* (this: ZipReader<unknown>, options) {
|
||||
yield* original.call(this, options);
|
||||
controller.abort(reason);
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
const failure: unknown = await parseNugetNupkg(
|
||||
bytes,
|
||||
artifactOf(bytes),
|
||||
defaults,
|
||||
controller.signal,
|
||||
).catch((cause: unknown) => cause);
|
||||
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
|
||||
expect(failure).toMatchObject({ reason: "cancelled" });
|
||||
expect((failure as ArtifactReaderFailure).cancellation?.reason).toBe(
|
||||
reason,
|
||||
);
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
const largeRelsFixture = () =>
|
||||
nugetNupkgFixture({
|
||||
includeRels: false,
|
||||
extraMembers: { "_rels/.rels": " ".repeat(4096) },
|
||||
});
|
||||
|
||||
it("refuses an OPC relationships member larger than the metadata budget before reading it", async () => {
|
||||
const bytes = await largeRelsFixture();
|
||||
await expect(
|
||||
parseNugetNupkg(bytes, artifactOf(bytes), {
|
||||
...defaults,
|
||||
max_nuspec_bytes: 1024,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
constructor: ParseFailureError,
|
||||
failure: {
|
||||
kind: "limit",
|
||||
limit: { name: "max_nuspec_bytes", maximum: 1024 },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("stops expanding an OPC relationships member at the budget when its declared size understates it", async () => {
|
||||
const bytes = await largeRelsFixture();
|
||||
const original = ZipReader.prototype.getEntriesGenerator;
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* (this: ZipReader<unknown>, options) {
|
||||
for await (const entry of original.call(this, options)) {
|
||||
if (entry.filename === "_rels/.rels") entry.uncompressedSize = 1;
|
||||
yield entry;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
await expect(
|
||||
parseNugetNupkg(bytes, artifactOf(bytes), {
|
||||
...defaults,
|
||||
max_nuspec_bytes: 1024,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
constructor: ParseFailureError,
|
||||
failure: {
|
||||
kind: "limit",
|
||||
limit: { name: "max_nuspec_bytes", maximum: 1024 },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("leaves an external manifest relationship unfollowed even when it names a ZIP member", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
includeRels: false,
|
||||
extraMembers: {
|
||||
"_rels/.rels": `<?xml version="1.0" encoding="utf-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" Target="content/Other.nuspec" TargetMode="External" Id="R1" />
|
||||
</Relationships>
|
||||
`,
|
||||
"content/Other.nuspec": ungroupedNuspec,
|
||||
},
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.nuspec).toMatchObject({
|
||||
path: "Demo.Package.nuspec",
|
||||
source: "root-nuspec",
|
||||
});
|
||||
expect(report.identity?.id).toBe("Demo.Package");
|
||||
expect(report.limitations).toContain(
|
||||
'OPC manifest relationship Target "content/Other.nuspec" is external and was not followed.',
|
||||
);
|
||||
});
|
||||
|
||||
const manifestRels = (target: string) => `<?xml version="1.0" encoding="utf-8"?>
|
||||
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
|
||||
<Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" Target="${target}" Id="R1" />
|
||||
</Relationships>
|
||||
`;
|
||||
|
||||
it.for(["manifests/./Actual.nuspec", "/manifests/extra/../Actual.nuspec"])(
|
||||
"resolves dot segments in the manifest relationship Target %s",
|
||||
async (target) => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
includeRels: false,
|
||||
extraMembers: {
|
||||
"_rels/.rels": manifestRels(target),
|
||||
"manifests/Actual.nuspec": ungroupedNuspec,
|
||||
},
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.nuspec).toMatchObject({
|
||||
path: "manifests/Actual.nuspec",
|
||||
source: "opc-relationship",
|
||||
});
|
||||
expect(report.identity?.id).toBe("Ungrouped.Package");
|
||||
},
|
||||
);
|
||||
|
||||
it("does not follow a manifest relationship Target that resolves above the package root", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
includeRels: false,
|
||||
extraMembers: { "_rels/.rels": manifestRels("../Actual.nuspec") },
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.limitations).toContain(
|
||||
'OPC manifest relationship Target "../Actual.nuspec" leaves the package and was not followed.',
|
||||
);
|
||||
});
|
||||
|
||||
const utf16Nuspec = (littleEndian: boolean) => {
|
||||
const text = ungroupedNuspec.replace('encoding="utf-8"', 'encoding="utf-16"');
|
||||
const bytes = new Uint8Array(2 + text.length * 2);
|
||||
const view = new DataView(bytes.buffer);
|
||||
view.setUint16(0, 0xfeff, littleEndian);
|
||||
for (let index = 0; index < text.length; index += 1)
|
||||
view.setUint16(2 + index * 2, text.charCodeAt(index), littleEndian);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
it.for([true, false])(
|
||||
"decodes a BOM-marked UTF-16 .nuspec (little-endian %s)",
|
||||
async (littleEndian) => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
nuspecBytes: utf16Nuspec(littleEndian),
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.identity?.id).toBe("Ungrouped.Package");
|
||||
expect(report.dependency_groups).not.toEqual([]);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps a Zstandard dictionary refusal as an unsupported layout instead of a malformed package", async () => {
|
||||
const bytes = await nugetNupkgFixture();
|
||||
const refusal = Object.assign(new Error("Dictionary mismatch"), {
|
||||
code: "ZSTD_error_dictionary_wrong",
|
||||
});
|
||||
const original = ZipReader.prototype.getEntriesGenerator;
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* (this: ZipReader<unknown>, options) {
|
||||
for await (const entry of original.call(this, options)) {
|
||||
if (entry.filename === "Demo.Package.nuspec" && !entry.directory) {
|
||||
entry.compressionMethod = 93;
|
||||
entry.getData = () => Promise.reject(refusal);
|
||||
}
|
||||
yield entry;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
const failure: unknown = await parseNugetNupkg(
|
||||
bytes,
|
||||
artifactOf(bytes),
|
||||
defaults,
|
||||
).catch((cause: unknown) => cause);
|
||||
expect(failure).toBeInstanceOf(ParseFailureError);
|
||||
expect(failure).toMatchObject({ failure: { kind: "unsupported" } });
|
||||
expect((failure as Error).message).toContain("Zstandard dictionary");
|
||||
expect(((failure as Error).cause as ArtifactReaderFailure).cause).toBe(
|
||||
refusal,
|
||||
);
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps a Zstandard decoder window refusal as a memory limit instead of a malformed package", async () => {
|
||||
const bytes = await nugetNupkgFixture();
|
||||
const refusal = Object.assign(new Error("Frame requires too much memory"), {
|
||||
code: "ZSTD_error_frameParameter_windowTooLarge",
|
||||
});
|
||||
const original = ZipReader.prototype.getEntriesGenerator;
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* (this: ZipReader<unknown>, options) {
|
||||
for await (const entry of original.call(this, options)) {
|
||||
if (entry.filename === "Demo.Package.nuspec" && !entry.directory) {
|
||||
entry.compressionMethod = 93;
|
||||
entry.getData = () => Promise.reject(refusal);
|
||||
}
|
||||
yield entry;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
const failure: unknown = await parseNugetNupkg(
|
||||
bytes,
|
||||
artifactOf(bytes),
|
||||
defaults,
|
||||
).catch((cause: unknown) => cause);
|
||||
expect(failure).toBeInstanceOf(ArtifactReaderFailure);
|
||||
expect(failure).toMatchObject({ reason: "limit", boundary: "memory" });
|
||||
expect((failure as ArtifactReaderFailure).cause).toBe(refusal);
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("reads manifest text written as CDATA and as mixed text and CDATA", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
nuspec: ungroupedNuspec
|
||||
.replace(
|
||||
"<id>Ungrouped.Package</id>",
|
||||
"<id><![CDATA[Ungrouped.Package]]></id>",
|
||||
)
|
||||
.replace(
|
||||
/<description>[^<]*<\/description>/u,
|
||||
"<description>A <![CDATA[& B]]> C</description>",
|
||||
),
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.identity).toMatchObject({
|
||||
id: "Ungrouped.Package",
|
||||
description: "A & B C",
|
||||
});
|
||||
});
|
||||
|
||||
it.for(["constructor/file.txt", "__proto__/file.txt", "toString/file.txt"])(
|
||||
"keeps payload folder %s at the unknown role",
|
||||
async (name) => {
|
||||
const bytes = await nugetNupkgFixture({ extraMembers: { [name]: "x" } });
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.contents.find((entry) => entry.path === name)?.role).toBe(
|
||||
"unknown",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves identity unknown when the manifest relationship matches case-variant members", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
includeRels: false,
|
||||
nuspecName: "First.nuspec",
|
||||
extraMembers: {
|
||||
"_rels/.rels": manifestRels("/FIRST.nuspec"),
|
||||
"first.nuspec": ungroupedNuspec,
|
||||
},
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.identity).toBeNull();
|
||||
expect(report.nuspec).toBeNull();
|
||||
expect(report.limitations).toContain(
|
||||
"OPC manifest relationships resolve to more than one .nuspec ZIP member; identity was not decoded.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports an encrypted manifest above the metadata budget without decoding it", async () => {
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("Demo.Package.nuspec", new TextReader(ungroupedNuspec), {
|
||||
password: "fixture",
|
||||
level: 0,
|
||||
});
|
||||
const bytes = await writer.close();
|
||||
const input = inspectNugetNupkgInputSchema.parse({
|
||||
path: defaults.path,
|
||||
max_nuspec_bytes: 1,
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), input),
|
||||
);
|
||||
expect(report.nuspec).toEqual({
|
||||
path: "Demo.Package.nuspec",
|
||||
bytes: null,
|
||||
source: "root-nuspec",
|
||||
});
|
||||
expect(report.coverage.examined_nuspec_bytes).toBe(0);
|
||||
expect(report.contents[0]?.encrypted).toBe(true);
|
||||
});
|
||||
|
||||
it("follows no relationships when two members normalize to _rels/.rels", async () => {
|
||||
const bytes = await nugetNupkgFixture({
|
||||
extraMembers: {
|
||||
"./_rels/.rels": manifestRels("/content/Other.nuspec"),
|
||||
"content/Other.nuspec": ungroupedNuspec,
|
||||
},
|
||||
});
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.nuspec).toMatchObject({
|
||||
path: "Demo.Package.nuspec",
|
||||
source: "root-nuspec",
|
||||
});
|
||||
expect(report.limitations).toContain(
|
||||
"More than one ZIP member is the OPC relationships part; relationships were not followed and the .nuspec was selected by ZIP name when possible.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports unknown coverage when the central directory leaves bytes unaccounted", async () => {
|
||||
const packed = Buffer.from(await nugetNupkgFixture());
|
||||
// Splice opaque bytes in front of the central directory and move the
|
||||
// end-of-central-directory offset past them, as an omitted local entry would.
|
||||
const eocd = packed.lastIndexOf(Buffer.from([0x50, 0x4b, 0x05, 0x06]));
|
||||
const directory = packed.readUInt32LE(eocd + 16);
|
||||
const hidden = Buffer.alloc(64, 0x41);
|
||||
const bytes = Buffer.concat([
|
||||
packed.subarray(0, directory),
|
||||
hidden,
|
||||
packed.subarray(directory),
|
||||
]);
|
||||
bytes.writeUInt32LE(directory + hidden.length, eocd + hidden.length + 16);
|
||||
const report = nugetNupkgSchema.parse(
|
||||
await parseNugetNupkg(bytes, artifactOf(bytes), defaults),
|
||||
);
|
||||
expect(report.coverage.status).toBe("unknown");
|
||||
expect(report.identity?.id).toBe("Demo.Package");
|
||||
expect(
|
||||
report.limitations.some((line) =>
|
||||
line.includes("does not account for 64 byte"),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("stops resolving manifest targets once a second distinct member is found", () => {
|
||||
const bucket = Array.from({ length: 10_000 }, (_, index) => ({ index }));
|
||||
const match = vi.fn((_target: string) => bucket);
|
||||
const targets = Array.from(
|
||||
{ length: 10_000 },
|
||||
(_, index) => `T${index}.nuspec`,
|
||||
);
|
||||
expect(distinctTargetMatches(targets, match)).toEqual([bucket[0], bucket[1]]);
|
||||
expect(match).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps one member when every manifest target resolves to it", () => {
|
||||
const member = { name: "Only.nuspec" };
|
||||
const match = vi.fn((_target: string) => [member]);
|
||||
const targets = Array.from({ length: 1_000 }, () => "ONLY.nuspec");
|
||||
expect(distinctTargetMatches(targets, match)).toEqual([member]);
|
||||
expect(match).toHaveBeenCalledTimes(1_000);
|
||||
});
|
||||
@@ -0,0 +1,720 @@
|
||||
import { accountZipMemberRegion } from "../domain/zip/zipMemberRegion.js";
|
||||
import {
|
||||
decodeLimit,
|
||||
malformedInput,
|
||||
ParseFailureError,
|
||||
unsupportedInput,
|
||||
} from "../domain/parseFailure.js";
|
||||
import {
|
||||
Uint8ArrayReader,
|
||||
Uint8ArrayWriter,
|
||||
ZipReader,
|
||||
type Entry,
|
||||
type FileEntry,
|
||||
} from "@zip.js/zip.js";
|
||||
import type { Element, Node } from "@xmldom/xmldom";
|
||||
|
||||
import { ArtifactReaderFailure } from "../resources/index.js";
|
||||
import {
|
||||
decodeZipEntryText,
|
||||
zipEntryNameLimitations,
|
||||
typedZipFailure,
|
||||
ZIP_READER_OPTIONS,
|
||||
zipEntryPath,
|
||||
zipListingCoverage,
|
||||
} from "../resources/index.js";
|
||||
import { parseXmlDocument } from "../domain/xmlDocument.js";
|
||||
import { decodeXmlPlistText } from "../domain/propertyListXmlText.js";
|
||||
import { hasZipSignature } from "../domain/zipPackageFormat.js";
|
||||
import {
|
||||
NUGET_NUPKG_FORMAT,
|
||||
nugetNupkgEntryRole,
|
||||
nugetNupkgLogicalPath,
|
||||
type InspectNugetNupkgInput,
|
||||
type NugetNupkg,
|
||||
} from "../domain/nuget/nupkg.js";
|
||||
import { redactRecordedTransportUrl } from "../domain/recordedTransportUrl.js";
|
||||
import { Budget } from "../domain/budget.js";
|
||||
|
||||
/** Limitation wording owned by the parser; tests assert delivery through these. */
|
||||
export const NUPKG_LIMITATIONS = {
|
||||
memberRoles:
|
||||
"Member roles are derived from NuGet folder conventions in the ZIP names; they are not restore-time asset selection.",
|
||||
noNuspec: "No .nuspec was selected.",
|
||||
ambiguousRootNuspec:
|
||||
"Multiple root .nuspec members are present; identity was not decoded.",
|
||||
malformedNuspec: "The selected .nuspec is not well-formed XML.",
|
||||
} as const;
|
||||
|
||||
const BASE_LIMITATIONS = [
|
||||
"This workflow reads the .nupkg ZIP and .nuspec metadata without restoring, executing, or contacting a NuGet feed.",
|
||||
NUPKG_LIMITATIONS.memberRoles,
|
||||
"Dependency version ranges are recorded as spelled in the .nuspec; restore results are unknown.",
|
||||
"Directory ZIP markers are omitted from contents; only file members are listed.",
|
||||
] as const;
|
||||
|
||||
const isElement = (node: Node | null): node is Element =>
|
||||
node !== null && node.nodeType === 1;
|
||||
|
||||
const childElements = (element: Element): Element[] => {
|
||||
const children: Element[] = [];
|
||||
for (
|
||||
let child = element.firstChild;
|
||||
child !== null;
|
||||
child = child.nextSibling
|
||||
)
|
||||
if (isElement(child)) children.push(child);
|
||||
return children;
|
||||
};
|
||||
|
||||
const childrenNamed = (element: Element, local: string): Element[] =>
|
||||
childElements(element).filter((child) => child.localName === local);
|
||||
|
||||
const firstNamed = (element: Element, local: string): Element | undefined =>
|
||||
childrenNamed(element, local)[0];
|
||||
|
||||
const nonempty = (value: string | null | undefined): string | null => {
|
||||
if (value === null || value === undefined) return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed === "" ? null : trimmed;
|
||||
};
|
||||
|
||||
const attribute = (element: Element, name: string): string | null =>
|
||||
nonempty(element.getAttribute(name));
|
||||
|
||||
const elementText = (element: Element): string | null => {
|
||||
const parts: string[] = [];
|
||||
for (
|
||||
let child = element.firstChild;
|
||||
child !== null;
|
||||
child = child.nextSibling
|
||||
)
|
||||
// Text (3) and CDATA section (4) nodes both carry character data.
|
||||
if (child.nodeType === 3 || child.nodeType === 4)
|
||||
parts.push(child.nodeValue ?? "");
|
||||
return nonempty(parts.join(""));
|
||||
};
|
||||
|
||||
const zipSize = (value: number | undefined): number | null =>
|
||||
typeof value === "number" && Number.isSafeInteger(value) && value >= 0
|
||||
? value
|
||||
: null;
|
||||
|
||||
const asFileEntry = (entry: Entry): entry is FileEntry =>
|
||||
!entry.directory && "getData" in entry;
|
||||
|
||||
const wrapZipFailure = (
|
||||
cause: unknown,
|
||||
signal: AbortSignal | undefined,
|
||||
compressionMethod?: number,
|
||||
): never => {
|
||||
// zip.js rejects with the caller's abort reason; keep it as cancellation
|
||||
// rather than reporting the package as damaged.
|
||||
if (signal?.aborted === true && Object.is(cause, signal.reason))
|
||||
throw new ArtifactReaderFailure("cancelled", "Artifact read cancelled", {
|
||||
cause: signal.reason,
|
||||
});
|
||||
if (
|
||||
cause instanceof ArtifactReaderFailure ||
|
||||
cause instanceof ParseFailureError
|
||||
)
|
||||
throw cause;
|
||||
// The shared ZIP reader owns ZIP failure classification, including native
|
||||
// decoder faults: a Zstandard window above its fixed allowance is a
|
||||
// resource limit, and a feature it cannot provide (encryption, split
|
||||
// archives, a Zstandard dictionary) is an unsupported layout. Project its
|
||||
// typed result instead of re-reading the error text here.
|
||||
const typed = typedZipFailure(cause, compressionMethod);
|
||||
if (typed instanceof ArtifactReaderFailure && typed.reason === "limit")
|
||||
throw typed;
|
||||
if (typed instanceof ArtifactReaderFailure && typed.reason === "unavailable")
|
||||
throw unsupportedInput(
|
||||
NUGET_NUPKG_FORMAT,
|
||||
`NuGet package ZIP uses an unsupported layout: ${typed.message}`,
|
||||
{ cause: typed },
|
||||
);
|
||||
if (typed instanceof ArtifactReaderFailure && typed.reason === "format")
|
||||
throw malformedInput(NUGET_NUPKG_FORMAT, typed.message, { cause: typed });
|
||||
throw cause;
|
||||
};
|
||||
|
||||
/** Refuse expansion past the metadata budget before buffering more output. */
|
||||
class BoundedUint8ArrayWriter extends Uint8ArrayWriter {
|
||||
readonly #budget: Budget;
|
||||
|
||||
constructor(
|
||||
maximum: number,
|
||||
private readonly exceeded: (required: number) => Error,
|
||||
) {
|
||||
super();
|
||||
this.#budget = new Budget(maximum);
|
||||
}
|
||||
|
||||
override async init(size?: number): Promise<void> {
|
||||
if (size !== undefined && size > this.#budget.maximum)
|
||||
throw this.exceeded(size);
|
||||
await super.init?.(size);
|
||||
}
|
||||
|
||||
override async writeUint8Array(array: Uint8Array): Promise<void> {
|
||||
this.#budget.charge(array.length, () =>
|
||||
this.exceeded(this.#budget.used + array.length),
|
||||
);
|
||||
await super.writeUint8Array(array);
|
||||
}
|
||||
}
|
||||
|
||||
/** Read one metadata member under max_nuspec_bytes, declared and expanded. */
|
||||
const readMemberBytes = async (
|
||||
entry: FileEntry,
|
||||
signal: AbortSignal | undefined,
|
||||
maximum: number,
|
||||
label: string,
|
||||
): Promise<Uint8Array> => {
|
||||
const exceeded = (required: number) =>
|
||||
decodeLimit(
|
||||
NUGET_NUPKG_FORMAT,
|
||||
`${label} exceeds the ${String(maximum)}-byte budget.`,
|
||||
{ name: "max_nuspec_bytes", maximum, required },
|
||||
);
|
||||
const declared = zipSize(entry.uncompressedSize);
|
||||
if (declared !== null && declared > maximum) throw exceeded(declared);
|
||||
try {
|
||||
return await entry.getData(new BoundedUint8ArrayWriter(maximum, exceeded), {
|
||||
checkSignature: true,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
});
|
||||
} catch (cause: unknown) {
|
||||
return wrapZipFailure(cause, signal, entry.compressionMethod);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolve a package-level relationship Target against the package root:
|
||||
* `.` segments drop, `..` pops, and escaping above the root is undefined.
|
||||
*/
|
||||
const resolvePackageTarget = (target: string): string | undefined => {
|
||||
const segments: string[] = [];
|
||||
for (const segment of target.replaceAll("\\", "/").split("/")) {
|
||||
if (segment === "" || segment === ".") continue;
|
||||
if (segment === "..") {
|
||||
if (segments.pop() === undefined) return undefined;
|
||||
continue;
|
||||
}
|
||||
segments.push(segment);
|
||||
}
|
||||
return segments.length === 0 ? undefined : segments.join("/");
|
||||
};
|
||||
|
||||
interface OpcManifestTarget {
|
||||
readonly lookup: string;
|
||||
readonly display: string | null;
|
||||
}
|
||||
|
||||
const targetLabel = (display: string | null): string =>
|
||||
display === null ? "[URL withheld]" : JSON.stringify(display);
|
||||
|
||||
const opcManifestTargets = (
|
||||
xml: string,
|
||||
limitations: string[],
|
||||
): OpcManifestTarget[] => {
|
||||
const parsed = parseXmlDocument(xml, {
|
||||
doctype: "reject",
|
||||
lineEndings: "preserve",
|
||||
});
|
||||
if (!parsed.ok) {
|
||||
limitations.push(
|
||||
parsed.error.kind === "unsupported"
|
||||
? "OPC relationships declare a document type, which is unsupported; the .nuspec was selected by ZIP name when possible."
|
||||
: "OPC relationships are not well-formed XML; the .nuspec was selected by ZIP name when possible.",
|
||||
);
|
||||
return [];
|
||||
}
|
||||
const root = parsed.value.documentElement;
|
||||
if (!isElement(root) || root.localName !== "Relationships") {
|
||||
limitations.push(
|
||||
"OPC relationships root is not Relationships; the .nuspec was selected by ZIP name when possible.",
|
||||
);
|
||||
return [];
|
||||
}
|
||||
const targets = new Map<string, OpcManifestTarget>();
|
||||
for (const relationship of childrenNamed(root, "Relationship")) {
|
||||
const type = attribute(relationship, "Type");
|
||||
if (type === null || !type.toLowerCase().endsWith("/manifest")) continue;
|
||||
const target = attribute(relationship, "Target");
|
||||
if (target === null) continue;
|
||||
const displayedTarget = redactRecordedTransportUrl(target).url;
|
||||
// OPC external targets may be relative, so the mode decides, not the URI shape.
|
||||
if (attribute(relationship, "TargetMode")?.toLowerCase() === "external") {
|
||||
limitations.push(
|
||||
`OPC manifest relationship Target ${targetLabel(displayedTarget)} is external and was not followed.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (/^[a-z][a-z0-9+.-]*:/iu.test(target) || target.startsWith("//")) {
|
||||
limitations.push(
|
||||
`OPC manifest relationship Target ${targetLabel(displayedTarget)} has a URI scheme or authority and was not followed.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const logical = resolvePackageTarget(target);
|
||||
if (logical === undefined) {
|
||||
limitations.push(
|
||||
`OPC manifest relationship Target ${targetLabel(displayedTarget)} leaves the package and was not followed.`,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (!targets.has(logical))
|
||||
targets.set(logical, { lookup: logical, display: displayedTarget });
|
||||
}
|
||||
return [...targets.values()];
|
||||
};
|
||||
|
||||
const parseBooleanAttribute = (value: string | null): boolean | null => {
|
||||
if (value === null) return null;
|
||||
const folded = value.toLowerCase();
|
||||
if (folded === "true") return true;
|
||||
if (folded === "false") return false;
|
||||
return null;
|
||||
};
|
||||
|
||||
const parseDependencies = (
|
||||
metadata: Element,
|
||||
): NugetNupkg["dependency_groups"] => {
|
||||
const container = firstNamed(metadata, "dependencies");
|
||||
if (container === undefined) return [];
|
||||
const groups = childrenNamed(container, "group");
|
||||
const ungrouped = childrenNamed(container, "dependency");
|
||||
const readDependency = (
|
||||
element: Element,
|
||||
): NugetNupkg["dependency_groups"][number]["dependencies"][number] => ({
|
||||
id: attribute(element, "id"),
|
||||
version: attribute(element, "version"),
|
||||
include: attribute(element, "include"),
|
||||
exclude: attribute(element, "exclude"),
|
||||
development_dependency: parseBooleanAttribute(
|
||||
attribute(element, "developmentDependency"),
|
||||
),
|
||||
});
|
||||
const fromGroup = (
|
||||
element: Element,
|
||||
): NugetNupkg["dependency_groups"][number] => ({
|
||||
target_framework: attribute(element, "targetFramework"),
|
||||
dependencies: childrenNamed(element, "dependency").map(readDependency),
|
||||
});
|
||||
if (groups.length > 0)
|
||||
return [
|
||||
...groups.map(fromGroup),
|
||||
...(ungrouped.length === 0
|
||||
? []
|
||||
: [
|
||||
{
|
||||
target_framework: null,
|
||||
dependencies: ungrouped.map(readDependency),
|
||||
},
|
||||
]),
|
||||
];
|
||||
if (ungrouped.length === 0) return [];
|
||||
return [
|
||||
{ target_framework: null, dependencies: ungrouped.map(readDependency) },
|
||||
];
|
||||
};
|
||||
|
||||
const parseNuspecDocument = (
|
||||
xml: string,
|
||||
limitations: string[],
|
||||
): Pick<
|
||||
NugetNupkg,
|
||||
"identity" | "license" | "repository" | "dependency_groups"
|
||||
> => {
|
||||
const empty: Pick<
|
||||
NugetNupkg,
|
||||
"identity" | "license" | "repository" | "dependency_groups"
|
||||
> = {
|
||||
identity: null,
|
||||
license: null,
|
||||
repository: null,
|
||||
dependency_groups: [],
|
||||
};
|
||||
const parsed = parseXmlDocument(xml, {
|
||||
doctype: "reject",
|
||||
lineEndings: "preserve",
|
||||
});
|
||||
if (!parsed.ok) {
|
||||
limitations.push(
|
||||
parsed.error.kind === "unsupported"
|
||||
? "The selected .nuspec declares a document type, which is unsupported."
|
||||
: NUPKG_LIMITATIONS.malformedNuspec,
|
||||
);
|
||||
return empty;
|
||||
}
|
||||
const root = parsed.value.documentElement;
|
||||
if (!isElement(root) || root.localName !== "package") {
|
||||
limitations.push("The selected .nuspec root element is not package.");
|
||||
return empty;
|
||||
}
|
||||
const metadata = firstNamed(root, "metadata");
|
||||
if (metadata === undefined) {
|
||||
limitations.push("The selected .nuspec has no metadata element.");
|
||||
return empty;
|
||||
}
|
||||
const metadataText = (local: string): string | null => {
|
||||
const element = firstNamed(metadata, local);
|
||||
return element === undefined ? null : elementText(element);
|
||||
};
|
||||
const licenseElement = firstNamed(metadata, "license");
|
||||
const licenseType = licenseElement ? attribute(licenseElement, "type") : null;
|
||||
const repositoryElement = firstNamed(metadata, "repository");
|
||||
return {
|
||||
identity: {
|
||||
id: metadataText("id"),
|
||||
version: metadataText("version"),
|
||||
authors: metadataText("authors"),
|
||||
description: metadataText("description"),
|
||||
},
|
||||
license:
|
||||
licenseElement === undefined
|
||||
? null
|
||||
: {
|
||||
type:
|
||||
licenseType === "expression" || licenseType === "file"
|
||||
? licenseType
|
||||
: null,
|
||||
value: elementText(licenseElement),
|
||||
},
|
||||
repository:
|
||||
repositoryElement === undefined
|
||||
? null
|
||||
: {
|
||||
type: attribute(repositoryElement, "type"),
|
||||
...redactRecordedTransportUrl(attribute(repositoryElement, "url")),
|
||||
commit: attribute(repositoryElement, "commit"),
|
||||
branch: attribute(repositoryElement, "branch"),
|
||||
},
|
||||
dependency_groups: parseDependencies(metadata),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Collect the distinct members the manifest targets resolve to, stopping at
|
||||
* the second. Many package-controlled targets can each hit one large
|
||||
* case-folded bucket, so the matches are never materialized together.
|
||||
*/
|
||||
export const distinctTargetMatches = <T>(
|
||||
targets: readonly string[],
|
||||
match: (target: string) => readonly T[],
|
||||
): T[] => {
|
||||
const found = new Set<T>();
|
||||
for (const target of targets)
|
||||
for (const member of match(target)) {
|
||||
found.add(member);
|
||||
if (found.size > 1) return [...found];
|
||||
}
|
||||
return [...found];
|
||||
};
|
||||
|
||||
const findNuspec = (
|
||||
files: readonly { readonly entry: FileEntry; readonly name: string }[],
|
||||
relsXml: string | undefined,
|
||||
limitations: string[],
|
||||
): {
|
||||
readonly member:
|
||||
| { readonly entry: FileEntry; readonly name: string }
|
||||
| undefined;
|
||||
readonly source: "opc-relationship" | "root-nuspec" | undefined;
|
||||
} => {
|
||||
// Every ZIP occurrence stays distinct: duplicate or case-variant names must
|
||||
// surface as ambiguity rather than collapse to an archive-order winner.
|
||||
// Index once: every target is then a constant-time lookup, however many
|
||||
// relationships the package declares.
|
||||
const exactNames = new Map<string, (typeof files)[number][]>();
|
||||
const foldedNames = new Map<string, (typeof files)[number][]>();
|
||||
for (const file of files) {
|
||||
const exact = exactNames.get(file.name);
|
||||
if (exact === undefined) exactNames.set(file.name, [file]);
|
||||
else exact.push(file);
|
||||
const lower = file.name.toLowerCase();
|
||||
const folded = foldedNames.get(lower);
|
||||
if (folded === undefined) foldedNames.set(lower, [file]);
|
||||
else folded.push(file);
|
||||
}
|
||||
const matchTarget = (target: string) =>
|
||||
exactNames.get(target) ?? foldedNames.get(target.toLowerCase()) ?? [];
|
||||
if (relsXml !== undefined) {
|
||||
const targets = opcManifestTargets(relsXml, limitations);
|
||||
const resolved = distinctTargetMatches(
|
||||
targets.map((target) => target.lookup),
|
||||
matchTarget,
|
||||
);
|
||||
if (resolved.length > 1) {
|
||||
limitations.push(
|
||||
"OPC manifest relationships resolve to more than one .nuspec ZIP member; identity was not decoded.",
|
||||
);
|
||||
return { member: undefined, source: undefined };
|
||||
}
|
||||
if (resolved.length === 1) {
|
||||
const member = resolved[0]!;
|
||||
if (!targets.some((target) => target.lookup === member.name))
|
||||
limitations.push(
|
||||
"The OPC manifest relationship matched a .nuspec member by case-insensitive ZIP name.",
|
||||
);
|
||||
return { member, source: "opc-relationship" };
|
||||
}
|
||||
if (targets.length === 1)
|
||||
limitations.push(
|
||||
`OPC manifest relationship Target ${targetLabel(targets[0]!.display)} is missing from the package; identity was not decoded from that path.`,
|
||||
);
|
||||
}
|
||||
const rootNuspecs = files.filter(
|
||||
(file) =>
|
||||
!file.name.includes("/") && file.name.toLowerCase().endsWith(".nuspec"),
|
||||
);
|
||||
if (rootNuspecs.length > 1) {
|
||||
limitations.push(NUPKG_LIMITATIONS.ambiguousRootNuspec);
|
||||
return { member: undefined, source: undefined };
|
||||
}
|
||||
if (rootNuspecs.length === 1)
|
||||
return { member: rootNuspecs[0], source: "root-nuspec" };
|
||||
limitations.push(NUPKG_LIMITATIONS.noNuspec);
|
||||
return { member: undefined, source: undefined };
|
||||
};
|
||||
|
||||
/** Decode one bounded NuGet .nupkg without restore, execution, or network. */
|
||||
export const parseNugetNupkg = async (
|
||||
bytes: Uint8Array,
|
||||
artifact: { path: string; sha256: string; bytes: number },
|
||||
input: InspectNugetNupkgInput,
|
||||
signal?: AbortSignal,
|
||||
): Promise<NugetNupkg> => {
|
||||
if (bytes.length !== artifact.bytes)
|
||||
throw malformedInput(
|
||||
NUGET_NUPKG_FORMAT,
|
||||
"Selected artifact length disagrees with the retained bytes.",
|
||||
);
|
||||
if (!hasZipSignature(bytes))
|
||||
throw malformedInput(
|
||||
NUGET_NUPKG_FORMAT,
|
||||
"Selected file is not a ZIP archive (NuGet .nupkg).",
|
||||
);
|
||||
const reader = new ZipReader(new Uint8ArrayReader(bytes), ZIP_READER_OPTIONS);
|
||||
const limitations: string[] = [...BASE_LIMITATIONS];
|
||||
try {
|
||||
// Count while enumerating so an oversized directory stops at the budget
|
||||
// instead of materializing and decoding every member first.
|
||||
const entries: Entry[] = [];
|
||||
try {
|
||||
for await (const entry of reader.getEntriesGenerator({
|
||||
decodeText: decodeZipEntryText,
|
||||
...(signal === undefined ? {} : { signal }),
|
||||
})) {
|
||||
if (entries.length >= input.max_entries)
|
||||
throw decodeLimit(
|
||||
NUGET_NUPKG_FORMAT,
|
||||
`NuGet package ZIP exceeds the ${String(input.max_entries)}-entry budget.`,
|
||||
{
|
||||
name: "max_entries",
|
||||
maximum: input.max_entries,
|
||||
required: entries.length + 1,
|
||||
},
|
||||
);
|
||||
entries.push(entry);
|
||||
}
|
||||
} catch (cause: unknown) {
|
||||
return wrapZipFailure(cause, signal);
|
||||
}
|
||||
// The inventory comes from the central directory; local entries it omits
|
||||
// are only visible as bytes no listed record accounts for.
|
||||
const directoryOffset = reader.directoryOffset;
|
||||
const listing = zipListingCoverage(
|
||||
directoryOffset === undefined
|
||||
? undefined
|
||||
: await accountZipMemberRegion(
|
||||
entries.map((entry) => ({
|
||||
offset: entry.offset,
|
||||
compressedSize: entry.compressedSize,
|
||||
uncompressedSize: entry.uncompressedSize,
|
||||
crc32: entry.crc32,
|
||||
zip64: entry.zip64,
|
||||
dataDescriptor: entry.bitFlag?.dataDescriptor ?? false,
|
||||
})),
|
||||
directoryOffset,
|
||||
(at, length) => Promise.resolve(bytes.subarray(at, at + length)),
|
||||
),
|
||||
);
|
||||
limitations.push(...listing.limitations);
|
||||
const files: { entry: FileEntry; name: string }[] = [];
|
||||
const contents: NugetNupkg["contents"] = [];
|
||||
for (const entry of entries) {
|
||||
if (entry.directory) continue;
|
||||
if (!asFileEntry(entry)) continue;
|
||||
const sourceName = zipEntryPath(entry);
|
||||
const name = nugetNupkgLogicalPath(sourceName);
|
||||
if (name === "") continue;
|
||||
for (const limitation of zipEntryNameLimitations(entry))
|
||||
limitations.push(
|
||||
`ZIP member ${JSON.stringify(sourceName)}: ${limitation}`,
|
||||
);
|
||||
files.push({ entry, name });
|
||||
contents.push({
|
||||
name: sourceName,
|
||||
path: name,
|
||||
uncompressed_size: zipSize(entry.uncompressedSize),
|
||||
compressed_size: zipSize(entry.compressedSize),
|
||||
role: nugetNupkgEntryRole(name),
|
||||
encrypted: entry.encrypted === true,
|
||||
});
|
||||
}
|
||||
const relsMembers = files.filter(
|
||||
(file) => file.name.toLowerCase() === "_rels/.rels",
|
||||
);
|
||||
// Spellings such as "./_rels/.rels" normalize to the same logical path; with
|
||||
// more than one, ZIP order would choose the manifest, so follow none.
|
||||
if (relsMembers.length > 1)
|
||||
limitations.push(
|
||||
"More than one ZIP member is the OPC relationships part; relationships were not followed and the .nuspec was selected by ZIP name when possible.",
|
||||
);
|
||||
const rels = relsMembers.length === 1 ? relsMembers[0] : undefined;
|
||||
let relsXml: string | undefined;
|
||||
if (rels !== undefined) {
|
||||
if (rels.entry.encrypted)
|
||||
limitations.push(
|
||||
"OPC relationships member is encrypted and was not extracted.",
|
||||
);
|
||||
else {
|
||||
const relsBytes = await readMemberBytes(
|
||||
rels.entry,
|
||||
signal,
|
||||
input.max_nuspec_bytes,
|
||||
"OPC relationships member",
|
||||
);
|
||||
try {
|
||||
relsXml = decodeXmlPlistText(relsBytes);
|
||||
} catch {
|
||||
limitations.push(
|
||||
"OPC relationships member is not valid UTF-8 or BOM-marked UTF-16 XML text; the .nuspec was selected by ZIP name when possible.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
const selected = findNuspec(files, relsXml, limitations);
|
||||
if (selected.member === undefined || selected.source === undefined)
|
||||
return {
|
||||
artifact: {
|
||||
path: artifact.path,
|
||||
sha256: artifact.sha256,
|
||||
bytes: artifact.bytes,
|
||||
},
|
||||
identity: null,
|
||||
license: null,
|
||||
repository: null,
|
||||
dependency_groups: [],
|
||||
contents,
|
||||
nuspec: null,
|
||||
coverage: {
|
||||
status: listing.status,
|
||||
entries: contents.length,
|
||||
examined_nuspec_bytes: 0,
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
if (selected.member.entry.encrypted) {
|
||||
limitations.push(
|
||||
`Selected .nuspec ${JSON.stringify(selected.member.name)} is encrypted and was not extracted.`,
|
||||
);
|
||||
return {
|
||||
artifact: {
|
||||
path: artifact.path,
|
||||
sha256: artifact.sha256,
|
||||
bytes: artifact.bytes,
|
||||
},
|
||||
identity: null,
|
||||
license: null,
|
||||
repository: null,
|
||||
dependency_groups: [],
|
||||
contents,
|
||||
nuspec: {
|
||||
path: selected.member.name,
|
||||
// Nothing was decoded; the declared size remains in contents.
|
||||
bytes: null,
|
||||
source: selected.source,
|
||||
},
|
||||
coverage: {
|
||||
status: listing.status,
|
||||
entries: contents.length,
|
||||
examined_nuspec_bytes: 0,
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
}
|
||||
const nuspecBytes = await readMemberBytes(
|
||||
selected.member.entry,
|
||||
signal,
|
||||
input.max_nuspec_bytes,
|
||||
"Selected .nuspec",
|
||||
);
|
||||
let xml: string;
|
||||
try {
|
||||
xml = decodeXmlPlistText(nuspecBytes);
|
||||
} catch {
|
||||
limitations.push(
|
||||
"The selected .nuspec is not valid UTF-8 or BOM-marked UTF-16 XML text.",
|
||||
);
|
||||
return {
|
||||
artifact: {
|
||||
path: artifact.path,
|
||||
sha256: artifact.sha256,
|
||||
bytes: artifact.bytes,
|
||||
},
|
||||
identity: null,
|
||||
license: null,
|
||||
repository: null,
|
||||
dependency_groups: [],
|
||||
contents,
|
||||
nuspec: {
|
||||
path: selected.member.name,
|
||||
bytes: nuspecBytes.length,
|
||||
source: selected.source,
|
||||
},
|
||||
coverage: {
|
||||
status: listing.status,
|
||||
entries: contents.length,
|
||||
examined_nuspec_bytes: nuspecBytes.length,
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
}
|
||||
const decoded = parseNuspecDocument(xml, limitations);
|
||||
if (
|
||||
decoded.identity !== null &&
|
||||
decoded.identity.id === null &&
|
||||
decoded.identity.version === null &&
|
||||
decoded.identity.authors === null &&
|
||||
decoded.identity.description === null
|
||||
)
|
||||
limitations.push(
|
||||
"The selected .nuspec metadata did not include id, version, authors, or description.",
|
||||
);
|
||||
return {
|
||||
artifact: {
|
||||
path: artifact.path,
|
||||
sha256: artifact.sha256,
|
||||
bytes: artifact.bytes,
|
||||
},
|
||||
...decoded,
|
||||
contents,
|
||||
nuspec: {
|
||||
path: selected.member.name,
|
||||
bytes: nuspecBytes.length,
|
||||
source: selected.source,
|
||||
},
|
||||
coverage: {
|
||||
status: listing.status,
|
||||
entries: contents.length,
|
||||
examined_nuspec_bytes: nuspecBytes.length,
|
||||
},
|
||||
limitations,
|
||||
};
|
||||
} finally {
|
||||
await reader.close().catch(() => undefined);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,196 @@
|
||||
import { NUGET_NUPKG_PROVIDER_IDENTITY } from "./NugetNupkgProviderIdentity.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
ArtifactResourceScope,
|
||||
artifactFilePrimaryFacts,
|
||||
projectArtifactCloseFailure,
|
||||
projectOwnedArtifactIdentityFailure,
|
||||
projectOwnedArtifactInputFailure,
|
||||
projectSelectedArtifactFileFailure,
|
||||
projectStableArtifactFailure,
|
||||
readStableArtifact,
|
||||
translateArtifactFailure,
|
||||
type ArtifactFilePrimaryFacts,
|
||||
type StableArtifactSnapshot,
|
||||
} from "../resources/index.js";
|
||||
import {
|
||||
isParseLimit,
|
||||
parseFailureAnalysisError,
|
||||
parseLimitConstraint,
|
||||
} from "../domain/parseFailureAnalysisError.js";
|
||||
import { decodeLimit } from "../domain/parseFailure.js";
|
||||
import { fixedCeilingConstraint } from "../domain/analysisErrorCore.js";
|
||||
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
|
||||
import {
|
||||
NUGET_NUPKG_FORMAT,
|
||||
NUGET_NUPKG_LIMIT_MAXIMA,
|
||||
type InspectNugetNupkgInput,
|
||||
} from "../domain/nuget/nupkg.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { errorMessage } from "../kernel/errorMessage.js";
|
||||
import { parseNugetNupkg } from "./NugetNupkgParser.js";
|
||||
|
||||
const OPERATION = "inspect_nuget_nupkg";
|
||||
|
||||
const budgetRecovery = (
|
||||
parameter: keyof typeof NUGET_NUPKG_LIMIT_MAXIMA,
|
||||
selected: number,
|
||||
): string =>
|
||||
selected >= NUGET_NUPKG_LIMIT_MAXIMA[parameter]
|
||||
? `${parameter} is at this operation's maximum of ${String(NUGET_NUPKG_LIMIT_MAXIMA[parameter])}; select a complete artifact within that bound.`
|
||||
: `Raise ${parameter} above ${String(selected)}, up to ${String(NUGET_NUPKG_LIMIT_MAXIMA[parameter])}, or select a smaller artifact. The budget applies on the next call; repeating the unchanged request does not raise it.`;
|
||||
|
||||
const nupkgFailurePrimary = (
|
||||
facts: ArtifactFilePrimaryFacts,
|
||||
input: InspectNugetNupkgInput,
|
||||
) => {
|
||||
const { cause, origin } = facts;
|
||||
const identityFailure = projectOwnedArtifactIdentityFailure(
|
||||
facts,
|
||||
OPERATION,
|
||||
input.path,
|
||||
);
|
||||
if (identityFailure !== undefined) return identityFailure;
|
||||
if (isParseLimit(cause, NUGET_NUPKG_FORMAT)) {
|
||||
const parameter = (
|
||||
Object.keys(
|
||||
NUGET_NUPKG_LIMIT_MAXIMA,
|
||||
) as (keyof typeof NUGET_NUPKG_LIMIT_MAXIMA)[]
|
||||
).find((name) => name === cause.failure.limit.name);
|
||||
return parseLimitConstraint(
|
||||
OPERATION,
|
||||
cause.failure.limit.name === "max_entries" ? "capacity" : "memory",
|
||||
cause,
|
||||
{
|
||||
path: input.path,
|
||||
retryable: false,
|
||||
...(parameter === undefined
|
||||
? {}
|
||||
: {
|
||||
remediationAction: budgetRecovery(
|
||||
parameter,
|
||||
cause.failure.limit.maximum,
|
||||
),
|
||||
}),
|
||||
},
|
||||
);
|
||||
}
|
||||
const formatFailure = parseFailureAnalysisError(OPERATION, input.path, cause);
|
||||
if (formatFailure !== undefined) return formatFailure;
|
||||
const inputFailure = projectOwnedArtifactInputFailure(
|
||||
facts,
|
||||
OPERATION,
|
||||
input.path,
|
||||
);
|
||||
if (inputFailure !== undefined) return inputFailure;
|
||||
if (
|
||||
origin === "owned-or-classified" &&
|
||||
cause instanceof ArtifactReaderFailure
|
||||
) {
|
||||
if (cause.reason === "limit" && cause.fixedAllowance !== undefined)
|
||||
return fixedCeilingConstraint(
|
||||
OPERATION,
|
||||
cause.boundary ?? "memory",
|
||||
cause.message,
|
||||
cause.fixedAllowance,
|
||||
{ cause },
|
||||
);
|
||||
if (cause.reason === "limit" && cause.boundary === "file-size")
|
||||
return parseLimitConstraint(
|
||||
OPERATION,
|
||||
"file-size",
|
||||
decodeLimit(
|
||||
NUGET_NUPKG_FORMAT,
|
||||
cause.message,
|
||||
{ name: "max_file_bytes", maximum: input.max_file_bytes },
|
||||
{ cause },
|
||||
),
|
||||
{
|
||||
retryable: false,
|
||||
remediationAction: budgetRecovery(
|
||||
"max_file_bytes",
|
||||
input.max_file_bytes,
|
||||
),
|
||||
},
|
||||
);
|
||||
return translateArtifactFailure(OPERATION, cause);
|
||||
}
|
||||
const fileFailure = projectSelectedArtifactFileFailure(
|
||||
cause,
|
||||
OPERATION,
|
||||
input.path,
|
||||
"NuGet package",
|
||||
);
|
||||
if (fileFailure !== undefined) return fileFailure;
|
||||
return new ArtifactOperationError(
|
||||
OPERATION,
|
||||
"io",
|
||||
undefined,
|
||||
errorMessage(cause),
|
||||
{ cause },
|
||||
);
|
||||
};
|
||||
|
||||
const nupkgFailure = (
|
||||
cause: unknown,
|
||||
input: InspectNugetNupkgInput,
|
||||
snapshot?: StableArtifactSnapshot,
|
||||
) =>
|
||||
projectStableArtifactFailure(
|
||||
cause,
|
||||
nupkgFailurePrimary(artifactFilePrimaryFacts(cause), input),
|
||||
input.path,
|
||||
NUGET_NUPKG_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
snapshot,
|
||||
);
|
||||
|
||||
/** Portable parser over one bounded, identity-checked regular file. */
|
||||
export class NugetNupkgProvider {
|
||||
readonly identity = NUGET_NUPKG_PROVIDER_IDENTITY;
|
||||
readonly #resources = new ArtifactResourceScope();
|
||||
|
||||
async close(): Promise<void> {
|
||||
try {
|
||||
await this.#resources.close();
|
||||
} catch (cause: unknown) {
|
||||
throw projectArtifactCloseFailure(
|
||||
cause,
|
||||
NUGET_NUPKG_PROVIDER_IDENTITY.id,
|
||||
OPERATION,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async inspect(
|
||||
input: InspectNugetNupkgInput,
|
||||
options?: { readonly signal?: AbortSignal },
|
||||
) {
|
||||
let snapshot: StableArtifactSnapshot | undefined;
|
||||
try {
|
||||
return await this.#resources.run(async () => {
|
||||
snapshot = await readStableArtifact(
|
||||
input.path,
|
||||
input.max_file_bytes,
|
||||
options?.signal,
|
||||
undefined,
|
||||
this.#resources,
|
||||
);
|
||||
return ok(
|
||||
await parseNugetNupkg(
|
||||
snapshot.bytes,
|
||||
{
|
||||
path: input.path,
|
||||
sha256: snapshot.sha256,
|
||||
bytes: snapshot.bytes.length,
|
||||
},
|
||||
input,
|
||||
options?.signal,
|
||||
),
|
||||
);
|
||||
});
|
||||
} catch (cause) {
|
||||
return err(nupkgFailure(cause, input, snapshot));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
/** Bundled reader identity; package id and version are separate observed facts. */
|
||||
export const NUGET_NUPKG_PROVIDER_IDENTITY = {
|
||||
id: "rea-nuget-nupkg",
|
||||
name: "REA NuGet nupkg reader",
|
||||
version: "1",
|
||||
} as const;
|
||||
@@ -0,0 +1,20 @@
|
||||
import type {
|
||||
ExecutionOptions,
|
||||
ProviderIdentity,
|
||||
} from "../AnalysisProvider.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type {
|
||||
InspectNugetNupkgInput,
|
||||
NugetNupkg,
|
||||
} from "../../domain/nuget/nupkg.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Stable read and .nupkg ZIP/.nuspec decoding, independent of restore or a feed. */
|
||||
export interface NugetNupkgPort {
|
||||
readonly identity: ProviderIdentity;
|
||||
close(): Promise<void>;
|
||||
inspect(
|
||||
input: InspectNugetNupkgInput,
|
||||
options?: ExecutionOptions,
|
||||
): Promise<Result<NugetNupkg, AnalysisError>>;
|
||||
}
|
||||
@@ -421,7 +421,7 @@ export class ZipArtifactReader implements ArtifactReader {
|
||||
}
|
||||
|
||||
/** Coverage of a central-directory listing, given the member region's byte account. */
|
||||
const zipListingCoverage = (
|
||||
export const zipListingCoverage = (
|
||||
account: ZipMemberRegionAccount | undefined,
|
||||
): ArtifactReaderTraversal => {
|
||||
if (account === undefined)
|
||||
@@ -481,14 +481,14 @@ const projectZipEntry = (
|
||||
: [
|
||||
`ZIP member name ${JSON.stringify(sourcePath)} has a leading current-directory prefix omitted from its logical path.`,
|
||||
]),
|
||||
...legacyNameLimitations(entry),
|
||||
...zipEntryNameLimitations(entry),
|
||||
],
|
||||
adapterKey: `zip-entry:${index}`,
|
||||
};
|
||||
};
|
||||
|
||||
/** Preserve source bytes when an unflagged legacy name may use another code page. */
|
||||
const legacyNameLimitations = (entry: Entry): readonly string[] => {
|
||||
export const zipEntryNameLimitations = (entry: Entry): readonly string[] => {
|
||||
if (entry.filenameUTF8 || entry.extraFieldUnicodePath?.valid === true)
|
||||
return [];
|
||||
const bytes = entry.rawFilename;
|
||||
@@ -620,7 +620,7 @@ const ZIP_FAILURE_REASONS: ReadonlyMap<string, "format" | "unavailable"> =
|
||||
]);
|
||||
|
||||
/** Type a zip.js archive fault so consumers do not report it as file I/O. */
|
||||
const typedZipFailure = (
|
||||
export const typedZipFailure = (
|
||||
cause: unknown,
|
||||
compressionMethod?: number,
|
||||
): unknown => {
|
||||
|
||||
@@ -145,7 +145,11 @@ export {
|
||||
} from "./withArtifactTargetIdentity.js";
|
||||
export {
|
||||
ZIP_READER_OPTIONS,
|
||||
ZIP_ZSTANDARD_WINDOW_CEILING,
|
||||
ZipArtifactReader,
|
||||
decodeZipEntryText,
|
||||
zipEntryNameLimitations,
|
||||
zipEntryPath,
|
||||
zipListingCoverage,
|
||||
typedZipFailure,
|
||||
} from "./ZipArtifactReader.js";
|
||||
@@ -201,6 +201,7 @@ export const createServer = (
|
||||
windowsShortcut,
|
||||
electronFuses,
|
||||
releaseExposure,
|
||||
nugetNupkg,
|
||||
pythonPyc,
|
||||
dwarfUnits,
|
||||
elfDependencies,
|
||||
@@ -437,6 +438,7 @@ export const createServer = (
|
||||
goBinary,
|
||||
il2cppMetadata,
|
||||
rustBinary,
|
||||
nugetNupkg,
|
||||
pythonPyc,
|
||||
erlangBeam,
|
||||
v8CodeCache,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { NugetNupkgService } from "../application/nuget/NugetNupkgService.js";
|
||||
import type { DwarfUnitsService } from "../application/binaryDiagnostics/DwarfUnitsService.js";
|
||||
import type { ElfDependenciesService } from "../application/binaryDiagnostics/ElfDependenciesService.js";
|
||||
import type { AdbDeviceAnalysisService } from "../application/adb/AdbDeviceAnalysisService.js";
|
||||
@@ -615,6 +616,12 @@ const SERVICE_TOOL_BINDINGS = {
|
||||
run: (input, options) => service.inspect(input, options, retention),
|
||||
},
|
||||
})) satisfies Bind<RustBinaryService>,
|
||||
nugetNupkg: ((service) => ({
|
||||
inspect_nuget_nupkg: {
|
||||
admission: "application",
|
||||
run: (input, options) => service.inspect(input, options),
|
||||
},
|
||||
})) satisfies Bind<NugetNupkgService>,
|
||||
pythonPyc: ((service) => ({
|
||||
inspect_python_pyc: {
|
||||
admission: "application",
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
import { nugetNupkgSchema } from "../../src/domain/nuget/nupkg.js";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { expect } from "vitest";
|
||||
import { NUGET_NUPKG_TOOL_CONTRACTS } from "../../src/contracts/nuget/nupkgToolContracts.js";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import { parseEvidenceBundle } from "../../src/domain/evidenceBundle.js";
|
||||
import { contractNamed } from "../../src/cli/contractCliDescription.js";
|
||||
import {
|
||||
nugetNupkgFixture,
|
||||
NUPKG_NAME_ENCODING_CASES,
|
||||
nugetNupkgNameEncodingFixture,
|
||||
} from "../../src/nuget/NugetNupkg.fixture.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
||||
import { cliTest } from "../support/cli/cliFixture.js";
|
||||
|
||||
const nupkgContract = contractNamed(
|
||||
NUGET_NUPKG_TOOL_CONTRACTS,
|
||||
"inspect_nuget_nupkg",
|
||||
);
|
||||
const completeNupkgEvidenceSchema = nupkgContract.outputSchema.safeExtend({
|
||||
normalized_result: nugetNupkgSchema,
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"preserves ZIP filename bytes and encoding uncertainty through CLI, MCP and retained views",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nupkg-name-provenance-");
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const input of NUPKG_NAME_ENCODING_CASES) {
|
||||
const path = join(root, `${input.encoding}.nupkg`);
|
||||
await writeFile(path, await nugetNupkgNameEncodingFixture(input));
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-nuget-nupkg", path, "--json"],
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const cliEvidence = completeNupkgEvidenceSchema.parse(output.json);
|
||||
const response = await call("inspect_nuget_nupkg", { path });
|
||||
expect(response.isError, JSON.stringify(response)).not.toBe(true);
|
||||
const evidence = completeNupkgEvidenceSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
expect(evidence.normalized_result).toEqual(cliEvidence.normalized_result);
|
||||
expect(evidence.normalized_result.contents).toContainEqual(
|
||||
expect.objectContaining({ name: input.name, path: input.name }),
|
||||
);
|
||||
const warnings = evidence.normalized_result.limitations.filter((value) =>
|
||||
value.includes("CP437"),
|
||||
);
|
||||
if (input.uncertain) {
|
||||
expect(warnings).toEqual([
|
||||
expect.stringContaining(input.rawName.toString("hex")),
|
||||
]);
|
||||
expect(warnings[0]).toContain(JSON.stringify(input.name));
|
||||
expect(evidence.limitations).toContain(warnings[0]);
|
||||
} else expect(warnings).toEqual([]);
|
||||
const view = await call("inspect_analysis_view", {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: evidence.evidence_id,
|
||||
},
|
||||
view: { kind: "summary" },
|
||||
});
|
||||
expect(view.isError, JSON.stringify(view)).not.toBe(true);
|
||||
if (input.uncertain)
|
||||
expect(JSON.stringify(view.structuredContent)).toContain(
|
||||
input.rawName.toString("hex"),
|
||||
);
|
||||
else
|
||||
expect(JSON.stringify(view.structuredContent)).not.toContain("CP437");
|
||||
const retained = await call("get_evidence_bundle", {
|
||||
detail: "complete",
|
||||
});
|
||||
expect(retained.isError, JSON.stringify(retained)).not.toBe(true);
|
||||
const bundle = parseEvidenceBundle(
|
||||
toolContract("get_evidence_bundle").outputSchema.parse(
|
||||
retained.structuredContent,
|
||||
).result,
|
||||
);
|
||||
expect(
|
||||
bundle.records.find(
|
||||
(record) => record.evidence_id === evidence.evidence_id,
|
||||
),
|
||||
).toEqual(evidence);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"reports NuGet package identity and dependencies through the public CLI",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nupkg-cli-");
|
||||
const path = join(root, "Demo.Package.1.2.3.nupkg");
|
||||
await writeFile(path, await nugetNupkgFixture());
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-nuget-nupkg", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
const evidence = completeNupkgEvidenceSchema.parse(result.json);
|
||||
expect(evidence).toMatchObject({
|
||||
confidence: "observed",
|
||||
subject: { local_path: path, identity: { format: "file" } },
|
||||
});
|
||||
expect(evidence.normalized_result.identity).toEqual({
|
||||
id: "Demo.Package",
|
||||
version: "1.2.3",
|
||||
authors: "Alice, Bob",
|
||||
description: "A tiny fixture package.",
|
||||
});
|
||||
expect(evidence.normalized_result.dependency_groups).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ target_framework: "net8.0" }),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
evidence.normalized_result.contents.some(
|
||||
(entry) => entry.role === "lib" && entry.name === "lib/net8.0/Demo.dll",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(evidence.normalized_result.coverage.status).toBe("complete");
|
||||
},
|
||||
);
|
||||
|
||||
cliTest(
|
||||
"matches CLI and MCP observations for the same .nupkg",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nupkg-cli-mcp-");
|
||||
const path = join(root, "Demo.Package.nupkg");
|
||||
await writeFile(path, await nugetNupkgFixture());
|
||||
const output = await cli.run({
|
||||
arguments: ["inspect-nuget-nupkg", path, "--json"],
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const report = completeNupkgEvidenceSchema.parse(
|
||||
output.json,
|
||||
).normalized_result;
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
const reply = await call("inspect_nuget_nupkg", { path });
|
||||
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
|
||||
expect(
|
||||
completeNupkgEvidenceSchema.parse(reply.structuredContent)
|
||||
.normalized_result,
|
||||
).toEqual(report);
|
||||
},
|
||||
);
|
||||
|
||||
cliTest("refuses a non-ZIP file through the public CLI", async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nupkg-cli-invalid-");
|
||||
const path = join(root, "not-a-package.nupkg");
|
||||
await writeFile(path, "not a zip");
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-nuget-nupkg", path, "--json"],
|
||||
});
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
code: "invalid_request",
|
||||
category: "invalid_input",
|
||||
details: {
|
||||
operation: "inspect_nuget_nupkg",
|
||||
issues: [
|
||||
expect.objectContaining({
|
||||
path: ["path"],
|
||||
reason: "invalid_format",
|
||||
message: expect.stringContaining("not a ZIP"),
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
cliTest(
|
||||
"preserves selected budgets and redacts transport userinfo through CLI, MCP and retained views",
|
||||
async ({ cli }) => {
|
||||
const root = await createTestTempDirectory("rea-nupkg-provenance-");
|
||||
const path = join(root, "pkg.nupkg");
|
||||
const nuspec = `<package><metadata><id>Credentials.Package</id><version>1</version><repository type="git" url="HTTPS://user:password@Example.invalid/a/../b?token=visible#hash" /></metadata></package>`;
|
||||
const rels = `<Relationships><Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" TargetMode="External" Target="https://user:password@feed.invalid/package?token=visible" /><Relationship Type="http://schemas.microsoft.com/packaging/2010/07/manifest" Target="//user:password@feed.invalid/missing.nuspec?token=visible" /></Relationships>`;
|
||||
await writeFile(
|
||||
path,
|
||||
await nugetNupkgFixture({
|
||||
nuspec,
|
||||
includeRels: false,
|
||||
extraMembers: { "_rels/.rels": rels },
|
||||
}),
|
||||
);
|
||||
const { call } = await connectLocalToolsMcp();
|
||||
for (const maximum of [undefined, 67108864, 8192]) {
|
||||
const input = {
|
||||
path,
|
||||
...(maximum === undefined ? {} : { max_file_bytes: maximum }),
|
||||
};
|
||||
const output = await cli.run({
|
||||
arguments: [
|
||||
"inspect-nuget-nupkg",
|
||||
"./pkg.nupkg",
|
||||
"--json",
|
||||
...(maximum === undefined
|
||||
? []
|
||||
: ["--max-file-bytes", String(maximum)]),
|
||||
],
|
||||
cwd: root,
|
||||
});
|
||||
expect(output.exitCode, output.stderr).toBe(0);
|
||||
const cliEvidence = completeNupkgEvidenceSchema.parse(output.json);
|
||||
expect(cliEvidence.caller_input_path).toBe("./pkg.nupkg");
|
||||
expect(cliEvidence.parameters).toEqual(input);
|
||||
const reply = await call("inspect_nuget_nupkg", input);
|
||||
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
|
||||
const evidence = completeNupkgEvidenceSchema.parse(
|
||||
reply.structuredContent,
|
||||
);
|
||||
expect(evidence.parameters).toEqual(input);
|
||||
expect(evidence.normalized_result).toEqual(cliEvidence.normalized_result);
|
||||
expect(evidence.normalized_result.repository).toMatchObject({
|
||||
url: "HTTPS://Example.invalid/a/../b?token=visible#hash",
|
||||
url_credentials_redacted: true,
|
||||
});
|
||||
expect(JSON.stringify(evidence)).not.toContain("user:password");
|
||||
expect(evidence.normalized_result.limitations.join(" ")).toContain(
|
||||
"https://feed.invalid/package?token=visible",
|
||||
);
|
||||
expect(evidence.normalized_result.limitations.join(" ")).toContain(
|
||||
"//feed.invalid/missing.nuspec?token=visible",
|
||||
);
|
||||
const view = await call("inspect_analysis_view", {
|
||||
source: {
|
||||
kind: "retained-evidence",
|
||||
evidence_id: evidence.evidence_id,
|
||||
},
|
||||
view: { kind: "summary" },
|
||||
});
|
||||
expect(view.isError, JSON.stringify(view)).not.toBe(true);
|
||||
expect(JSON.stringify(view.structuredContent)).not.toContain(
|
||||
"user:password",
|
||||
);
|
||||
expect(JSON.stringify(view.structuredContent)).toContain(
|
||||
"HTTPS://Example.invalid/a/../b?token=visible#hash",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -273,6 +273,7 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
|
||||
["audit_release_exposure", { path: nul }],
|
||||
["inspect_binary_hardening", { path: nul }],
|
||||
["inspect_python_pyc", { path: nul }],
|
||||
["inspect_nuget_nupkg", { path: nul }],
|
||||
["inspect_erlang_beam", { path: nul }],
|
||||
["inspect_binary_layout", { path: nul }],
|
||||
["inspect_recorded_crash", { path: nul }],
|
||||
|
||||
@@ -10,6 +10,7 @@ import { WEB_SCRIPT_TOOL_CONTRACTS } from "../../../src/contracts/webScriptToolC
|
||||
import { API_CONTRACT_TOOL_CONTRACTS } from "../../../src/contracts/apiContractToolContracts.js";
|
||||
import { PLAYWRIGHT_TRACE_TOOL_CONTRACTS } from "../../../src/contracts/playwrightTraceToolContracts.js";
|
||||
import { PYTHON_PYC_TOOL_CONTRACTS } from "../../../src/contracts/python/pythonPycToolContracts.js";
|
||||
import { NUGET_NUPKG_TOOL_CONTRACTS } from "../../../src/contracts/nuget/nupkgToolContracts.js";
|
||||
import { RequestTrackingMcpServer } from "../../../src/server/RequestTrackingMcpServer.js";
|
||||
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
|
||||
import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js";
|
||||
@@ -21,6 +22,7 @@ const CONTRACTS = [
|
||||
...API_CONTRACT_TOOL_CONTRACTS,
|
||||
...PLAYWRIGHT_TRACE_TOOL_CONTRACTS,
|
||||
...PYTHON_PYC_TOOL_CONTRACTS,
|
||||
...NUGET_NUPKG_TOOL_CONTRACTS,
|
||||
...V8_CODE_CACHE_TOOL_CONTRACTS,
|
||||
];
|
||||
|
||||
@@ -35,6 +37,7 @@ const PATH_FIELDS = {
|
||||
inspect_devicetree: ["path"],
|
||||
inspect_playwright_trace: ["path"],
|
||||
inspect_python_pyc: ["path"],
|
||||
inspect_nuget_nupkg: ["path"],
|
||||
inspect_v8_code_cache: ["path"],
|
||||
export_web_scripts: ["capture_path", "output_directory"],
|
||||
recover_javascript_sources: ["path", "output_directory", "additional_paths"],
|
||||
@@ -141,6 +144,7 @@ it("rejects one relative path field at a time on tools/list", async () => {
|
||||
"inspect_devicetree.path",
|
||||
"inspect_playwright_trace.path",
|
||||
"inspect_python_pyc.path",
|
||||
"inspect_nuget_nupkg.path",
|
||||
"inspect_v8_code_cache.path",
|
||||
"export_web_scripts.capture_path",
|
||||
"export_web_scripts.output_directory",
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import { nugetNupkgSchema } from "../../../src/domain/nuget/nupkg.js";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { ZipReader } from "@zip.js/zip.js";
|
||||
import { expect, vi } from "vitest";
|
||||
import { NUGET_NUPKG_TOOL_CONTRACTS } from "../../../src/contracts/nuget/nupkgToolContracts.js";
|
||||
import { contractNamed } from "../../../src/cli/contractCliDescription.js";
|
||||
import { ZIP_ZSTANDARD_WINDOW_CEILING } from "../../../src/resources/index.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { createTestBinarySession } from "../../fixtures/binarySession.js";
|
||||
import { parseMcpToolError } from "../../fixtures/mcpToolError.js";
|
||||
import { nugetNupkgFixture } from "../../../src/nuget/NugetNupkg.fixture.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { mcpTest, type TestMcp } from "../../support/mcp/mcpFixture.js";
|
||||
|
||||
const nupkgContract = contractNamed(
|
||||
NUGET_NUPKG_TOOL_CONTRACTS,
|
||||
"inspect_nuget_nupkg",
|
||||
);
|
||||
const completeNupkgEvidenceSchema = nupkgContract.outputSchema.safeExtend({
|
||||
normalized_result: nugetNupkgSchema,
|
||||
});
|
||||
|
||||
const connect = async (mcp: TestMcp) => {
|
||||
const session = createTestBinarySession(() => {
|
||||
throw new Error("NuGet inspection must not start a deep provider");
|
||||
});
|
||||
const client = await mcp.connect(createServer({ kind: "session", session }));
|
||||
return { client, session };
|
||||
};
|
||||
|
||||
mcpTest(
|
||||
"advertises inspect_nuget_nupkg and reads package identity",
|
||||
async ({ mcp }) => {
|
||||
const { client, session } = await connect(mcp);
|
||||
try {
|
||||
const advertised = (await client.listTools()).tools.find(
|
||||
(tool) => tool.name === "inspect_nuget_nupkg",
|
||||
);
|
||||
expect(advertised?.annotations).toMatchObject({
|
||||
readOnlyHint: false,
|
||||
idempotentHint: true,
|
||||
});
|
||||
const root = await createTestTempDirectory("rea-nupkg-mcp-");
|
||||
const path = join(root, "Demo.Package.nupkg");
|
||||
await writeFile(path, await nugetNupkgFixture());
|
||||
const response = await client.callTool({
|
||||
name: "inspect_nuget_nupkg",
|
||||
arguments: { path },
|
||||
});
|
||||
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
|
||||
const evidence = completeNupkgEvidenceSchema.parse(
|
||||
response.structuredContent,
|
||||
);
|
||||
expect(evidence.normalized_result.identity?.id).toBe("Demo.Package");
|
||||
expect(evidence.normalized_result.identity?.version).toBe("1.2.3");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
mcpTest(
|
||||
"requires an absolute path for inspect_nuget_nupkg",
|
||||
async ({ mcp }) => {
|
||||
const { client, session } = await connect(mcp);
|
||||
try {
|
||||
const response = await client.callTool({
|
||||
name: "inspect_nuget_nupkg",
|
||||
arguments: { path: "pkg.nupkg" },
|
||||
});
|
||||
expect(response.isError).toBe(true);
|
||||
expect(parseMcpToolError(response).error).toMatchObject({
|
||||
code: "invalid_request",
|
||||
details: { operation: "inspect_nuget_nupkg" },
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
mcpTest(
|
||||
"advises a fixed allowance, not more memory, for a Zstandard window refusal",
|
||||
async ({ mcp }) => {
|
||||
const { client, session } = await connect(mcp);
|
||||
const refusal = Object.assign(new Error("Frame requires too much memory"), {
|
||||
code: "ZSTD_error_frameParameter_windowTooLarge",
|
||||
});
|
||||
const original = ZipReader.prototype.getEntriesGenerator;
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* (this: ZipReader<unknown>, options) {
|
||||
for await (const entry of original.call(this, options)) {
|
||||
if (entry.filename === "Demo.Package.nuspec" && !entry.directory) {
|
||||
entry.compressionMethod = 93;
|
||||
entry.getData = () => Promise.reject(refusal);
|
||||
}
|
||||
yield entry;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
const root = await createTestTempDirectory("rea-nupkg-mcp-");
|
||||
const path = join(root, "Demo.Package.nupkg");
|
||||
await writeFile(path, await nugetNupkgFixture());
|
||||
const response = await client.callTool({
|
||||
name: "inspect_nuget_nupkg",
|
||||
arguments: { path },
|
||||
});
|
||||
const { error } = parseMcpToolError(response);
|
||||
expect(error).toMatchObject({
|
||||
code: "resource_constraint",
|
||||
retryable: false,
|
||||
});
|
||||
expect(error.remediation.action).toContain(
|
||||
ZIP_ZSTANDARD_WINDOW_CEILING.name,
|
||||
);
|
||||
expect(error.details?.refusal).toMatchObject({
|
||||
kind: "fixed_ceiling",
|
||||
limit: ZIP_ZSTANDARD_WINDOW_CEILING.limit,
|
||||
unit: "bytes",
|
||||
});
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
mcpTest(
|
||||
"reports a Zstandard dictionary member as an unsupported target, not a malformed package",
|
||||
async ({ mcp }) => {
|
||||
const { client, session } = await connect(mcp);
|
||||
const refusal = Object.assign(new Error("Dictionary mismatch"), {
|
||||
code: "ZSTD_error_dictionary_wrong",
|
||||
});
|
||||
const original = ZipReader.prototype.getEntriesGenerator;
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* (this: ZipReader<unknown>, options) {
|
||||
for await (const entry of original.call(this, options)) {
|
||||
if (entry.filename === "Demo.Package.nuspec" && !entry.directory) {
|
||||
entry.compressionMethod = 93;
|
||||
entry.getData = () => Promise.reject(refusal);
|
||||
}
|
||||
yield entry;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
try {
|
||||
const root = await createTestTempDirectory("rea-nupkg-mcp-");
|
||||
const path = join(root, "Demo.Package.nupkg");
|
||||
await writeFile(path, await nugetNupkgFixture());
|
||||
const response = await client.callTool({
|
||||
name: "inspect_nuget_nupkg",
|
||||
arguments: { path },
|
||||
});
|
||||
const { error } = parseMcpToolError(response);
|
||||
expect(error.code).toBe("unsupported_target");
|
||||
expect(error.message).toMatch(/Zstandard dictionary/u);
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
await session.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -138,6 +138,7 @@ export const PROVIDER_CAPABILITY_CONFORMANCE: Readonly<
|
||||
peImports: { cases: ["tests/acceptance/peImportsCli.test.ts"] },
|
||||
peLoadConfig: { cases: ["tests/acceptance/peLoadConfigCli.test.ts"] },
|
||||
peResources: { cases: ["tests/acceptance/applications/peResources.test.ts"] },
|
||||
nugetNupkg: { cases: ["tests/acceptance/nugetNupkgCli.test.ts"] },
|
||||
pythonPyc: { cases: ["tests/acceptance/pythonPycCli.test.ts"] },
|
||||
recordedCrash: { cases: ["tests/boundary/mcp/recordedCrashMcp.test.ts"] },
|
||||
releaseExposure: { cases: ["tests/acceptance/releaseExposureCli.test.ts"] },
|
||||
|
||||
@@ -9,6 +9,7 @@ import { open, writeFile, type FileHandle } from "node:fs/promises";
|
||||
import { createHash } from "node:crypto";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, expect, it, vi } from "vitest";
|
||||
import { ZipReader } from "@zip.js/zip.js";
|
||||
|
||||
const fault = vi.hoisted(() => ({
|
||||
path: "",
|
||||
@@ -111,6 +112,10 @@ import { ArtifactReaderFailure } from "../../src/resources/ArtifactReader.js";
|
||||
import { GoBinaryProvider } from "../../src/go/GoBinaryProvider.js";
|
||||
import { PythonPycProvider } from "../../src/python/PythonPycProvider.js";
|
||||
import { inspectPythonPycInputSchema } from "../../src/domain/python/pythonPyc.js";
|
||||
import { NugetNupkgProvider } from "../../src/nuget/NugetNupkgProvider.js";
|
||||
import { NugetNupkgService } from "../../src/application/nuget/NugetNupkgService.js";
|
||||
import { nugetNupkgFixture } from "../../src/nuget/NugetNupkg.fixture.js";
|
||||
import { inspectNugetNupkgInputSchema } from "../../src/domain/nuget/nupkg.js";
|
||||
import { PeResourcesProvider } from "../../src/native/pe/PeResourcesProvider.js";
|
||||
import { Il2cppMetadataProvider } from "../../src/il2cpp/Il2cppMetadataProvider.js";
|
||||
import { ElfNotesProvider } from "../../src/native/elf/ElfNotesProvider.js";
|
||||
@@ -170,6 +175,88 @@ const staticProviders = [
|
||||
["IL2CPP metadata", () => new Il2cppMetadataProvider()],
|
||||
] as const;
|
||||
|
||||
it("preserves opaque NuGet decoder failures and the completed file identity", async () => {
|
||||
const path = await selectedImage();
|
||||
const bytes = await nugetNupkgFixture();
|
||||
await writeFile(path, bytes);
|
||||
fault.blockNew = false;
|
||||
const cause = new Error("controlled decoder runtime failure");
|
||||
const enumeration = vi
|
||||
.spyOn(ZipReader.prototype, "getEntriesGenerator")
|
||||
.mockImplementation(async function* () {
|
||||
throw cause;
|
||||
});
|
||||
const provider = new NugetNupkgProvider();
|
||||
try {
|
||||
const result = await provider.inspect(
|
||||
inspectNugetNupkgInputSchema.parse({ path }),
|
||||
);
|
||||
if (result.ok) throw new Error("Expected opaque decoder failure");
|
||||
expect(result.error._tag).toBe("ArtifactOperationError");
|
||||
expect(result.error.cause).toBe(cause);
|
||||
expect(result.error.cleanupIncomplete).toBe(false);
|
||||
expect(result.error.partialObservation).toEqual({
|
||||
kind: "file-snapshot-hash",
|
||||
path,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.length,
|
||||
});
|
||||
expect(fault.handles).toHaveLength(1);
|
||||
expect(fault.handles[0]?.fd).toBe(-1);
|
||||
} finally {
|
||||
enumeration.mockRestore();
|
||||
await provider.close();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["close failure", "close cancellation"])(
|
||||
"retains only the completed NuGet file snapshot through %s and cleanup retry",
|
||||
async (outcome) => {
|
||||
const path = await selectedImage();
|
||||
const bytes = await nugetNupkgFixture();
|
||||
await writeFile(path, bytes);
|
||||
const controller = new AbortController();
|
||||
const reason = { source: "NuGet file finalization" };
|
||||
if (outcome === "close cancellation")
|
||||
fault.onClose = () => controller.abort(reason);
|
||||
const service = new NugetNupkgService(new NugetNupkgProvider());
|
||||
try {
|
||||
const result = await service.inspect(
|
||||
{ path },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
if (result.ok)
|
||||
throw new Error("Expected descriptor finalization failure");
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
expect(result.error.partialObservation).toEqual({
|
||||
kind: "file-snapshot-hash",
|
||||
path,
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.length,
|
||||
});
|
||||
const beforeCleanup = projectAnalysisError(result.error).details
|
||||
?.partial_observation;
|
||||
if (outcome === "close cancellation")
|
||||
expect(result.error.cleanupPrimary?.cause).toBe(reason);
|
||||
await expect(service.close()).rejects.toBeDefined();
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
fault.blocked.clear();
|
||||
await service.close();
|
||||
expect(result.error.cleanupIncomplete).toBe(false);
|
||||
expect(
|
||||
projectAnalysisError(resolvedAnalysisError(result.error)).details
|
||||
?.partial_observation,
|
||||
).toEqual(beforeCleanup);
|
||||
expect(fault.handles).toHaveLength(1);
|
||||
expect(fault.handles[0]?.fd).toBe(-1);
|
||||
} finally {
|
||||
fault.onClose = undefined;
|
||||
fault.blocked.clear();
|
||||
await service.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(
|
||||
["Rust service", "selected producer input", "source map"].flatMap(
|
||||
(consumer) =>
|
||||
@@ -1035,6 +1122,7 @@ const stableArtifactProviders = [
|
||||
["Windows shortcut", () => new WindowsShortcutProvider()],
|
||||
["native exports", () => new NativeExportsProvider()],
|
||||
["Python pyc", () => new PythonPycProvider()],
|
||||
["NuGet nupkg", () => new NugetNupkgProvider()],
|
||||
] as const;
|
||||
|
||||
const fileFailureProviders = [
|
||||
@@ -1048,6 +1136,11 @@ const inspectFileFailure = (
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
const options = signal === undefined ? undefined : { signal };
|
||||
if (provider instanceof NugetNupkgProvider)
|
||||
return provider.inspect(
|
||||
inspectNugetNupkgInputSchema.parse({ path }),
|
||||
options,
|
||||
);
|
||||
if (provider instanceof PythonPycProvider)
|
||||
return provider.inspect(
|
||||
inspectPythonPycInputSchema.parse({ path }),
|
||||
@@ -1178,7 +1271,8 @@ it.each(
|
||||
provider instanceof ElfDependenciesProvider ||
|
||||
provider instanceof KernelBuildConfigProvider ||
|
||||
provider instanceof PeCertificatesProvider ||
|
||||
provider instanceof PeResourcesProvider
|
||||
provider instanceof PeResourcesProvider ||
|
||||
provider instanceof NugetNupkgProvider
|
||||
? "ArtifactOperationError"
|
||||
: "ProviderAdapterError"),
|
||||
);
|
||||
|
||||
@@ -1614,6 +1614,20 @@ export const PROVIDER_LIFECYCLE_COVERAGE: Readonly<
|
||||
),
|
||||
},
|
||||
},
|
||||
"rea-nuget-nupkg": inProcess(
|
||||
covered(
|
||||
test(
|
||||
"tests/boundary/mcp/nugetNupkgMcp.test.ts",
|
||||
"advertises inspect_nuget_nupkg and reads package identity",
|
||||
),
|
||||
),
|
||||
covered(
|
||||
test(
|
||||
"src/application/nuget/NugetNupkgService.test.ts",
|
||||
"retains completed Evidence and caller selections on late cancellation",
|
||||
),
|
||||
),
|
||||
),
|
||||
"rea-python-pyc": inProcess(
|
||||
covered(
|
||||
test(
|
||||
|
||||
Reference in new issue
Block a user