Skip to content

feat(artifacts): inventory Nintendo Switch NSO and NRO executables offline - #14655

Merged
morluto merged 9 commits into
morluto:mainfrom
mvanhorn:fix/switch-nso-nro-inventory
Nov 26, 2026
Merged

morluto merged 9 commits into
morluto:mainfrom
mvanhorn:fix/switch-nso-nro-inventory

Conversation

@mvanhorn

@mvanhorn mvanhorn commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Nintendo Switch homebrew and modding work starts from NSO modules (main, subsdk*, sdk) and NRO homebrew executables. REA does not recognize either format today, so inspect-artifact on main.nso refuses it as an unsupported binary format. To get the module id that pairs a build with crash logs and patches, or to load the decompressed text segment into a disassembler at the right offset, an analyst has to decode the header and the LZ4 segments with a separate tool and loses per-segment Evidence.

This adds offline nso and nro artifact formats. inspect-artifact and extract-artifact (and the MCP inspect_artifact / extract_artifact tools) report the header facts, list the text, rodata and data segments with file and memory offsets, decompress LZ4 segments in memory to hash and extract the loaded bytes, compare them with the header's SHA-256 values, and for NRO list the icon, NACP and RomFS ranges from the ASET trailer. Nothing is run, patched or disassembled. No issue exists for this; it is a format-inspection and ordinary-extraction addition within the supported contribution scope.

Problem and expected behavior

Use case: given main.nso, see its module id, flags, MOD0 offset and the three segments with their memory offsets and hash status, then extract text.bin as the decompressed code. Given an NRO, see the same header facts plus the asset ranges.

Observable outcome:

  • A file starting with NSO0 is recognized as nso, and a file with NRO0 at offset 0x10 as nro, regardless of filename.
  • The root occurrence carries format_metadata of kind switch-executable: format, version, flags, unknown_flags, module_id (lowercase hex), bss_size, the embedded, dynstr and dynsym extents, mod0_offset, mod0_present (NRO only), image_size (NRO only) and asset_section.
  • Each segment or asset is a child (text.bin, rodata.bin, data.bin, assets/icon.jpg, assets/control.nacp, assets/romfs.bin) with kind switch-executable-entry metadata: role, file and memory offsets, stored size, compressed, declared_sha256, observed_sha256 and hash_status (match, mismatch, not-checked, unavailable).
  • A hash mismatch is a limitation on the entry and the inventory; the segment is kept.
  • A segment whose stored range runs past the end of the file, that is not valid LZ4, or that would exceed the remaining artifact_limits.expanded_bytes allowance stays listed with hash_status: "unavailable", coverage becomes unknown, and opening it is refused. The other entries are still inventoried and extractable.
  • A header shorter than 0x100 bytes (NSO) or 0x80 bytes (NRO), an NSO segment that overlaps the header, or an NRO segment past the declared image size refuses the file as malformed.

Change and scope

  • src/domain/switchExecutable.ts owns parsing: magic checks, NSO and NRO header fields, segment and asset extents, truncation and overlap checks, the ASET header and MOD0 offset reads.
  • src/artifacts/SwitchExecutableArtifactReader.ts reads headers through bounded positional reads, decodes compressed NSO segments within the expansion allowance, hashes loaded bytes, and serves each entry either as a stored range or from the decoded segment.
  • PositionalArtifactReader gains a protected entrySource hook so a subclass can serve bytes that are not one stored carrier range (here a decoded segment). The base reader still owns the stream lifecycle, cancellation and the declared-size check. The default returns undefined, so existing readers are unchanged.
  • Registration in artifactFormats.ts, recognition in artifactFormatRecognition.ts, switch-executable and switch-executable-entry schemas in packageAndGameMetadata.ts and artifactFormatMetadata.ts, and nso / nro wiring in targetFormats.ts, artifactGraph.ts, artifactInventoryView.ts and ArtifactReader.ts.
  • Limits: each compressed segment's stored and decoded buffers are charged to the existing per-call artifact_limits.expanded_bytes parameter (default derived from the file size by artifactExpansionBudgetBytes), and its refusal reports that parameter through artifactReaderLimitFailure. No new fixed ceiling is added. The header sizes (0x100, 0x80, 0x38 for ASET) are format facts, and the 64 KiB READ_CHUNK_BYTES is a streaming read granularity, not an admission limit.
  • Docs: new docs/switch-executables.md, a row in docs/reference/supported-targets.md, NSO added to the expanded_bytes reader list in docs/reference/limits-and-recovery.md, CLI examples in docs/getting-started/cli.md, the docs sidebar, docs/README.md, and a Switch entry in the skill references under .agents/skills/reverse-engineer-anything/ and .cursor-plugin/.
  • One shared fix in src/artifacts/inventory/scanReader.ts: when a reader refuses entry content with ArtifactEntryContentUnavailable and the entry already lists the same limitation, the occurrence no longer records it twice. NSO segments that are truncated or over the expansion allowance hit this, and so do ISO 9660 fragmented and interleaved files on main today (an interleaved entry listed "ISO 9660 interleaved file units are listed but not read; the file's bytes were not established." twice). Hash status and traversal recording are unchanged.

Not included: KIP1, NSP, XCI and NCA containers, NACP or RomFS decoding, symbol or relocation parsing from dynsym / dynstr, and disassembly.

Follow the contribution scope. Not applicable: this reads a local file and does not add target execution, injection, mutation or protection recovery.

Contract and boundary impact

  • Semantic owner and earliest changed stage: switchExecutable.ts produces the header and extent facts at recognition and inventory; the reader, inventory graph and inventory view consume them without reparsing raw bytes.
  • Contribution scope fit and linked maintainer decision: format inspection and ordinary extraction of a local file; maintainer decision not applicable.
  • CLI and MCP/tool-catalog contract: no new tools or parameters. Existing artifact tools recognize two more format values, nso and nro.
  • Provider, bridge, target-format, or platform compatibility: new target formats nso and nro; existing formats unchanged. The PositionalArtifactReader hook defaults to the previous behavior.
  • Evidence, artifact, provenance, or reconstruction contract: new switch-executable and switch-executable-entry metadata shapes. Declared header hashes and REA-computed hashes are separate fields.
  • Target selection, authority, upstream behavior, and cleanup details (if applicable): not applicable.
  • Generated metadata (docs/public/product-catalog.json), package, or installation impact (CI generates and validates ignored catalogs and skills/; edit authored instructions in .agents/skills/reverse-engineer-anything/ and never commit build outputs): none committed; authored skill references updated under .agents/skills/reverse-engineer-anything/ and .cursor-plugin/.

Expected effects (check known effects; use documentation-only on its own).
Unchecked items do not establish absence; leave uncertainties visible.

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated: src/domain/switchExecutable.test.ts (magic checks, NSO and NRO header parsing, overlap and image-size refusals, ASET parsing, MOD0 offsets), src/artifacts/SwitchExecutableArtifactReader.test.ts and .boundaries.test.ts (compressed and stored segments, hash match, mismatch and unchecked hashes, unknown flag bits, truncated segments, invalid LZ4, the expansion allowance, NRO with and without assets, truncated assets, trailing bytes, cancellation while streaming), and TargetFormatVocabularies.test.ts. SwitchExecutableArtifactReader.boundaries.test.ts and Iso9660ArtifactReader.test.ts also assert that a refused occurrence carries its limitation once; both failed before the scanReader.ts change. Fixtures are built in src/domain/switchExecutable.fixture.ts.
  • Base reproduction or other evidence: source-derived for the base revision: upstream/main has no nso or nro format value, so these files fall through to the unsupported-format refusal. The behavior below is executed on this branch.
  • User-visible CLI/MCP output (executed, rea inspect-artifact main.nso --json on an NSO generated with buildNso(): compressed text and data, stored rodata, all three hash checks on). Excerpt of the root and text.bin occurrences:
{
  "logical_path": ".",
  "artifact_format": "nso",
  "declared_size": 326,
  "format_metadata": {
    "kind": "switch-executable",
    "format": "nso",
    "version": 0,
    "flags": 61,
    "unknown_flags": 0,
    "module_id": "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff",
    "bss_size": 64,
    "mod0_offset": 16,
    "mod0_present": null,
    "embedded": { "offset": 0, "size": 0 },
    "dynstr": { "offset": 0, "size": 0 },
    "dynsym": { "offset": 0, "size": 0 },
    "image_size": null,
    "asset_section": null
  },
  "limitations": []
}
{
  "logical_path": "text.bin",
  "declared_size": 32,
  "compressed_size": 34,
  "executable": true,
  "source_location": { "offset": 256, "length": 34 },
  "format_metadata": {
    "kind": "switch-executable-entry",
    "role": "text",
    "file_offset": 256,
    "memory_offset": 0,
    "file_size": 34,
    "compressed": true,
    "declared_sha256": "2a1a6382f2a0327f878edb59cd507994618b285acf49f05196f60f41ce9d7ea4",
    "observed_sha256": "2a1a6382f2a0327f878edb59cd507994618b285acf49f05196f60f41ce9d7ea4",
    "hash_status": "match"
  }
}

rea extract-artifact main.nso --output-root out --json wrote text.bin (32 bytes, SHA-256 2a1a6382..., starting with the branch and MOD0 at 0x10), rodata.bin (22 bytes) and data.bin (13 bytes, decompressed from 14 stored bytes) with containment_verified: true.

On an NRO generated with buildNro() and an icon, NACP and RomFS, coverage is complete, the root reports "image_size": 178, "asset_section": {"offset": 178, "version": 0}, "mod0_offset": 128, "mod0_present": true, and the assets are listed as assets/icon.jpg, assets/control.nacp and assets/romfs.bin with hash_status: "not-checked".

Limitations and refusals from the same run:

  • Hash mismatch (buildNso({ corruptHash: 1 })): coverage unknown, rodata.bin keeps its bytes with "hash_status": "mismatch" and the limitation "rodata segment SHA-256 6f8c15f4d6321cf32b44501ec62e18a91383e7e1c8cad1dc8b38e82c6c90eaa2 does not match the header's 908c15f4d6321cf32b44501ec62e18a91383e7e1c8cad1dc8b38e82c6c90eaa2".
  • Truncated segment (stored segments, last 4 bytes removed): data.bin is listed with "observed_sha256": null, "hash_status": "unavailable" and the limitation "data segment is truncated: it declares 13 stored bytes at offset 310 but the file has 319 bytes"; text.bin and rodata.bin still report match. extract-artifact on that file refuses with "detail": "Inventoried source bytes are unavailable for data.bin".
  • Expansion allowance (--artifact-limits '{"expanded_bytes":20}' on main.nso): text.bin is unavailable with "text segment decompresses to 32 bytes, over the remaining artifact_limits.expanded_bytes budget of 20", and data.bin is unavailable with "data segment allocates 14 stored bytes and 13 decoded bytes, over the remaining artifact_limits.expanded_bytes budget of 20". The stored rodata.bin still hashes and extracts.
  • Malformed header (NSO0 followed by 5 bytes):
{
  "code": "unsupported_target",
  "message": "Malformed nso target for inspect_artifact at .../short.nso: NSO is malformed: NSO header is truncated: 9 of 256 bytes",
  "details": { "failure_kind": "malformed", "format": "nso" }
}
  • Remaining proof gaps: tested only against generated fixtures that follow the public NSO and NRO layouts. No retail NSO or real homebrew NRO was checked. The fixture helper writes literal-only LZ4 blocks, so segments with back-references produced by a real compressor were not exercised through this reader.

For boundary fixes, identify the applicable boundary regressions and lifecycle regressions covered by the evidence above, and explain relevant gaps. Applicable: malformed input (short headers, overlap, truncated segments, invalid LZ4), capacity (expansion allowance refusal with the named parameter), and cancellation while streaming a decoded segment through the new entrySource hook.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Demo

Rendered walkthrough of the CLI inspect output above (simulated terminal, values taken from a real run on generated fixtures).

demo

rea-switch-demo.mp4

Validation performed

  • npm run test:local -- src/domain/switchExecutable.test.ts src/artifacts/SwitchExecutableArtifactReader.test.ts src/artifacts/SwitchExecutableArtifactReader.boundaries.test.ts src/application/binary/TargetFormatVocabularies.test.ts: 4 files, 84 tests passed
  • npm run test:local over every *.test.ts file under src/artifacts plus src/domain/artifactFormatRecognition.test.ts and src/domain/artifactGraph.test.ts (covers the other PositionalArtifactReader subclasses): 96 files passed, 2165 tests passed, 19 skipped
  • npm run check:fast: typecheck and lint passed (turbo cache hit), architecture guards passed across 3135 source files
  • npm run docs:check: passed, including readmeConsistency.test.ts (8 tests)
  • npm run format:check: all matched files use the correct format
  • npm run compile, then node scripts/rea.mjs inspect-artifact and extract-artifact on generated NSO and NRO fixtures: output as shown above
  • After the scanReader.ts change: npm run test:local on 13 files (Switch, ISO 9660, scanReader, ArtifactGraphConstruction, ArtifactInventoryFinalization, Android OTA and Asar tests): 201 tests passed; npm run check:fast, npm run docs:check, npm run format:check and npm run verify:advertised-schemas passed
  • inspect-artifact on a truncated NSO and an interleaved ISO before and after the change: the repeated limitation string appears once after it

Compatibility, safety, and release

  • Breaking changes or migration steps: none.
  • Real Hopper/Ghidra, browser, or OS coverage: not applicable; offline parsing only, run on macOS.
  • Package or release metadata impact: two new format values, nso and nro.
  • Security, privacy, process, or containment review: reads a local file only and extracts through the existing contained extraction path. Header fields are untrusted: segment and asset extents are checked against the header and file size before any read, and an NRO asset range past Number.MAX_SAFE_INTEGER is refused. LZ4 output is bounded by the declared segment size, and the stored and decoded buffers are charged to artifact_limits.expanded_bytes before they are allocated.

AI was used for assistance.

Author readiness

Human owner: @mvanhorn

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Author checklist (completed by the PR author before requesting review)

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.
  • I ran every test, build, or measurement needed to validate this change, reported a browser, GPU, or environment gap only when that runtime or hardware is unavailable, and reported the checks I ran and their results without presenting inferred correctness or speedups as measured.
  • Comments explain constraints or non-obvious decisions; task history and conversations stay out of code and docs.
  • Documentation is concise and factual, without punchy slogans or promotional language.
  • This change fixes the root cause and follows the engineering rules in AGENTS.md.
  • Formatted input is interpreted once at the owning boundary, and consumers use the owner's parsed facts. See Interpret boundary facts once.
  • Combined failures preserve partial observations, remaining resources, and cleanup facts. See Own the lifecycle.
  • A hardcoded limit is an REA_ runtime setting with a default, floor, and maximum, unless a fixed ceiling has a stated reason. See Adding a runtime setting.

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-26T04:29:54.954969Z
We couldn’t complete this review. Comment @codex review to try again.
28b31c1 PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@greptile-apps

greptile-apps Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 5/5 · The reviewed changes appear safe to merge, with no new actionable findings.RetriggerView in GreptileConfidence Score: 5/5 Tier: plus

[Medium impact] The reviewed changes appear safe to merge, with no new actionable findings.

Summary

Adds offline NSO/NRO recognition, segment extraction, hashes, header metadata, and NRO asset ranges.

  • REA can inspect and extract Nintendo Switch NSO and NRO executable parts.
  • Inventory entries show a repeated limitation only once.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Local file] --> B[Recognize NSO or NRO]
  B --> C[Parse headers and declared ranges]
  C --> D{Compressed segment?}
  D -->|Yes| E[Check allowance and decode LZ4]
  D -->|No| F[Read stored range]
  E --> G[Inventory bytes, hashes and limitations]
  F --> G
  G --> H[Extract selected entries through owned streams]
Loading

Reviews (9) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

Comment thread src/domain/switchExecutable.ts Resolved
Comment thread src/domain/switchExecutable.ts Resolved
mvanhorn and others added 2 commits November 26, 2026 00:55
…fline

Detection uses the bytes: NSO0 at the start of the file, or NRO0 at
offset 0x10. Inventory records the module id, flags, and MOD0 offset,
lists the text, rodata, and data segments, and for an NRO adds the ASET
icon, NACP, and RomFS when that trailer is present. Compressed NSO
segments are raw LZ4 blocks decoded under
artifact_limits.expanded_bytes, with the stored size and the decoded
size both reserved before allocation, and hash_status is match,
mismatch, not-checked, or unavailable. Truncated, over-budget, and
invalid-LZ4 entries stay listed while their bytes are refused, and a
positional reader can stream those decoded bytes instead of the stored
file range.
@mvanhorn
mvanhorn force-pushed the fix/switch-nso-nro-inventory branch from b835595 to 6e8549d Compare November 26, 2026 08:58
@morluto morluto added area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request labels Nov 26, 2026
# Conflicts:
#	.agents/skills/reverse-engineer-anything/references/native-and-artifacts.md
#	.cursor-plugin/skills/reverse-engineer-anything/references/native-and-artifacts.md
#	docs/reference/limits-and-recovery.md
- Remove the duplicate NSO decoded-only budget pre-check in #prepareNso so
  #admitStoredInput owns all compressed-segment admission and reports an
  accurate required_value covering both stored and decoded bytes.
- Use testWaitDeadline() in SwitchExecutableArtifactReader.boundaries.test.ts
  instead of a hardcoded 2_000 ms timeout.
- Reuse tests/fixtures/lz4LiteralBlock.ts in switchExecutable.fixture.ts.
Comment thread src/domain/switchExecutable.test.ts Resolved
@morluto
morluto enabled auto-merge (squash) November 26, 2026 18:13
# Conflicts:
#	docs/getting-started/cli.md
#	docs/reference/limits-and-recovery.md
#	src/artifacts/artifactFormats.ts
#	src/domain/artifactFormatRecognition.ts
@morluto
morluto merged commit 3970afe into morluto:main Nov 26, 2026
54 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: evidence Evidence, artifacts, and reconstruction enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants