feat(audit): report what a shipped app exposes to static analysis (#8525)

* feat(audit): report what a shipped app exposes to static analysis

Adds `audit_release_exposure` and `rea audit-release-exposure` to report
source maps, Electron fuse implications, extractable payloads, debug
information, build metadata, and credential markers. Checks carry stable
IDs, observations, statuses, and fixed remediation, while incomplete and
unassessed checks remain visible without implying a security verdict.
Credential findings include only rule IDs and locations. The CLI
supports `--fail_on` severity thresholds and exits 3 when an exposed
check meets the threshold.

* fix(audit): keep incomplete coverage unknown across text, fuses, Go flags and cancellation

Probe files with unrecognized names as text, keep undecided fuse slices
unknown, forward opaque container coverage, read paths from Go build flags,
and compare inventoried digests before accepting owner facts.

Keep typed cleanup failures and attach the partial report when a later owner
is cancelled. Pin the verifier's @electron/fuses version and move the tests
to the named contract family.

* fix(audit): match package members by source spelling and close remaining coverage gaps

Reopen package members by their source spelling and keep caller path
traversal in directory reads. Parse quoted and attached Go build flags, bind a
native image fuse read to its own digest, and keep reader resources and the
audit's partial report when cleanup or cancellation combine failures.

* fix(release-exposure): bind package members by ordinal and follow named map references

Package members were matched to container entries by sourcePath, which is
not unique in a PyInstaller executable, through a queue that only moved when
a member was reopened. Bind by container-relative path and duplicate ordinal,
the numbering inventory uses, so read order cannot change which bytes a
member gets.

A sourceMappingURL naming a file without a map extension was ignored. Local
targets are now examined as maps whatever their name, and a target already
scanned as plain text leaves coverage unknown.

* fix(release-exposure): match data: source map scheme case-insensitively

URL schemes are case-insensitive, so an inline declaration such as
//# sourceMappingURL=DATA:application/json;base64,... was routed to the
local-reference path, which ignores scheme URLs. Its embedded sources were
silently dropped and source_map_sources reported not_observed.

* fix(release-exposure): normalize declared map targets and count unreached ones

A sourceMappingURL that decodes to a decomposed name (cafe%CC%81.json)
never matched the inventoried member, whose logical path is NFC, so the
map was scanned as ordinary text and its sourcesContent went uncounted.
Map-target lookups now use an NFC key on both the record and lookup
side; the declared URL is left as written.

A declared map target that is never reached is now counted as a skipped
map, so the source-map checks read as unknown coverage instead of
not_observed.

* fix(release-exposure): recover indexed leaves after any map format failure

An indexed map whose one leaf has malformed mappings (such as AA) threw a
format failure that only recovered leaves for unsupported sections, so a
valid sibling leaf with sourcesContent was dropped and
javascript.source_map_sources read unknown instead of exposed. Leaves are
now recovered for any format failure, with the envelope parse guarded so
invalid JSON still falls through to the unparsed count.

A nested package that inventory recognized but did not expand was probed
as a plain binary and left the source-map checks at not_observed. It now
marks coverage unknown and records a limitation.

Reader tests assert the javascript.source_map_sources status for the NFC
map-name cases as well.

* fix(release-exposure): count an unexpanded nested package as a readable member

An unencrypted nested package that inventory recognized but did not
expand is still a member its parent package already read. Count it as
readable so packaging.extractable_payload reports exposed, while its
own contents keep coverage unknown.

* fix(release-exposure): bound the indexed leaf fallback by decoder limits

The fallback walk after a map format failure expanded every section and
built a full ancestor path per leaf, so a map refused for nesting depth
could still allocate far past the decoder budgets. Walk only to the
64-level section depth and the shared record budget, keeping leaf maps
without materializing section paths.

* fix(release-exposure): collect UNC roots from Go flag paths

A flag such as -I\\buildhost\sdk\include matched none of the path roots
in GO_FLAG_PATH, so a network path that was the only one in complete
build info left go.build_paths at not_observed. Accept \\host\share
roots alongside the slash-rooted, dot-relative and drive-letter forms.

* fix(release-exposure): keep Electron undecided without positive proof

The desktop owner names Electron only from an ASAR layout, so an asar: false
build has no candidate. A complete scan with no candidate was reported as
not_electron, which outranks unresolved and safe fuse outcomes and hid them
as not_applicable.

Leave the family unknown unless the fuse holder rules Electron out: an app
bundle with no Electron Framework, or a directory with complete coverage
whose native images were all read and hold no sentinel. A directory with no
native image is not proof, so its fuse checks now report unknown.

* fix(release-exposure): decode wide text members before scanning

A member's kind bypassed the NUL guard, so a UTF-16 plist was decoded as
UTF-8, matched nothing and still counted as scanned. A directory holding
only that member reported text.credential_markers as not_observed.

Decode by byte order mark at one boundary instead. UTF-16 is scanned in
either byte order, and inline maps read the same text. UTF-32 and NULs no
mark explains count as skipped, whatever the member's kind. A binary
plist keeps its raw scan. Unnamed members with a mark now reach the
scanner, and the plist decoder shares the same mark detection.

* fix(release-exposure): follow file: URL source map declarations

The scheme guard in noteLocalMapReference returned on every URL scheme, so
a declaration such as file:///release/debug.json was dropped with the remote
ones. A member without a .map name was then scanned as ordinary text and
javascript.source_map_sources reported not_observed.

Convert file: URLs with fileURLToPath and record them in mapTargets through
the same step as relative declarations. A target that is never reached, or
that was already scanned as text, counts as skipped, and so does a malformed
file: URL. A file: URL names one absolute location, so a .map target outside
the inventory stays unassessed rather than being trusted by its name. Remote
schemes stay ignored.

* fix(release-exposure): match backslash-relative Go flag paths

GO_FLAG_PATH accepted dot-relative roots only with a forward slash, so
`-I..\sdk\include` and `-I.\sdk` produced no path and go.build_paths came
back not_observed. Accept either separator after the dots.

The CLI acceptance test now expects unknown for electron.run_as_node on a
directory with no native images, matching the service.

* fix(release-exposure): keep fuses unknown on incomplete inventory

A directory inventory that stops at an acquisition limit never reports
the images it did not reach, so the native image sample has no omission
and safe fuses on an included helper settled to not_observed even though
scan coverage was unknown.

Treat unknown coverage like a truncated sample until the Electron
executable is accounted for. A selected native file is that executable,
so it keeps its decided fuse result.

* fix(release-exposure): decode binary plists before scanning

A binary plist stores each string as ASCII or UTF-16BE. Scanning the raw
bytes as UTF-8 missed any string the encoder kept in UTF-16, such as one
with a non-ASCII character, and still counted the member as fully
scanned, so text.credential_markers read not_observed.

Decode through the plist owner and scan its strings, dictionary keys and
data. A plist that cannot be decoded keeps its raw bytes in the scan and
counts as skipped, so coverage stays unknown.

* fix(release-exposure): keep UTF-8 members that hold a NUL

Any NUL in a member's first 512 bytes made the decoder give up, so a script
with a literal NUL in a string never reached the credential or inline-map
checks. An exposed marker in it read as unknown, and --fail_on high exited 0.

Validity alone cannot tell wide text from UTF-8, since ASCII in UTF-16 is
valid UTF-8. Treat a header that is an eighth or more NUL bytes as wide text
and anything not UTF-8 as undecoded, and scan the rest.

The docs now separate BOM-marked UTF-16, which is scanned, from wide text
with no byte order mark, which is not.

* fix(audit): scan every string a binary plist stores

The plist scan read only the decoded value, which drops objects the root no
longer references and entries a later duplicate key replaced. Those bytes
still ship, but the audit marked the scan complete, so a credential stored
there read as not observed and --fail_on high exited 0.

Read strings, keys and data from the object table instead. A stored object
that cannot be read leaves the member unassessed, and a total byte budget
bounds table entries that overlap to repeat the same text.

* fix(audit): keep packaged native images from ruling out Electron

The applicability check only looked at the "native images" omission. An
Electron executable inside a compressed .NET or PyInstaller member is recorded
under "packaged native images", so a directory whose on-disk hosts had no fuse
sentinel read as not Electron and all four fuse checks as not applicable.

Treat that omission as an unread image too.

* fix(audit): keep readable plist text when one object is unreadable

Throwing on one unreadable stored object discarded every string already
decoded, so a UTF-16BE credential beside a truncated unused object was lost:
the raw bytes that replaced it cannot match NUL-separated text.

Return the decoded text with complete false instead, and keep the raw bytes
in the scan beside it so ASCII in the unread object is still seen. The member
stays unassessed. Text past the budget ends the same way.

* fix(audit): read escaped inline maps and extensionless SEA entries

A data URL may percent-escape its base64 payload, so a map such as one padded
with %3D did not decode and the audit counted no embedded source map. Decode
the escapes before reading the base64.

A directory walk classed a SEA entry by its code path, so a main script whose
code path names no script was never scanned as JavaScript and its inline map
went unseen. Class it by the role the SEA metadata gives it.

* fix(audit): check plist text against the budget before decoding it

decodeBinaryPlistText decoded each stored object before comparing its size
with the remaining budget, and it keeps going after an object is rejected so
later text is still read. A plist under the input limit could repeat a large
range through overlapping table entries and force gigabytes of decoding that
the audit then discarded.

Separate finding a stored payload from decoding it, so a range past the
remaining budget is rejected without allocating its text. Earlier text and
the incomplete result stay as they were.

* fix(audit): count a packaged PE with an unread header as a native image

A package member whose PE signature lies beyond the 4 KiB probe recorded only
a PDB failure. The image was neither read nor listed under packaged native
images, so a directory whose on-disk hosts had no fuse sentinel read as not
Electron and all four fuse checks as not applicable.

Count it as a packaged native image, the omission that keeps the question
open, and keep probing it for text as before.

* fix(audit): keep cleanup-incomplete errors from composed readers

A desktop, fuse, Go or Rust failure became a string on that check, so an
error with unfinished cleanup lost its resources and live bindings while the
audit reported success, and the MCP handler does not close the service after
each request.

Treat unfinished cleanup like cancellation: stop the remaining owners and
return the error with the partial audit. When the owner attached its own
partial, keep the error and replace the partial, so cleanup stays attributed.

* fix(audit): keep safe fuses unknown past a packaged native image

The fuse check counted sampled-out images as possibly unread but not native
images inside a package. A complete directory scan with a safe-fuse image on
disk, no ASAR hint, and an unopened packaged image reported the four Electron
checks as not_observed, although the Electron executable could be that image.

The fuse check, the Go and Rust checks, and the Electron rule-out each decided
this for themselves and had drifted apart. Move the decision to one domain
predicate, nativeImagesMayBeUnread, and use it in all three. A hinted
executable that was read still settles the check.

* fix(audit): settle fuses only on an identified host, and read Bun and HTML maps

A retained helper set electron_executable_included because the rank marks
every .exe or extensionless sibling of resources/app.asar. With more than four
siblings, or an inventory that stopped early, safe fuses on a helper reported
not_observed while the host went unread. Rank stays a sampling hint. The check
now settles only on an executable named as the host, or when inventory was
complete and every executable that could be the host was sampled.

A Bun sourcemap region is named .bunmap, so its role was lost and a complete
audit reported no source maps. Carry the region role from the reader's metadata
into the member view, in the expanded and unexpanded paths, and treat it as a
JavaScript map so an unparsable region stays unresolved, not a debug companion.

An HTML member was scanned as text but its inline scripts were never checked
for source maps. The HTML owner now returns each body, the reader examines it
like a script file, and bodies past the owner's limit count as skipped.

* fix(audit): charge map reads to the count before opening the member

An oversized or unreadable .map returned before readSourceMap counted it, so
the allowance of 32 never ran out. An unexpanded .NET or PyInstaller package
could then decompress every listed map member, about 1 MiB each, up to the
4,096 entry cap.

The count bounds reads, so examineMap now reserves the slot before it opens the
member. A map past the count is skipped unopened, and a linker map past it is
still settled from its bounded prefix. An inline data: map is already in memory
and keeps its charge at the point it is parsed.

* fix(audit): examine scripts HTML loads whatever they are called

isJavaScriptMember knows a script by its suffix or an assigned kind, and the
reader dropped the script references the HTML owner parses. An extensionless
main loaded by <script src="main"> was scanned as ordinary text, so a complete
inventory reported javascript.source_map_sources not_observed with shipped
sources in its inline map.

The reader now resolves each JavaScript script reference against the page and
its base href, and a local target without a JavaScript name is examined as a
script when reached. A target read before its HTML file, never reached, or not
placeable on disk counts as a skipped map, so the check stays unknown.

* fix(audit): charge sibling map reads to the map count

Every generic .map beside a selected file got a full 1 MiB read and a
parse, with no cumulative bound, so the 4,096-entry listing allowed about
4 GiB of reading for one small selection.

Move the slot rule into chargeMapRead, which examineMap and sibling
classification now share. Past the count a sibling reads only the header:
a linker map is still identified, and one that may be a source map stays
a skipped companion.

* fix(audit): report cleanup failures raised by member reads

A close failure during an embedded-package probe, member read or inventory
reaches the shared read filter as an ordinary reader failure. The filter kept
only cancellation and integrity, so the member became a skipped read, inspect
succeeded, and the retained descriptor was reported nowhere. MCP does not close
the service after each request, so no caller saw it.

Propagate any failure that carries cleanup, whatever its reason, so it reaches
releaseExposureFailure and the audit reports its retained resources.

* fix(audit): charge unsuccessful text reads to the byte allowance

An oversized, undecodable, or failed text read left textBytes unchanged, so
every member got the full per-member budget and the cumulative allowance did
not bound what a package decompressed. Count the bytes member reads produce
and charge them whatever the read yields. An oversized file on disk still
costs only its probe.

* fix(audit): bound the paths kept for HTML script targets

A base href is copied into every script target it resolves, so a page under
the text member allowance could retain hundreds of megabytes of paths. Charge
each new target's resolved path to a byte allowance and leave targets past it
unassessed.

* fix(audit): keep examining a page loaded as a script as HTML

A script element naming an .html member promoted that member to a
script, and the text pass then chose one reading. The page's own script
elements were never read, so an inline map in it was lost and a shipped
sourcesContent went unreported.

Run the script reading and the HTML reading independently, and list the
script target allowance among the cases that leave source map coverage
undecided.

* fix(audit): detect credential markers that end in a hyphen

The Google, GitLab, and Slack rules allow a hyphen in the token but ended
on a word boundary, so a token ending in a hyphen at the rule's minimum
length was missed and the audit reported the check as not observed.
Open-ended rules now take the whole token, and the fixed-length Google
rule checks the full token alphabet after its last character.

* fix(audit): confirm FAT identity for probed package members

The package probe treated a decoded FAT table as a universal Mach-O. A
JVM class past the 4 KiB probe shares the FAT magic, so its truncated
prefix decoded as a table, the member counted as an unread native image,
and Electron could not be ruled out of a complete scan.

Pass the member's declared size to the sniff and take identity from
classifyFatContainerEvidence. A member with no usable size, or with
slices past the probe, stays counted as possibly native.

* fix(audit): admit binary plists in package member probes

A package member's probe judged text by its own NUL test, which accepted
byte order marks but not the binary plist signature decodeMemberText also
reads. A PyInstaller executable shipping a binary Localizable.strings was
rejected without a scan or a skipped count, so a UTF-16BE private key
marker inside it could report not_observed.

Name the encodings that explain their own NULs in one predicate, and move
the plist fixture builders to module scope.

* fix(audit): locate Go findings only in images that retain build paths

The exposed decision required non-empty paths, but the locations took
every image whose build info read. An image with no paths was named as a
source of the leak beside the one that had them.

One predicate now decides both.

* fix(audit): keep completed findings when member cleanup fails

A descriptor close failure aborts the member scan, and the scan's state
was dropped with it, so the caller got a typed cleanup failure and no
report. Source maps already counted and credential hits already collected
were lost.

The reader now hands the service what it assembled, with coverage unknown
and a limitation saying so, alongside the failure. The service runs that
scan through its existing stopped-audit path: no later owner runs, and the
report goes on the error as its partial observation.

* fix(audit): keep coverage unknown for nested ASARs in package hosts

A member of a PyInstaller or .NET host reaches the binary probe as a
plain file. An ASAR among them has a NUL-bearing header, so the probe
dropped it with no traversal and no omission, and source map checks could
read not_observed with complete coverage.

Ask the ASAR owner's signature probe, and record a match as a nested
package that was not expanded, as inventory-classified ones already are.

* fix(audit): let native format facts outrank member names

examineMember tried the name-based text and map routes first, so a PE an
owner identified inside an ASAR, named payload.json, was read as text.
Its CodeView path and the packaged-native omission were both lost, and
native.pdb_path read not_applicable.

Route an owner-established native format to the native probe first, and
count an encrypted one as a packaged native image for the same reason.

* fix(audit): report relative paths given to compiler path flags

go.build_paths only kept rooted paths, so retained build settings like
CGO_CFLAGS=-Iprivate-sdk read not_observed even though the setting names
a directory.

Take the relative argument of a C compiler path flag, attached or in the
next field. Scope this to compiler settings, because Go's own tools use
the same letters for non-paths such as -B gobuildid and -T 0x1000.

* test(javascript): expect retained text on SVG inline scripts

The SVG test from main predates this branch's inlineScripts text field,
so each side passed alone and only their merge failed.

* fix(audit): keep an unresolved Electron host's fuses unknown

fuseCheck decided from whatever outcomes the images reported, so a host
with no fuse answer read not_observed as soon as any other image in the
directory reported safe fuses.

Pass the images named as the host into the report and leave a check
unknown when one of them has no answer for it. Other images stay free to
have no fuses, because helpers in a real Electron install have none.

* fix(audit): bound the paths kept for local source map targets

noteMapTarget kept every declared target resolved against its member's
directory, so a short URL under a long directory could retain far more
than the script's own size, with no cumulative limit.

Add the allowance noteScriptTarget already has. A target past it stays
unassessed and counts as a skipped map, and is never read.

* fix(audit): borrow the audit's scope admission for inventory

inspect holds resources.run for the whole audit, and inventoryArtifact
entered the same scope again. With failed cleanup pending from another
audit, the inner run waits for a drain that waits for the outer run.

Add inventoryArtifactInScope, which takes the caller's admission.

* fix(audit): run the exposure verifier's commands under supervision

The verifier launched npm and the CLI with raw execFile and then removed
its temporary tree, so a timed-out child could outlive the tree it was
using.

Use the shared verifier commands and close them before removing the tree.
Their exit error carries stdout on its snapshot, so the audit's exit-code
branch reads it from there.

* fix(audit): read relative -L paths and split flag arguments

The relative-path reader handled C compiler settings only, so a directory
kept through Go's own linker flag, such as -ldflags='-L private-sdk -s -w',
reported go.build_paths as not_observed.

A quoted flag and argument also reached it as one field. The separating
space stayed on the argument, which reported rooted paths twice and kept a
leading space on relative ones.

Give -ldflags its own pattern that matches only -L, so -B gobuildid and
-T 0x1000 stay ignored, and consume the separator in the flag patterns.

* fix(audit): keep embedded leaves beside schema-invalid map fields

The reader recovers independent indexed leaves only after a
SourceMapFormatFailure, but inspectSourceMap let the schema's ZodError
through. A sibling with mappings "!", a section with a bad offset or a
root with a bad field skipped recovery, so a valid leaf with
sourcesContent reported javascript.source_map_sources as unknown.

Normalize schema rejection in SourceMapFormat, which owns these parses,
so every structural failure reaches consumers as a format failure. The
message is unchanged, and the codec and web fetcher already map both
cases to the same result.

* fix(audit): keep packaged executables' own packages unknown

examinePackagedBinary counted a native image inside a package and moved
on, while only on-disk images reached the embedded-package probes. An
ASAR carrying a PyInstaller, Bun, Node SEA or .NET executable with a
source map therefore scanned complete and reported
javascript.source_map_sources as not_observed.

Run the same classifier on packaged images. The probes read carrier
offsets from a file, so the member's bytes stay in a temporary file for
the probe alone. A detected package keeps member coverage unknown, as a
nested ASAR does, and an image past one file's total byte allowance
stays unprobed and unknown. A plain native member leaves coverage intact.

* fix(audit): read an app's sampled images for fuses

A .app target sent only the bundle candidate to the fuse reader, which
resolves to the outer Electron Framework. A sidecar with RunAsNode enabled
was never read, so the check reported not_observed in the app view while
the directory view reported exposed.

Send the bundle candidate first and then the sampled native images. An
image whose digest matches the bundle's read is skipped, so the framework
is not read twice. A sidecar's safe fuses cannot settle the outer framework,
so a bundle read with no answer for a fuse keeps that check unknown.

* fix(audit): read a Node shebang as script identity

The path classifier gives an extensionless executable a resource kind,
so a script such as bin/runner with a `#!/usr/bin/env node` header was
scanned as text without its inline maps being examined or counted. A
complete inventory then reported no shipped sources for it.

The probe holds the first bytes a member reader sees, so establish the
identity there. The script keeps the usual outcomes: a map that is read
counts, and one past an allowance or undecodable stays unknown.

* fix(audit): keep linker strings out of Go build paths

Reading `-X 'main.usage=-L level'` as a library directory made
go.build_paths report `level`, so a plain string could fail an audit
under --fail_on low.

Read the optional package selector once, before the setting's first
flag, and keep the argument of -X attached to it, so a string it sets
is never scanned as another option.

* fix(audit): keep a failed probe directory removal owned

A packaged image's probe copies the member's full bytes into a temporary
directory. When removing it failed, the error became an ordinary
unreadable probe: the audit could still succeed, nothing could retry the
removal, and the client heard nothing about the leftover bytes.

Hold the directory in the reader's resource scope, so close retries it,
and report the unfinished cleanup without replacing a primary failure.

* fix(audit): keep a declared .map from reading as a linker map

A script's sourceMappingURL=assets.map was dropped because the name
already looked like a map. A malformed assets.map then settled as a
linker map, so both source-map checks read not_observed and
native.debug_companions reported an exposure the release does not ship.

Keep a generic .map name as a declared target and read it as a
JavaScript map, in either scan order, so it stays unresolved.

* test(audit): rethrow typed errors from release exposure checks

A failed Result was rewrapped in a plain Error, which dropped its type,
cause and cleanup details from the test output.

* fix(audit): match companions by member identity, not spelling

An ASAR member's location is relative, and a declared map target is
absolute, so a malformed assets.map read before z.js stayed a linker
companion. The examined-map lookup, which is normalized, then returned
early, leaving both source-map checks not_observed.

Index companions by memberLocationKey and keep each reported spelling
under it. Spellings stay distinct because symlinks can make them differ.

* fix(audit): retract only guessed linker maps on a declaration

A script declaring sourceMappingURL=symbols.pdb after the scan reached
symbols.pdb removed the shipped PDB from the companion list, because a
late declaration retracted any companion. native.debug_companions could
then read not_observed.

Keep name-identified companions in their own set, and retract only maps
that were read as non-JSON and guessed to be linker maps.

* fix(audit): record an unfollowed map link as skipped

The directory and ASAR readers do not follow links, so a symlinked
app.js.map dropped out before any map counter moved. Its target was
scanned as plain text, and both source-map checks read not_observed.

Count a link that names a map as skipped wherever entries reach the
audit, and mark it examined so a declaration does not count it twice.

* fix(audit): read relative paths in Go compiler and assembler flags

A binary built with -gcflags=-I private-sdk keeps that setting, but
relative parsing covered only C compiler settings and -ldflags, so the
directory dropped out of go.build_paths.

Give -gcflags and -asmflags their own path options, taken from what
go tool compile and go tool asm document, and strip the package selector
as -ldflags does. The assembler's -D defines a symbol, so it is not one.

* docs(audit): state the packaged image read allowance

Packaged ELF, Mach-O and PE images are read in full and copied to a
temporary file, sharing one max_file_bytes allowance, but the docs and
coverage.allowances still said only a PE gets more than a header read.

Name the allowance and the copies in docs/release-exposure.md,
RELEASE_EXPOSURE_ALLOWANCES and the max_file_bytes description.

* docs(audit): say how go.build_paths treats rooted -X values

A rooted -X value cannot be told from a file path, so the audit reports
it. State that, and why, so the rule is a contract rather than a side
effect of how flags are scanned.

* fix(audit): keep a declared sibling map out of the linker guess

When the selected file declared a sibling map, the sibling classifier
never consulted the declaration. A malformed assets.map then read as a
linker map and raised native.debug_companions.

Leave a declared sibling to the unreached-target accounting, as members
already are, so it stays an unresolved source map.

* fix(audit): keep undecodable Go and Rust metadata unknown

Unsupported meant two things: a container this reader does not handle,
and metadata the image holds in a form the reader cannot decode, such as
a compressed .dep-v0 section. Both read as not_applicable, so an image
that carries metadata reported that the check did not apply.

Mark the second case on the format failure and carry it on
AnalysisUnsupportedTargetError, so the audit records a failed read and
stays unknown. The tools' own errors and messages do not change.

* fix(audit): keep coverage unknown for a PE header past the probe

A packaged member whose PE signature lies beyond the probe prefix stayed
unclassified, so the embedded-package probe never ran and coverage stayed
complete. A map inside such an image then read as not_observed.

Record the member as an unexamined package where it is already marked as
a possible native image.

* fix(audit): read the scripts of a standalone SVG

An SVG can carry a script with an inline source map, but only .html and
.htm members reached the script owner, so such a file left every map
counter at zero and javascript.source_map_sources read not_observed.

Treat .svg as a script-bearing page. htmlArtifactReferences already
reads SVG script elements, so this adds no parsing.

* fix(audit): keep every possible host when no name picks one out

With no named Electron host, every sibling ranks alike and
electron_host_paths stayed empty, so one image's safe fuses settled the
checks even when another possible host reported none.

Keep all sampled candidates as hosts in that case, so a candidate
without fuses leaves the checks unknown.

* fix(audit): read a text-named native member by its bytes

A PE member called payload.json took the text route, so it reached no
native probe, and its CodeView path and packaged-native uncertainty were
lost.

Decide from the bytes the text read already loaded, so real text costs
no extra read and the map and text allowances stay as they were.

* fix(audit): let a map or script read identify a native member

A package lists names without formats, so a PE called payload.js.map
took the map route and never reached a native probe. Its CodeView path
was lost, and with nothing counted as failed, native.pdb_path could read
not_applicable. A PE at a declared script or map target was lost the same
way, because declaration overrode the route.

Decide from the bytes the route already read, in the map route as in the
text route, and keep the listed kind for a promoted script target. Real
text and maps cost no extra read, so those allowances are unchanged.

* fix(audit): name a symlinked sibling debug companion

Selecting an executable skipped every symlink beside it before the name
check, so an app.pdb link left no companion path and no skip count, and
native.debug_companions read not_observed. Selecting the directory
reports the same link.

Check the name first. The map branch already needs a regular file, so no
link is followed.

* fix(audit): keep map coverage unknown for a linked script

A link named app.js to an extensionless payload was skipped as a link,
and its target was read as plain text with no map directives parsed. An
inline map there left no parsed or skipped count, so
javascript.source_map_sources read not_observed. Only links with a map
name were counted.

Count a link under any name that can declare a map, the set an unread
member already uses. It stays one omission when a page or a directive
also names it. The target is still not followed.

* fix(audit): keep a declared JavaScript map beside a selected file unknown

A local sourceMappingURL with a JavaScript map name such as app.js.map
was dropped on the assumption that it would be examined as a member.
When the selection is a file, sibling .js.map files are never read, so
the declared map left javascript.source_map_sources not_observed while
the same target spelled as a file: URL left it unknown. Record every
local target so an unreached one counts as skipped.

* fix(audit): read paths a C compiler forwards to the linker

CGO flags can hand linker options through -Wl,a,b or -Xlinker a. The
compiler flag parser saw -Wl,-L,private-sdk as one field and missed the
relative library directory, so go.build_paths reported not_observed.

Split forwarded options out before reading paths and read them with the
linker's own path options (-L, -T, --library-path, --script). This also
stops -Xlinker -Bsymbolic from being read as the compiler's -B prefix.

* fix(audit): read forwarded linker options by their linker meaning

The forwarded linker flag pattern read -Ttext=0x400000 as a script path
named text=0x400000, and it ignored -I, so -Xlinker -Ilib/ld-custom.so
lost the interpreter path the compiler flag pattern found before the
split.

Exclude the -T section and segment address options (bss, data, text,
text-segment, rodata-segment, ldata-segment) and read -I and
--dynamic-linker as paths.

* fix(audit): split Go flags as Go does and read external linker flags

Go splits a flag value with quoted.Split: a field that starts with a
quote runs to the matching quote, and any other quote is a literal
character. The reader stripped every quote, so CGO_CFLAGS
-I"/home/O'Neil/include" reported /home/ONeil/include, while cc was
given the directory "/home/O'Neil/include", quotes included.

-ldflags kept -extldflags values with the Go linker flags, where only
-L counts, so -extldflags=-Lprivate-sdk reported no path. The values
are now read as the C compiler driver reads them, including -Wl, and
-Xlinker forwarding.

A package member named payload.json or payload.js.map that holds an
ASAR took the text or map route, which checked only native signatures,
so the nested archive was scanned as text and coverage read complete.
The route's own read now recognizes the ASAR signature as well, and the
nested package leaves coverage unknown.

* fix(audit): keep a named script beside a selected HTML file unknown

A script element whose target had a JavaScript name such as app.js was
dropped on the assumption that it would be examined as a member. When
the selection is an HTML file, sibling scripts are never read, so a
sibling holding an inline map left javascript.source_map_sources
not_observed while the same target named app left it unknown. Record
every local script target so an unreached one counts as skipped.

* fix(audit): read a retained -pgo setting as one profile path

`-pgo file` names a single profile, and under -trimpath Go keeps only
its file name, so the flag readers dropped values such as
`private-training.pgo` and split paths with spaces or commas. Report
the value whole, skipping `auto` and `off`.

* fix(audit): read -extldflags paths as the external linker splits them

With -ldflags set to -extldflags '-L "/srv/private sdk"', the outer
flag reader could not match the path behind the inner quote, and the
external reader kept only relative paths, so go.build_paths read
not_observed. Read each -extldflags value once, as go tool link splits
it with quoted.Split, and collect rooted and relative paths from those
same arguments. The rest of the setting is read as before.

* fix(audit): read the Go linker's other path options

go.build_paths read only -L as a Go linker path option, so a retained
-ldflags='-tmpdir=private-obj -s -w' reported no path and --fail_on low
missed the directory.

Read every option `go tool link -h` documents as taking a directory,
path or file: -I, -L, -benchmarkprofile, -capturehostobjs, -cpuprofile,
-fipso, -importcfg, -memprofile, -o, -r and -tmpdir. -extld, -extar and
-libgcc name a program or `none`, so only their rooted values count.

* fix(audit): keep a quoted Go argument whole

goFields already reads -L "/tmp/private - sdk" as two arguments, but
each field was then split again before every whitespace-led dash, so
go.build_paths reported /tmp/private instead of the retained directory.

Split again only a field that begins with a flag, after any package
selector, as a quoted "-L dir -s -w" does. Any other field is one
argument and is kept whole, in -ldflags, -extldflags and CGO flags.

* fix(audit): keep coverage unknown for an unread packaged image

When a listed package member is a native image but its first read
fails, examinePackagedBinary returned before probePackagedImage could
mark its possible embedded package unexamined. Coverage stayed complete
and javascript.source_map_sources could report not_observed for a
payload nobody read.

Mark member coverage unknown wherever a native member goes unread,
including an encrypted one, as an image the probe could not read
already does, and say so in the limitations.

* fix(audit): read rooted Go tool path arguments whole

`-L "/tmp/private,sdk"` and `-L=/tmp/a=b` name one directory, so a `,` or
`=` in a documented path flag's argument is literal. `-trimpath` keeps its
prefix=replacement structure.

* fix(audit): count an unread packaged member once

* fix(audit): keep trimpath rewrites and directory fields apart from selectors

* fix(audit): keep a .map unsettled once a declaration was discarded

* fix(audit): skip env option arguments when reading a Node shebang

* fix(audit): keep companion coverage unresolved for a generic .map link

* fix(audit): count a dropped linker-map guess as a skipped companion

* fix(audit): read env settings after -- in a Node shebang

* fix(audit): route a selected native image named .map by its format

A directly selected or listed native image has no package format, so
examineMember skipped its native-first branch and sent a file such as
release.map through map routing. Its bytes then became a linker-map
guess and marked native.debug_companions exposed. Native format now
outranks the name for every member, packaged or not.

* fix(audit): read forwarded -rpath and -rpath-link as linker paths

A cgo build with CGO_LDFLAGS=-Wl,-rpath,private-runtime kept the
relative directory, but the forwarded linker parser only knew -L, -T,
-I, --library-path, --dynamic-linker and --script, so go.build_paths
reported not_observed. Add -rpath and -rpath-link to the same parser,
in the attached, = and next-field forms. Loader-expanded values such as
$ORIGIN/../lib and @loader_path/Frameworks name no build-host directory
and stay unreported.

* fix(audit): read each entry of a forwarded linker search list

-rpath and -rpath-link take a colon-separated search list. The loader
token filter tested the whole list, so -Wl,-rpath,$ORIGIN:/opt/private-runtime
dropped /opt/private-runtime along with $ORIGIN, and the rooted-path pass
cannot see an entry that follows a colon. Split each search list into its
entries and drop only the loader-expanded ones.

* fix(audit): expand loader tokens only in a linker search list

The runtime loader expands $ORIGIN and @loader_path only in a -rpath or
-rpath-link search list. The token filter also ran on the argument of -T,
-L and -I, so -Wl,-T,$ORIGIN.ld dropped a literal linker script path and
a complete read could report go.build_paths as not observed. Search list
entries keep the filter; every other linker path argument is kept as is.

* fix(audit): count a .map link beside a selected file as a skipped companion

The sibling scan skipped any .map entry that was not a regular file, so a
symlink such as symbols.map -> payload beside a selected executable left
debug companion coverage at not observed. The reader never follows links,
so the linker map such a link may name is unread, not absent. Count a
generic .map sibling link as a skipped companion without following it,
as noteUnfollowedMapLink already does inside a selected directory.

* fix(audit): split a linker search list only for an ELF image

Only the ELF linker reads a -rpath or -rpath-link argument as a
colon-separated list. The Mach-O linker stores each -rpath argument as one
directory, so -Wl,-rpath,@loader_path/lib:extra is a single loader-relative
entry, yet it was split and extra was reported as a build path. Carry the
native image format into the Go flag reader and split search lists only for
ELF; other formats read the whole argument as one entry.

* fix(audit): expand only the image loader's runtime tokens

A runtime search path token is expanded only by the loader of the image's
format. The ELF loader expands $ORIGIN, $LIB and $PLATFORM; dyld expands
@executable_path, @loader_path and @rpath. Each is literal text to the
other loader, so -Wl,-rpath,$ORIGIN:/opt/private-runtime on a Mach-O image
names a literal directory, yet it was dropped and go.build_paths reported
not_observed. Pick the token set from the native image format; the PE
loader reads no search list, so it expands none.

* fix(audit): keep a declared .map link beside a selected script a source map

The sibling scan counted any .map symlink as a skipped debug companion
before checking whether the selected script declared it as its source
map. classifySiblingMap already excludes a declared target that is a
regular file, so a declared symbols.map link added a false unknown to
debug_companions. Apply the declared-target check before either file-type
branch; noteUnreachedTargets still counts the unread map as skipped.

* fix(audit): byte-check members whose kind is only an inventory path role

Inventory gives a packaged member a role from its name, such as resource
for payload.json or source-map for payload.map. The packaged-format guard
treated any kind other than "file" as owner-stated, so a nested ASAR an
ASAR lists under one of those names skipped signature recognition and
cleared coverage. Track whether the package owner stated the kind (Bun
sourcemap region, SEA main script) and only skip the byte check then.

* fix(audit): read Go's linker -r setting as a runtime search list

go tool link -r sets the ELF dynamic linker search path, dir1:dir2:...,
which the linker writes to RUNPATH. It was read as one whole path, so a
release built with -ldflags='-r=$ORIGIN/../lib' reported the
loader-relative entry as a build path and go.build_paths as exposed.
Read -r entry by entry with the same image-loader-aware split and token
filter a forwarded -rpath uses: ELF splits at ':' and drops $ORIGIN
entries; Mach-O keeps the argument as one directory.

* fix(audit): keep a selected package executable's native carrier format

A directly selected PyInstaller executable named release.map recorded the
package format as its member format, even though its ELF or PE carrier was
already recognized. examineMember then missed the native-first branch and
treated the executable as a linker map, reporting a debug companion.
Forward the native carrier format for the selected file, as listed members
already do.

* fix(audit): keep coverage unknown for an unread unclassified member

A packaged member with no format of its own, such as a PyInstaller
payload.bin, recorded only a skipped text member when its read failed
before the header. Member coverage then stayed complete, though the
member could be a native image or carry a nested package. Leave
coverage unknown and say which member could not be read, as an unread
native member already does.

* fix(audit): keep ASAR header admission distinct from max_file_bytes

A directory holding an ASAR whose header exceeds the header admission
was reported as a file-size refusal with max_file_bytes advice, which
cannot fix it. Report the header admission as its own bound instead.

* fix(audit): thread the shared ASAR header admission into release exposure

createReleaseExposureService built ReleaseExposureReader with no admission,
so its inventory and every reopened ASAR reader stayed on the 16 MiB
default and ignored REA_ASAR_MAX_HEADER_BYTES and asar.max_header_bytes.

Resolve the admission in the composition with runtimeAsarHeaderAdmission,
as the Electron and V8 observation providers do, and pass it to both
inventoryArtifactInScope calls, the reopened container readers, and the
nested ASAR signature probe. The refusal now names the setting that can
raise it instead of claiming there is no runtime override.

* fix(audit): keep a nested ASAR probe stopped at the admission undecided

The release exposure reader treated an ASAR signature probe that stopped
at the header admission as "not an ASAR". A packaged member such as
payload.json holding an ASAR whose JSON starts past asar.max_header_bytes
was then read as plain text, its inner maps went unread, and
javascript.source_map_sources could stay not_observed.

A probe that reaches the admission limit, or runs out of a prefix read
after its extents parse, now marks package coverage unknown and records
a limitation, while the member is still examined as text.

* fix(cli): parse audit-release-exposure --max-file-bytes as a decimal token

Main now requires every numeric CLI option to admit decimal tokens and
reject 0x10 and 1e3 (tests/boundary/cli/cliDecimalArguments.test.ts).
Wrap the release exposure maxFileBytes option in cliDecimalField like the
other maxFileBytes options, so the domain field keeps its bounds and default.

* docs(specs): add the release exposure audit specification

Add spec.md, plan.md and tasks.md under docs/specs/artifacts/release-exposure/
as docs/development/documentation.md requires for a new feature, and list
them in docs/specs/README.md. The existing guide at docs/release-exposure.md
keeps describing current behavior and its route is unchanged.

* fix(audit): bind unpacked ASAR member reads to their inventoried digests

A selected ASAR is captured and checked against its inventoried digest, which
binds packed members. An unpacked member is read from its .unpacked companion
on disk instead, and readContainerMember and readEntryBytes never compared
those bytes with the member digest inventory recorded, so a companion
replaced between inventory and the scan was accepted.

readContainerMember now passes the member's inventoried digest for unpacked
entries, and readStreamBounded hashes the full stream, draining past the read
allowance when needed, and fails with "ASAR member changed before
interpretation", which surfaces as an artifact_changed error like the
container check. A regression test replaces a companion after inventory. The
guide, spec, plan and tasks describe the binding.

* fix(audit): let stated JavaScript roles outrank a .map name

isDeclaredMap() routed any member whose name ended in .map to map
handling before the owner's stated role or a page's script declaration
was considered. A Node SEA main script at boot.map, which the SEA reader
marks as javascript, and a .map script an HTML file loads both became
linker-map guesses, so their inline maps were never read and
native.debug_companions was reported exposed.

An owner-stated source-map role or a declared map target still makes a
member a map. Otherwise a stated javascript kind or a script target now
wins, and only then does the .map suffix, or the inventory path role that
repeats it, decide. Regression tests cover both cases, and the guide
notes that a SEA main script is read as a script whatever it is called.

* fix(audit): keep coverage unknown when a packaged text member fails to read

A compressed member named as text, such as payload.json in an unexpanded
PyInstaller host, can fail inflation before any header is returned. The
.bin case already leaves member coverage unknown because an unread header
may hide a nested image or package, but examineTextMember() only counted
the member as skipped text, so otherwise complete coverage stayed
complete and package-dependent checks could settle.

An unread packaged member whose kind its package did not state now goes
through noteUnreadBinary(), which counts it as skipped text, marks
coverage unknown, and records the limitation. A regression test corrupts
the zlib stream of payload.json in a CArchive host and checks the intact
member keeps coverage complete. The guide describes the rule.

* fix(audit): keep the unpacked ASAR digest check inside the read allowance

ea87cf8 made readStreamBounded hash an unpacked ASAR companion to its end
so it could compare against the inventoried digest, which drained the
stream past the read allowance. A 1 GiB unpacked module was read in full
for a 4 KiB header probe and again for a package probe, and a companion
that grew after inventory had no byte limit on that path.

readStreamBounded now stops at the allowance as every other member read
does, and compares the digest only when the member ended within the
allowance. A companion past the allowance stays over_allowance without a
digest verification. A test counts the bytes each scan read pulls from an
8 MiB companion. The guide and spec state the bound.

* fix(audit): read a script target whose bytes are a source map as a map

1d3f89f let a stated javascript kind or an HTML script target outrank a
.map name, so an HTML `<script src="main.map">` that points at a valid
source map with sourcesContent was read only as a script. Its sources
were never counted and javascript.source_map_sources could miss an
exposed finding.

A script role says how a member is loaded, not what its bytes hold. A
.map member or loaded script whose text parses as a source map, a JSON
object with version and mappings, sources, or sections, is now read as
a source map. Anything else is still read as a script, so a SEA main
script named boot.map and a .map script carrying an inline map keep
reaching examineInlineMaps. A regression test covers the map case, and
the guide states the rule.

* fix(audit): retract a linker-map guess when a page loads the map as a script

noteScriptTarget() returned early for a target already read, counting its
source-map coverage as skipped but leaving any linker-map guess the first
read recorded. When a directory or ASAR listed a non-JSON app.map before
the index.html that loads it with <script src="app.map">, app.map stayed in
native.debug_companions and the result depended on enumeration order.
noteMapTarget() already retracted such a guess for a late map declaration.

A late script declaration now retracts the guess too, and still counts the
script as skipped because it was never examined as JavaScript. A test
covers the directory and ASAR order, and the guide states the outcome.

* fix(audit): respect script and native identity for sibling linker maps

classifySiblingMap() guessed a linker map for any sibling .map whose bytes
could not begin a JSON object. A sibling boot.map that a selected index.html
loads with <script src="boot.map">, or an ELF image named release.map beside
a selected executable, was therefore reported in native.debug_companions.

scanSiblings() now skips a sibling that is a script target as well as a map
target, leaving noteUnreachedTargets() to count it, and classifySiblingMap()
records no guess when sniffNativeFormat() recognizes the header. Tests cover
both cases and the guide states the outcome.

* fix(audit): read a script-loaded map from the text that recognized it

scriptHoldsMap() recognizes a .map or script target as a source map from
decodeMemberText(), which honors a UTF-16 byte order mark, but
readScriptAsMap() then passed the raw bytes to readSourceMap(), which reads
UTF-8. A BOM-marked UTF-16 main.map loaded by <script src="main.map"> failed
the second parse and its prefix became a linker-map guess.

readScriptAsMap() now hands the decoded text to readSourceMapText(), which
readSourceMap() also uses for byte input, so both stages read the same text.
A test covers a UTF-16 map with embedded sources.

* fix(release-exposure): honor byte order marks in binary plist data

A binary plist data object holding BOM-marked UTF-16 text was decoded as
UTF-8, so credential markers in it went unmatched while coverage still
read complete. Decode such payloads with the encoding their mark declares,
and leave coverage incomplete for UTF-32, which no reader scans.

* fix(audit): keep an unprobed package member past the text allowance unknown

Once the cumulative text allowance was spent, examineTextMember() counted a
packaged member named like text, such as payload.json in a .NET or
PyInstaller bundle, as skipped text without reading its header. Coverage
stayed complete even though the member could be a native image or a nested
ASAR, while the same bytes named payload.bin kept coverage unknown.

An unexpanded package member whose kind the owner did not state now leaves
coverage unknown with a limitation when the allowance skips it, the same
uncertainty an unread .bin member carries. No extra read is made, so the
allowance still bounds what is opened. A test covers an ASAR with an
embedded source map named payload.json after sixteen full text members.

* fix(release-exposure): require a read host for every Electron layout

A directory with several resources/app.asar layouts counted one named
host as fuse coverage for all of them. Track host coverage per layout so
safe fuses stay unknown when a whole layout's possible hosts were
dropped from the native image sample.

* fix(release-exposure): keep a .map script past the target allowance unassessed

When HTML script references spent the resolved-path allowance, a later
.map script target was dropped without its script role, so its JavaScript
bytes settled as a linker-map guess and debug_companions reported an
exposure. A refused script target now sets mapTargetsDiscarded, the same
flag a refused map target sets, so a later .map stays unassessed instead
of becoming companion evidence.

* fix(release-exposure): read a Node shebang as script in any text member

A selected or listed text file such as runner.txt that starts with a Node
shebang went straight to the text reader, which never gave it a JavaScript
role, so its inline map went unread and source_map_sources read
not_observed. The text reader now takes the role from the bytes it read,
so every route into it sees the shebang, and the probed-text path no longer
sets the role itself.

* fix(release-exposure): exclude Go search lists by position, not by value

compilerPaths dropped every literal path whose text equalled a forwarded
-rpath or -rpath-link list, so CGO_LDFLAGS=-Wl,-L,$ORIGIN -Wl,-rpath,$ORIGIN
lost the literal -L directory and go.build_paths read not_observed. The
literal flags are now read with each search list option and its argument
removed by position, and the search lists are still read entry by entry.

* fix(release-exposure): keep a probed Node launcher's role past the allowance

The probe recognized a Node shebang but handed the text reader the member
without its JavaScript role. Once earlier text spent the shared allowance,
the text reader returned before reading the header again, so an
extensionless launcher added no skipped map and both source-map checks read
not_observed instead of unknown. The probe now passes the role it found.

* fix(release-exposure): decode a map in the encoding its byte order mark names

The map reader, its prefix check and the sibling classifier decoded map
bytes as UTF-8, so a generic symbols.map holding BOM-marked UTF-16 source
map JSON failed to parse and its prefix read as a linker map: a spurious
debug companion and source_map_sources not_observed. Map bytes are now
decoded by their byte order mark at that boundary, and a UTF-32 map, which
this reader does not decode, stays unresolved.

* fix(release-exposure): keep a lone dash inside a quoted Go path argument

splitGoField split a quoted field before every whitespace-led dash, so the
retained -ldflags '-s "-L=/tmp/private - sdk" -w' read the dash inside the
directory as a new flag and goPaths reported /tmp/private. A quoted field
now splits only before a dash that begins a flag, so a dash followed by a
space stays part of the path.

* fix(release-exposure): choose possible Electron hosts within each layout

The named-or-possible host choice ran across every kept image, so a named
a/a.exe removed the unnamed b/launcher.exe of a second ASAR layout from
electron_host_paths, and its unresolved fuses no longer held
electron.run_as_node at unknown. Each layout now chooses its own named or
possible hosts, and the sets are combined.

* fix(release-exposure): read a relative compiler --sysroot as a build path

The compiler path flag list had no --sysroot, and the rooted-path fallback
cannot see a relative operand, so CGO_LDFLAGS=--sysroot=private-sdk left
go.build_paths at not_observed. --sysroot is now a compiler path flag,
attached with = or given as the next field.

* fix(release-exposure): recognize Windows Electron layouts by the owner's path

The desktop owner gives each file a native local_path, such as
C:\ship\App\resources\app.asar on Windows, and desktopPathConventions only
splits on /, so every ASAR basis was skipped: host ranking and
electron_host_paths stayed empty and a named host with no sentinel let a
safe helper read electron.run_as_node as not_observed. Each basis now
carries whether the owner's slash-separated path is an ASAR layout, and the
layout folders read a Windows absolute path with Windows separators on any
host.

* fix(release-exposure): read a Bun module by its JavaScript loader

An extensionless Bun contents member such as $bunfs/root/release carries
loader_name js, but ownerStatedKind kept only the sourcemap region, so the
member was never read as a script and its inline map went unseen. Give a
Bun contents region the javascript role for the js, jsx, ts and tsx
loaders, as SEA main scripts get it.

* fix(release-exposure): read a Node shebang .map as a script

An undeclared `.map` was routed as a source or linker map before its
first bytes were checked, so a Node script named `runner.map` recorded a
linker-map companion and never had its inline map read. When the map
read of an undeclared `.map` starts with a Node shebang, its map slot is
returned and the text reader examines it as JavaScript, so its inline
map is parsed and no companion is reported.

* Detect full-length GitHub refresh tokens

Narrow github.token to gh[opus]_ with 36 characters and give ghr_ its
own 76-character github.refresh_token rule, with a test.

* fix(release-exposure): bind a negative package probe to the inventoried image

An on-disk native image whose embedded-package probe finds nothing clears member coverage, so it now hashes the probed descriptor and compares it with the inventoried digest before accepting absent. A replacement after inventory fails as a changed member instead of reporting complete coverage.

* fix(release-exposure): let an app bundle read settle only its own layout

An app target, an app-bundle fuse read or a sampled selected executable used to mark the Electron executable as included for every ASAR layout, so safe outer fuses reported not_observed even when a nested Electron app's host was never read. Those reads now settle only their own layout; every other discovered layout still needs its own host read, so an omitted nested host keeps fuse checks unknown.

* fix(release-exposure): honor a Node shebang before guessing a sibling linker map

A sibling .map beside the selected file that starts with a Node shebang is a script, as it already is for a member .map, so classifySiblingMap no longer records it as a linker-map debug companion.

* fix(release-exposure): name a bundle's own layout by the owner's path

The settled layout set joined the caller's bundle spelling with Contents, so a selected /tmp/App.app missed the owner's resolved /private/tmp/App.app/Contents layout and safe fuse checks fell to unknown. Each archive basis now carries the owner's relative layout folder, and the bundle's own layout is the one whose relative folder is Contents, looked up by the owner's resolved folder.

* fix(release-exposure): read file-valued linker options as build paths

LINKER_PATH_FLAG listed --script but not the other linker options that read a file, so -extldflags=-Wl,--version-script=private-versions.map left go.build_paths not_observed. --version-script, --dynamic-list and --retain-symbols-file now read their operand as a path, attached or in the next field.

* fix(release-exposure): count a macOS bundle's framework and MacOS hosts in its layout

A .app layout resolves to its Contents folder, but its hosts are Contents/MacOS/* and the Electron framework binary under Contents/Frameworks, so per-layout host ranking and fuse coverage dropped them and one bundle's safe fuses could settle another bundle. Those images now belong to the bundle's layout, with the framework binary ranked as its host.

* fix(release-exposure): keep a bundle's launcher out of its fuse hosts

A macOS bundle's Electron Framework binary carries its fuses. When it
is among a layout's named hosts, it is now the layout's only fuse host;
the MacOS launcher beside it is still sampled but no longer leaves safe
fuse checks undecided when it has no sentinel.

* fix(release-exposure): keep an undecided PE package member out of linker maps

An unexpanded package member named .map whose PE signature lies past the
retained prefix fell through to noteUnreadMap, which read its MZ prefix as
a linker map and reported native.debug_companions exposed with complete
coverage. The map route now records the same undecided-PE uncertainty the
binary route does, so the member stays unexamined and coverage unknown.

* fix(release-exposure): scan the text of an undecided PE map member

A packaged .map member whose MZ header is undecided returned before its
fully read bytes reached the credential scanner, so a PEM key in it read
as unknown instead of exposed. Scan bytes read in full before returning,
while still keeping PE coverage undecided.

* fix(release-exposure): keep an oversized text member's undecided PE header

A packaged text member past the per-member allowance keeps only its prefix,
so an MZ header whose PE signature lies further in returned null and the
text route dropped the native and package uncertainty. Note the undecided
header as the map and binary routes do.

* fix(release-exposure): join Electron layouts by caller path and keep partial discovery unknown

The desktop owner resolves its root, so a target selected through a
symlinked parent got canonical local_paths that never matched the
audit's caller-spelled images, and the named host dropped out of
electron_host_paths. Rebase owner paths under the canonical root onto
the selected path.

When discovery stopped after it found one Electron layout, the basis
list was treated as exhaustive. Report the layouts as incomplete so safe
fuses on the listed host stay unknown.

* fix(release-exposure): keep Electron hosts under a trailing-slash selection

Join the rebased archive path with appendCallerPath so a selected
`/work/app/` yields `/work/app/resources/app.asar`, whose layout folder
matches the inventoried executables' parent.

* fix(release-exposure): keep maps unassessed for unread text past the allowance

A text-named member such as `runner.txt` can start with a Node shebang.
Once the text allowance is spent its header is not read either, so count
every unread member that could hold a script as a skipped map instead of
trusting the filename-derived role.

* fix(release-exposure): keep an unread packaged map member undecided

When a packaged map member yields no header (a failed read or no map
slot), its name is no evidence of its format. Route it through
noteUnreadBinary, as the text route does, so a member that may be a
native image or package keeps coverage unknown.

* fix(release-exposure): keep an undecided sibling PE header out of linker-map guesses

A sibling .map past the map allowance keeps only its probe, so an MZ
header whose PE signature lies further in is undecided. Share the
undecided-PE test with packaged members and count such a sibling as a
skipped companion instead of guessing a linker map.

* fix(release-exposure): keep possible fuse hosts when no ASAR layout names one

Without an ASAR basis no image is ranked, so no image counted as a fuse
host and one image's safe fuses could settle a sentinel-less sibling.
While the desktop family is undecided and no layout names a host, treat
every sampled image as a possible host.

* fix(release-exposure): keep images outside a found ASAR layout as possible fuse hosts

An asar: false build beside a discovered ASAR layout gets no basis, so
its executables were never fuse hosts and the layout's safe fuses could
settle a sentinel-less image in the other build. When no name picks out
a host outside the found layouts, treat every sampled image there as a
possible host, as the no-layout case already does while the family is
undecided.

* fix(release-exposure): keep a dropped host outside a found ASAR layout unread

An asar: false build beside a found ASAR layout names no host, so an
executable outside every layout that the native-image sample dropped may
be that build's unread fuse host. Coverage no longer counts as proven
when such an image was inventoried but not sampled.

* fix(release-exposure): read Go build-path response files named in compiler and linker flags

A CGO setting such as `-Wl,@/tmp/private-link.rsp` or
`-Xlinker @/tmp/private-link.rsp` names a response file the linker reads
options from, and a bare `@FILE` is read by the compiler driver. Report
the file's path, relative or rooted like other path arguments, without
opening it. An option's own value, such as `-install_name
@rpath/libx.dylib`, and dyld runtime tokens are not response files.

* fix(release-exposure): keep a dropped host outside an ASAR layout unread whatever its name

The guard for a sampled-out host beside a found ASAR layout ruled images
out by filename, so an asar: false host named like `b/My.App` was missed
and safe fuses from the sampled layout settled the installation. Every
inventoried native image outside the found layouts that the sample
dropped now keeps the fuse checks unknown.

* fix(release-exposure): keep maps unassessed for an unreadable extensionless launcher

An unclassified file whose initial header probe fails, such as an
extensionless `runner` that became unreadable after inventory, may carry
a Node shebang and a map directive. The probe failure now leaves its
maps unassessed, as an unread `runner.js` or packaged member does,
instead of counting the file as holding no script.

* fix(release-exposure): read a response file named like a dyld token

`-Wl,@rpath/private-link.rsp` names a linker response file, not a dyld
runtime path, so dropping every `@rpath` or `@loader_path` argument hid
it. A dyld token is now skipped only as the value of an option that takes
one, such as `-install_name` or `-dylib_file`.

* fix(release-exposure): keep the partial member scan on ordinary cancellation

A scan cancelled after some members were examined reported its partial
scan only when cleanup also failed, so a clean cancellation dropped the
recovered source-map and credential observations. A cancelled scan now
hands its assembled facts to the interrupted-scan visitor with unknown
coverage and a cancellation limitation, and the caller still receives
the cancellation error carrying that partial audit.

* docs(release-exposure): describe the partial report kept when the member scan is cancelled

Since the member scan keeps what it examined on ordinary cancellation,
the status guide no longer says that cancelling the scan returns no
partial report. It now describes the partial observation and limits the
no-report case to cancellation before the scan can be assembled.

* fix(release-exposure): keep maps unassessed when a text header is cut short

A text-named member read with one or two bytes of the text allowance
left returns only `#` or `#!`, which cannot establish a Node shebang, so
`runner.txt` kept its non-script role and its unexamined inline map was
treated as absent. A partial or missing header that could still start a
shebang line now leaves the member's maps unassessed, as an unread
member's do once the allowance is spent.

* fix(release-exposure): keep dotted executables as possible hosts in ASAR layouts

Inside an ASAR layout, a sibling whose name had a dot and no `.exe`
suffix, such as `my.app`, was neither ranked for the native sample nor
counted as a possible Electron host. With shared libraries filling the
sample, that image could be dropped while the layout still counted its
host as read, so safe fuses on a helper reported `run_as_node` as not
observed. A dotted sibling that is not named like a shared library is
now sampled after plain siblings and counted as a possible host.

* fix(release-exposure): split env -S shebangs on unquoted blanks only

The env shebang reader split the whole line on spaces before handling -S,
so a launcher such as `#!/usr/bin/env -S NODE_OPTIONS='--conditions
development' node` named `development'` as its program and its maps were
never assessed. An -S operand now takes the rest of the line and is split
the way GNU env -S splits it: single and double quotes, backslash escapes,
\_ and \c, and a leading # comment. A string env itself rejects, such as an
unterminated quote, runs no program.

* fix(release-exposure): keep owner facts completed before cancellation

When a Go, Rust, fuse or desktop owner finished its Evidence and then saw
cancellation, completeProviderEvidence returned that Evidence as the
error's partial observation, but the audit only kept the error and
substituted a not-run fact, so a recovered Go build path or Rust package
list reported unknown. Each owner's Evidence-to-fact reading now lives in
one function used for both a successful read and a completed partial, so
the partial passes the same schema and inventory digest checks before its
fact is kept. Later owners still do not run.

* fix(release-exposure): keep env -S programs named by a variable unassessed

`env -S` expands `${NAME}` from the environment, so a launcher such as
`#!/usr/bin/env -S ${NODE_BIN}` may run Node, but the shebang reader kept
the placeholder as the program name and treated the file as plain text,
reporting its inline map as absent. The env splitter now marks fields that
expand a variable, and a program whose name holds one leaves the shebang
undecided: the member's maps count as unassessed, and a `.map` companion
with such a header is not taken as a linker map. Quoted or escaped `${`
stays literal, and a resolved basename such as `${DIR}/bin/deno` still
decides.

* fix(release-exposure): keep the ASAR header admission for selected files

A directly selected app.asar whose header exceeds asar.max_header_bytes
now returns the typed header admission refusal and its recovery, as the
directory scan already does, instead of a generic partial report.

* fix(release-exposure): keep a map member with a variable env -S program unassessed

An undeclared `runner.map` whose `env -S` program is `${NODE_BIN}` may
run Node, so `examineMapMember` now treats an undecided `nodeShebang`
result as an unassessed map and companion, as `classifySiblingMap`
already does, rather than falling through to a linker-map guess.

* fix(release-exposure): read a forwarded -Map linker map path

splitForwardedLinkerFlags hands -Wl,-Map=private-link.map to the linker
side, but LINKER_PATH_FLAG had no Map entry, so the relative map path was
dropped and go.build_paths read not_observed. Add Map to the file-valued
linker options so -Map=FILE and -Map FILE are both reported.

* fix(release-exposure): count unread text in undecided map branches

An oversized .map whose shebang names its program with an unresolved
variable, or a package member with an undecided PE header, returned
before counting its unscanned text, so credential markers could read
not_observed. Count any non-bytes read as skipped text in both branches.

* fix(audit): bound map reads and preserve linker paths

* fix(audit): retain unread package uncertainty

* fix(audit): retain ambiguous linker operands

* fix(audit): preserve compiler path separators

* fix(audit): retain distinct linker map occurrences

* fix(audit): apply map declarations to their exact source path

A declaration recorded only its NFC lookup key, so every member or
sibling sharing that key took the declared JavaScript-map route. On a
normalization-sensitive filesystem an unrelated linker map spelled in
another form lost its companion evidence when the declaring script was
scanned first.

Record the resolved spellings each declaration writes and treat only an
exact match as declared. Another spelling in the bucket is read as an
undeclared map; when no declared spelling is reached, its linker-map
guess stays unresolved coverage rather than companion evidence.

* fix(audit): keep partial inventory from settling fuse-host coverage

When a directory read found ASAR layouts but the inventory stopped
early, a separate asar: false build outside those layouts may never
have been listed. Only sampled-then-dropped images counted as a
possible missed host, so reading every found layout's host reported
safe fuses as not_observed for the whole selection.

In limitNativeSample, treat an incomplete inventory as a possible
missed host outside the found layouts unless the read root is itself
a found layout, where host identity already settles coverage.

* fix(audit): apply script targets to their exact source path

A page's script element was recorded only by its NFC lookup key, so on
a normalization-sensitive filesystem a distinct file spelled in another
normalization form inherited the JavaScript role. An unrelated linker
map such as café.map beside a loaded café.map was never classified
and debug companion coverage could settle as not observed.

Keep the resolved spellings each page wrote under the lookup key, as map
declarations already do, and give the script role only to a member or
sibling whose exact path a page loaded.

* fix(audit): keep partial inventory uncertain beside a root ASAR layout

When the read root was itself a found ASAR layout, an incomplete
inventory was trusted to have listed every possible fuse host. A second
asar: false build under a subdirectory names no layout and sits outside
the root layout, so an inventory that stopped after the root host could
miss its launcher and still report the root's safe fuses as
not_observed. The same launcher, once listed, already kept the result
unknown.

Drop the root-layout exemption in limitNativeSample so any incomplete
inventory beside a found layout keeps fuse-host coverage unknown. A
complete inventory that lists only the named host still settles.

* fix(audit): read the linker's --just-symbols file operand

A Go build that forwarded -Wl,--just-symbols=private.syms through
-extldflags or CGO_LDFLAGS kept the relative symbol file in its build
settings, but the forwarded linker matcher knew only the short -R
spelling. Complete metadata then reported go.build_paths as
not_observed while the equivalent -R build was exposed.

Add --just-symbols to the linker options that read a file. Only -R
turns into -rpath when given a directory, so the $ORIGIN ambiguity
check stays on the short spelling.

* fix(audit): anchor expanded package members to the selected path

An inventory-expanded package member reports its location relative to
the selected path, such as app.asar/boot.map, but its lookup identity
resolved that location against the process working directory. An
on-disk page loading app.asar/boot.map, or an absolute file: map
declaration into the archive, resolved under the selected root, so the
declaration never matched the member it named. A script target with an
inline map then settled as a linker map, and a declared map stayed
skipped.

Resolve every member lookup and declaration base against the selected
path, and keep the reported location as written. Linker-map retraction
compares the same anchored spelling.

* fix(audit): read GCC's -I- include barrier as an option

CGO_CFLAGS=-I- is GCC's include barrier, the same as --include-barrier,
not -I with the directory "-". The compiler path matcher read it as a
build path, so a Go binary retaining it reported go.build_paths exposed.
Skip that exact field before path matching.

* fix(audit): keep packaged-image uncertainty after reading the host

A native image stored inside a package is never opened by a fuse reader,
so reading the Electron host on disk does not settle its fuses. Count the
packaged omission toward a partial fuse sample on its own, so safe host
implications stay unknown instead of not_observed while a packaged image
is unread.

* fix(audit): require every named host in a layout to be sampled

An ASAR layout can name more than one host, such as `a/a.exe` beside
`a/electron.exe`. The sample counted the layout as read when any one
named host was kept, so dropping the other still reported the Electron
executable as included and let safe fuses from the sampled images settle
run_as_node as not_observed. Count a layout as read only when every host
it could have was sampled, reusing the named-host selection the fuse
reducer already applies.

* fix(audit): keep a layout-less bundle read from settling partial inventory

A bundle with no ASAR layout, such as an asar: false build, counted its
framework read as covering the Electron host even when inventory stopped
early or the sample dropped an image. A nested build's host could sit in
the part never listed, so the root framework settled RunAsNode as
not_observed. Apply the same incomplete-inventory guard the layout branch
uses to the bundle read.

* fix(audit): read the linker's --sysroot directory operand

A Go ELF build that forwarded -Wl,--sysroot=private-sdk through
-extldflags or CGO_LDFLAGS kept the relative sysroot in its build
settings, but the forwarded linker matcher did not know the option.
Complete metadata then reported go.build_paths as not_observed, while
the compiler-owned --sysroot was already recognized.

Add --sysroot to the linker options that take a path, so the -Wl comma
form, the -Wl = form and both -Xlinker forms are read.

* test(audit): group Deno boundary regressions

* fix(audit): preserve Go linker file operands

* fix(audit): track script completion per source occurrence

* refactor(audit): give Go path parsing one semantic owner

* refactor(audit): preserve map roles at the parsing boundary

* refactor(audit): consume toolchain operands once

---------

Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2026-11-11 09:57:55 -05:00
1 parent 5fde39454e
commit 7aca4cef64
72 files changed
+17402 -68

No files matched your search

@@ -168,6 +168,7 @@ explicit path or endpoint and do not need it.
Facts retain all-recorded-events-before-selection scope. Other qlog layouts
and PCAP correlation are unsupported.
- User-owned Electron runtime already open: `list_electron_targets`. Before an electron-main Inspector attempt, check packaged fuses with `inspect_electron_fuses`; disabled `EnableNodeCliInspectArguments` means the app ignores `--inspect`.
- Shipped application exposure for a local `.app`, install directory, ASAR, or executable: `audit_release_exposure` / `rea audit-release-exposure`. Each check has a stable id, a status, and fixed remediation. Unknown and unassessed checks stay in the report. This does not establish that an application is secure. Credential-marker hits report the rule id and location only. See [release exposure](https://github.com/morluto/rea/blob/main/docs/release-exposure.md).
- Packet-field discovery: `inspect_packet_fields` searches installed protocols
and field names/types before choosing fields for `inspect_packet_capture`.
Query/page the relevant records; registrations do not establish observed traffic.
@@ -62,6 +62,16 @@ runtime presence. For compact CLI output, use
`inspect-desktop-application PATH --detail summary --evidence_output BUNDLE`.
See [desktop installations](https://github.com/morluto/rea/blob/main/docs/desktop-applications.md).
## Release exposure
Use `audit_release_exposure` (`rea audit-release-exposure PATH`) when the question is what static analysis of a shipped `.app`, install directory, ASAR, or executable recovers. Each check has a stable id, a status, the observation behind it, and fixed remediation. Unknown and unassessed checks stay in the report. The report does not establish that the application is secure.
`text.credential_markers` reports a rule id and location only. Matched bytes, previews, lengths, and hashes of matched bytes are omitted.
`native.hardening`, `macho.hardened_runtime`, and `android.manifest` are not assessed here. Their next probes are `inspect_binary_hardening`, `inspect_signature`, and `inspect_android_package`.
See [release exposure](https://github.com/morluto/rea/blob/main/docs/release-exposure.md).
## Go build metadata
Use `inspect_go_binary` for an explicit local ELF, PE or Mach-O (universal
@@ -168,6 +168,7 @@ explicit path or endpoint and do not need it.
Facts retain all-recorded-events-before-selection scope. Other qlog layouts
and PCAP correlation are unsupported.
- User-owned Electron runtime already open: `list_electron_targets`. Before an electron-main Inspector attempt, check packaged fuses with `inspect_electron_fuses`; disabled `EnableNodeCliInspectArguments` means the app ignores `--inspect`.
- Shipped application exposure for a local `.app`, install directory, ASAR, or executable: `audit_release_exposure` / `rea audit-release-exposure`. Each check has a stable id, a status, and fixed remediation. Unknown and unassessed checks stay in the report. This does not establish that an application is secure. Credential-marker hits report the rule id and location only. See [release exposure](https://github.com/morluto/rea/blob/main/docs/release-exposure.md).
- Packet-field discovery: `inspect_packet_fields` searches installed protocols
and field names/types before choosing fields for `inspect_packet_capture`.
Query/page the relevant records; registrations do not establish observed traffic.
@@ -62,6 +62,16 @@ runtime presence. For compact CLI output, use
`inspect-desktop-application PATH --detail summary --evidence_output BUNDLE`.
See [desktop installations](https://github.com/morluto/rea/blob/main/docs/desktop-applications.md).
## Release exposure
Use `audit_release_exposure` (`rea audit-release-exposure PATH`) when the question is what static analysis of a shipped `.app`, install directory, ASAR, or executable recovers. Each check has a stable id, a status, the observation behind it, and fixed remediation. Unknown and unassessed checks stay in the report. The report does not establish that the application is secure.
`text.credential_markers` reports a rule id and location only. Matched bytes, previews, lengths, and hashes of matched bytes are omitted.
`native.hardening`, `macho.hardened_runtime`, and `android.manifest` are not assessed here. Their next probes are `inspect_binary_hardening`, `inspect_signature`, and `inspect_android_package`.
See [release exposure](https://github.com/morluto/rea/blob/main/docs/release-exposure.md).
## Go build metadata
Use `inspect_go_binary` for an explicit local ELF, PE or Mach-O (universal
+1 -1
View File
@@ -215,7 +215,7 @@ Additional tools and host support depend on the target:
| 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 |
| Recorded Linux crashes | Raw notes, every recorded thread's registers/signals and optional mapping candidates | Caller-supplied pwntools on Linux x64; optional GDB/pwndbg; [recorded crashes](docs/guides/native/recorded-crashes.md) |
| JavaScript / Electron | Modules, imports, source maps, routes, IPC and native add-on relationships | Node.js and npm; Linux: procps-compatible `ps`; [application analysis](docs/guides/javascript/javascript-application-workflows.md) |
| JavaScript / Electron | Modules, imports, source maps, routes, IPC, native add-ons, `rea audit-release-exposure` | Node.js and npm; Linux: procps-compatible `ps`; [application analysis](docs/guides/javascript/javascript-application-workflows.md) |
| Websites | Page structure, scripts, network observations and requested screenshots | A Chrome-family browser; [browser analysis](docs/guides/web/browser-observation.md) |
| Saved network captures | Requests, responses, exposed payloads and source locations | HAR or Fiddler Everywhere SAZ; mitmdump on Linux for native mitmproxy; [capture guide](docs/guides/web/web-network-captures.md) |
| .NET assemblies | Metadata, CIL instructions, declared native dependencies and build comparisons | None (static only); [managed-code guide](docs/guides/managed/managed-code-analysis.md) |
+5
View File
@@ -660,6 +660,11 @@ export const documentationSections = [
source: "reconstruction-coverage.md",
route: "/reconstruction-coverage",
},
{
text: "Release exposure",
source: "release-exposure.md",
route: "/release-exposure",
},
{
text: "Reverse-engineering tool integrations",
source: "reverse-engineering-tools.md",
+1
View File
@@ -197,6 +197,7 @@ the exact commit messages and references from the release they describe.
- [Python packaged applications](python-packaged-applications.md)
- [CPython pyc inspection](python-pyc.md)
- [Reconstruction coverage](reconstruction-coverage.md)
- [Release exposure](release-exposure.md)
- [Reverse-engineering tool integrations](reverse-engineering-tools.md)
- [Rust binary dependency metadata](rust-binaries.md)
- [U-Boot legacy uImage containers](uimage.md)
+13
View File
@@ -1428,6 +1428,7 @@ the CLI result should use JSON; either argument order is accepted.
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `0` | The operation completed. Its result may include partial evidence, warnings or unresolved questions. |
| `1` | The operation could not complete. Structured output identifies invalid input, permissions, cancellation, timeouts or another failure when available. |
| `3` | `audit-release-exposure` completed with `--fail_on` and an exposed check meets that severity. Unknown and unassessed checks do not change this status. |
| `128 + N` | Signal-derived status. An unhandled signal may have ended the process, with the shell or runtime preserving the conventional status; a command may instead have handled the signal, waited for its operation and cleanup to settle, and assigned the same status (`130` for SIGINT, `143` for SIGTERM). In the handled case, it may also have printed a structured `cancelled` result. |
`rea mcp --http` is long-running and prints no structured result. It exits
@@ -1561,6 +1562,18 @@ Bun standalone executables use the existing `inspect-artifact` and
sourcemaps and bytecode without running the executable. See
[Bun standalone executables](../bun-standalone.md) for layout coverage and limits.
### Release exposure
```sh
rea audit-release-exposure /absolute/path/to/MyApp.app --json
rea audit-release-exposure ./dist/MyApp.app --fail_on high --json
```
Reports what static analysis of a shipped `.app`, install directory, ASAR, or
executable recovers. `--fail_on high|medium|low` exits `3` when a completed
audit has an exposed check at that severity. Unknown and unassessed checks stay
in the report and do not change the exit status. See
[Release exposure](../release-exposure.md).
Deno compile executables use the same commands to inventory and materialize the
embedded virtual filesystem, remote modules, and recorded options. Inventory retains
embedded environment-file values and certificate bytes in local Evidence with their
+1 -1
View File
@@ -55,7 +55,7 @@ The [documentation directory](README.md) lists every guide by domain.
| 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), [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) |
| 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), [.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) |
+67
View File
@@ -0,0 +1,67 @@
# Release exposure
`audit_release_exposure` / `audit-release-exposure` reads one shipped artifact and reports what static analysis of that artifact recovers. The input is a macOS `.app` bundle, an install directory, an ASAR, or a single executable. Each check has a stable id, a status, the observation behind that status, and fixed remediation text.
The report does not establish that an application is secure. A check that could not be completed is `unknown` or `not_assessed`, and those counts stay beside the findings. There is no pass verdict and no letter grade.
```bash
rea audit-release-exposure /Applications/Example.app --json
rea audit-release-exposure ./dist/MyApp.app --fail_on high --json
```
Without `--fail_on`, the exit status reflects only whether the audit finished. With `--fail_on high`, `--fail_on medium`, or `--fail_on low`, a completed audit exits `3` when an `exposed` check meets that severity. `high` matches high. `medium` matches high and medium. `low` matches high, medium, and low. `unknown` and `not_assessed` do not change the exit status. A tool failure is still exit `1`.
The CLI resolves a relative path against the caller's working directory. MCP requires an absolute filesystem path and returns the same report. MCP has no exit status.
```json
{
"name": "audit_release_exposure",
"arguments": { "path": "/Applications/Example.app" }
}
```
## What is read
The audit composes existing readers. It does not reread Electron fuse bytes itself, and it does not rewrite the artifact.
| Check | Exposed when | Severity |
| ------------------------------- | ------------------------------------------------------------------------------ | -------- |
| `javascript.source_map_sources` | A shipped source map has `sourcesContent` | high |
| `javascript.source_maps` | A shipped source map has no embedded sources | medium |
| `electron.run_as_node` | The fuse implication is honored | high |
| `electron.asar_integrity` | Embedded ASAR integrity is not enforced | medium |
| `electron.only_load_from_asar` | Loading is not restricted to `app.asar` | medium |
| `electron.node_cli_inspect` | Node CLI inspect arguments are honored | medium |
| `packaging.extractable_payload` | A Bun, Deno, Node SEA, PyInstaller, .NET bundle, or ASAR has a readable member | low |
| `native.debug_companions` | A `.pdb`, `.dSYM`, `.debug`, or linker `.map` ships beside the release | medium |
| `native.pdb_path` | A PE CodeView record names a PDB path | low |
| `go.build_paths` | Go build info or its build flags contain file paths | low |
| `rust.dependency_metadata` | cargo-auditable metadata is present | low |
| `text.credential_markers` | A text member contains a provider-prefixed marker | high |
| `native.hardening` | Not assessed in this audit | |
| `macho.hardened_runtime` | Not assessed in this audit | |
| `android.manifest` | Not assessed in this audit | |
`go.build_paths` reads a flag's arguments by the rules of the tool that takes them. A linker `-X` value is an application string, so a relative one is not a path. A rooted one cannot be told from a file path, so it is reported: `-X main.route=/api/v1` is sampled like `-X main.root=/srv/build`, because dropping both would miss the second.
`text.credential_markers` matches provider-prefixed forms such as a PEM private-key header and documented vendor token prefixes. The report contains the rule id and location only. Matched bytes, previews, lengths, and hashes of matched bytes are omitted.
`native.hardening`, `macho.hardened_runtime`, and `android.manifest` stay `not_assessed`. Their next probes are `inspect_binary_hardening`, `inspect_signature`, and `inspect_android_package`.
Source map text is counted and then dropped. A selected file is read through the stable artifact reader. Text and source-map members stay inside the allowances listed under `coverage.allowances`, and each kind has its own allowance, so binary members cannot use up the read that a later source map needs. Native images on disk are registered from inventory classification and are not limited to those allowances. Other files and package members are identified from a bounded header. The bytes a package member's text or map read returns decide before its name does, so a PE called `payload.js.map` is read as a PE. A header with no NUL byte, or one that starts with a UTF-16 byte order mark, is scanned as text, so names such as `.env.production`, `server.key`, and `credentials` do not depend on an extension list. UTF-16 without a byte order mark has NUL bytes and is not recognized this way. A member already known to be text, such as a script, is also scanned when it is UTF-8 holding a stray NUL. One whose header is at least an eighth NUL bytes is taken to be wide text. It is not decoded and is counted as skipped, as is UTF-32. A binary plist is decoded, so its strings, dictionary keys and data are scanned in whichever encoding each object uses. One that cannot be decoded still has its bytes scanned and is counted as skipped. A file whose header could not be read leaves `text.credential_markers` undecided. A packaged ELF, Mach-O, or PE image is read in full and written to a temporary copy, removed afterward, so it can be probed for an embedded package. All packaged images share one `max_file_bytes` allowance. An image that does not fit, or whose bytes cannot be read, is not probed and leaves member coverage `unknown`. A packaged PE is also read for its debug records. An SVG file is read for its scripts as an HTML file is. A script that an HTML file loads, or a Node SEA main script, is examined as a script whatever it is called, so a name such as `boot.map` does not make it a map, and an HTML file loaded this way is still examined as HTML. Its bytes still decide over that role: a `.map` or loaded script whose text parses as a source map, a JSON object with `version` and `mappings`, `sources`, or `sections`, is read as a source map, so `<script src="main.map">` pointing at a map with `sourcesContent` still reports `javascript.source_map_sources` exposed. One read before that HTML file, one that is not found, one at a location the audit cannot place, or one past the 1 MiB of resolved script paths the audit keeps (`MAX_RELEASE_EXPOSURE_SCRIPT_TARGET_BYTES`) leaves `javascript.source_map_sources` undecided. A `.map` read before the HTML file that loads it is not reported as a linker map. Skipped members are listed under `coverage.omitted`. When the selection is a file, the parent directory is listed up to a fixed entry allowance for sibling `.pdb`, `.dSYM`, `.debug`, and linker `.map` debug companions. A sibling source map that the selected file declares, such as `app.js.map`, or a sibling script that a selected HTML file loads, such as `app.js`, is not read as part of the artifact, so it leaves `javascript.source_map_sources` undecided.
Inventory stops at 65,536 entries or 2 GiB of hashed bytes, and member coverage then stays `unknown`. A packed ASAR member is read from the captured archive, whose digest must match inventory. An unpacked member is read from its `.unpacked` companion, so its full bytes must also match the digest inventory recorded for that member, and a companion replaced after inventory fails the audit as a changed artifact. That digest check stays inside the read allowance: a companion larger than the allowance is read only up to the allowance, is not hashed to its end, and is treated as over its allowance without a digest verification. A declared integrity value that disagrees with the bytes does not stop the audit, because signing an unpacked native module after packaging is routine. The contradiction is recorded in the limitations and the audit continues.
A member of a package that inventory did not expand is reported as the host file path followed by the member path, for example `/dist/app.dll/notes.txt`. Inventory-expanded members keep their path relative to the selection.
A package member skipped by a read allowance still counts as readable for `packaging.extractable_payload`, because the format stores it unencrypted. An encrypted member or one that failed to read counts as unreadable. A member that failed to read, such as a compressed `payload.json` whose stream does not inflate, also leaves member coverage `unknown` unless its package states what it is, because its name does not rule out a nested image or package.
A map read counts against the source-map allowance when it starts, so an oversized or unreadable `.map` uses a read as a parsed one does. A sibling `.map` beside a selected file spends the same allowance, after the selected artifact has been read, and past it only the bounded header is read. A sibling whose header can begin a JSON object is then counted as skipped. A sibling `.map` that a selected HTML file loads as a script, or whose header is an ELF, Mach-O, or PE image, is not a linker map. A `.map` too large to parse is a linker map when its header cannot begin a JSON object. A larger `.map` that begins as JSON, or that has a JavaScript name such as `app.js.map`, is counted as skipped. `native.debug_companions` identifies a companion from its name or from a `.map` body that is not a source map, so its `exposed` result has `inferred` confidence. A symlink with a companion name counts by that name, and its target is not read. A symlink named as a source map, script, HTML, SVG, or CSS file is counted as skipped, whatever it points at, because links are not followed and that name is all the audit knows of what it would load. The target can still be scanned as a member under its own name, where a name such as `payload` is not read for map directives.
## Status
`exposed` means the check's condition was observed. `not_observed` means that condition was absent in a completed scan. `not_applicable` means the check does not apply to this artifact, for example Electron fuses on an app bundle with no Electron Framework, or on a directory whose native images were all read and hold no fuse sentinel. `unknown` means the check could not be decided, including a directory with no ASAR layout where those reads are missing or incomplete (an `asar: false` Electron build has no ASAR to find), safe fuses from an incomplete inventory, an unopened packaged native image, or a dropped image when the sample did not read an executable named as the Electron host or every executable that could be it, a missing fuse sentinel on an Electron target, a universal binary with a slice that has no sentinel or an undecided fuse, a file that changed after inventory, Electron fuses on a selected ASAR (which does not include the executable that holds them), a PE inside a package that was too large to read, Go or Rust metadata on a native image stored inside a package, and Go or Rust metadata that was not present. Absence of that metadata is not proof the binary is something else. `not_assessed` means this audit did not run the check.
Cancellation during a Go, Rust, fuse, or desktop read returns a typed cancellation error. Its partial observation holds the report with completed facts, and checks whose readers did not run are `unknown`. Cancellation during the member scan returns the same typed cancellation error. Its partial observation holds the members examined before the cancellation, with member coverage `unknown` and a limitation saying the scan was cancelled. Cancellation before the scan can be assembled, such as during inventory, returns no partial report.
Severity is `null` unless the status is `exposed`.
+2
View File
@@ -33,3 +33,5 @@ for new work, roadmap granularity and producer-owned contracts.
- [ELF unwind function ranges](native/elf-unwind-ranges/spec.md) ([plan](native/elf-unwind-ranges/plan.md), [tasks](native/elf-unwind-ranges/tasks.md))
- [Linux kernel build config](native/kernel-build-config/spec.md) ([plan](native/kernel-build-config/plan.md), [tasks](native/kernel-build-config/tasks.md))
- [Native initializers](native/native-initializers/spec.md) ([plan](native/native-initializers/plan.md), [tasks](native/native-initializers/tasks.md))
- [Release exposure audit](artifacts/release-exposure/spec.md) ([plan](artifacts/release-exposure/plan.md), [tasks](artifacts/release-exposure/tasks.md))
@@ -0,0 +1,42 @@
# Implementation plan
## Boundary and contract
`src/domain/releaseExposure.ts` owns the report schema, check ids, statuses,
severities and read allowances. `src/domain/releaseExposureCredentialMarkers.ts`
owns the provider-prefixed marker rules. `src/artifacts/ReleaseExposureReader.ts`
owns the bounded scan of the selected artifact and its members.
`src/application/releaseExposure/ReleaseExposureService.ts` composes the existing
owners through `ReleaseExposurePort` and decides each check from their results.
`src/contracts/releaseExposureToolContracts.ts`, `src/cli/releaseExposureCommands.ts`
and `src/server/registerReleaseExposureTool.ts` are thin adapters over the same
service.
## Changes to existing owners
- `inventoryArtifact` gains optional `acquisitionLimits`. Only this audit sets
them. Exhausting one keeps a partial inventory with unknown coverage. Other
callers are unchanged.
- `src/domain/binaryTarget.ts` adds `inspectPeCodeViewFromBuffer`, which
separates absent CodeView records from incomplete parsing.
`parsePeCodeViewFromBuffer` keeps its behavior on top of it.
- `src/artifacts/inventory/classify.ts` exports
`classifyEmbeddedExecutablePackage`, so the audit recognizes a packaged
executable with the same probes as inventory.
- Declared integrity uses `record-and-continue` for this audit only.
## Change detection
Every file read is bound to its inventoried digest. A file or container whose
bytes differ from inventory at read time adds a change diagnostic and leaves the
affected checks `unknown`. An unpacked ASAR member is read from its companion
on disk rather than the captured archive, so its bytes are compared with the
member digest that inventory recorded, and findings cannot mix an inventoried
release with bytes written later. Native images carry their
inventory digest into the Go, Rust and fuse reads.
## Effects and compatibility
The tool is read-only, local and additive to the CLI and MCP catalogs. It adds no
provider and no runtime dependency. `verify:release-exposure` installs
`@electron/fuses` into a temporary prefix when it runs.
@@ -0,0 +1,75 @@
# Release exposure audit
Pull request: https://github.com/morluto/rea/pull/8525
## Problem and outcome
REA can show what static analysis recovers from a shipped application, but a
developer who wants that answer for their own release has to run several tools
and combine the results by hand. Add one read-only audit that reads a single
shipped artifact through the existing readers and reports, per named check,
what was observed, so a team can review or gate a release before it ships.
## Requirements
- Accept one local `.app` bundle, install directory, ASAR or single executable
through `audit_release_exposure` (MCP, absolute path) and
`rea audit-release-exposure` (CLI, path resolved against the caller's working
directory). Both adapters return the same report.
- Report a fixed set of checks, each with a stable id, a status of `exposed`,
`not_observed`, `not_applicable`, `unknown` or `not_assessed`, the observation
behind it, its locations and fixed remediation text. Severity is `null` unless
the status is `exposed`.
- Report no pass verdict, score or grade. The report states that it does not
establish that an application is secure, and `unknown` and `not_assessed`
counts stay beside the findings.
- Compose existing owners: artifact inventory, Electron fuses, Go build info,
cargo-auditable metadata, PE CodeView, embedded package classification and
source-map parsing. Do not reimplement their parsing.
- Never execute, modify or rewrite the artifact, and make no network request.
- Bound every read. Inventory stops at 65,536 entries or 2 GiB of hashed bytes.
Text, source-map and packaged-image reads have separate allowances reported
under `coverage.allowances`; skipped members are listed under
`coverage.omitted`. An exhausted bound leaves the affected checks `unknown`.
An unpacked ASAR companion is compared with its inventoried digest only when
it ends within the read allowance; one past the allowance is not read further
to finish the digest and stays over its allowance, unverified.
- Fail toward `unknown`: a read that could not be completed, a file or member
whose bytes no longer match the inventoried digest, an unresolved or oversized
source map, or missing metadata never becomes `not_observed`.
- For `text.credential_markers`, report the rule id and location only. Matched
bytes, previews, lengths and hashes of matched bytes are omitted. Source-map
text is counted and then dropped.
- Without `--fail_on`, the CLI exit status reflects only whether the audit
finished. With `--fail_on high|medium|low`, a completed audit exits `3` when an
`exposed` check meets that severity. A tool failure exits `1`.
- A declared integrity value that disagrees with the bytes is recorded as a
limitation and the audit continues.
- Cancellation during a composed owner returns the typed cancellation error with
the partial report attached.
## Acceptance
- Domain tests cover status aggregation, severity, `--fail_on` thresholds and the
absence of a verdict.
- Reader tests cover source maps with and without `sourcesContent`, inline
`data:` maps, HTML and SVG script loading, debug companions, credential markers
in text members and binary plists, UTF-16 and NUL handling, read allowances,
same-name package members, packaged native images and changed bytes after
inventory, including an unpacked ASAR companion replaced after inventory and
an oversized companion that is not read past its allowance.
- Service tests cover Electron fuse decisions, Go and Rust metadata, partial
inventory and cancellation with a partial report.
- CLI and MCP return the same report; `--max-file-bytes` accepts the documented
decimal token form.
- `npm run verify:release-exposure` audits real fixtures, recorded in
[the verification record](../../../verification/release-exposure-2026-10-31.md).
- The [release exposure guide](../../../release-exposure.md) documents current
behavior and limitations.
## Non-goals
Obfuscation, stripping, signing, active protection, modifying the artifact,
running the target, network calls and a security verdict. `native.hardening`,
`macho.hardened_runtime` and `android.manifest` stay `not_assessed` and name
their next probes instead.
@@ -0,0 +1,10 @@
# Tasks
- [x] Define the report contract, checks, statuses and read allowances (FR: report, bounds).
- [x] Add the bounded reader and the service that composes existing owners (FR: compose, fail toward unknown).
- [x] Add CLI and MCP adapters with `--fail_on` exit status 3 (FR: exit status).
- [x] Add domain, reader and service tests listed under acceptance.
- [x] Verify real fixtures with `npm run verify:release-exposure`.
- [x] Document current behavior in the release exposure guide.
- [x] Accept decimal `--max-file-bytes` tokens through `cliDecimalField`.
- [x] Bind unpacked ASAR member reads to their inventoried digests.
@@ -0,0 +1,49 @@
# Release exposure verification 2026-10-31
Ran `node scripts/verify-release-exposure.mjs` with Node v24.22.1. The package script is `npm run verify:release-exposure`, which runs `npm run build:cached` first because `scripts/rea.mjs` loads the compiled CLI. `@electron/fuses` 2.1.3 was installed into a temporary prefix and `flipFuses` was called on the after framework binary.
The fixture is `MyApp.app`. `Contents/Resources/app.asar` holds `app.js`. Before, it also holds `app.js.map` with `sourcesContent`. `Contents/Frameworks/Electron Framework.framework/Electron Framework` is an ELF larger than 256 KiB with the Electron fuse sentinel and a version-1 fuse wire. After, the archive is rebuilt without the map and `flipFuses` disables `RunAsNode` and `EnableNodeCliInspectArguments` and enables `OnlyLoadAppFromAsar` and `EnableEmbeddedAsarIntegrityValidation`. `app.js` remains, so `packaging.extractable_payload` stays exposed. Embedded ASAR integrity stays `unknown` on ELF. Go and Rust stay `unknown` because the framework binary is registered and has no build metadata; that is not `not_applicable`.
`--fail_on high` on the before app exited 3.
## Before
| Check | Status | Severity |
| ------------------------------- | ---------------- | -------- |
| `javascript.source_map_sources` | `exposed` | `high` |
| `javascript.source_maps` | `not_observed` | `null` |
| `electron.run_as_node` | `exposed` | `high` |
| `electron.asar_integrity` | `unknown` | `null` |
| `electron.only_load_from_asar` | `exposed` | `medium` |
| `electron.node_cli_inspect` | `exposed` | `medium` |
| `packaging.extractable_payload` | `exposed` | `low` |
| `native.debug_companions` | `not_observed` | `null` |
| `native.pdb_path` | `not_applicable` | `null` |
| `go.build_paths` | `unknown` | `null` |
| `rust.dependency_metadata` | `unknown` | `null` |
| `text.credential_markers` | `not_observed` | `null` |
| `native.hardening` | `not_assessed` | `null` |
| `macho.hardened_runtime` | `not_assessed` | `null` |
| `android.manifest` | `not_assessed` | `null` |
## After
| Check | Status | Severity |
| ------------------------------- | ---------------- | -------- |
| `javascript.source_map_sources` | `not_observed` | `null` |
| `javascript.source_maps` | `not_observed` | `null` |
| `electron.run_as_node` | `not_observed` | `null` |
| `electron.asar_integrity` | `unknown` | `null` |
| `electron.only_load_from_asar` | `not_observed` | `null` |
| `electron.node_cli_inspect` | `not_observed` | `null` |
| `packaging.extractable_payload` | `exposed` | `low` |
| `native.debug_companions` | `not_observed` | `null` |
| `native.pdb_path` | `not_applicable` | `null` |
| `go.build_paths` | `unknown` | `null` |
| `rust.dependency_metadata` | `unknown` | `null` |
| `text.credential_markers` | `not_observed` | `null` |
| `native.hardening` | `not_assessed` | `null` |
| `macho.hardened_runtime` | `not_assessed` | `null` |
| `android.manifest` | `not_assessed` | `null` |
`javascript.source_map_sources`, `electron.run_as_node`, `electron.node_cli_inspect`, and `electron.only_load_from_asar` changed from `exposed` to `not_observed`. `electron.asar_integrity` stayed `unknown`. `packaging.extractable_payload` stayed `exposed`.
+1
View File
@@ -209,6 +209,7 @@
"verify:apktool": "npm run build:cached && node scripts/verify-apktool.mjs",
"verify:pcap": "npm run build:cached && node scripts/verify-pcap.mjs",
"verify:pe:load-config": "npm run build:cached && node scripts/verify-pe-load-config.mjs",
"verify:release-exposure": "npm run build:cached && node scripts/verify-release-exposure.mjs",
"verify:binary-hardening": "node scripts/verify-binary-hardening.mjs",
"verify:elf:unwind-ranges": "npm run build:cached && node scripts/verify-elf-unwind-ranges.mjs",
"verify:flutter": "npm run build:cached && node scripts/verify-flutter.mjs",
+300
View File
@@ -0,0 +1,300 @@
/** Audit a local Electron .app before and after fuse and source-map remediation. */
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { withVerifierCleanup } from "./lib/verifier-cleanup.mjs";
import { importVerifierSource } from "./lib/verifier-source-loader.mjs";
import { createVerifierCommands } from "./lib/verify-commands.mjs";
const { ELECTRON_FUSE_SENTINEL } = await importVerifierSource(
new URL("../src/domain/electron/electronFuses.ts", import.meta.url).href,
import.meta.url,
);
const PLANTED_SOURCE = "release-exposure-planted-secret-7c2e9a";
const OUTPUT = resolve("docs/verification/release-exposure-2026-10-31.md");
const TEXT_MEMBER_BYTES = 256 * 1024;
const ELECTRON_FUSES_VERSION = "2.1.3";
const asarArchive = (files) => {
let offset = 0;
const table = {};
const bodies = [];
for (const file of files) {
table[file.name] = { size: file.bytes.length, offset: String(offset) };
bodies.push(file.bytes);
offset += file.bytes.length;
}
const text = Buffer.from(JSON.stringify({ files: table }));
const aligned = Math.ceil(text.length / 4) * 4;
const headerSize = 8 + aligned;
const header = Buffer.alloc(8 + headerSize);
header.writeUInt32LE(4, 0);
header.writeUInt32LE(headerSize, 4);
header.writeUInt32LE(headerSize - 4, 8);
header.writeUInt32LE(text.length, 12);
text.copy(header, 16);
return Buffer.concat([header, ...bodies]);
};
const frameworkBinary = (states) => {
const header = Buffer.alloc(64);
header[0] = 0x7f;
header[1] = 0x45;
header[2] = 0x4c;
header[3] = 0x46;
header[4] = 2;
header[5] = 1;
header[6] = 1;
header.writeUInt16LE(2, 16);
header.writeUInt16LE(62, 18);
header.writeUInt32LE(1, 20);
header.writeUInt16LE(64, 52);
const wire = Buffer.concat([
Buffer.from(ELECTRON_FUSE_SENTINEL, "ascii"),
Buffer.from([1, states.length, ...states]),
]);
return Buffer.concat([header, wire, Buffer.alloc(TEXT_MEMBER_BYTES)]);
};
const sourceMap = () =>
Buffer.from(
JSON.stringify({
version: 3,
file: "app.js",
sources: ["app.js"],
names: [],
mappings: "",
sourcesContent: [`export const secret = "${PLANTED_SOURCE}";\n`],
}),
);
const writeApp = async (root, { withMap, states }) => {
const resources = join(root, "Contents", "Resources");
const framework = join(
root,
"Contents",
"Frameworks",
"Electron Framework.framework",
);
await mkdir(resources, { recursive: true });
await mkdir(framework, { recursive: true });
const files = [{ name: "app.js", bytes: Buffer.from("console.log(1)\n") }];
if (withMap) files.push({ name: "app.js.map", bytes: sourceMap() });
await writeFile(join(resources, "app.asar"), asarArchive(files));
await writeFile(
join(framework, "Electron Framework"),
frameworkBinary(states),
);
};
const audit = async (directory, extraArgs = []) => {
const args = [
resolve("scripts/rea.mjs"),
"audit-release-exposure",
directory,
"--json",
...extraArgs,
];
try {
const { stdout } = await commands.exec(process.execPath, args, {
maxBuffer: 32 * 1024 * 1024,
timeout: 180000,
});
return { status: 0, stdout };
} catch (cause) {
const stdout = cause.snapshot?.stdout.text ?? "";
const status = typeof cause.code === "number" ? cause.code : undefined;
if (status !== undefined && stdout.length > 0) return { status, stdout };
throw cause;
}
};
const checksOf = (stdout) => {
const evidence = JSON.parse(stdout);
const report = evidence.normalized_result;
return report.checks.map((check) => ({
id: check.id,
status: check.status,
severity: check.severity,
}));
};
const statusOf = (checks, id) =>
checks.find((check) => check.id === id)?.status;
const expectStatus = (label, checks, id, value) => {
if (statusOf(checks, id) !== value)
throw new Error(
`${label} ${id} is ${statusOf(checks, id)}, expected ${value}`,
);
};
const table = (checks) => {
const rows = [
["Check", "Status", "Severity"],
...checks.map((check) => [
`\`${check.id}\``,
`\`${check.status}\``,
`\`${String(check.severity)}\``,
]),
];
const widths = rows[0].map((_, column) =>
Math.max(...rows.map((row) => row[column].length)),
);
const line = (cells) =>
`| ${cells.map((cell, column) => cell.padEnd(widths[column])).join(" | ")} |`;
return [
line(rows[0]),
line(widths.map((width) => "-".repeat(width))),
...rows.slice(1).map(line),
].join("\n");
};
const installFuses = async (root) => {
const prefix = join(root, "fuses");
await mkdir(prefix);
await commands.exec(
"npm",
[
"install",
"--prefix",
prefix,
`@electron/fuses@${ELECTRON_FUSES_VERSION}`,
],
{ timeout: 180000 },
);
const packageJson = JSON.parse(
await readFile(
join(prefix, "node_modules", "@electron", "fuses", "package.json"),
"utf8",
),
);
const exported = packageJson.exports;
const dot =
exported !== null && typeof exported === "object"
? exported["."]
: exported;
const nested = dot !== null && typeof dot === "object" ? dot : undefined;
const entry =
(typeof dot === "string" ? dot : undefined) ??
(typeof nested?.import === "string" ? nested.import : undefined) ??
(typeof nested?.default === "string" ? nested.default : undefined) ??
(typeof packageJson.module === "string" ? packageJson.module : undefined) ??
(typeof packageJson.main === "string" ? packageJson.main : undefined);
if (entry === undefined)
throw new Error("@electron/fuses package entry was not a file path");
const href = pathToFileURL(
join(prefix, "node_modules", "@electron", "fuses", entry),
).href;
const api = await import(href);
return { version: packageJson.version, api };
};
const commands = await createVerifierCommands();
const root = await mkdtemp(join(tmpdir(), "rea-release-exposure-"));
await withVerifierCleanup(async () => {
const beforeApp = join(root, "before", "MyApp.app");
const afterApp = join(root, "after", "MyApp.app");
const enabled = [0x31, 0x31, 0x31, 0x31, 0x30, 0x30];
await writeApp(beforeApp, { withMap: true, states: enabled });
await writeApp(afterApp, { withMap: false, states: enabled });
const { version, api } = await installFuses(root);
const { flipFuses, FuseVersion, FuseV1Options } = api;
await flipFuses(
join(
afterApp,
"Contents",
"Frameworks",
"Electron Framework.framework",
"Electron Framework",
),
{
version: FuseVersion.V1,
resetAdHocDarwinSignature: false,
[FuseV1Options.RunAsNode]: false,
[FuseV1Options.EnableNodeCliInspectArguments]: false,
[FuseV1Options.EnableEmbeddedAsarIntegrityValidation]: true,
[FuseV1Options.OnlyLoadAppFromAsar]: true,
},
);
const gated = await audit(beforeApp, ["--fail_on", "high"]);
if (gated.status !== 3)
throw new Error(
`--fail_on high exited ${String(gated.status)}, expected 3`,
);
const before = await audit(beforeApp);
const after = await audit(afterApp);
if (
before.stdout.includes(PLANTED_SOURCE) ||
after.stdout.includes(PLANTED_SOURCE) ||
gated.stdout.includes(PLANTED_SOURCE)
)
throw new Error("Planted source text was copied into the audit report");
const beforeChecks = checksOf(before.stdout);
const afterChecks = checksOf(after.stdout);
for (const id of [
"javascript.source_map_sources",
"packaging.extractable_payload",
"electron.run_as_node",
"electron.node_cli_inspect",
"electron.only_load_from_asar",
])
expectStatus("before", beforeChecks, id, "exposed");
expectStatus("before", beforeChecks, "electron.asar_integrity", "unknown");
expectStatus("before", beforeChecks, "go.build_paths", "unknown");
expectStatus("before", beforeChecks, "rust.dependency_metadata", "unknown");
expectStatus(
"after",
afterChecks,
"javascript.source_map_sources",
"not_observed",
);
expectStatus("after", afterChecks, "javascript.source_maps", "not_observed");
expectStatus("after", afterChecks, "electron.run_as_node", "not_observed");
expectStatus(
"after",
afterChecks,
"electron.node_cli_inspect",
"not_observed",
);
expectStatus(
"after",
afterChecks,
"electron.only_load_from_asar",
"not_observed",
);
expectStatus("after", afterChecks, "electron.asar_integrity", "unknown");
expectStatus(
"after",
afterChecks,
"packaging.extractable_payload",
"exposed",
);
expectStatus("after", afterChecks, "go.build_paths", "unknown");
expectStatus("after", afterChecks, "rust.dependency_metadata", "unknown");
const document = `# Release exposure verification 2026-10-31
Ran \`node scripts/verify-release-exposure.mjs\` with Node ${process.version}. The package script is \`npm run verify:release-exposure\`, which runs \`npm run build:cached\` first because \`scripts/rea.mjs\` loads the compiled CLI. \`@electron/fuses\` ${version} was installed into a temporary prefix and \`flipFuses\` was called on the after framework binary.
The fixture is \`MyApp.app\`. \`Contents/Resources/app.asar\` holds \`app.js\`. Before, it also holds \`app.js.map\` with \`sourcesContent\`. \`Contents/Frameworks/Electron Framework.framework/Electron Framework\` is an ELF larger than 256 KiB with the Electron fuse sentinel and a version-1 fuse wire. After, the archive is rebuilt without the map and \`flipFuses\` disables \`RunAsNode\` and \`EnableNodeCliInspectArguments\` and enables \`OnlyLoadAppFromAsar\` and \`EnableEmbeddedAsarIntegrityValidation\`. \`app.js\` remains, so \`packaging.extractable_payload\` stays exposed. Embedded ASAR integrity stays \`unknown\` on ELF. Go and Rust stay \`unknown\` because the framework binary is registered and has no build metadata; that is not \`not_applicable\`.
\`--fail_on high\` on the before app exited ${String(gated.status)}.
## Before
${table(beforeChecks)}
## After
${table(afterChecks)}
\`javascript.source_map_sources\`, \`electron.run_as_node\`, \`electron.node_cli_inspect\`, and \`electron.only_load_from_asar\` changed from \`exposed\` to \`not_observed\`. \`electron.asar_integrity\` stayed \`unknown\`. \`packaging.extractable_payload\` stayed \`exposed\`.
`;
await writeFile(OUTPUT, document);
console.log(`wrote ${OUTPUT}`);
console.log(`node ${process.version}`);
console.log(`@electron/fuses ${version}`);
console.log(`fail_on high exit ${String(gated.status)}`);
}, [() => commands.close(), () => rm(root, { recursive: true, force: true })]);
+1
View File
@@ -677,6 +677,7 @@ const workflowAvailabilityFor = (
name === "inspect_kernel_module" ||
name === "inspect_kernel_build_config" ||
name === "inspect_pe_load_config" ||
name === "audit_release_exposure" ||
name === "inspect_binary_hardening"
)
return { reason: "available", remediation: null };
@@ -0,0 +1,29 @@
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { RELEASE_EXPOSURE_PROVIDER } from "../../domain/investigationProviders.js";
import type { ReleaseExposureScan } from "../../domain/releaseExposure.js";
import type { Result } from "../../domain/result.js";
/** Receives each text member the reader admits. `location` names that member. */
export type ReleaseExposureTextVisitor = (
text: string,
location: string,
) => void;
/**
* Receives what a scan established before it failed with unfinished cleanup,
* so a typed cleanup failure does not erase completed findings.
*/
export type ReleaseExposureScanVisitor = (scan: ReleaseExposureScan) => void;
/** Bounded, read-only view of one shipped artifact. */
export interface ReleaseExposurePort {
readonly identity: typeof RELEASE_EXPOSURE_PROVIDER;
inspect(
input: { readonly path: string; readonly max_file_bytes?: number },
options: ExecutionOptions | undefined,
visitText: ReleaseExposureTextVisitor,
visitInterruptedScan?: ReleaseExposureScanVisitor,
): Promise<Result<ReleaseExposureScan, AnalysisError>>;
close(): Promise<void>;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,68 @@
import { access, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { asarHeaderBytes } from "../../tests/fixtures/asarHeader.js";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { nodeSeaElf } from "./nodeSea/NodeSea.fixture.js";
import { ReleaseExposureReader } from "./ReleaseExposureReader.js";
vi.mock("node:fs/promises", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs/promises")>();
return { ...actual, rm: vi.fn(actual.rm) };
});
const asarWith = (name: string, bytes: Buffer): Buffer =>
Buffer.concat([
asarHeaderBytes(
JSON.stringify({
files: { [name]: { size: bytes.length, offset: "0" } },
}),
),
bytes,
]);
describe("ReleaseExposureReader probe directory cleanup", () => {
it("reports a failed removal and retries it on close", async () => {
const root = await createTestTempDirectory("rea-release-exposure-probe-");
await writeFile(
join(root, "app.asar"),
asarWith("tool.node", nodeSeaElf()),
);
const actual =
await vi.importActual<typeof import("node:fs/promises")>(
"node:fs/promises",
);
const removed: string[] = [];
vi.mocked(rm).mockImplementation(async (path, options) => {
const target = String(path);
if (target.includes("rea-release-member-") && removed.length === 0) {
removed.push(target);
throw Object.assign(new Error("busy"), { code: "EBUSY" });
}
await actual.rm(path, options);
});
const reader = new ReleaseExposureReader();
try {
const result = await reader.inspect(
{ path: root },
undefined,
() => undefined,
);
expect(result.ok).toBe(false);
if (result.ok) return;
const [directory] = removed;
if (directory === undefined) throw new Error("No probe directory.");
expect(result.error).toMatchObject({
cleanup: { resources: expect.arrayContaining([directory]) },
});
await expect(access(directory)).resolves.toBeUndefined();
await reader.close();
await expect(access(directory)).rejects.toThrow();
} finally {
vi.mocked(rm).mockImplementation(actual.rm);
await reader.close();
}
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,10 +1,13 @@
import { expect, it } from "vitest";
import { expect, it, vi } from "vitest";
import { binaryPlistObjectTable } from "../../../tests/fixtures/binaryPlistObjectTable.js";
import { createPlistNumberProjection } from "../../domain/apple/plistNumbers.js";
import { projectPlistValue } from "../../domain/apple/plistValue.js";
import { scanBinaryPlistScalars } from "./PlistScalars.js";
import { plistUidValue } from "../../domain/apple/plistUid.js";
import { decodeBinaryPlistValue } from "./BinaryPlistMaterializer.js";
import {
decodeBinaryPlistText,
decodeBinaryPlistValue,
} from "./BinaryPlistMaterializer.js";
import { estimateBinaryPlistExpansion } from "./PropertyListDecodeBudget.js";
import { parseXmlPropertyList } from "../../domain/propertyListKeys.js";
@@ -179,3 +182,121 @@ it("keeps uint64 wrapping for nine-byte offset and reference declarations", () =
expect(decode(bytes)).toEqual([7]);
expect(bytes.equals(original)).toBe(true);
});
const dictionary = (...references: readonly number[]): Buffer =>
Buffer.from([0xd0 | (references.length / 2), ...references]);
const budget = 1024 * 1024;
it("reads a string no object references", () => {
const bytes = source([
dictionary(1, 2),
text("key"),
text("kept"),
text("orphan"),
]);
expect(decodeBinaryPlistText(bytes, budget).text).toContain("orphan");
});
it("reads the value a later duplicate key replaced", () => {
const bytes = source([
dictionary(1, 1, 2, 3),
text("key"),
text("replaced"),
text("final"),
]);
expect(decode(bytes)).toEqual({ key: "final" });
expect(decodeBinaryPlistText(bytes, budget).text).toContain("replaced");
});
it("reads an unreferenced UTF-16BE string and data object", () => {
const wide = Buffer.concat([
Buffer.from([0x62]),
Buffer.from("é!", "utf16le").swap16(),
]);
const data = Buffer.concat([Buffer.from([0x44]), Buffer.from("blob")]);
const bytes = source([
dictionary(1, 2),
text("key"),
text("kept"),
wide,
data,
]);
const { text: decoded, complete } = decodeBinaryPlistText(bytes, budget);
expect(decoded).toContain("é!");
expect(decoded).toContain("blob");
expect(complete).toBe(true);
});
it("honors a byte order mark in a data object", () => {
const data = (payload: Buffer): Buffer =>
Buffer.concat([Buffer.from([0x4f, 0x10, payload.length]), payload]);
const header = "-----BEGIN PRIVATE KEY-----";
const little = Buffer.from(`\ufeff${header}`, "utf16le");
const big = Buffer.from(little).swap16();
for (const payload of [little, big])
expect(
decodeBinaryPlistText(
source([dictionary(1, 2), text("key"), data(payload)]),
budget,
),
).toEqual({ text: expect.stringContaining(header), complete: true });
const wider = Buffer.from([0xff, 0xfe, 0, 0, 0x6b, 0, 0, 0]);
expect(
decodeBinaryPlistText(
source([dictionary(1, 2), text("key"), data(wider)]),
budget,
).complete,
).toBe(false);
});
it("keeps readable text beside an unreferenced string it cannot read", () => {
const bytes = source([
dictionary(1, 2),
text("key"),
text("kept"),
Buffer.from([0x5f, 0x10, 0xff]),
]);
expect(decodeBinaryPlistText(bytes, budget)).toEqual({
text: expect.stringContaining("kept"),
complete: false,
});
});
it("bounds the text that overlapping table entries repeat", () => {
const entries = 200;
const headerBytes = 6;
const shared = Buffer.alloc(60_000 + entries * headerBytes, 0x61);
const root = Buffer.from([0xd1, 1, 2, 0x51, 0x6b, 0x51, 0x76]);
const offsets = [8, 11, 13];
for (let entry = 0; entry < entries; entry += 1) {
const at = entry * headerBytes;
shared.set([0x4f, 0x12], at);
shared.writeUInt32BE(shared.length - at - headerBytes, at + 2);
offsets.push(8 + root.length + at);
}
const table = 8 + root.length + shared.length;
const bytes = Buffer.alloc(table + offsets.length * 4 + 32);
bytes.write("bplist00", "latin1");
root.copy(bytes, 8);
shared.copy(bytes, 8 + root.length);
offsets.forEach((offset, entry) =>
bytes.writeUInt32BE(offset, table + entry * 4),
);
const trailer = bytes.length - 32;
bytes[trailer + 6] = 4;
bytes[trailer + 7] = 1;
bytes.writeBigUInt64BE(BigInt(offsets.length), trailer + 8);
bytes.writeBigUInt64BE(BigInt(table), trailer + 24);
const toString = vi.spyOn(Buffer.prototype, "toString");
const decoded = decodeBinaryPlistText(bytes, 2 * budget);
const decodedBytes = toString.mock.contexts.reduce(
(total, buffer) => total + (buffer as Buffer).length,
0,
);
toString.mockRestore();
expect(decoded.complete).toBe(false);
expect(decoded.text.length).toBeLessThanOrEqual(2 * budget + offsets.length);
expect(decoded.text).toContain("k");
// A range past the remaining budget is rejected before it is decoded.
expect(decodedBytes).toBeLessThanOrEqual(2 * budget + bytes.length);
});
+97 -1
View File
@@ -1,12 +1,17 @@
import { readBinaryPlistLayout } from "./BinaryPlistLayout.js";
import { parseBinary } from "plist";
import { markPlistDictionary } from "../../domain/apple/plistUid.js";
import { byteOrderMarkEncoding } from "../../domain/textByteOrderMark.js";
import {
binaryPlistObjectEnd,
decodeBinaryPlistScalars,
scanBinaryPlistScalars,
type BinaryPlistScalarMetadata,
} from "./PlistScalars.js";
import type { PlistDecodePreflight } from "./PropertyListDecodeBudget.js";
import {
preflightPropertyListDecode,
type PlistDecodePreflight,
} from "./PropertyListDecodeBudget.js";
/** Build one array of source scalar references; upstream never constructs a dictionary. */
const scalarArrayInput = (
@@ -128,3 +133,94 @@ export const decodeBinaryPlistValue = (
}
return root.value;
};
/** The payload of one stored string or data object, or null for any other type. */
const storedPlistPayload = (
bytes: Buffer,
offset: number,
objectEnd: number,
referenceWidth: number,
):
| { readonly type: number; readonly payload: Buffer }
| "unreadable"
| null => {
const marker = bytes[offset];
if (marker === undefined) return "unreadable";
const type = marker >> 4;
if (type !== 4 && type !== 5 && type !== 6 && type !== 7) return null;
const end = binaryPlistObjectEnd(bytes, offset, objectEnd, referenceWidth);
if (end === undefined) return "unreadable";
const start =
(marker & 0x0f) === 0x0f
? offset + 2 + (1 << (bytes[offset + 1]! & 0x0f))
: offset + 1;
return { type, payload: bytes.subarray(start, end) };
};
/** The text a data payload holds, honoring a byte order mark; null when no reader scans it. */
const storedDataText = (payload: Buffer): string | null => {
const encoding = byteOrderMarkEncoding(payload);
if (encoding === "utf-32") return null;
return encoding === null
? payload.toString("utf8")
: new TextDecoder(encoding).decode(payload);
};
/**
* Decode a payload `storedPlistPayload` found; call only once it fits the
* budget. Null when its encoding cannot be scanned.
*/
const storedPlistText = (type: number, payload: Buffer): string | null =>
type === 5
? payload.toString("latin1")
: type === 6
? Buffer.from(payload).swap16().toString("utf16le")
: type === 4
? storedDataText(payload)
: payload.toString("utf8");
/** The text a binary plist stores; `complete` is false when part of it went unread. */
export interface BinaryPlistText {
readonly text: string;
readonly complete: boolean;
}
/**
* Decode every string, dictionary key and data payload a binary plist stores.
* Its strings are stored per object as ASCII, UTF-16BE or UTF-8, so the raw
* bytes do not show them all. This reads the object table rather than the
* decoded value, because a value drops objects its root no longer references
* and entries a later duplicate key replaced, and those bytes still ship.
* A stored object it cannot read, or text past `maxBytes` from table entries
* that overlap, leaves the result incomplete and keeps the text already read.
* Throws on a plist that cannot be decoded within `maxBytes`.
*/
export const decodeBinaryPlistText = (
bytes: Buffer,
maxBytes: number,
): BinaryPlistText => {
decodeBinaryPlistValue(bytes, preflightPropertyListDecode(bytes, maxBytes));
const layout = readBinaryPlistLayout(bytes);
if (!layout.ok) throw new RangeError("binary plist trailer is truncated");
const texts: string[] = [];
let decoded = 0;
let complete = true;
for (const offset of new Set(layout.value.objectOffsets())) {
const stored = storedPlistPayload(
bytes,
Number(offset),
layout.value.trailerOffset,
layout.value.referenceWidth,
);
if (stored === null) continue;
if (stored === "unreadable" || decoded + stored.payload.length > maxBytes) {
complete = false;
continue;
}
decoded += stored.payload.length;
const text = storedPlistText(stored.type, stored.payload);
if (text === null) complete = false;
else texts.push(text);
}
return { text: texts.join("\n"), complete };
};
@@ -31,6 +31,15 @@ export const inventoryArtifact = async (
});
};
/** Inventory under an admission the caller already holds on its scope. */
export const inventoryArtifactInScope = async (
inputPath: string,
options: ArtifactInventoryOptions,
): Promise<ArtifactInventoryResult> =>
artifactInventoryResultSchema.parse(
await scanArtifactInventoryInScope(inputPath, options),
);
export const scanArtifactInventoryInScope = async (
inputPath: string,
options: ArtifactInventoryOptions,
+75 -20
View File
@@ -24,6 +24,9 @@ import {
ArtifactEmbeddedFormatProbes,
type ArtifactEmbeddedFormatProbeFacts,
} from "../ArtifactEmbeddedFormatProbes.js";
import type { BunStandaloneProbe } from "../bun/BunModuleGraphLayout.js";
import type { NodeSeaLocation } from "../nodeSea/NodeSeaLocation.js";
import type { PyInstallerCookie } from "../pyinstaller/CArchiveLayout.js";
import {
assertStableRegularFileIdentity,
RegularFileChangedError,
@@ -235,6 +238,53 @@ export const classifyAndHashRootForInventory = async (
return outcome.value;
};
type DenoPresentProbe = Extract<
Awaited<ReturnType<ArtifactEmbeddedFormatProbes["denoStandalone"]>>,
{ readonly status: "present" }
>;
export type EmbeddedExecutablePackage =
| { readonly format: "deno-standalone"; readonly probe: DenoPresentProbe }
| { readonly format: "node-sea"; readonly location: NodeSeaLocation }
| {
readonly format: "bun-standalone";
readonly probe: Extract<
BunStandaloneProbe,
{ readonly status: "present" }
>;
}
| { readonly format: "dotnet-bundle"; readonly headerOffset: number }
| { readonly format: "pyinstaller"; readonly cookie: PyInstallerCookie };
/**
* Executable-branch package order for a native image.
* Root classification and release-exposure probing both use this decision.
*/
export const classifyEmbeddedExecutablePackage = async (
probes: ArtifactEmbeddedFormatProbes,
nativeFormat: string,
signal?: AbortSignal,
): Promise<EmbeddedExecutablePackage | undefined> => {
const sea = await probes.nodeSea();
abortIfNeeded(signal);
if (sea !== undefined) return { format: "node-sea", location: sea };
const bun = await probes.bunStandalone();
if (bun.status === "present") return { format: "bun-standalone", probe: bun };
const deno = await probes.denoStandalone();
if (deno.status === "present")
return { format: "deno-standalone", probe: deno };
const packaged = await probes.pyInstaller();
abortIfNeeded(signal);
if (nativeFormat !== "mach-o-universal") {
const headerOffset = await probes.dotnetBundle();
if (headerOffset !== undefined)
return { format: "dotnet-bundle", headerOffset };
}
if (packaged !== undefined)
return { format: "pyinstaller", cookie: packaged };
return undefined;
};
const classifyRootFormat = async (
path: string,
source: RootInventorySource,
@@ -374,42 +424,47 @@ const classifyRootFormat = async (
)
return zipRootPackageFormat(lower);
if (["elf", "pe", "mach-o", "mach-o-universal"].includes(format)) {
const sea = await embeddedProbes.nodeSea();
abortIfNeeded(signal);
if (sea !== undefined) {
const embedded = await classifyEmbeddedExecutablePackage(
embeddedProbes,
format,
signal,
);
if (embedded?.format === "node-sea") {
const decoded = await decodeNodeSeaBlob(
await readNodeSeaBlob(source, sea, signal, readerLimits.node_sea),
await readNodeSeaBlob(
source,
embedded.location,
signal,
readerLimits.node_sea,
),
signal,
readerLimits.node_sea,
);
return {
kind: "node-sea",
source,
location: sea,
location: embedded.location,
decoded,
limits: readerLimits.node_sea,
};
}
const bun = await embeddedProbes.bunStandalone();
if (bun.status === "present")
return { kind: "bun-standalone", source, probe: bun };
const deno = await embeddedProbes.denoStandalone();
if (deno.status === "present")
return { kind: "deno-standalone", source, probe: deno };
const packaged = await embeddedProbes.pyInstaller();
abortIfNeeded(signal);
if (format !== "mach-o-universal") {
const headerOffset = await embeddedProbes.dotnetBundle();
if (headerOffset !== undefined)
return { kind: "dotnet-bundle", source, headerOffset };
}
if (embedded?.format === "bun-standalone")
return { kind: "bun-standalone", source, probe: embedded.probe };
if (embedded?.format === "deno-standalone")
return { kind: "deno-standalone", source, probe: embedded.probe };
if (embedded?.format === "dotnet-bundle")
return {
kind: "dotnet-bundle",
source,
headerOffset: embedded.headerOffset,
};
// A valid cookie also proves enough bytes for a thin Mach-O identity;
// PE and universal Mach-O classification already require stronger proof.
if (packaged !== undefined)
if (embedded?.format === "pyinstaller")
return {
kind: "pyinstaller",
source,
cookie: packaged,
cookie: embedded.cookie,
carrierPathDialect: format === "pe" ? "windows" : "posix",
};
}
+1
View File
@@ -170,6 +170,7 @@ const scanCanonical = async (
options.signal,
options.integrity,
options.asarHeaderAdmission,
options.acquisitionLimits,
);
outcome = {
kind: "completed",
@@ -1,4 +1,5 @@
import { expect, it } from "vitest";
import { Readable } from "node:stream";
import {
ArtifactEntryContentUnavailable,
ArtifactReaderFailure,
@@ -7,6 +8,70 @@ import {
} from "../ArtifactReader.js";
import { scanReader } from "./scanReader.js";
it.each(["entries", "declared bytes", "unknown bytes", "understated bytes"])(
"bounds inventory acquisition by %s and retains completed members",
async (scenario) => {
let opened = 0;
let chunks = 0;
let returned = false;
const reader: ArtifactReader = {
format: "asar",
async *entries() {
try {
yield entry;
yield {
...entry,
path: "large",
declaredSize:
scenario === "unknown bytes"
? null
: scenario === "declared bytes"
? 10
: 1,
};
throw new Error("traversal must stop before the next entry");
} finally {
returned = true;
}
},
async open(member) {
opened += 1;
if (member.path === "member") return Readable.from([Buffer.from("x")]);
return Readable.from(
(async function* () {
for (let index = 0; index < 100; index += 1) {
chunks += 1;
yield Buffer.alloc(2);
}
})(),
{ highWaterMark: 1 },
);
},
provenance: () => [],
async close() {},
};
const result = await scanReader(
reader,
[reader],
undefined,
"fail",
undefined,
{
maximumEntries: scenario === "entries" ? 1 : 10,
maximumBytes: 2,
},
);
expect(result.occurrences).toHaveLength(1);
expect(result.occurrences[0]?.hash_status).toBe("verified");
expect(result.traversal.status).toBe("unknown");
expect(opened).toBe(
scenario === "entries" || scenario === "declared bytes" ? 1 : 2,
);
expect(chunks).toBeLessThanOrEqual(2);
expect(returned).toBe(true);
},
);
const entry: ArtifactEntry = {
path: "member",
kind: "file",
+65 -8
View File
@@ -22,7 +22,12 @@ import {
type ArtifactReaderTraversal,
} from "../ArtifactReader.js";
import { ArtifactTraversalObservation } from "../ArtifactTraversalObservation.js";
import { DirectoryArtifactEntryAccessDenied } from "../DirectoryArtifactReader.js";
import {
DirectoryArtifactEntryAccessDenied,
DirectoryArtifactReader,
DirectoryArtifactTraversalLimit,
} from "../DirectoryArtifactReader.js";
import type { ArtifactInventoryOptions } from "./types.js";
import { AsarArtifactReader } from "../AsarArtifactReader.js";
import {
InesArtifactReader,
@@ -57,6 +62,9 @@ const emptyScan = (): {
} => ({ nodes: new Map(), occurrences: [], pendingContradictions: [] });
interface ScanContext {
readonly acquisitionLimits: ArtifactInventoryOptions["acquisitionLimits"];
entriesExamined: number;
bytesRead: number;
readonly reader: ArtifactReader;
readonly signal: AbortSignal | undefined;
readonly integrity: ArtifactIntegrityPolicyName;
@@ -84,6 +92,7 @@ export const scanReader = async (
signal?: AbortSignal,
integrity: ArtifactIntegrityPolicyName = "fail",
asarHeaderAdmission?: AsarHeaderAdmission,
acquisitionLimits?: ArtifactInventoryOptions["acquisitionLimits"],
): Promise<{
readonly nodes: Map<string, ArtifactNode>;
readonly occurrences: MutableOccurrence[];
@@ -111,6 +120,9 @@ export const scanReader = async (
rootContradiction: undefined,
};
const context: ScanContext = {
acquisitionLimits,
entriesExamined: 0,
bytesRead: 0,
reader,
signal,
integrity,
@@ -175,6 +187,15 @@ const containerContradiction = (
return pair;
};
class InventoryAcquisitionLimit extends ArtifactReaderFailure {
constructor() {
super(
"limit",
"Artifact inventory acquisition allowance exhausted; member coverage is incomplete.",
);
}
}
const inventoryEntries = (
context: ScanContext,
reader: ArtifactReader,
@@ -183,6 +204,14 @@ const inventoryEntries = (
reader
.entries(context.signal, {
onCoverage: context.traversal.onCoverage,
...(reader instanceof DirectoryArtifactReader &&
context.acquisitionLimits !== undefined
? {
maximumEntries:
context.acquisitionLimits.maximumEntries -
context.entriesExamined,
}
: {}),
onOmission: (omission) =>
context.traversal.onOmission({
...omission,
@@ -221,6 +250,12 @@ const visitArtifactEntries = async (
continue;
}
const entry = next.value;
if (
context.acquisitionLimits !== undefined &&
context.entriesExamined >= context.acquisitionLimits.maximumEntries
)
throw new InventoryAcquisitionLimit();
context.entriesExamined += 1;
const logicalPath = normalizeArtifactPath(
frame.prefix.length === 0
? entry.path
@@ -330,7 +365,15 @@ const visitArtifactEntries = async (
}
}
} catch (cause: unknown) {
failure = { cause };
if (
cause instanceof InventoryAcquisitionLimit ||
cause instanceof DirectoryArtifactTraversalLimit
)
context.traversal.onCoverage({
status: "unknown",
limitations: [cause.message],
});
else failure = { cause };
} finally {
// Readers remain owned by the inventory until its complete observation is built.
for (const { iterator, prefix, reader } of stack.reverse()) {
@@ -368,6 +411,13 @@ const digestArtifactEntry = async (
> => {
if ((entry.kind !== "file" && entry.kind !== "slice") || entry.encrypted)
return undefined;
if (
context.acquisitionLimits !== undefined &&
entry.declaredSize !== null &&
entry.declaredSize >
context.acquisitionLimits.maximumBytes - context.bytesRead
)
throw new InventoryAcquisitionLimit();
const reconstruction =
currentReader === context.reader ? context.reconstruction : undefined;
if (reconstruction !== undefined && entry.byteOffset !== reconstruction.bytes)
@@ -377,12 +427,19 @@ const digestArtifactEntry = async (
context.signal,
entry.declaredIntegrity?.algorithm,
context.asarHeaderAdmission,
reconstruction === undefined
? undefined
: (chunk) => {
reconstruction.hash.update(chunk);
reconstruction.bytes += chunk.length;
},
(chunk) => {
if (
context.acquisitionLimits !== undefined &&
chunk.length >
context.acquisitionLimits.maximumBytes - context.bytesRead
)
throw new InventoryAcquisitionLimit();
context.bytesRead += chunk.length;
if (reconstruction !== undefined) {
reconstruction.hash.update(chunk);
reconstruction.bytes += chunk.length;
}
},
);
reconstruction?.regionOrder.push(entry.path);
const claim = entry.declaredIntegrity;
+7
View File
@@ -6,6 +6,13 @@ import type { ArtifactReaderLimits } from "../../domain/artifactReaderLimits.js"
/** Options shared by artifact inventory scans. */
export interface ArtifactInventoryOptions {
/** Optional acquisition bounds; exhaustion retains a partial inventory. */
readonly acquisitionLimits?:
| {
readonly maximumEntries: number;
readonly maximumBytes: number;
}
| undefined;
readonly readerLimits?: ArtifactReaderLimits | undefined;
readonly resourceScope: ArtifactResourceScope;
/** Identity of a previously admitted file root; directory roots have no file digest. */
+2
View File
@@ -14,6 +14,7 @@ import { snapshotEnvironment } from "./process/snapshotEnvironment.js";
import { createDirectAnalysis } from "./composition/directAnalysis.js";
import { registerEvmCommands } from "./cli/evmCommands.js";
import { registerDesktopApplicationCommands } from "./cli/desktopApplicationCommands.js";
import { registerReleaseExposureCommands } from "./cli/releaseExposureCommands.js";
import { registerGoCommands } from "./cli/goCommands.js";
import { registerModelCommands } from "./cli/modelCommands.js";
import { registerIl2cppCommands } from "./cli/il2cppCommands.js";
@@ -195,6 +196,7 @@ export const createCli = (
registerSignalCommands(cli, logger, environment);
registerEvmCommands(cli, logger, environment);
registerDesktopApplicationCommands(cli, logger);
registerReleaseExposureCommands(cli, logger, environment);
registerGoCommands(cli, logger);
registerIl2cppCommands(cli, logger);
registerModelCommands(cli, logger);
+87
View File
@@ -0,0 +1,87 @@
import { z } from "incur";
import type { Logger } from "pino";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { createReleaseExposureService } from "../composition/releaseExposure.js";
import { localPathStringSchema } from "../domain/localPath.js";
import {
auditReleaseExposureInputSchema,
exposureMeetsFailOn,
releaseExposureReportSchema,
} from "../domain/releaseExposure.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js";
import { cliDecimalField } from "./options.js";
import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js";
import type { CliInstance } from "./types.js";
/** Report what static analysis recovers from one shipped artifact. */
export const registerReleaseExposureCommands = (
cli: CliInstance,
logger: Logger,
environment: Readonly<Record<string, string | undefined>>,
): void => {
cli.command(CLI_COMMANDS.auditReleaseExposure, {
description:
"Report what static analysis of a shipped artifact recovers. Reads the selected path. When the selection is a file, the parent directory is listed for sibling .pdb, .dSYM, .debug, and .map debug companions.",
args: z.object({
path: localPathStringSchema.describe(
"Shipped .app bundle, install directory, ASAR, or executable",
),
}),
options: z.object({
fail_on: z
.enum(["high", "medium", "low"])
.optional()
.describe(
"Completed audit exits 3 when an exposed check meets this severity. Unknown and unassessed checks do not.",
),
maxFileBytes: cliDecimalField(
auditReleaseExposureInputSchema.shape.max_file_bytes,
),
}),
run: ({ args, options }) =>
withCommandCancellation(async (signal) => {
const service = createReleaseExposureService(environment);
return await logCliCommand(
logger,
CLI_COMMANDS.auditReleaseExposure,
async () => {
const projected = await finishCliEvidenceCommand(
args.path,
() =>
service.inspect(
{
path: absoluteCallerPath(args.path),
max_file_bytes: options.maxFileBytes,
},
{ signal },
),
service,
"rea-release-exposure",
"audit_release_exposure",
signal,
).then(projectCliAnalysisResult);
if (
options.fail_on !== undefined &&
projected !== null &&
typeof projected === "object" &&
"normalized_result" in projected
) {
const report = releaseExposureReportSchema.safeParse(
projected.normalized_result,
);
if (
report.success &&
exposureMeetsFailOn(report.data, options.fail_on)
)
process.exitCode = 3;
}
return projected;
},
);
}),
});
};
+1
View File
@@ -66,6 +66,7 @@ export const CLI_COMMANDS = Object.freeze({
debugWithRizin: "debug-with-rizin",
inspectDesktopApplication: "inspect-desktop-application",
auditReleaseExposure: "audit-release-exposure",
inspectGoBinary: "inspect-go-binary",
inspectIl2cppMetadata: "inspect-il2cpp-metadata",
inspectModelArtifact: "inspect-model-artifact",
@@ -45,6 +45,7 @@ import {
PE_IMPORTS_PROVIDER,
PE_LOAD_CONFIG_PROVIDER,
PE_RESOURCES_PROVIDER,
RELEASE_EXPOSURE_PROVIDER,
WEB_SCRIPT_EXPORT_PROVIDER,
WINDOWS_SHORTCUT_PROVIDER,
} from "../domain/investigationProviders.js";
@@ -479,6 +480,13 @@ export const CAPABILITY_DECLARATIONS = {
}),
],
},
releaseExposure: {
providers: [
providerBinding(RELEASE_EXPOSURE_PROVIDER, {
group: "RELEASE_EXPOSURE_TOOL_CONTRACTS",
}),
],
},
v8CodeCache: {
providers: [
providerBinding(V8_CODE_CACHE_PROVIDER_IDENTITY, {
+4
View File
@@ -34,6 +34,7 @@ import { createV8CodeCacheService } from "./v8CodeCache.js";
import { createModelArtifactService } from "./model.js";
import { createIl2cppMetadataService } from "./il2cpp.js";
import { createElectronFuseService } from "./electronFuses.js";
import { createReleaseExposureService } from "./releaseExposure.js";
import { createPythonPycService } from "./pythonPyc.js";
import { createWebNetworkCaptureService } from "./webNetworkCaptures.js";
import { createWebSourceLocationService } from "./webSourceLocations.js";
@@ -380,6 +381,9 @@ const modules = {
electronFuses: service(
({ options }) => options.electronFuses ?? createElectronFuseService(),
),
releaseExposure: service(({ environment, settings }) =>
createReleaseExposureService(environment, settings),
),
pythonPyc: service(
({ options }) => options.pythonPyc ?? createPythonPycService(),
),
+27
View File
@@ -0,0 +1,27 @@
import type { AnalysisSettingsReader } from "../domain/analysisSettings.js";
import { runtimeAsarHeaderAdmission } from "../config/runtimeAnalysisSettings.js";
import { ReleaseExposureReader } from "../artifacts/ReleaseExposureReader.js";
import { ReleaseExposureService } from "../application/releaseExposure/ReleaseExposureService.js";
import { createDesktopApplicationService } from "./desktop.js";
import { createElectronFuseService } from "./electronFuses.js";
import { createGoBinaryService } from "./go.js";
import { createRustBinaryService } from "./rust.js";
/**
* Compose the read-only release-exposure audit. The reader admits ASAR
* headers under the shared REA_ASAR_MAX_HEADER_BYTES and runtime
* asar.max_header_bytes admission, like every other ASAR owner.
*/
export const createReleaseExposureService = (
environment: Readonly<Record<string, string | undefined>> = process.env,
settings?: AnalysisSettingsReader,
): ReleaseExposureService =>
new ReleaseExposureService({
reader: new ReleaseExposureReader(
runtimeAsarHeaderAdmission(environment, settings),
),
electronFuses: createElectronFuseService(),
desktop: createDesktopApplicationService(),
goBinaries: createGoBinaryService(),
rustBinaries: createRustBinaryService(),
});
@@ -0,0 +1,26 @@
import {
auditReleaseExposureInputSchema,
releaseExposureReportSchema,
} from "../domain/releaseExposure.js";
import type { ToolContract } from "./toolContractTypes.js";
import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemaPrimitives.js";
/** Read-only report of what static analysis recovers from one shipped artifact. */
export const RELEASE_EXPOSURE_TOOL_CONTRACTS = [
{
name: "audit_release_exposure",
...toolContractMetadata("audit_release_exposure"),
kind: "artifact-provider",
description:
"Report what static analysis of a shipped application artifact recovers. Accepts one local .app bundle, installation directory, ASAR, or executable. Each check has a stable id, a status, the observation behind it, and fixed remediation text. Unknown and unassessed checks stay in the report. This does not establish that an application is secure. Reads the selected artifact. When the selection is a file, the parent directory is listed for sibling .pdb, .dSYM, .debug, and .map debug companions.",
inputSchema: auditReleaseExposureInputSchema,
outputSchema: evidenceResultOf(releaseExposureReportSchema),
examples: [
{
title: "Audit a shipped application",
input: { path: "/artifacts/MyApp.app" },
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -19,6 +19,7 @@ import { ANALYSIS_VIEW_TOOL_CONTRACTS } from "./analysisViewToolContracts.js";
import { BINARY_DIAGNOSTICS_TOOL_CONTRACTS } from "./native/binaryDiagnosticsToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "./native/nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { RELEASE_EXPOSURE_TOOL_CONTRACTS } from "./releaseExposureToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "./managed/managedToolContracts.js";
import { FIRMWARE_TOOL_CONTRACTS } from "./firmware/firmwareToolContracts.js";
import { ANDROID_TOOL_CONTRACTS } from "./android/androidToolContracts.js";
@@ -55,6 +56,7 @@ export const TOOL_CONTRACTS = [
...BINARY_DIAGNOSTICS_TOOL_CONTRACTS,
...ANALYSIS_VIEW_TOOL_CONTRACTS,
...ARTIFACT_TOOL_CONTRACTS,
...RELEASE_EXPOSURE_TOOL_CONTRACTS,
...DESKTOP_APPLICATION_TOOL_CONTRACTS,
...EVM_TOOL_CONTRACTS,
...GO_TOOL_CONTRACTS,
+5
View File
@@ -734,6 +734,11 @@ const TOOL_EFFECT_AUDIT: Readonly<Record<string, EffectAudit>> = {
launchesProcess: true,
}),
inspect_electron_fuses: evidence,
audit_release_exposure: effects({
mutatesSession: true,
launchesProcess: true,
writesFilesystem: true,
}),
export_web_scripts: effects({
mutatesSession: true,
writesFilesystem: true,
+3
View File
@@ -16,6 +16,7 @@ import { REVERSE_ENGINEERING_TOOL_CONTRACTS } from "./reverseEngineeringToolCont
import { GDB_TOOL_CONTRACTS } from "./gdbToolContracts.js";
import { RIZIN_DEBUG_TOOL_CONTRACTS } from "./rizinDebugToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { RELEASE_EXPOSURE_TOOL_CONTRACTS } from "./releaseExposureToolContracts.js";
import { APK_SIGNATURE_TOOL_CONTRACTS } from "./apkSignature/apkSignatureToolContracts.js";
import { ERLANG_BEAM_TOOL_CONTRACTS } from "./erlang/beamToolContracts.js";
import { V8_CODE_CACHE_TOOL_CONTRACTS } from "./v8/v8CodeCacheToolContracts.js";
@@ -90,6 +91,7 @@ export const TOOL_CONTRACT_GROUPS = {
OFFICIAL_TOOL_CONTRACTS,
PCAP_TOOL_CONTRACTS,
PYTHON_PYC_TOOL_CONTRACTS,
RELEASE_EXPOSURE_TOOL_CONTRACTS,
REVERSE_ENGINEERING_TOOL_CONTRACTS,
RIZIN_DEBUG_TOOL_CONTRACTS,
RUST_TOOL_CONTRACTS,
@@ -145,6 +147,7 @@ export const TOOL_FAMILY_DEFINITIONS = [
surface: "artifact-provider",
contracts: [
...TOOL_CONTRACT_GROUPS.ARTIFACT_TOOL_CONTRACTS,
...TOOL_CONTRACT_GROUPS.RELEASE_EXPOSURE_TOOL_CONTRACTS,
...TOOL_CONTRACT_GROUPS.DESKTOP_APPLICATION_TOOL_CONTRACTS,
...TOOL_CONTRACT_GROUPS.EVM_TOOL_CONTRACTS,
...TOOL_CONTRACT_GROUPS.GO_TOOL_CONTRACTS,
+7 -1
View File
@@ -10,14 +10,20 @@ export class AnalysisUnsupportedTargetError extends AnalysisError {
readonly _tag = "AnalysisUnsupportedTargetError";
/** Refusal-specific recovery, when the producer knows an available workflow. */
readonly remediationAction: string | undefined;
/** The target holds the content, so unsupported does not make it inapplicable. */
readonly undecodedContent: boolean;
constructor(
readonly operation: string,
readonly path: string,
readonly reason: string,
options?: AnalysisErrorOptions & { readonly remediationAction?: string },
options?: AnalysisErrorOptions & {
readonly remediationAction?: string;
readonly undecodedContent?: boolean;
},
) {
super(`Unsupported target for ${operation} at ${path}: ${reason}`, options);
this.remediationAction = options?.remediationAction;
this.undecodedContent = options?.undecodedContent ?? false;
}
}
+57 -11
View File
@@ -733,27 +733,61 @@ export const parsePeCodeViewFromBuffer = (
fileBytes: Buffer,
peOffset: number,
): PeCodeViewRecord | undefined => {
if (fileBytes.length < peOffset + 24) return undefined;
const result = inspectPeCodeViewFromBuffer(fileBytes, peOffset);
return result.ok ? result.value : undefined;
};
/** Distinguish absent CodeView records from incomplete bounded parsing. */
export const inspectPeCodeViewFromBuffer = (
fileBytes: Buffer,
peOffset: number,
): Result<
PeCodeViewRecord | undefined,
{ readonly kind: "incomplete"; readonly message: string }
> => {
const incomplete = (message: string) =>
err({ kind: "incomplete" as const, message });
if (fileBytes.length < peOffset + 24)
return incomplete("Truncated PE header.");
const coff = readPeCoffHeader(
fileBytes.subarray(peOffset + 4, peOffset + 24),
);
if (!coff.ok) return undefined;
if (!coff.ok) return incomplete(coff.error.message);
const { sectionCount: numberOfSections, optionalHeaderSize } = coff.value;
if (
optionalHeaderSize > 4096 ||
fileBytes.length < peOffset + 24 + optionalHeaderSize
)
return undefined;
return incomplete(
"PE optional header is truncated or exceeds the parsing allowance.",
);
const optionalHeader = fileBytes.subarray(
peOffset + 24,
peOffset + 24 + optionalHeaderSize,
);
const debugDir = peDebugDirectoryEntry(optionalHeader);
if (debugDir === undefined) return undefined;
const fixed = readPeOptionalHeaderFixedFields(optionalHeader);
if (!fixed.ok) return incomplete(fixed.error.message);
const observed = readPeOptionalHeaderDirectory(
optionalHeader,
fixed.value,
6,
);
if (observed.state === "absent") return ok(undefined);
if (observed.state !== "present")
return incomplete("Truncated PE debug directory declaration.");
const { address: debugRva, size: debugSize } = observed.directory;
if (debugRva === 0 && debugSize === 0) return ok(undefined);
if (debugRva === 0 || debugSize < 28 || debugSize % 28 !== 0)
return incomplete("Invalid PE debug directory declaration.");
const debugDir = {
debugRva,
debugSize,
sizeOfHeaders: fixed.value.sizeOfHeaders,
};
const sectionTableOffset = peOffset + 24 + optionalHeaderSize;
const sectionTableSize = numberOfSections * 40;
if (fileBytes.length < sectionTableOffset + sectionTableSize)
return undefined;
return incomplete("Truncated PE section table.");
const sectionTable = fileBytes.subarray(
sectionTableOffset,
sectionTableOffset + sectionTableSize,
@@ -765,17 +799,27 @@ export const parsePeCodeViewFromBuffer = (
debugDir.sizeOfHeaders,
Math.min(debugDir.debugSize, 4096),
);
if (debugFileOffset === undefined || fileBytes.length < debugFileOffset + 28)
return undefined;
if (
debugFileOffset === undefined ||
fileBytes.length < debugFileOffset + debugDir.debugSize
)
return incomplete("PE debug directory is unmapped or truncated.");
const maxDebugBytes = Math.min(
debugDir.debugSize,
fileBytes.length - debugFileOffset,
);
const directory = fileBytes.subarray(
debugFileOffset,
debugFileOffset + maxDebugBytes,
);
let codeViewEntries = 0;
for (let offset = 0; offset < directory.length; offset += 28)
if (directory.readUInt32LE(offset + 12) === 2) codeViewEntries += 1;
for (const {
fileOffset: pointerToRawData,
declaredSize: sizeOfData,
} of peCodeViewDataRanges(
fileBytes.subarray(debugFileOffset, debugFileOffset + maxDebugBytes),
directory,
sectionTable,
numberOfSections,
debugDir.sizeOfHeaders,
@@ -787,9 +831,11 @@ export const parsePeCodeViewFromBuffer = (
Math.min(fileBytes.length, pointerToRawData + sizeOfData),
);
const parsed = parseCodeViewData(codeViewData, sizeOfData);
if (parsed !== undefined) return parsed;
if (parsed !== undefined) return ok(parsed);
}
return undefined;
return codeViewEntries > 0
? incomplete("PE CodeView records could not be decoded completely.")
: ok(undefined);
};
/** CPU family a Mach-O cpu type names, or undefined when it names none here. */
+7
View File
@@ -212,6 +212,13 @@ export const PE_LOAD_CONFIG_PROVIDER = Object.freeze({
version: "1",
} as const);
/** Provider identity for the read-only release exposure audit. */
export const RELEASE_EXPOSURE_PROVIDER = Object.freeze({
id: "rea-release-exposure",
name: "REA release exposure audit",
version: "1",
} as const);
/** Provider identity for portable ELF, PE, and Mach-O hardening inspection. */
export const BINARY_HARDENING_PROVIDER = Object.freeze({
id: "rea-binary-hardening",
@@ -161,6 +161,7 @@ it("shares precise body coordinates and location limits across HTML and SVG", ()
).toEqual([
{
scriptType: "classic",
text: body,
location: { start: { line: 2, column: 30 }, end: { line: 4, column: 0 } },
},
]);
@@ -182,6 +183,7 @@ it("retains exact inline script body coordinates, including unclosed scripts", (
{
scriptType: "classic",
location: { start: { line: 2, column: 8 }, end: { line: 4, column: 0 } },
text: body,
},
]);
const unclosed = `${prefix}${body}`;
@@ -189,6 +191,7 @@ it("retains exact inline script body coordinates, including unclosed scripts", (
{
scriptType: "classic",
location: { start: { line: 2, column: 8 }, end: { line: 4, column: 0 } },
text: body,
},
]);
});
@@ -206,6 +209,7 @@ it("counts every inline body but retains bounded locations", () => {
start: { line: 1, column },
end: { line: 1, column: column + 1 },
},
text: "x",
});
});
@@ -22,6 +22,8 @@ export interface HtmlInlineScript {
readonly scriptType: "classic" | "module";
/** The body's range, between the opening and closing tags. */
readonly location: JavaScriptSourceRange;
/** The body as the HTML parser decoded it. */
readonly text: string;
}
/**
@@ -157,7 +159,7 @@ export const htmlArtifactReferences = (
if (inline !== undefined && scriptType !== null) {
inlineScriptCount += 1;
if (inlineScripts.length < HTML_INLINE_SCRIPT_LOCATION_LIMIT)
inlineScripts.push({ scriptType, location: inline });
inlineScripts.push({ scriptType, ...inline });
}
}
}
@@ -173,22 +175,27 @@ export const htmlArtifactReferences = (
/** Locate a script element's non-blank body; browsers ignore it when src is set. */
const inlineScriptBody = (
node: DefaultTreeAdapterTypes.Element,
): JavaScriptSourceRange | undefined => {
): Pick<HtmlInlineScript, "location" | "text"> | undefined => {
const startTag = node.sourceCodeLocation?.startTag;
if (startTag === undefined) return undefined;
let blank = true;
let text = "";
let end: DefaultTreeAdapterTypes.TextNode["sourceCodeLocation"];
for (const child of node.childNodes) {
if (!defaultTreeAdapter.isTextNode(child)) continue;
if (blank && /\S/u.test(child.value)) blank = false;
text += child.value;
end = child.sourceCodeLocation ?? end;
}
// An unclosed script's element range ends at its opening tag, so the body's
// own text location bounds it.
if (blank || end == null) return undefined;
return {
start: sourcePoint(startTag.endLine, startTag.endCol),
end: sourcePoint(end.endLine, end.endCol),
location: {
start: sourcePoint(startTag.endLine, startTag.endCol),
end: sourcePoint(end.endLine, end.endCol),
},
text,
};
};
+1
View File
@@ -114,6 +114,7 @@ export const desktopPathConventions = (path: string, rootName?: string) => {
electronArchive:
folded.at(-2) === "resources" &&
(name === "app.asar" || name === "default_app.asar"),
electronFramework: folded.includes("electron framework.framework"),
unrealContainer:
(name.endsWith(".pak") || name.endsWith(".utoc")) &&
folded.some(
+5 -13
View File
@@ -1,3 +1,5 @@
import { byteOrderMarkEncoding } from "./textByteOrderMark.js";
export class XmlPlistTextDecodeError extends TypeError {
constructor(
readonly reason:
@@ -15,24 +17,14 @@ export class XmlPlistTextDecodeError extends TypeError {
/** Decode BOM-aware XML plist text and verify any declaration against its bytes. */
export const decodeXmlPlistText = (bytes: Uint8Array): string => {
if (
(bytes[0] === 0xff &&
bytes[1] === 0xfe &&
bytes[2] === 0 &&
bytes[3] === 0) ||
(bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 0xfe && bytes[3] === 0xff)
)
const marked = byteOrderMarkEncoding(bytes);
if (marked === "utf-32")
throw new XmlPlistTextDecodeError(
"unsupported-encoding",
"Unsupported XML encoding: UTF-32. Supported encodings are UTF-8 and BOM-marked UTF-16 in either byte order.",
"UTF-32",
);
const encoding =
bytes[0] === 0xff && bytes[1] === 0xfe
? "utf-16le"
: bytes[0] === 0xfe && bytes[1] === 0xff
? "utf-16be"
: "utf-8";
const encoding = marked ?? "utf-8";
// An ASCII declaration can identify an unsupported legacy encoding before
// its body is incorrectly subjected to UTF-8 validation.
const prolog = encoding === "utf-8" ? asciiXmlDeclaration(bytes) : undefined;
+807
View File
@@ -0,0 +1,807 @@
import { describe, expect, it } from "vitest";
import {
assembleReleaseExposureReport,
exposureMeetsFailOn,
PACKAGED_NATIVE_IMAGES,
RELEASE_EXPOSURE_CHECK_IDS,
RELEASE_EXPOSURE_LIMITATION,
type ReleaseExposureOwnerFacts,
type ReleaseExposureScan,
} from "./releaseExposure.js";
const SHA = "ab".repeat(32);
const scan = (
overrides: Partial<ReleaseExposureScan> = {},
): ReleaseExposureScan => ({
target: {
selected_path: "/work/app",
kind: "directory",
format: "directory",
sha256: null,
},
subject: { path: "/work/app", sha256: SHA, format: "directory" },
native_images: [],
fuse_candidates: [],
source_maps: {
embedded: 0,
without_sources: 0,
unparsed: 0,
skipped: 0,
samples: [],
},
extractable: {
formats: [],
readable_members: 0,
unreadable_members: 0,
samples: [],
},
debug_companions: { paths: [], skipped: 0 },
pdb: { examined: 0, paths: [], failed: 0 },
text_members: { scanned: 1, skipped: 0 },
coverage: "complete",
omitted: [],
limitations: [],
...overrides,
});
const owners = (
overrides: Partial<ReleaseExposureOwnerFacts> = {},
): ReleaseExposureOwnerFacts => ({
electron_family: "not_electron",
fuse_images: [],
go_images: [],
rust_images: [],
credential_markers: { hits: [], omitted_hits: 0 },
...overrides,
});
const reportFor = (
scanned: ReleaseExposureScan = scan(),
ownerFacts: ReleaseExposureOwnerFacts = owners(),
) => assembleReleaseExposureReport(scanned, ownerFacts);
const statusOf = (
report: ReturnType<typeof reportFor>,
id: (typeof RELEASE_EXPOSURE_CHECK_IDS)[number],
) => report.checks.find((check) => check.id === id)?.status;
describe("release exposure checks", () => {
it("keeps the fixed check order and the security limitation", () => {
const report = reportFor();
expect(report.checks.map((check) => check.id)).toEqual([
...RELEASE_EXPOSURE_CHECK_IDS,
]);
expect(report.limitations[0]).toBe(RELEASE_EXPOSURE_LIMITATION);
expect(report.summary.no_exposure_observed_in_assessed_checks).toBe(true);
expect(report.summary.by_status.not_assessed).toBe(3);
expect(report.summary.highest_exposed_severity).toBeNull();
expect(statusOf(report, "native.hardening")).toBe("not_assessed");
expect(statusOf(report, "macho.hardened_runtime")).toBe("not_assessed");
expect(statusOf(report, "android.manifest")).toBe("not_assessed");
});
it("grades shipped source maps separately from embedded sources", () => {
const embedded = reportFor(
scan({
source_maps: {
embedded: 1,
without_sources: 0,
unparsed: 0,
skipped: 0,
samples: ["app.js.map"],
},
}),
);
expect(statusOf(embedded, "javascript.source_map_sources")).toBe("exposed");
expect(embedded.checks[0]?.severity).toBe("high");
expect(embedded.checks[0]?.locations).toEqual([
{ kind: "artifact-path", path: "app.js.map" },
]);
expect(statusOf(embedded, "javascript.source_maps")).toBe("not_observed");
expect(exposureMeetsFailOn(embedded, "high")).toBe(true);
const mapsOnly = reportFor(
scan({
source_maps: {
embedded: 0,
without_sources: 2,
unparsed: 0,
skipped: 0,
samples: ["vendor.js.map"],
},
}),
);
expect(statusOf(mapsOnly, "javascript.source_maps")).toBe("exposed");
expect(mapsOnly.checks[1]?.severity).toBe("medium");
expect(exposureMeetsFailOn(mapsOnly, "high")).toBe(false);
expect(exposureMeetsFailOn(mapsOnly, "medium")).toBe(true);
expect(exposureMeetsFailOn(mapsOnly, "low")).toBe(true);
});
it("leaves an unread map unknown unless a confirmed category is already exposed", () => {
const report = reportFor(
scan({
source_maps: {
embedded: 1,
without_sources: 0,
unparsed: 1,
skipped: 0,
samples: ["app.js.map", "broken.js.map"],
},
}),
);
expect(statusOf(report, "javascript.source_map_sources")).toBe("exposed");
expect(statusOf(report, "javascript.source_maps")).toBe("unknown");
});
});
describe("release exposure fuse and package checks", () => {
it("derives Electron exposure from fuse outcomes and leaves a missing wire unknown only for Electron", () => {
const insecure = reportFor(
scan(),
owners({
electron_family: "electron",
fuse_images: [
{
kind: "report",
role: "app-bundle",
implications: [
{ subject: "electron_run_as_node", outcome: "honored" },
{
subject: "node_cli_inspect_arguments",
outcome: "honored",
},
{
subject: "embedded_asar_integrity_validation",
outcome: "not_enforced",
},
{
subject: "only_load_app_from_asar",
outcome: "not_restricted_to_app_asar",
},
],
},
],
}),
);
expect(statusOf(insecure, "electron.run_as_node")).toBe("exposed");
expect(statusOf(insecure, "electron.node_cli_inspect")).toBe("exposed");
expect(statusOf(insecure, "electron.asar_integrity")).toBe("exposed");
expect(statusOf(insecure, "electron.only_load_from_asar")).toBe("exposed");
expect(insecure.checks[2]?.confidence).toBe("inferred");
expect(insecure.checks[2]?.severity).toBe("high");
const flipped = reportFor(
scan(),
owners({
electron_family: "electron",
fuse_images: [
{
kind: "report",
role: "native-image",
implications: [
{ subject: "electron_run_as_node", outcome: "not_honored" },
{
subject: "node_cli_inspect_arguments",
outcome: "not_honored",
},
{
subject: "embedded_asar_integrity_validation",
outcome: "unknown",
},
{
subject: "only_load_app_from_asar",
outcome: "restricted_to_app_asar",
},
],
},
],
}),
);
expect(statusOf(flipped, "electron.run_as_node")).toBe("not_observed");
expect(statusOf(flipped, "electron.node_cli_inspect")).toBe("not_observed");
expect(statusOf(flipped, "electron.asar_integrity")).toBe("unknown");
expect(statusOf(flipped, "electron.only_load_from_asar")).toBe(
"not_observed",
);
expect(flipped.checks[2]?.severity).toBeNull();
const plain = reportFor(
scan(),
owners({
electron_family: "not_a_directory",
fuse_images: [
{
kind: "report",
role: "native-image",
implications: [],
},
],
}),
);
expect(statusOf(plain, "electron.run_as_node")).toBe("not_applicable");
const bundle = reportFor(
scan(),
owners({
electron_family: "electron",
fuse_images: [
{
kind: "report",
role: "app-bundle",
implications: [],
},
],
}),
);
expect(statusOf(bundle, "electron.run_as_node")).toBe("unknown");
const nativeApp = reportFor(
scan(),
owners({
electron_family: "not_electron",
fuse_images: [
{
kind: "report",
role: "app-bundle",
path: "/work/Native.app",
implications: [],
},
],
}),
);
expect(statusOf(nativeApp, "electron.run_as_node")).toBe("not_applicable");
expect(statusOf(nativeApp, "electron.asar_integrity")).toBe(
"not_applicable",
);
});
});
describe("release exposure fuse sampling", () => {
it.each(["not_a_directory", "not_electron"] as const)(
"keeps fuse applicability unknown for an unread packaged native image under %s",
(family) => {
const report = reportFor(
scan({
omitted: [
{
subject: PACKAGED_NATIVE_IMAGES,
count: 1,
reason: "stored inside a package",
},
],
}),
owners({
electron_family: family,
fuse_images: [
{ kind: "report", role: "native-image", implications: [] },
],
}),
);
expect(statusOf(report, "electron.run_as_node")).toBe("unknown");
},
);
it("keeps a directly selected Electron executable observed when its fuses are safe", () => {
const safe = reportFor(
scan({
target: {
selected_path: "/work/MyApp.exe",
kind: "executable",
format: "pe",
sha256: SHA,
},
}),
owners({
electron_family: "not_a_directory",
fuse_images: [
{
kind: "report",
role: "native-image",
path: "/work/MyApp.exe",
implications: [
{ subject: "electron_run_as_node", outcome: "not_honored" },
{
subject: "node_cli_inspect_arguments",
outcome: "not_honored",
},
{
subject: "embedded_asar_integrity_validation",
outcome: "enforced",
},
{
subject: "only_load_app_from_asar",
outcome: "restricted_to_app_asar",
},
],
},
],
}),
);
expect(statusOf(safe, "electron.run_as_node")).toBe("not_observed");
expect(statusOf(safe, "electron.asar_integrity")).toBe("not_observed");
const uncertain = reportFor(
scan(),
owners({
electron_family: "not_a_directory",
fuse_images: [
{
kind: "report",
role: "native-image",
implications: [
{ subject: "electron_run_as_node", outcome: "unknown" },
],
},
],
}),
);
expect(statusOf(uncertain, "electron.run_as_node")).toBe("unknown");
const failed = reportFor(
scan(),
owners({
electron_family: "not_a_directory",
fuse_images: [
{
kind: "failed",
role: "native-image",
path: "/work/MyApp.exe",
reason: "inspect_electron_fuses failed",
},
],
}),
);
expect(statusOf(failed, "electron.run_as_node")).toBe("unknown");
expect(
failed.checks.find((check) => check.id === "electron.run_as_node")
?.observation.samples,
).toContain("inspect_electron_fuses failed");
});
});
describe("release exposure unread fuse images", () => {
it("does not treat a partial native sample as an absent fuse", () => {
const sampled = scan({
omitted: [
{
subject: "native images",
count: 1,
reason:
"Only 4 native images are passed to language and fuse readers.",
},
],
});
const implications = [
{ subject: "electron_run_as_node", outcome: "not_honored" },
];
const omitted = reportFor(
sampled,
owners({
electron_family: "electron",
fuse_images: [{ kind: "report", role: "native-image", implications }],
}),
);
expect(statusOf(omitted, "electron.run_as_node")).toBe("unknown");
const included = reportFor(
sampled,
owners({
electron_family: "electron",
electron_executable_included: true,
fuse_images: [{ kind: "report", role: "native-image", implications }],
}),
);
expect(statusOf(included, "electron.run_as_node")).toBe("not_observed");
});
it("does not treat a packaged native image as an absent fuse, even once the host was read", () => {
const packaged = scan({
omitted: [
{
subject: PACKAGED_NATIVE_IMAGES,
count: 1,
reason: "Fuse readers run on files on disk.",
},
],
});
const fuseFacts = {
electron_family: "unknown" as const,
fuse_images: [
{
kind: "report" as const,
role: "native-image" as const,
implications: [
{ subject: "electron_run_as_node", outcome: "not_honored" },
],
},
],
};
expect(
statusOf(
reportFor(
packaged,
owners({ ...fuseFacts, electron_executable_included: false }),
),
"electron.run_as_node",
),
).toBe("unknown");
expect(
statusOf(
reportFor(
packaged,
owners({ ...fuseFacts, electron_executable_included: true }),
),
"electron.run_as_node",
),
).toBe("unknown");
});
it("does not treat a partial desktop layout list as an absent fuse", () => {
const fuseFacts = {
electron_family: "electron" as const,
electron_executable_included: true,
fuse_images: [
{
kind: "report" as const,
role: "native-image" as const,
implications: [
{ subject: "electron_run_as_node", outcome: "not_honored" },
],
},
],
};
expect(
statusOf(
reportFor(
scan({}),
owners({ ...fuseFacts, electron_layouts_complete: false }),
),
"electron.run_as_node",
),
).toBe("unknown");
expect(
statusOf(reportFor(scan({}), owners(fuseFacts)), "electron.run_as_node"),
).toBe("not_observed");
});
it("does not treat incomplete inventory as an absent fuse", () => {
const fuseFacts = {
electron_family: "electron" as const,
fuse_images: [
{
kind: "report" as const,
role: "native-image" as const,
implications: [
{ subject: "electron_run_as_node", outcome: "not_honored" },
],
},
],
};
const incomplete = scan({ coverage: "unknown" });
expect(
statusOf(
reportFor(incomplete, owners(fuseFacts)),
"electron.run_as_node",
),
).toBe("unknown");
expect(
statusOf(
reportFor(
incomplete,
owners({ ...fuseFacts, electron_executable_included: true }),
),
"electron.run_as_node",
),
).toBe("not_observed");
});
});
describe("release exposure package checks", () => {
it("treats readable package members as inherent exposure and skips encrypted members", () => {
const exposed = reportFor(
scan({
target: {
selected_path: "/work/app.asar",
kind: "asar",
format: "asar",
sha256: SHA,
},
extractable: {
formats: ["asar"],
readable_members: 2,
unreadable_members: 0,
samples: ["app.js"],
},
}),
);
expect(statusOf(exposed, "packaging.extractable_payload")).toBe("exposed");
expect(
exposed.checks.find(
(check) => check.id === "packaging.extractable_payload",
)?.severity,
).toBe("low");
expect(exposureMeetsFailOn(exposed, "medium")).toBe(false);
expect(exposureMeetsFailOn(exposed, "low")).toBe(true);
const sealed = reportFor(
scan({
extractable: {
formats: ["asar"],
readable_members: 0,
unreadable_members: 3,
samples: [],
},
}),
);
expect(statusOf(sealed, "packaging.extractable_payload")).toBe("unknown");
const unread = reportFor(
scan({
extractable: {
formats: [],
readable_members: 0,
unreadable_members: 1,
samples: [],
},
}),
);
expect(statusOf(unread, "packaging.extractable_payload")).toBe("unknown");
});
});
describe("release exposure native and text checks", () => {
it("reports debug companions and CodeView paths separately from source maps", () => {
const report = reportFor(
scan({
debug_companions: { paths: ["/work/app.pdb"], skipped: 0 },
pdb: {
examined: 1,
paths: ["C:\\build\\app.pdb"],
image_paths: ["/work/app.exe"],
failed: 0,
},
}),
);
expect(statusOf(report, "native.debug_companions")).toBe("exposed");
expect(
report.checks.find((check) => check.id === "native.debug_companions")
?.locations,
).toEqual([{ kind: "artifact-path", path: "/work/app.pdb" }]);
expect(statusOf(report, "native.pdb_path")).toBe("exposed");
const pdb = report.checks.find((check) => check.id === "native.pdb_path");
expect(pdb?.locations).toEqual([
{ kind: "artifact-path", path: "/work/app.exe" },
]);
expect(pdb?.observation.samples).toContain("C:\\build\\app.pdb");
expect(
report.checks.find((check) => check.id === "native.pdb_path")?.severity,
).toBe("low");
});
it("keeps null Go and Rust metadata unknown and unsupported images inapplicable", () => {
const unknown = reportFor(
scan(),
owners({
go_images: [{ kind: "absent" }],
rust_images: [{ kind: "absent" }],
}),
);
expect(statusOf(unknown, "go.build_paths")).toBe("unknown");
expect(statusOf(unknown, "rust.dependency_metadata")).toBe("unknown");
const exposed = reportFor(
scan(),
owners({
go_images: [
{ kind: "paths", path: "/work/app", paths: ["/home/dev/main.go"] },
],
rust_images: [{ kind: "packages", packages: ["app"] }],
}),
);
expect(statusOf(exposed, "go.build_paths")).toBe("exposed");
const go = exposed.checks.find((check) => check.id === "go.build_paths");
expect(go?.locations).toEqual([
{ kind: "artifact-path", path: "/work/app" },
]);
expect(go?.observation.samples).toContain("/home/dev/main.go");
expect(statusOf(exposed, "rust.dependency_metadata")).toBe("exposed");
const omitted = reportFor(
scan({
coverage: "unknown",
omitted: [
{
subject: "native images",
count: 2,
reason: "later native images were dropped",
},
],
}),
owners({
go_images: [{ kind: "unsupported" }],
rust_images: [],
}),
);
expect(statusOf(omitted, "go.build_paths")).toBe("unknown");
expect(statusOf(omitted, "rust.dependency_metadata")).toBe("unknown");
const other = reportFor(
scan(),
owners({
go_images: [{ kind: "unsupported" }],
rust_images: [{ kind: "unsupported" }],
}),
);
expect(statusOf(other, "go.build_paths")).toBe("not_applicable");
expect(statusOf(other, "rust.dependency_metadata")).toBe("not_applicable");
});
it("reports credential rule locations and never stores matched bytes", () => {
const planted = "release-exposure-planted-secret-7c2e9a";
const report = reportFor(
scan(),
owners({
credential_markers: {
hits: [{ rule_id: "pem.private_key", path: "config.txt", line: 2 }],
omitted_hits: 0,
},
}),
);
expect(statusOf(report, "text.credential_markers")).toBe("exposed");
expect(
report.checks.find((check) => check.id === "text.credential_markers")
?.locations,
).toEqual([{ kind: "artifact-path", path: "config.txt" }]);
const serialized = JSON.stringify(report);
expect(serialized).not.toContain(planted);
expect(serialized).toContain("pem.private_key config.txt:2");
expect(exposureMeetsFailOn(report, "high")).toBe(true);
});
});
describe("release exposure gate and undecided checks", () => {
it("does not let unknown or unassessed checks trip the gate", () => {
const report = reportFor(
scan({
source_maps: {
embedded: 0,
without_sources: 0,
unparsed: 1,
skipped: 0,
samples: ["broken.js.map"],
},
}),
);
expect(report.summary.by_status.unknown).toBeGreaterThan(0);
expect(report.summary.by_status.not_assessed).toBe(3);
expect(exposureMeetsFailOn(report, "low")).toBe(false);
expect(report.summary.no_exposure_observed_in_assessed_checks).toBe(true);
});
it("does not treat an unscanned text member as an absent credential", () => {
const report = reportFor(
scan({ text_members: { scanned: 0, skipped: 0 } }),
);
expect(statusOf(report, "text.credential_markers")).toBe("not_applicable");
const scanned = reportFor();
expect(statusOf(scanned, "text.credential_markers")).toBe("not_observed");
const skipped = reportFor(
scan({ text_members: { scanned: 1, skipped: 1 } }),
);
expect(statusOf(skipped, "text.credential_markers")).toBe("unknown");
});
it("does not report absent CodeView paths when member coverage is unknown", () => {
const report = reportFor(
scan({
pdb: { examined: 1, paths: [], failed: 0 },
coverage: "unknown",
}),
);
expect(statusOf(report, "native.pdb_path")).toBe("unknown");
});
it("keeps Go and Rust unknown while a packaged native image is unexamined", () => {
const report = reportFor(
scan({
omitted: [
{
subject: PACKAGED_NATIVE_IMAGES,
count: 1,
reason: "stored inside a package",
},
],
}),
);
expect(statusOf(report, "go.build_paths")).toBe("unknown");
expect(statusOf(report, "rust.dependency_metadata")).toBe("unknown");
});
it("labels a companion's identity as inferred from its name", () => {
const report = reportFor(
scan({ debug_companions: { paths: ["app.map"], skipped: 0 } }),
);
const check = report.checks.find(
(item) => item.id === "native.debug_companions",
);
expect(check?.status).toBe("exposed");
expect(check?.confidence).toBe("inferred");
});
it("names the real @electron/fuses option on every fuse remediation", () => {
const fuses = reportFor().checks.filter((check) =>
check.id.startsWith("electron."),
);
expect(fuses).toHaveLength(4);
for (const check of fuses) {
expect(check.remediation).toContain("FuseV1Options.");
expect(check.remediation).toContain("@electron/fuses");
expect(check.remediation).not.toContain("ElectronFuseV1");
}
});
});
describe("go.build_paths locations", () => {
it("names only the images that retain build paths", () => {
const report = reportFor(
scan(),
owners({
go_images: [
{ kind: "paths", path: "/work/leaky", paths: ["/home/dev/main.go"] },
{ kind: "paths", path: "/work/clean", paths: [] },
],
}),
);
const go = report.checks.find((check) => check.id === "go.build_paths");
expect(go?.status).toBe("exposed");
expect(go?.locations).toEqual([
{ kind: "artifact-path", path: "/work/leaky" },
]);
});
});
describe("electron host fuses beside other images", () => {
const safeImage = {
kind: "report" as const,
role: "native-image" as const,
path: "/work/app/helper",
implications: [
{ subject: "electron_run_as_node", outcome: "not_honored" },
{ subject: "node_cli_inspect_arguments", outcome: "not_honored" },
{ subject: "embedded_asar_integrity_validation", outcome: "enforced" },
{ subject: "only_load_app_from_asar", outcome: "restricted_to_app_asar" },
],
};
const hostWithoutFuses = {
kind: "report" as const,
role: "native-image" as const,
path: "/work/app/app",
implications: [],
};
const report = (electron_host_paths?: readonly string[]) =>
reportFor(
scan(),
owners({
electron_family: "electron",
electron_executable_included: true,
...(electron_host_paths === undefined ? {} : { electron_host_paths }),
fuse_images: [hostWithoutFuses, safeImage],
}),
);
it("leaves an unresolved host unknown whatever another image reports", () => {
expect(statusOf(report(["/work/app/app"]), "electron.run_as_node")).toBe(
"unknown",
);
});
it("does not let a fuseless helper unsettle the host's safe answer", () => {
expect(statusOf(report(["/work/app/helper"]), "electron.run_as_node")).toBe(
"not_observed",
);
expect(statusOf(report(), "electron.run_as_node")).toBe("not_observed");
});
});
+959
View File
@@ -0,0 +1,959 @@
import { z } from "zod";
import { digestSchema } from "./digests.js";
import { evidenceLocationSchema, type EvidenceLocation } from "./evidence.js";
import {
absoluteLocalPathStringSchema,
localPathStringSchema,
} from "./localPath.js";
/** Selected-file ceiling for one release-exposure audit. */
export const MAX_RELEASE_EXPOSURE_FILE_BYTES = 256 * 1024 * 1024;
/** Members inventoried from one installation or package. */
export const MAX_RELEASE_EXPOSURE_INVENTORY_ENTRIES = 65_536;
/** Bytes hashed while inventorying one installation or package. */
export const MAX_RELEASE_EXPOSURE_INVENTORY_BYTES = 2 * 1024 * 1024 * 1024;
/** Bytes read from one text member. */
export const MAX_RELEASE_EXPOSURE_TEXT_MEMBER_BYTES = 256 * 1024;
/** Bytes read across all text members. */
export const MAX_RELEASE_EXPOSURE_TEXT_BYTES = 4 * 1024 * 1024;
/** Resolved paths retained for HTML script targets across one audit. */
export const MAX_RELEASE_EXPOSURE_SCRIPT_TARGET_BYTES = 1024 * 1024;
/** Resolved paths retained for local source map targets across one audit. */
export const MAX_RELEASE_EXPOSURE_MAP_TARGET_BYTES = 1024 * 1024;
/** Source maps read from one artifact. */
export const MAX_RELEASE_EXPOSURE_SOURCE_MAPS = 32;
/** Bytes read from one source map. */
export const MAX_RELEASE_EXPOSURE_SOURCE_MAP_BYTES = 1024 * 1024;
/** Bytes read to identify a package member that is neither text nor a map. */
export const MAX_RELEASE_EXPOSURE_MEMBER_PROBE_BYTES = 4096;
/** Bytes read from one PE stored inside a package. */
export const MAX_RELEASE_EXPOSURE_PACKAGED_PE_BYTES = 256 * 1024;
/** PE images stored inside packages that are read for debug records. */
export const MAX_RELEASE_EXPOSURE_PACKAGED_PE_READS = 64;
/** Native images passed to Go, Rust, and Electron fuse readers. */
export const MAX_RELEASE_EXPOSURE_NATIVE_IMAGES = 4;
/** Paths, rule ids, and other samples kept on one check. */
export const MAX_RELEASE_EXPOSURE_SAMPLES = 8;
export const RELEASE_EXPOSURE_OPERATION = "audit_release_exposure";
export const RELEASE_EXPOSURE_LIMITATION =
"This report states what static analysis of the selected artifact recovered. It does not establish that the application is secure.";
export const RELEASE_EXPOSURE_ALLOWANCES = [
`Selected file reads stop at ${String(MAX_RELEASE_EXPOSURE_FILE_BYTES)} bytes.`,
`Text member scans read at most ${String(MAX_RELEASE_EXPOSURE_TEXT_MEMBER_BYTES)} bytes each and ${String(MAX_RELEASE_EXPOSURE_TEXT_BYTES)} bytes in total.`,
`HTML script targets keep at most ${String(MAX_RELEASE_EXPOSURE_SCRIPT_TARGET_BYTES)} bytes of resolved paths. Later targets stay unassessed.`,
`Local source map targets keep at most ${String(MAX_RELEASE_EXPOSURE_MAP_TARGET_BYTES)} bytes of resolved paths. Later targets stay unassessed.`,
`Source map scans read at most ${String(MAX_RELEASE_EXPOSURE_SOURCE_MAPS)} maps and ${String(MAX_RELEASE_EXPOSURE_SOURCE_MAP_BYTES)} bytes each. sourcesContent text is counted and then dropped.`,
`Other files and package members are identified from their first ${String(MAX_RELEASE_EXPOSURE_MEMBER_PROBE_BYTES)} bytes, and those without a NUL byte in that prefix are scanned as text. Up to ${String(MAX_RELEASE_EXPOSURE_PACKAGED_PE_READS)} packaged PE images are read for debug records, ${String(MAX_RELEASE_EXPOSURE_PACKAGED_PE_BYTES)} bytes each.`,
"Packaged ELF, Mach-O, and PE images are read in full and copied to a temporary file to probe for an embedded package. They share one max_file_bytes allowance, and an image that does not fit is not probed.",
`Go, Rust, and Electron fuse readers run on at most ${String(MAX_RELEASE_EXPOSURE_NATIVE_IMAGES)} native images.`,
] as const;
export const RELEASE_EXPOSURE_STATUSES = [
"exposed",
"not_observed",
"not_applicable",
"unknown",
"not_assessed",
] as const;
export const RELEASE_EXPOSURE_SEVERITIES = [
"high",
"medium",
"low",
"info",
] as const;
export const RELEASE_EXPOSURE_FAIL_LEVELS = ["high", "medium", "low"] as const;
export const RELEASE_EXPOSURE_CHECK_IDS = [
"javascript.source_map_sources",
"javascript.source_maps",
"electron.run_as_node",
"electron.asar_integrity",
"electron.only_load_from_asar",
"electron.node_cli_inspect",
"packaging.extractable_payload",
"native.debug_companions",
"native.pdb_path",
"go.build_paths",
"rust.dependency_metadata",
"text.credential_markers",
"native.hardening",
"macho.hardened_runtime",
"android.manifest",
] as const;
const statusSchema = z.enum(RELEASE_EXPOSURE_STATUSES);
const severitySchema = z.enum(RELEASE_EXPOSURE_SEVERITIES);
type Status = z.infer<typeof statusSchema>;
type Severity = z.infer<typeof severitySchema>;
export type ReleaseExposureCheckId =
(typeof RELEASE_EXPOSURE_CHECK_IDS)[number];
export type ReleaseExposureFailLevel =
(typeof RELEASE_EXPOSURE_FAIL_LEVELS)[number];
const CHECK_TABLE = {
"javascript.source_map_sources": {
severity: "high",
remediation:
"Ship the release without sourcesContent. Remove the source maps or omit sourcesContent from maps that ship.",
next_probe: null,
},
"javascript.source_maps": {
severity: "medium",
remediation: "Do not ship source maps beside the release.",
next_probe: null,
},
"electron.run_as_node": {
severity: "high",
remediation:
"Set FuseV1Options.RunAsNode to false with @electron/fuses before packaging.",
next_probe: "inspect_electron_fuses",
},
"electron.asar_integrity": {
severity: "medium",
remediation:
"Set FuseV1Options.EnableEmbeddedAsarIntegrityValidation to true with @electron/fuses. Electron compiles this check for macOS and Windows; an ELF byte stays unknown.",
next_probe: "inspect_electron_fuses",
},
"electron.only_load_from_asar": {
severity: "medium",
remediation:
"Set FuseV1Options.OnlyLoadAppFromAsar to true with @electron/fuses so the packaged app loads application code from app.asar.",
next_probe: "inspect_electron_fuses",
},
"electron.node_cli_inspect": {
severity: "medium",
remediation:
"Set FuseV1Options.EnableNodeCliInspectArguments to false with @electron/fuses so the packaged app ignores --inspect.",
next_probe: "inspect_electron_fuses",
},
"packaging.extractable_payload": {
severity: "low",
remediation:
"Readable members are part of this package format. Treat packaged sources as public. This check does not rewrite the artifact.",
next_probe: "inspect_artifact",
},
"native.debug_companions": {
severity: "medium",
remediation:
"Do not ship .pdb, .dSYM, .debug, or linker map files beside the release.",
next_probe: null,
},
"native.pdb_path": {
severity: "low",
remediation:
"Rebuild without a CodeView PDB path, or accept that the path string is recoverable from the PE. The PDB file itself is a separate check.",
next_probe: null,
},
"go.build_paths": {
severity: "low",
remediation:
"Rebuild with -trimpath so file paths are not written into the binary. Module names can remain.",
next_probe: "inspect_go_binary",
},
"rust.dependency_metadata": {
severity: "low",
remediation:
"Omit cargo-auditable metadata from the release if the crate list should not ship.",
next_probe: "inspect_rust_binary",
},
"text.credential_markers": {
severity: "high",
remediation:
"Remove the provider-prefixed credential from the shipped text and rotate it if it is real. This check reports the rule id and location only.",
next_probe: null,
},
"native.hardening": {
severity: "info",
remediation:
"This audit does not assess native hardening. Use inspect_binary_hardening when that tool is available.",
next_probe: "inspect_binary_hardening",
},
"macho.hardened_runtime": {
severity: "info",
remediation:
"This audit does not assess the Mach-O hardened runtime. inspect_signature reads code signatures and would change this tool's effects, so it stays a next probe.",
next_probe: "inspect_signature",
},
"android.manifest": {
severity: "info",
remediation:
"This audit does not read Android manifests. Use inspect_android_package, which needs JADX.",
next_probe: "inspect_android_package",
},
} as const satisfies Record<
ReleaseExposureCheckId,
{
readonly severity: Severity;
readonly remediation: string;
readonly next_probe: string | null;
}
>;
const observationSchema = z.strictObject({
counts: z.record(z.string().min(1), z.int().nonnegative()),
samples: z.array(z.string().min(1)).max(MAX_RELEASE_EXPOSURE_SAMPLES),
});
const releaseExposureCheckSchema = z.strictObject({
id: z.enum(RELEASE_EXPOSURE_CHECK_IDS),
status: statusSchema,
severity: severitySchema.nullable(),
confidence: z.enum(["observed", "inferred"]),
observation: observationSchema,
locations: z.array(evidenceLocationSchema).max(MAX_RELEASE_EXPOSURE_SAMPLES),
remediation: z.string().min(1),
next_probe: z.string().min(1).nullable(),
});
const countSchema = z.strictObject({
exposed: z.int().nonnegative(),
not_observed: z.int().nonnegative(),
not_applicable: z.int().nonnegative(),
unknown: z.int().nonnegative(),
not_assessed: z.int().nonnegative(),
});
const severityCountSchema = z.strictObject({
high: z.int().nonnegative(),
medium: z.int().nonnegative(),
low: z.int().nonnegative(),
info: z.int().nonnegative(),
});
export const releaseExposureReportSchema = z
.strictObject({
target: z.strictObject({
selected_path: localPathStringSchema,
kind: z.enum(["app", "directory", "asar", "executable", "file"]),
format: z.string().min(1),
sha256: digestSchema.nullable(),
}),
checks: z.array(releaseExposureCheckSchema),
summary: z.strictObject({
by_status: countSchema,
by_severity: severityCountSchema,
highest_exposed_severity: severitySchema.nullable(),
no_exposure_observed_in_assessed_checks: z.boolean(),
}),
coverage: z.strictObject({
allowances: z.array(z.string().min(1)),
omitted: z.array(
z.strictObject({
subject: z.string().min(1),
count: z.int().nonnegative(),
reason: z.string().min(1),
}),
),
}),
limitations: z.array(z.string().min(1)),
})
.superRefine((report, context) => {
if (
report.checks.length !== RELEASE_EXPOSURE_CHECK_IDS.length ||
report.checks.some(
(check, index) => check.id !== RELEASE_EXPOSURE_CHECK_IDS[index],
)
)
context.addIssue({
code: "custom",
path: ["checks"],
message: "Checks must be the fixed release-exposure table, in order.",
});
for (const [index, check] of report.checks.entries()) {
const policy = CHECK_TABLE[check.id];
if (
check.remediation !== policy.remediation ||
check.next_probe !== policy.next_probe
)
context.addIssue({
code: "custom",
path: ["checks", index],
message: "Remediation and next probe are fixed per check.",
});
if (check.status === "exposed" && check.severity !== policy.severity)
context.addIssue({
code: "custom",
path: ["checks", index, "severity"],
message: "Exposed severity comes from the check policy.",
});
if (check.status !== "exposed" && check.severity !== null)
context.addIssue({
code: "custom",
path: ["checks", index, "severity"],
message: "Severity is null unless the check is exposed.",
});
}
const summary = summarizeReleaseExposureChecks(report.checks);
if (
JSON.stringify(summary) !== JSON.stringify(report.summary) ||
report.limitations[0] !== RELEASE_EXPOSURE_LIMITATION
)
context.addIssue({
code: "custom",
path: ["summary"],
message: "Summary and the leading limitation do not match the checks.",
});
});
export const auditReleaseExposureInputSchema = z.strictObject({
path: absoluteLocalPathStringSchema.describe(
"Absolute path to a shipped .app bundle, install directory, ASAR, or executable",
),
max_file_bytes: z
.int()
.positive()
.max(MAX_RELEASE_EXPOSURE_FILE_BYTES)
.default(MAX_RELEASE_EXPOSURE_FILE_BYTES)
.describe(
"Selected-file, on-disk PE, and shared packaged-image read ceiling. Text, source-map, and other package members use the smaller allowances in coverage.allowances.",
),
});
export type ReleaseExposureReport = z.infer<typeof releaseExposureReportSchema>;
export type ReleaseExposureCheck = z.infer<typeof releaseExposureCheckSchema>;
export type AuditReleaseExposureInput = z.infer<
typeof auditReleaseExposureInputSchema
>;
export interface ReleaseExposureTargetFact {
readonly selected_path: string;
readonly kind: ReleaseExposureReport["target"]["kind"];
readonly format: string;
readonly sha256: string | null;
}
export interface ReleaseExposureNativeImage {
readonly path: string;
readonly format: "elf" | "mach-o" | "mach-o-universal" | "pe";
/** Digest from inventory, when the audit has one to bind owner reads to. */
readonly sha256?: string;
}
export interface ReleaseExposureFuseCandidate {
readonly path: string;
readonly role: "app-bundle" | "native-image";
}
/** Omission subject for native images stored inside a package. */
export const PACKAGED_NATIVE_IMAGES = "packaged native images";
export interface ReleaseExposureMarkerHit {
readonly rule_id: string;
readonly path: string;
readonly line: number;
}
export interface ReleaseExposureScan {
readonly target: ReleaseExposureTargetFact;
readonly subject: {
readonly path: string;
readonly sha256: string;
readonly format: string;
};
readonly native_images: readonly ReleaseExposureNativeImage[];
readonly fuse_candidates: readonly ReleaseExposureFuseCandidate[];
readonly source_maps: {
readonly embedded: number;
readonly without_sources: number;
readonly unparsed: number;
readonly skipped: number;
readonly samples: readonly string[];
readonly embedded_paths?: readonly string[];
readonly plain_paths?: readonly string[];
};
readonly extractable: {
readonly formats: readonly string[];
readonly readable_members: number;
readonly unreadable_members: number;
readonly samples: readonly string[];
};
readonly debug_companions: {
readonly paths: readonly string[];
readonly skipped: number;
};
readonly pdb: {
readonly examined: number;
readonly paths: readonly string[];
readonly image_paths?: readonly string[];
readonly failed: number;
};
readonly text_members: {
readonly scanned: number;
readonly skipped: number;
};
readonly coverage: "complete" | "unknown";
readonly omitted: readonly {
readonly subject: string;
readonly count: number;
readonly reason: string;
}[];
readonly limitations: readonly string[];
}
export interface FuseImageFact {
readonly kind: "unsupported" | "failed" | "report";
readonly role: "app-bundle" | "native-image";
readonly path?: string;
/** Digest of the file the reader resolved, on a report. */
readonly sha256?: string;
readonly reason?: string;
readonly implications?: readonly {
readonly subject: string;
readonly outcome: string;
}[];
}
export type MetadataImageFact = (
| { readonly kind: "unsupported" }
| { readonly kind: "failed"; readonly reason: string }
| { readonly kind: "absent" }
| {
readonly kind: "paths";
readonly paths: readonly string[];
readonly complete?: boolean;
readonly limitations?: readonly string[];
}
| { readonly kind: "packages"; readonly packages: readonly string[] }
) & { readonly path?: string };
export interface ReleaseExposureOwnerFacts {
readonly electron_family:
| "electron"
| "not_electron"
| "unknown"
| "not_a_directory";
readonly electron_family_reason?: string | null;
readonly electron_executable_included?: boolean;
/** Images named as the Electron host. Others may be helpers with no fuses. */
readonly electron_host_paths?: readonly string[];
/**
* False when desktop discovery stopped before it listed every ASAR layout,
* so a layout it never reached may hold a host whose fuses were not read.
*/
readonly electron_layouts_complete?: boolean;
readonly fuse_images: readonly FuseImageFact[];
readonly go_images: readonly MetadataImageFact[];
readonly rust_images: readonly MetadataImageFact[];
readonly credential_markers: {
readonly hits: readonly ReleaseExposureMarkerHit[];
readonly omitted_hits: number;
};
}
const SEVERITY_RANK: Record<Severity, number> = {
info: 1,
low: 2,
medium: 3,
high: 4,
};
const FAIL_RANK: Record<ReleaseExposureFailLevel, number> = {
low: 2,
medium: 3,
high: 4,
};
const boundSamples = (samples: readonly string[]): string[] => {
const unique: string[] = [];
for (const sample of samples) {
if (sample.length === 0 || unique.includes(sample)) continue;
unique.push(sample);
if (unique.length === MAX_RELEASE_EXPOSURE_SAMPLES) break;
}
return unique;
};
const boundLocations = (
locations: readonly EvidenceLocation[],
): EvidenceLocation[] => locations.slice(0, MAX_RELEASE_EXPOSURE_SAMPLES);
const makeCheck = (
id: ReleaseExposureCheckId,
status: Status,
confidence: "observed" | "inferred",
counts: Record<string, number>,
samples: readonly string[],
locations: readonly EvidenceLocation[],
): ReleaseExposureCheck => {
const policy = CHECK_TABLE[id];
return {
id,
status,
severity: status === "exposed" ? policy.severity : null,
confidence,
observation: { counts, samples: boundSamples(samples) },
locations: boundLocations(locations),
remediation: policy.remediation,
next_probe: policy.next_probe,
};
};
const targetLocation = (path: string): EvidenceLocation[] => [
{ kind: "artifact-path", path },
];
const findingLocations = (
paths: readonly string[],
fallback: string,
): EvidenceLocation[] => {
const locations = [...new Set(paths.filter((path) => path.length > 0))]
.slice(0, MAX_RELEASE_EXPOSURE_SAMPLES)
.map((path) => ({ kind: "artifact-path" as const, path }));
return locations.length > 0 ? locations : targetLocation(fallback);
};
const sourceMapCheck = (
id: ReleaseExposureCheckId,
present: number,
scan: ReleaseExposureScan,
): ReleaseExposureCheck => {
const { source_maps: maps, coverage, target } = scan;
const unresolved = maps.unparsed + maps.skipped > 0 || coverage === "unknown";
const status: Status =
present > 0 ? "exposed" : unresolved ? "unknown" : "not_observed";
const findingPaths =
id === "javascript.source_map_sources"
? (maps.embedded_paths ?? (present > 0 ? maps.samples : []))
: (maps.plain_paths ?? (present > 0 ? maps.samples : []));
return makeCheck(
id,
status,
status === "unknown" ? "inferred" : "observed",
{
embedded: maps.embedded,
without_sources: maps.without_sources,
unparsed: maps.unparsed,
skipped: maps.skipped,
},
maps.samples,
status === "exposed"
? findingLocations(findingPaths, target.selected_path)
: targetLocation(target.selected_path),
);
};
const FUSE_SUBJECTS = {
"electron.run_as_node": {
subject: "electron_run_as_node",
exposed: "honored",
safe: "not_honored",
},
"electron.node_cli_inspect": {
subject: "node_cli_inspect_arguments",
exposed: "honored",
safe: "not_honored",
},
"electron.asar_integrity": {
subject: "embedded_asar_integrity_validation",
exposed: "not_enforced",
safe: "enforced",
},
"electron.only_load_from_asar": {
subject: "only_load_app_from_asar",
exposed: "not_restricted_to_app_asar",
safe: "restricted_to_app_asar",
},
} as const;
/** Fuse implication subjects that decide an Electron check. */
export const RELEASE_EXPOSURE_FUSE_SUBJECTS = Object.values(FUSE_SUBJECTS).map(
(spec) => spec.subject,
);
/**
* Whether a native image may have gone unread: inventory stopped early, the
* sample dropped one, or one sits inside a package no owner reader opens.
*/
export const nativeImagesMayBeUnread = (scan: ReleaseExposureScan): boolean =>
scan.coverage === "unknown" ||
scan.omitted.some(
(item) =>
(item.subject === "native images" ||
item.subject === PACKAGED_NATIVE_IMAGES) &&
item.count > 0,
);
/**
* Whether a native image stored inside a package went unread. No fuse reader
* opens it, so reading a host on disk does not settle its fuses.
*/
const packagedNativeImagesUnread = (scan: ReleaseExposureScan): boolean =>
scan.omitted.some(
(item) => item.subject === PACKAGED_NATIVE_IMAGES && item.count > 0,
);
const fuseCheck = (
id: keyof typeof FUSE_SUBJECTS,
scan: ReleaseExposureScan,
owners: ReleaseExposureOwnerFacts,
): ReleaseExposureCheck => {
const path = scan.target.selected_path;
const spec = FUSE_SUBJECTS[id];
const images = owners.fuse_images;
const outcomes = images.flatMap((image) =>
image.kind === "report"
? (image.implications ?? [])
.filter((item) => item.subject === spec.subject)
.map((item) => item.outcome)
: [],
);
const failed = images.some((image) => image.kind === "failed");
// A bundle's framework holds its fuses, so an image beside it cannot settle them.
const hostUnresolved = images.some(
(image) =>
image.kind !== "failed" &&
(image.role === "app-bundle" ||
(image.path !== undefined &&
owners.electron_host_paths?.includes(image.path) === true)) &&
!(image.implications ?? []).some((item) => item.subject === spec.subject),
);
const partialFuseSample =
owners.electron_layouts_complete === false ||
packagedNativeImagesUnread(scan) ||
(nativeImagesMayBeUnread(scan) &&
owners.electron_executable_included !== true);
let status: Status;
if (outcomes.includes(spec.exposed)) status = "exposed";
else if (owners.electron_family === "not_electron")
status = nativeImagesMayBeUnread(scan) ? "unknown" : "not_applicable";
else if (outcomes.includes("unknown") || failed || hostUnresolved)
status = "unknown";
else if (outcomes.length > 0 && outcomes.every((item) => item === spec.safe))
status = partialFuseSample ? "unknown" : "not_observed";
else if (owners.electron_family === "not_a_directory")
status = nativeImagesMayBeUnread(scan) ? "unknown" : "not_applicable";
else status = "unknown";
const familyReason = owners.electron_family_reason;
const exposedPaths = images.flatMap((image) => {
if (image.kind !== "report" || image.path === undefined) return [];
const hit = (image.implications ?? []).some(
(item) => item.subject === spec.subject && item.outcome === spec.exposed,
);
return hit ? [image.path] : [];
});
return makeCheck(
id,
status,
"inferred",
{
images: images.length,
implications: outcomes.length,
},
[
...images.flatMap((image) =>
image.reason === undefined ? [] : [image.reason],
),
...(status === "unknown" &&
familyReason !== undefined &&
familyReason !== null
? [familyReason]
: []),
],
status === "exposed"
? findingLocations(exposedPaths, path)
: targetLocation(path),
);
};
const extractableCheck = (scan: ReleaseExposureScan): ReleaseExposureCheck => {
const { extractable, coverage, target } = scan;
let status: Status;
if (extractable.readable_members > 0) status = "exposed";
else if (
extractable.unreadable_members > 0 ||
extractable.formats.length > 0 ||
coverage !== "complete"
)
status = "unknown";
else status = "not_observed";
return makeCheck(
"packaging.extractable_payload",
status,
status === "unknown" ? "inferred" : "observed",
{
readable_members: extractable.readable_members,
unreadable_members: extractable.unreadable_members,
formats: extractable.formats.length,
},
[...extractable.formats, ...extractable.samples],
status === "exposed"
? findingLocations(extractable.samples, target.selected_path)
: targetLocation(target.selected_path),
);
};
const companionCheck = (scan: ReleaseExposureScan): ReleaseExposureCheck => {
const { debug_companions: companions, coverage, target } = scan;
const status: Status =
companions.paths.length > 0
? "exposed"
: companions.skipped > 0 || coverage === "unknown"
? "unknown"
: "not_observed";
return makeCheck(
"native.debug_companions",
status,
// A companion's identity comes from its name or an unparseable .map body.
status === "not_observed" ? "observed" : "inferred",
{ companions: companions.paths.length, skipped: companions.skipped },
companions.paths,
status === "exposed"
? findingLocations(companions.paths, target.selected_path)
: targetLocation(target.selected_path),
);
};
const pdbCheck = (scan: ReleaseExposureScan): ReleaseExposureCheck => {
const { pdb, coverage, target } = scan;
let status: Status;
if (pdb.paths.length > 0) status = "exposed";
else if (pdb.failed > 0 || coverage !== "complete") status = "unknown";
else if (pdb.examined === 0) status = "not_applicable";
else status = "not_observed";
const imagePaths = pdb.image_paths ?? [];
return makeCheck(
"native.pdb_path",
status,
status === "unknown" ? "inferred" : "observed",
{ examined: pdb.examined, paths: pdb.paths.length, failed: pdb.failed },
pdb.paths,
status === "exposed"
? findingLocations(imagePaths, target.selected_path)
: targetLocation(target.selected_path),
);
};
const metadataStatus = (
images: readonly MetadataImageFact[],
present: (image: MetadataImageFact) => boolean,
unresolved: boolean,
): Status => {
if (images.some(present)) return "exposed";
if (
unresolved ||
images.some((image) => image.kind === "failed" || image.kind === "absent")
)
return "unknown";
if (
images.length === 0 ||
images.every((image) => image.kind === "unsupported")
)
return "not_applicable";
return "not_observed";
};
const retainsBuildPaths = (image: MetadataImageFact): boolean =>
image.kind === "paths" && image.paths.length > 0;
const goCheck = (
scan: ReleaseExposureScan,
images: readonly MetadataImageFact[],
): ReleaseExposureCheck => {
const path = scan.target.selected_path;
const paths = images.flatMap((image) =>
image.kind === "paths" ? image.paths : [],
);
const reasons = images.flatMap((image) =>
image.kind === "failed" ? [image.reason] : [],
);
const imagePaths = images.flatMap((image) =>
retainsBuildPaths(image) && image.path !== undefined ? [image.path] : [],
);
const status = metadataStatus(
images,
retainsBuildPaths,
nativeImagesMayBeUnread(scan) ||
images.some(
(image) => image.kind === "paths" && image.complete === false,
),
);
return makeCheck(
"go.build_paths",
status,
status === "unknown" ? "inferred" : "observed",
{ images: images.length, paths: paths.length },
[...paths, ...reasons],
status === "exposed"
? findingLocations(imagePaths, path)
: targetLocation(path),
);
};
const rustCheck = (
scan: ReleaseExposureScan,
images: readonly MetadataImageFact[],
): ReleaseExposureCheck => {
const path = scan.target.selected_path;
const packages = images.flatMap((image) =>
image.kind === "packages" ? image.packages : [],
);
const reasons = images.flatMap((image) =>
image.kind === "failed" ? [image.reason] : [],
);
const imagePaths = images.flatMap((image) =>
image.kind === "packages" && image.path !== undefined ? [image.path] : [],
);
const status = metadataStatus(
images,
(image) => image.kind === "packages",
nativeImagesMayBeUnread(scan),
);
return makeCheck(
"rust.dependency_metadata",
status,
status === "unknown" ? "inferred" : "observed",
{ images: images.length, packages: packages.length },
[...packages, ...reasons],
status === "exposed"
? findingLocations(imagePaths, path)
: targetLocation(path),
);
};
const credentialCheck = (
scan: ReleaseExposureScan,
markers: ReleaseExposureOwnerFacts["credential_markers"],
): ReleaseExposureCheck => {
const { text_members: members, coverage, target } = scan;
const counts: Record<string, number> = {
scanned_members: members.scanned,
skipped_members: members.skipped,
omitted_hits: markers.omitted_hits,
};
for (const hit of markers.hits)
counts[hit.rule_id] = (counts[hit.rule_id] ?? 0) + 1;
const status: Status =
markers.hits.length > 0
? "exposed"
: members.skipped > 0 || coverage === "unknown"
? "unknown"
: members.scanned === 0
? "not_applicable"
: "not_observed";
return makeCheck(
"text.credential_markers",
status,
status === "unknown" ? "inferred" : "observed",
counts,
markers.hits.map((hit) => `${hit.rule_id} ${hit.path}:${String(hit.line)}`),
status === "exposed"
? findingLocations(
markers.hits.map((hit) => hit.path),
target.selected_path,
)
: targetLocation(target.selected_path),
);
};
const notAssessed = (
id: "native.hardening" | "macho.hardened_runtime" | "android.manifest",
path: string,
): ReleaseExposureCheck =>
makeCheck(
id,
"not_assessed",
"inferred",
{ assessed: 0 },
[],
targetLocation(path),
);
/** Build the fixed check list from reader facts and owner results. */
export const assembleReleaseExposureReport = (
scan: ReleaseExposureScan,
owners: ReleaseExposureOwnerFacts,
): ReleaseExposureReport => {
const path = scan.target.selected_path;
const checks = [
sourceMapCheck(
"javascript.source_map_sources",
scan.source_maps.embedded,
scan,
),
sourceMapCheck(
"javascript.source_maps",
scan.source_maps.without_sources,
scan,
),
fuseCheck("electron.run_as_node", scan, owners),
fuseCheck("electron.asar_integrity", scan, owners),
fuseCheck("electron.only_load_from_asar", scan, owners),
fuseCheck("electron.node_cli_inspect", scan, owners),
extractableCheck(scan),
companionCheck(scan),
pdbCheck(scan),
goCheck(scan, owners.go_images),
rustCheck(scan, owners.rust_images),
credentialCheck(scan, owners.credential_markers),
notAssessed("native.hardening", path),
notAssessed("macho.hardened_runtime", path),
notAssessed("android.manifest", path),
];
return releaseExposureReportSchema.parse({
target: scan.target,
checks,
summary: summarizeReleaseExposureChecks(checks),
coverage: {
allowances: [...RELEASE_EXPOSURE_ALLOWANCES],
omitted: scan.omitted.filter((item) => item.count > 0),
},
limitations: [
RELEASE_EXPOSURE_LIMITATION,
...scan.limitations.filter(
(item) => item !== RELEASE_EXPOSURE_LIMITATION,
),
...owners.go_images.flatMap((image) =>
image.kind === "paths" ? (image.limitations ?? []) : [],
),
],
});
};
/** Count check outcomes. Severity counts include exposed checks only. */
export const summarizeReleaseExposureChecks = (
checks: readonly ReleaseExposureCheck[],
): ReleaseExposureReport["summary"] => {
const byStatus = {
exposed: 0,
not_observed: 0,
not_applicable: 0,
unknown: 0,
not_assessed: 0,
};
const bySeverity = { high: 0, medium: 0, low: 0, info: 0 };
let highest: Severity | null = null;
for (const check of checks) {
byStatus[check.status] += 1;
if (check.status !== "exposed" || check.severity === null) continue;
bySeverity[check.severity] += 1;
if (
highest === null ||
SEVERITY_RANK[check.severity] > SEVERITY_RANK[highest]
)
highest = check.severity;
}
return {
by_status: byStatus,
by_severity: bySeverity,
highest_exposed_severity: highest,
no_exposure_observed_in_assessed_checks: byStatus.exposed === 0,
};
};
/**
* Whether an exposed check meets a CI threshold.
* `high` matches high. `medium` matches high and medium. `low` matches high,
* medium, and low. Unknown and not_assessed checks do not match.
*/
export const exposureMeetsFailOn = (
report: ReleaseExposureReport,
level: ReleaseExposureFailLevel,
): boolean =>
report.checks.some(
(check) =>
check.status === "exposed" &&
check.severity !== null &&
SEVERITY_RANK[check.severity] >= FAIL_RANK[level],
);
@@ -0,0 +1,78 @@
import { describe, expect, it } from "vitest";
import { scanCredentialMarkers } from "./releaseExposureCredentialMarkers.js";
const PLANTED = "release-exposure-planted-secret-7c2e9a";
const AWS_KEY = "AKIAPLANT9EXPOSUREXX";
describe("release exposure credential markers", () => {
it("reports rule id and location without the matched bytes", () => {
const scan = scanCredentialMarkers(
[
"-----BEGIN PRIVATE KEY-----",
PLANTED,
"-----END PRIVATE KEY-----",
`token ${AWS_KEY}`,
"github_pat_11AAAAAABBBBCCCCDDDDEE",
"ordinary configuration",
].join("\n"),
"resources/config.txt",
);
expect(scan.hits.map((hit) => hit.rule_id)).toEqual([
"pem.private_key",
"aws.access_key_id",
"github.fine_grained_pat",
]);
expect(scan.hits.map((hit) => hit.line)).toEqual([1, 4, 5]);
const serialized = JSON.stringify(scan);
expect(serialized).not.toContain(PLANTED);
expect(serialized).not.toContain(AWS_KEY);
expect(serialized).not.toContain("github_pat_11AAAAAABBBBCCCCDDDDEE");
expect(serialized).not.toContain("BEGIN PRIVATE KEY");
});
it("counts hits past the storage cap without retaining them", () => {
const line = "npm_" + "a".repeat(36);
const scan = scanCredentialMarkers(
Array.from({ length: 40 }, () => line).join("\n"),
"tokens.txt",
);
expect(scan.hits).toHaveLength(32);
expect(scan.omitted_hits).toBe(8);
expect(JSON.stringify(scan)).not.toContain(line);
});
});
describe("release exposure credential marker boundaries", () => {
const GOOGLE_KEY = `AIza${"A".repeat(34)}-`;
const GITLAB_PAT = `glpat-${"a".repeat(19)}-`;
const SLACK_TOKEN = `xoxb-${"a".repeat(9)}-`;
const ruleIds = (text: string) =>
scanCredentialMarkers(text, "config.json").hits.map((hit) => hit.rule_id);
it.each([
["google.api_key", GOOGLE_KEY],
["gitlab.pat", GITLAB_PAT],
["slack.token", SLACK_TOKEN],
])("reports a %s that ends in a hyphen", (ruleId, token) => {
expect(ruleIds(JSON.stringify({ token }))).toEqual([ruleId]);
expect(ruleIds(`${token} next`)).toEqual([ruleId]);
expect(ruleIds(token)).toEqual([ruleId]);
});
it("reports a full-length GitHub refresh token", () => {
const refreshToken = `ghr_${"a".repeat(76)}`;
expect(ruleIds(JSON.stringify({ token: refreshToken }))).toEqual([
"github.refresh_token",
]);
expect(ruleIds(`ghr_${"a".repeat(36)}`)).toEqual([]);
expect(ruleIds(`gho_${"a".repeat(36)}`)).toEqual(["github.token"]);
});
it("keeps a Google API key to its exact length", () => {
expect(ruleIds(`${GOOGLE_KEY}-`)).toEqual([]);
expect(ruleIds(`${GOOGLE_KEY}A`)).toEqual([]);
expect(ruleIds(`AIza${"A".repeat(35)}-suffix`)).toEqual([]);
});
});
@@ -0,0 +1,73 @@
/** High-precision credential markers for an owner-side release audit. */
/*
* A token alphabet that includes "-" cannot end on `\b`: a final hyphen before
* a quote, whitespace, or end of input has no word boundary after it. Open-ended
* rules consume the whole token, and fixed-length rules check the full alphabet.
*/
const MARKER_RULES = [
{
id: "pem.private_key",
pattern:
/-----BEGIN (?:RSA |EC |OPENSSH |PGP )?PRIVATE KEY(?: BLOCK)?-----/u,
},
{ id: "aws.access_key_id", pattern: /\bAKIA[0-9A-Z]{16}\b/u },
{ id: "github.token", pattern: /\bgh[opus]_[A-Za-z0-9]{36}\b/u },
{ id: "github.refresh_token", pattern: /\bghr_[A-Za-z0-9]{76}\b/u },
{
id: "github.fine_grained_pat",
pattern: /\bgithub_pat_[A-Za-z0-9_]{22,}\b/u,
},
{ id: "gitlab.pat", pattern: /\bglpat-[A-Za-z0-9_-]{20,}/u },
{ id: "slack.token", pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}/u },
{ id: "stripe.live_secret", pattern: /\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/u },
{
id: "google.api_key",
pattern: /\bAIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])/u,
},
{ id: "npm.token", pattern: /\bnpm_[A-Za-z0-9]{36}\b/u },
] as const;
/** Rule ids this scanner can report. Matched bytes are never returned. */
export const CREDENTIAL_MARKER_RULE_IDS = MARKER_RULES.map((rule) => rule.id);
/** A hit records the rule and where it matched. It does not record the bytes. */
export interface CredentialMarkerHit {
readonly rule_id: (typeof CREDENTIAL_MARKER_RULE_IDS)[number];
readonly path: string;
readonly line: number;
}
export interface CredentialMarkerScan {
readonly hits: readonly CredentialMarkerHit[];
readonly omitted_hits: number;
}
const HIT_LIMIT = 32;
/**
* Scan one text member line by line.
* The returned value contains rule ids, paths, and 1-based line numbers only.
*/
export const scanCredentialMarkers = (
text: string,
path: string,
): CredentialMarkerScan => {
const hits: CredentialMarkerHit[] = [];
let omittedHits = 0;
const lines = text.split("\n");
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index] ?? "";
for (const rule of MARKER_RULES) {
if (!rule.pattern.test(line)) continue;
if (hits.length >= HIT_LIMIT) omittedHits += 1;
else
hits.push({
rule_id: rule.id,
path,
line: index + 1,
});
}
}
return { hits, omitted_hits: omittedHits };
};
+387
View File
@@ -0,0 +1,387 @@
import type { GoBinary } from "./go/goBinary.js";
import type { ReleaseExposureNativeImage } from "./releaseExposure.js";
const filesystemPath = (value: string | null | undefined): string | null => {
if (value === null || value === undefined || value.length === 0) return null;
if (
value.startsWith("/") ||
value.startsWith("./") ||
value.startsWith("../") ||
value.includes("\\") ||
/^[A-Za-z]:[\\/]/u.test(value)
)
return value;
return null;
};
/** Go build settings whose values are flags. */
const GO_FLAG_SETTING =
/^(?:CGO_[A-Z]+FLAGS|-asmflags|-gccgoflags|-gcflags|-ldflags)$/u;
/**
* `-pgo file` names one profile, so its value is a whole path, or under
* `-trimpath` the bare file name; `auto` and `off` name no file.
*/
const goProfilePath = (value: string): string | null =>
value.length === 0 || value === "auto" || value === "off" ? null : value;
/**
* One field as Go's `quoted.Split` reads a flag value: a field that begins with
* `"` or `'` runs to the matching quote, which it drops; any other field runs to
* whitespace and keeps every quote in it as a literal character.
*/
const GO_FLAG_FIELD = /"([^"]*)"|'([^']*)'|[^\s"'][^\s]*/gu;
/** A path after a flag prefix, whitespace, `=`, or `,`, as in `-isystem/opt/x`. */
const GO_FLAG_PATH =
/(?:^|[\s=,])(?:-(?:idirafter|imacros|include|iprefix|iquote|isysroot|isystem|[BFILT]))?((?:\.{1,2}[\\/]|\/|[A-Za-z]:[\\/]|\\{2}[^\\\s=,]+\\)[^=,]+)/gu;
/**
* Settings read by a C compiler, where the flags below take a directory or file.
* Go's own tools reuse those letters: `-ldflags` takes `-B gobuildid` and
* `-T 0x1000`, so their relative arguments are not paths. The exact field
* `-I-` is GCC's include barrier, the same as `--include-barrier`, and names
* no directory.
*/
const GO_COMPILER_SETTING = /^(?:CGO_[A-Z]+FLAGS|-gccgoflags)$/u;
const GO_COMPILER_PATH_FLAG =
/^(?:-(?:idirafter|imacros|include|iprefix|iquote|isysroot|isystem|[BFLT]|I(?!-$))=?\s*|--sysroot(?:=|\s+|$))(.*)$/su;
/**
* Linker options a C compiler forwards through `-Wl,a,b` or `-Xlinker a`. The
* linker reads its own letters: `-L`, `-T` and `-I` (the ELF interpreter) take
* a path, `-Bstatic` does not, and `-Ttext=0x400000` and its siblings set a
* section or segment address. `-rpath` and `-rpath-link` take a runtime or
* link-time library search directory. `--version-script`, `--dynamic-list` and
* `--retain-symbols-file` read a file, as `--script` does, and `-Map` writes
* the linker map to one. `--just-symbols` reads a symbol file; it is the long
* spelling of `-R`, but only `-R` turns into `-rpath` for a directory.
* `--sysroot` sets the linker's own sysroot directory, apart from the one the
* compiler driver reads.
*/
const LINKER_PATH_FLAG =
/^(?:-(?!T(?:bss|data|text|(?:ldata|rodata|text)-segment)(?:=|$))[ILRT]|-{1,2}(?:dynamic-linker|dynamic-list|just-symbols|library-path|Map|retain-symbols-file|rpath|rpath-link|script|sysroot|version-script)(?==|$))=?(.*)$/su;
type NativeImageFormat = ReleaseExposureNativeImage["format"];
/**
* A runtime search path the image's loader expands, which names no directory
* on the build host. The ELF loader expands `$ORIGIN/../lib`; dyld expands
* `@loader_path/Frameworks`. Each token is literal text to the other loader,
* and the PE loader reads no search list, so it expands neither.
*/
const DYLD_RUNTIME_TOKEN = /^@(?:executable_path|loader_path|rpath)(?:\/|$)/u;
const LINKER_RUNTIME_TOKENS: Record<NativeImageFormat, RegExp | null> = {
elf: /^(?:\$(?:ORIGIN|LIB|PLATFORM)\b|\$\{(?:ORIGIN|LIB|PLATFORM)\})/u,
"mach-o": DYLD_RUNTIME_TOKEN,
"mach-o-universal": DYLD_RUNTIME_TOKEN,
pe: null,
};
/** `-rpath` and `-rpath-link` take a search list, not one directory. */
const LINKER_SEARCH_LIST_FLAG = /^-{1,2}(?:rpath|rpath-link)(?==|$)/u;
/**
* The `:` between search list entries. A `:` after a lone drive letter, as in
* `C:\lib`, is part of the entry.
*/
const LINKER_SEARCH_LIST_SEPARATOR = /(?<!(?:^|:)[A-Za-z]):/u;
/**
* The options `go tool link -h` documents as taking a directory, path or file,
* as `-L dir` or `-L=dir`, never attached. `-extld` and `-extar` name
* programs, so only their rooted values read as paths. `-libgcc` takes a file
* or the disabling sentinel `none`.
*/
const GO_LINKER_PATH_FLAG =
/^-{1,2}(?:I|L|benchmarkprofile|capturehostobjs|cpuprofile|fipso|importcfg|libgcc|memprofile|o|r|tmpdir)(?:=|$)(.*)$/su;
/** The options `go tool compile -h` documents as taking a directory, path or file. */
const GO_COMPILE_PATH_FLAG =
/^-{1,2}(?:D|I|asmhdr|bench|blockprofile|coveragecfg|cpuprofile|embedcfg|importcfg|linkobj|memprofile|mutexprofile|o|pgoprofile|symabis|traceprofile|trimpath)(?:=|\s+|$)(.*)$/su;
/** `go tool asm` shares `-I`, `-o` and `-trimpath`, but its `-D` defines a symbol. */
const GO_ASSEMBLE_PATH_FLAG = /^-{1,2}(?:I|o|trimpath)(?:=|\s+|$)(.*)$/su;
const GO_TOOL_PATH_FLAGS = new Map([
["-asmflags", GO_ASSEMBLE_PATH_FLAG],
["-gcflags", GO_COMPILE_PATH_FLAG],
["-ldflags", GO_LINKER_PATH_FLAG],
]);
/** The one `pattern=` that `go build` allows before a setting's first flag. */
const GO_PACKAGE_SELECTOR = /^[^\s=-][^\s=]*=(?=-)/u;
/**
* `go tool link -extldflags` passes its value, split like any Go flag value, to
* the external linker, which Go runs through the C compiler driver.
*/
const GO_EXTERNAL_LINKER_FLAGS = /^-{1,2}extldflags(?:=(.*))?$/su;
/** Fields in one value, without their delimiting quotes. */
const goFields = (value: string): string[] =>
[...value.matchAll(GO_FLAG_FIELD)].map(
([field, double, single]) => double ?? single ?? field,
);
/** Rooted paths in flags, with their `=` and `,` structure kept. */
const flagPaths = (flags: string[]): string[] =>
flags.flatMap((flag) =>
[...flag.matchAll(GO_FLAG_PATH)].flatMap(([, path]) =>
path === undefined ? [] : [path],
),
);
/** Consume each normalized linker option and its operand exactly once. */
const linkerPaths = (
flags: string[],
format: NativeImageFormat,
onAmbiguousLinkerR: () => void,
): { paths: string[]; searchPaths: string[]; remaining: string[] } => {
const paths: string[] = [];
const searchPaths: string[] = [];
const remaining: string[] = [];
for (let index = 0; index < flags.length; index += 1) {
const flag = flags[index];
if (flag === undefined) continue;
const attached = LINKER_PATH_FLAG.exec(flag)?.[1];
if (attached === undefined) {
remaining.push(flag);
continue;
}
const next = flags[index + 1];
const fromNext =
attached.length === 0 && !flag.endsWith("=") && next !== undefined;
const argument = fromNext ? next : attached;
if (fromNext) index += 1;
if (argument.length === 0) continue;
if (LINKER_SEARCH_LIST_FLAG.test(flag)) {
searchPaths.push(...searchListEntries(argument, format));
continue;
}
if (
flag.startsWith("-R") &&
format === "elf" &&
LINKER_RUNTIME_TOKENS.elf?.test(argument) === true
) {
onAmbiguousLinkerR();
continue;
}
if (/^-{1,2}Map(?:=|$)/u.test(flag) && argument === "-") continue;
paths.push(argument);
}
return { paths, searchPaths, remaining };
};
/**
* `-trimpath` takes `prefix=replacement` rewrites separated by `;`, so its
* rooted value is read by `flagPaths` with that structure kept.
*/
const GO_PATH_LIST_FLAG = /^-{1,2}trimpath(?:=|\s+|$)/u;
/**
* `go tool link -r` sets the dynamic linker search path, `dir1:dir2:...`, so
* it is read entry by entry like a forwarded `-rpath`.
*/
const GO_LINKER_SEARCH_LIST_FLAG = /^-{1,2}r(?:=|\s+|$)/u;
/**
* A runtime search list's build-host entries. Only the ELF loader splits a
* list at `:`; dyld reads each argument as one directory. An entry the image's
* loader expands, such as `$ORIGIN` on ELF, drops only itself.
*/
const searchListEntries = (
list: string,
format: NativeImageFormat,
): string[] => {
const token = LINKER_RUNTIME_TOKENS[format];
return (
format === "elf" ? list.split(LINKER_SEARCH_LIST_SEPARATOR) : [list]
).filter((entry) => entry.length > 0 && token?.test(entry) !== true);
};
/** Consume compiler operands before interpreting any remaining forwarding syntax. */
const splitForwardedLinkerFlags = (
flags: string[],
): { compiler: string[]; linker: string[]; paths: string[] } => {
const compiler: string[] = [];
const linker: string[] = [];
const paths: string[] = [];
for (let index = 0; index < flags.length; index += 1) {
const flag = flags[index];
if (flag === undefined) continue;
const attached = GO_COMPILER_PATH_FLAG.exec(flag)?.[1];
if (attached !== undefined) {
const next = flags[index + 1];
const fromNext =
attached.length === 0 && !flag.endsWith("=") && next !== undefined;
const argument = fromNext ? next : attached;
if (argument.length > 0) paths.push(argument);
if (fromNext) index += 1;
} else if (flag === "-Xlinker" && flags[index + 1] !== undefined) {
const forwarded = flags[index + 1];
if (forwarded !== undefined) linker.push(forwarded);
index += 1;
} else if (flag.startsWith("-Wl,"))
linker.push(...flag.slice(4).split(","));
else compiler.push(flag);
}
return { compiler, linker, paths };
};
/**
* Options whose separate argument is a dyld install name or path, which may
* start with a runtime token such as `@rpath`: `-install_name @rpath/libx.dylib`.
*/
const LINKER_DYLD_VALUE_FLAG =
/^-{1,2}(?:dylib_file|dylib_install_name|install_name|rpath)$/u;
/**
* Each `@FILE` response file the compiler driver or linker reads options from,
* named in its own argument and never opened here. An argument after an option
* that takes one is that option's value, as is a dyld runtime token after
* `-install_name`; a standalone `@rpath/x.rsp` is still a response file.
*/
const responseFilePaths = (args: string[], pathFlag: RegExp): string[] =>
args.flatMap((arg, index) => {
if (!arg.startsWith("@")) return [];
const path = arg.slice(1);
const previous = args[index - 1];
return path.length === 0 ||
(previous !== undefined &&
(pathFlag.exec(previous)?.[1] === "" ||
LINKER_DYLD_VALUE_FLAG.test(previous)))
? []
: [path];
});
/**
* Rooted and relative paths in flags a C compiler driver reads. A forwarded
* search list is read entry by entry, so an entry the image's loader expands,
* such as `$ORIGIN` on ELF, drops only itself. Only a search list is loader-expanded: the
* argument of `-T`, `-L` or `-I` is a literal path even when it reads `$ORIGIN`.
* Only the ELF linker splits a search list at `:`. The Mach-O linker stores
* each `-rpath` argument as one directory, so `@loader_path/lib:extra` is one
* loader-relative entry.
*/
const compilerPaths = (
value: string,
format: NativeImageFormat,
onAmbiguousLinkerR: () => void,
): string[] => {
const { compiler, linker, paths } = splitForwardedLinkerFlags(
goFields(value),
);
const extracted = linkerPaths(linker, format, onAmbiguousLinkerR);
return [
...flagPaths([...compiler, ...extracted.remaining]),
...paths,
...extracted.paths,
...responseFilePaths(compiler, GO_COMPILER_PATH_FLAG),
...responseFilePaths(extracted.remaining, LINKER_PATH_FLAG),
...extracted.searchPaths,
];
};
/** Interpret a consumed Go path operand without treating its bytes as more flags. */
const goToolOperandPaths = (
flag: string,
argument: string,
pathFlag: RegExp | undefined,
format: NativeImageFormat,
): { paths: string[]; remaining: string[] } => {
if (
argument.length === 0 ||
(pathFlag === GO_LINKER_PATH_FLAG &&
/^-{1,2}libgcc(?:=|$)/u.test(flag) &&
argument === "none")
)
return { paths: [], remaining: [] };
if (GO_PATH_LIST_FLAG.test(flag))
return {
paths: filesystemPath(argument) === null ? [argument] : [],
remaining: [argument],
};
return {
paths: GO_LINKER_SEARCH_LIST_FLAG.test(flag)
? searchListEntries(argument, format)
: [argument],
remaining: [],
};
};
/**
* Paths in a flag setting. Each `-extldflags` value is read only as the
* external linker splits it, so a path quoted inside it is read whole.
*/
const goSettingPaths = (
key: string,
value: string,
format: NativeImageFormat,
onAmbiguousLinkerR: () => void,
): string[] => {
if (GO_COMPILER_SETTING.test(key))
return compilerPaths(value, format, onAmbiguousLinkerR);
const pathFlag = GO_TOOL_PATH_FLAGS.get(key);
const fields = goFields(value);
const paths: string[] = [];
const external: string[] = [];
const remaining: string[] = [];
for (let index = 0; index < fields.length; index += 1) {
const field = fields[index];
if (field === undefined) continue;
const flag = index === 0 ? field.replace(GO_PACKAGE_SELECTOR, "") : field;
const attached = pathFlag?.exec(flag)?.[1];
if (attached !== undefined) {
const next = fields[index + 1];
const fromNext =
attached.length === 0 && !flag.endsWith("=") && next !== undefined;
const argument = fromNext ? next : attached;
if (fromNext) index += 1;
const operand = goToolOperandPaths(flag, argument, pathFlag, format);
paths.push(...operand.paths);
remaining.push(...operand.remaining);
continue;
}
const externalFlags = GO_EXTERNAL_LINKER_FLAGS.exec(flag);
if (externalFlags !== null) {
const argument = externalFlags[1] ?? fields[++index];
if (argument !== undefined) external.push(argument);
continue;
}
remaining.push(field);
if (/^-{1,2}X$/u.test(flag)) {
const argument = fields[++index];
if (argument !== undefined) remaining.push(argument);
}
}
return [
...flagPaths(remaining),
...paths,
...external.flatMap((flags) =>
compilerPaths(flags, format, onAmbiguousLinkerR),
),
];
};
export const goBuildPaths = (
module: NonNullable<GoBinary["build_info"]>["module"],
format: NativeImageFormat,
): { readonly paths: string[]; readonly ambiguousLinkerR: boolean } => {
const paths = new Set<string>();
let ambiguousLinkerR = false;
const add = (value: string | null | undefined) => {
const path = filesystemPath(value);
if (path !== null) paths.add(path);
};
add(module.path);
add(module.main?.path);
add(module.main?.replacement?.path);
for (const dependency of module.dependencies) {
add(dependency.path);
add(dependency.replacement?.path);
}
for (const setting of module.settings) {
if (setting.key === "-pgo") {
const path = goProfilePath(setting.value);
if (path !== null) paths.add(path);
continue;
}
if (!GO_FLAG_SETTING.test(setting.key)) continue;
for (const path of goSettingPaths(
setting.key,
setting.value,
format,
() => {
ambiguousLinkerR = true;
},
))
paths.add(path);
}
return { paths: [...paths], ambiguousLinkerR };
};
+20
View File
@@ -0,0 +1,20 @@
/**
* The wide Unicode encoding a byte order mark declares, or null when there is
* none. UTF-32 is reported apart because no consumer decodes it, and it is
* checked first because its little-endian mark begins with UTF-16's.
*/
export const byteOrderMarkEncoding = (
bytes: Uint8Array,
): "utf-16le" | "utf-16be" | "utf-32" | null => {
if (
(bytes[0] === 0xff &&
bytes[1] === 0xfe &&
bytes[2] === 0 &&
bytes[3] === 0) ||
(bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 0xfe && bytes[3] === 0xff)
)
return "utf-32";
if (bytes[0] === 0xff && bytes[1] === 0xfe) return "utf-16le";
if (bytes[0] === 0xfe && bytes[1] === 0xff) return "utf-16be";
return null;
};
+1
View File
@@ -129,6 +129,7 @@ export const readGoBinaryImage = (
throw new BinaryFormatFailure(
"unsupported",
"Go build-info flags contain an unsupported format bit",
true,
);
if ((flags & 2) === 0 && (flags & 1) !== (byte_order === "big" ? 1 : 0))
throw new BinaryFormatFailure(
+1
View File
@@ -117,6 +117,7 @@ const failureForPrimary = (
return cause.kind === "unsupported"
? new AnalysisUnsupportedTargetError(OPERATION, path, cause.message, {
cause,
undecodedContent: cause.undecodedContent,
})
: new AnalysisInputError(OPERATION, { cause }, [
{
+1
View File
@@ -70,6 +70,7 @@ export const goBuildInfoSearch = (
throw new BinaryFormatFailure(
"unsupported",
"Compressed ELF build-info sections are unsupported",
true,
);
const search = {
...reader.fileRange(
+108 -4
View File
@@ -67,6 +67,16 @@ export class SourceMapFormatFailure extends Error {
}
}
/** Report schema rejection through the one failure type consumers classify. */
const parseStructure = <Schema extends z.ZodType>(
schema: Schema,
value: unknown,
): z.output<Schema> => {
const parsed = schema.safeParse(value);
if (parsed.success) return parsed.data;
throw new SourceMapFormatFailure("format", parsed.error.message);
};
/** Raw declaration identity, separate from flattened engine URL identity. */
export interface SourceMapSourceDeclaration {
readonly sectionPath: readonly number[];
@@ -153,7 +163,7 @@ const addSections = ({
const limits = options.limits ?? WEB_SOURCE_MAP_LIMITS;
options.check?.();
consumeRecords(budget, limits, rawSections.length);
const sections = z.array(sectionSchema).parse(rawSections);
const sections = parseStructure(z.array(sectionSchema), rawSections);
const embeddedMaps: Extract<
SourceMapSection,
{ readonly kind: "embedded" }
@@ -279,7 +289,7 @@ const inspectLeaf = (
node.value === null ||
Array.isArray(node.value)
)
return leafSchema.parse(node.value);
return parseStructure(leafSchema, node.value);
const rawMap = node.value as Readonly<Record<string, unknown>>;
const rawSources = rawMap.sources;
const rawNames = rawMap.names;
@@ -296,7 +306,7 @@ const inspectLeaf = (
Array.isArray(rawContents) ? rawContents.length : 0,
);
options.check?.();
const leaf = leafSchema.parse(node.value);
const leaf = parseStructure(leafSchema, node.value);
const layout = inspectMappingLayout(leaf.mappings, limits, options.check);
consumeRecords(budget, limits, layout.segments + layout.lines);
if (
@@ -332,7 +342,7 @@ export const inspectSourceMapValue = (
} => {
const limits = options.limits ?? WEB_SOURCE_MAP_LIMITS;
options.check?.();
const root = mapHeaderSchema.parse(value);
const root = parseStructure(mapHeaderSchema, value);
const declarations: SourceMapSourceDeclaration[] = [];
const leaves: SourceMapLeaf[] = [];
const pending: PendingMap[] = [
@@ -390,3 +400,97 @@ export const inspectSourceMapValue = (
leaves,
};
};
/**
* Leaf maps reachable within the decoder's section depth and record budgets.
* Deeper or excess sections are dropped rather than expanded, so a map the
* decoder refused for its limits cannot allocate past them here.
*/
const boundedSourceMapLeaves = (
root: unknown,
options: Pick<SourceMapStructureOptions, "limits" | "check">,
): Record<string, unknown>[] => {
const limits = options.limits ?? WEB_SOURCE_MAP_LIMITS;
const leaves: Record<string, unknown>[] = [];
if (
typeof root !== "object" ||
root === null ||
Array.isArray(root) ||
(root as { version?: unknown }).version !== 3
)
return leaves;
const pending: { map: unknown; depth: number }[] = [{ map: root, depth: 0 }];
let records = 0;
while (pending.length > 0) {
options.check?.();
const current = pending.pop();
if (current === undefined) break;
const sections = classifySourceMapSections(current.map);
if (sections.kind === "invalid") continue;
if (sections.kind === "regular") {
leaves.push(current.map as Record<string, unknown>);
continue;
}
if (current.depth >= limits.sectionDepth) continue;
records += sections.sections.length;
if (records > limits.decodedRecords) break;
for (let index = sections.sections.length - 1; index >= 0; index -= 1) {
const section = classifySourceMapSection(sections.sections[index]);
if (section.kind === "embedded")
pending.push({ map: section.map, depth: current.depth + 1 });
}
}
return leaves;
};
/** Recover observed source content without treating incomplete maps as absent. */
export const inspectSourceMapSourceContent = (
text: string,
options: Pick<SourceMapStructureOptions, "limits" | "check"> = {},
):
| { readonly embedded: boolean; readonly complete: true }
| {
readonly embedded: boolean;
readonly complete: false;
readonly failure: SourceMapFormatFailure;
} => {
options.check?.();
let value: unknown;
try {
value = JSON.parse(sourceMapJsonText(text));
} catch (cause) {
if (!(cause instanceof SyntaxError)) throw cause;
return {
embedded: false,
complete: false,
failure: new SourceMapFormatFailure("format", cause.message),
};
}
const hasContent = (
inspection: ReturnType<typeof inspectSourceMapValue>,
): boolean =>
inspection.declarations.some(
(declaration) =>
declaration.content !== null && declaration.content.length > 0,
);
try {
return {
embedded: hasContent(inspectSourceMapValue(value, options)),
complete: true,
};
} catch (failure) {
if (!(failure instanceof SourceMapFormatFailure)) throw failure;
const budget = { records: 0 };
let embedded = false;
for (const leaf of boundedSourceMapLeaves(value, options)) {
try {
const inspected = inspectSourceMapValue(leaf, { ...options, budget });
embedded ||= hasContent(inspected);
} catch (cause) {
if (!(cause instanceof SourceMapFormatFailure)) throw cause;
// An unresolved leaf cannot discard content observed in valid siblings.
}
}
return { embedded, complete: false, failure };
}
};
@@ -35,6 +35,23 @@ it("classifies external indexed sections as unsupported with their exact URL", (
}
});
it.each([
["root field", { ...leaf, version: 2 }],
["leaf field", { ...leaf, mappings: "!" }],
[
"section field",
{ version: 3, sections: [{ offset: { line: "0" }, map: leaf }] },
],
])("reports a %s schema rejection as a format failure", (_, map) => {
try {
inspectSourceMap(JSON.stringify(map));
throw new Error("Expected schema rejection");
} catch (error: unknown) {
expect(error).toBeInstanceOf(SourceMapFormatFailure);
expect(error).toMatchObject({ reason: "format" });
}
});
it("uses the same conservative section classification for URL-plus-map and malformed URLs", () => {
const externalUrl = "https://app.test/maps/part.map";
const external = () =>
+2
View File
@@ -10,6 +10,8 @@ export class BinaryFormatFailure extends Error {
constructor(
readonly kind: "malformed" | "unsupported",
message: string,
/** The image holds the metadata, in a form this reader cannot decode. */
readonly undecodedContent = false,
) {
super(message);
this.name = "BinaryFormatFailure";
+4 -1
View File
@@ -38,12 +38,15 @@ const documentSchema = documentVersionSchema
/** Malformed or unsupported dependency-section bytes. */
export class RustAuditableFormatFailure extends Error {
/** The image holds the metadata, in a form this reader cannot decode. */
readonly undecodedContent: boolean;
constructor(
readonly kind: "malformed" | "unsupported",
message: string,
options?: ErrorOptions,
options?: ErrorOptions & { readonly undecodedContent?: boolean },
) {
super(message, options);
this.undecodedContent = options?.undecodedContent ?? false;
this.name = "RustAuditableFormatFailure";
}
}
+1
View File
@@ -95,6 +95,7 @@ const dependencySection = (
throw new RustAuditableFormatFailure(
"unsupported",
"Compressed dependency sections are unsupported",
{ undecodedContent: true },
);
if (!section.file_backed)
throw new RustAuditableFormatFailure(
+1
View File
@@ -351,6 +351,7 @@ const failureForPrimary = (
return cause.kind === "unsupported"
? new AnalysisUnsupportedTargetError(OPERATION, path, cause.message, {
cause,
undecodedContent: cause.undecodedContent,
})
: new AnalysisInputError(OPERATION, { cause }, [
{
+9
View File
@@ -25,6 +25,7 @@ import { registerAppleIpsTool } from "./registerAppleIpsTool.js";
import { registerKernelModuleTool } from "./registerKernelModuleTool.js";
import { registerKernelBuildConfigTool } from "./registerKernelBuildConfigTool.js";
import { registerPeLoadConfigTool } from "./registerPeLoadConfigTool.js";
import { registerReleaseExposureTool } from "./registerReleaseExposureTool.js";
import { registerBinaryHardeningTool } from "./registerBinaryHardeningTool.js";
import { registerPeCertificatesTool } from "./registerPeCertificatesTool.js";
import { registerPeImportsTool } from "./registerPeImportsTool.js";
@@ -233,6 +234,7 @@ export const createServer = (
peImports,
windowsShortcut,
electronFuses,
releaseExposure,
pythonPyc,
webNetworkCapture,
javascriptRecovery,
@@ -547,6 +549,13 @@ export const createServer = (
recordEvidence,
analysisAdmission,
);
registerReleaseExposureTool(
server,
releaseExposure,
toolLogger,
recordEvidence,
analysisAdmission,
);
registerBinaryHardeningTool(
server,
binaryHardening,
+31
View File
@@ -0,0 +1,31 @@
import type { ReleaseExposureService } from "../application/releaseExposure/ReleaseExposureService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
import type { WithAdmittedAnalysis } from "./analysisAdmission.js";
import { createEvidenceToolHandler } from "./contractToolHandler.js";
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
/** Register the read-only release-exposure audit and retain its Evidence. */
export const registerReleaseExposureTool = (
server: EvidenceMcpServer,
service: ReleaseExposureService,
logger: Logger,
recordEvidence?: EvidenceWriter["recordEvidence"],
withAdmittedAnalysis?: WithAdmittedAnalysis,
): void => {
const contract = toolContract("audit_release_exposure");
const handler = createEvidenceToolHandler(
server,
(input, options) => service.inspect(input, options),
logger,
recordEvidence,
withAdmittedAnalysis,
);
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
handler(contract),
);
};
+124
View File
@@ -0,0 +1,124 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { RELEASE_EXPOSURE_TOOL_CONTRACTS } from "../../src/contracts/releaseExposureToolContracts.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
import { cliTest } from "../support/cli/cliFixture.js";
const PLANTED_SOURCE = "release-exposure-planted-secret-7c2e9a";
const releaseExposureContract = RELEASE_EXPOSURE_TOOL_CONTRACTS.find(
(contract) => contract.name === "audit_release_exposure",
);
if (releaseExposureContract === undefined)
throw new Error("Missing release exposure contract");
const outputSchema = releaseExposureContract.outputSchema;
cliTest(
"exits 3 when a shipped source map embeds sources",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-release-exposure-cli-");
await writeFile(join(root, "app.js"), "export const value = 1;\n");
await writeFile(
join(root, "app.js.map"),
JSON.stringify({
version: 3,
file: "app.js",
sources: ["app.js"],
names: [],
mappings: "",
sourcesContent: [`export const value = "${PLANTED_SOURCE}";\n`],
}),
);
const clean = await cli.run({
arguments: ["audit-release-exposure", root, "--json"],
});
expect(clean.exitCode, clean.stderr).toBe(0);
const evidence = outputSchema.parse(clean.json);
const report = evidence.normalized_result;
expect(
report.checks.find(
(check) => check.id === "javascript.source_map_sources",
),
).toMatchObject({ status: "exposed", severity: "high" });
expect(
report.checks.find((check) => check.id === "electron.run_as_node")
?.status,
).toBe("unknown");
expect(
report.checks.find((check) => check.id === "native.pdb_path")?.status,
).toBe("not_applicable");
expect(
report.checks.find((check) => check.id === "go.build_paths")?.status,
).toBe("not_applicable");
expect(JSON.stringify(evidence)).not.toContain(PLANTED_SOURCE);
const gated = await cli.run({
arguments: [
"audit-release-exposure",
root,
"--fail_on",
"high",
"--json",
],
});
expect(gated.exitCode, gated.stderr).toBe(3);
},
60_000,
);
cliTest(
"gates a marker in a text file outside the extension list",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-release-exposure-key-");
await writeFile(join(root, "hello.txt"), "hello\n");
await writeFile(
join(root, ".env.production"),
"-----BEGIN PRIVATE KEY-----\n",
);
const result = await cli.run({
arguments: [
"audit-release-exposure",
root,
"--fail_on",
"high",
"--json",
],
});
expect(result.exitCode, result.stderr).toBe(3);
expect(
outputSchema
.parse(result.json)
.normalized_result.checks.find(
(check) => check.id === "text.credential_markers",
),
).toMatchObject({
status: "exposed",
locations: [
{ kind: "artifact-path", path: join(root, ".env.production") },
],
});
},
60_000,
);
cliTest(
"keeps a clean directory at exit 0 when the gate is high",
async ({ cli }) => {
const root = await createTestTempDirectory("rea-release-exposure-clean-");
await writeFile(join(root, "hello.txt"), "hello\n");
const result = await cli.run({
arguments: [
"audit-release-exposure",
root,
"--fail_on",
"high",
"--json",
],
});
expect(result.exitCode, result.stderr).toBe(0);
const report = outputSchema.parse(result.json).normalized_result;
expect(report.summary.no_exposure_observed_in_assessed_checks).toBe(true);
expect(report.summary.by_status.not_assessed).toBe(3);
},
60_000,
);
@@ -257,6 +257,7 @@ const pathRequests: readonly [string, Record<string, unknown>][] = [
["inspect_kernel_module", { path: nul }],
["inspect_kernel_build_config", { path: nul }],
["inspect_pe_load_config", { path: nul }],
["audit_release_exposure", { path: nul }],
["inspect_binary_hardening", { path: nul }],
["inspect_python_pyc", { path: nul }],
["inspect_erlang_beam", { path: nul }],
@@ -0,0 +1,344 @@
import { mkdir, symlink, truncate, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackageWithOptions } from "@electron/asar";
import { describe, expect, it } from "vitest";
import {
buildDenoSection,
denoElf,
} from "../../../src/artifacts/deno/DenoStandalone.fixture.js";
import { createReleaseExposureService } from "../../../src/composition/releaseExposure.js";
import { DEFAULT_ASAR_MAX_HEADER_BYTES } from "../../../src/domain/analysisResourceLimits.js";
import { AnalysisResourceConstraintError } from "../../../src/domain/analysisErrorCore.js";
import { releaseExposureReportSchema } from "../../../src/domain/releaseExposure.js";
import { prependAsarJsonWhitespace } from "../../fixtures/asarHeader.js";
import { thinFuseImage } from "../../fixtures/electron/fuseImage.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
describe("release exposure Deno filesystem boundary", () => {
it.each(["vfs", "remote"] as const)(
"audits Deno %s source maps using their retained roles",
async (kind) => {
const root = await createTestTempDirectory("rea-release-exposure-deno-");
const path = join(root, "application");
const script = Buffer.from("export const value = 1;\n");
const map = Buffer.from(
JSON.stringify({
version: 3,
sources: ["private.ts"],
sourcesContent: ["export const value: number = 1;"],
names: [],
mappings: "AAAA",
}),
);
await writeFile(
path,
denoElf(
buildDenoSection(
kind === "remote"
? {
specifiers: [{ text: "https://example.com/module", id: 1 }],
remoteModules: [
{
specifierId: 1,
mediaType: 0,
data: `export const value = 1;\n//# sourceMappingURL=data:application/json;base64,${map.toString("base64")}`,
},
],
}
: {
vfs: [
{
File: {
n: "main.ts",
o: [0, script.length],
s: [script.length, map.length],
u: true,
},
},
],
vfsFileData: Buffer.concat([script, map]),
},
),
),
);
const service = createReleaseExposureService();
try {
const result = await service.inspect({ path });
if (!result.ok) throw result.error;
const report = releaseExposureReportSchema.parse(
result.value.normalized_result,
);
expect(
report.checks.find(
(check) => check.id === "javascript.source_map_sources",
)?.status,
).toBe("exposed");
} finally {
await service.close();
}
},
);
});
describe("release exposure filesystem boundary", () => {
it("retains unknown JavaScript coverage for an external-section bundle.map", async () => {
const root = await createTestTempDirectory("rea-release-exposure-map-");
await writeFile(
join(root, "bundle.map"),
JSON.stringify({
version: 3,
sections: [{ offset: { line: 0, column: 0 }, url: "external.map" }],
}),
);
const service = createReleaseExposureService();
try {
const result = await service.inspect({ path: root });
if (!result.ok) throw result.error;
const report = releaseExposureReportSchema.parse(
result.value.normalized_result,
);
for (const id of [
"javascript.source_maps",
"javascript.source_map_sources",
])
expect(report.checks.find((check) => check.id === id)?.status).toBe(
"unknown",
);
expect(
report.checks.find((check) => check.id === "native.debug_companions")
?.status,
).toBe("not_observed");
} finally {
await service.close();
}
});
it("audits an ASAR whose unpacked module was signed after packaging", async () => {
const root = await createTestTempDirectory("rea-release-exposure-signed-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "native.node"), "packaged module");
const archive = join(root, "app.asar");
await createPackageWithOptions(source, archive, { unpack: "*.node" });
await writeFile(
join(`${archive}.unpacked`, "native.node"),
"signed module",
);
const service = createReleaseExposureService();
try {
const result = await service.inspect({ path: archive });
if (!result.ok) throw result.error;
expect(result.value.limitations.join("\n")).toContain(
"integrity contradiction",
);
expect(
releaseExposureReportSchema
.parse(result.value.normalized_result)
.checks.find((check) => check.id === "packaging.extractable_payload")
?.status,
).toBe("exposed");
} finally {
await service.close();
}
});
it("rejects a missing path and a symlink", async () => {
const root = await createTestTempDirectory("rea-release-exposure-files-");
const path = join(root, "hello.txt");
const alias = join(root, "alias.txt");
await writeFile(path, "hello\n");
await symlink(path, alias);
const service = createReleaseExposureService();
try {
for (const [candidate, reason] of [
[alias, "invalid_format"],
[join(root, "missing.txt"), "invalid_value"],
] as const) {
const result = await service.inspect({ path: candidate });
if (result.ok) throw new Error("Expected file acquisition failure");
expect(result.error).toMatchObject({
_tag: "AnalysisInputError",
operation: "audit_release_exposure",
issues: [{ path: ["path"], reason, message: expect.any(String) }],
});
}
} finally {
await service.close();
}
});
it("returns typed resource and cancellation failures", async () => {
const root = await createTestTempDirectory("rea-release-exposure-budget-");
const path = join(root, "blob.bin");
await writeFile(path, Buffer.alloc(128, 1));
const service = createReleaseExposureService();
try {
const tooSmall = await service.inspect({ path, max_file_bytes: 64 });
if (tooSmall.ok) throw new Error("Expected resource budget failure");
expect(tooSmall.error._tag).toBe("AnalysisResourceConstraintError");
const cancelled = await service.inspect(
{ path },
{ signal: AbortSignal.abort() },
);
if (cancelled.ok) throw new Error("Expected cancellation");
expect(cancelled.error._tag).toBe("AnalysisCancelledError");
} finally {
await service.close();
}
});
it("reads a directory of plain text", async () => {
const root = await createTestTempDirectory("rea-release-exposure-dir-");
await writeFile(join(root, "hello.txt"), "hello\n");
const service = createReleaseExposureService();
try {
const result = await service.inspect({ path: root });
if (!result.ok) throw result.error;
const report = result.value.normalized_result as {
summary: {
no_exposure_observed_in_assessed_checks: boolean;
by_status: { not_assessed: number };
};
};
expect(report.summary.no_exposure_observed_in_assessed_checks).toBe(true);
expect(report.summary.by_status.not_assessed).toBe(3);
} finally {
await service.close();
}
});
});
describe("release exposure app bundle boundary", () => {
it("reports a sidecar's RunAsNode fuse in an app bundle with safe outer fuses", async () => {
const root = await createTestTempDirectory("rea-release-exposure-app-");
const app = join(root, "Sample.app");
const framework = join(
app,
"Contents",
"Frameworks",
"Electron Framework.framework",
);
const resources = join(app, "Contents", "Resources");
await mkdir(framework, { recursive: true });
await mkdir(resources, { recursive: true });
const disabled = 0x30;
const enabled = 0x31;
await writeFile(
join(framework, "Electron Framework"),
thinFuseImage(Array.from({ length: 6 }, () => disabled)).bytes,
);
const sidecar = join(resources, "sidecar");
await writeFile(
sidecar,
thinFuseImage([enabled, disabled, disabled, disabled, disabled, disabled])
.bytes,
);
const service = createReleaseExposureService();
try {
const result = await service.inspect({ path: app });
if (!result.ok) throw result.error;
const check = releaseExposureReportSchema
.parse(result.value.normalized_result)
.checks.find((item) => item.id === "electron.run_as_node");
expect(check?.status).toBe("exposed");
expect(JSON.stringify(check?.locations)).toContain("sidecar");
} finally {
await service.close();
}
});
});
describe("release exposure ASAR header admission", () => {
it("keeps a directory ASAR's header admission instead of the file-size ceiling", async () => {
const root = await createTestTempDirectory("rea-release-exposure-header-");
const archive = join(root, "app.asar");
const headerBytes = DEFAULT_ASAR_MAX_HEADER_BYTES + 4;
const json = Buffer.from("{}");
const prefix = Buffer.alloc(16);
prefix.writeUInt32LE(4, 0);
prefix.writeUInt32LE(headerBytes, 4);
prefix.writeUInt32LE(headerBytes - 4, 8);
prefix.writeUInt32LE(json.length, 12);
await writeFile(archive, Buffer.concat([prefix, json]));
// Declare the extent without allocating a header-sized buffer.
await truncate(archive, headerBytes + 8);
const service = createReleaseExposureService({});
try {
const result = await service.inspect({ path: root });
expect(result.ok).toBe(false);
if (result.ok) return;
const error = result.error;
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return;
expect(error.resource).not.toBe("file-size");
expect(error.reportedLimits).not.toHaveProperty("max_file_bytes");
expect(error.reportedLimits).toMatchObject({
asar_max_header_bytes: DEFAULT_ASAR_MAX_HEADER_BYTES,
required_header_bytes: headerBytes,
});
expect(error.reason).toContain("ASAR header/index");
expect(error.fixedAllowance).toBeUndefined();
expect(error.remediationAction).toContain("asar.max_header_bytes");
expect(error.limit).toMatchObject({
setting: "asar.max_header_bytes",
effective_value: DEFAULT_ASAR_MAX_HEADER_BYTES,
source: "default",
});
} finally {
await service.close();
}
});
it("reads a 20 MiB header under a 32 MiB setting and refuses it under a lower caller limit", async () => {
const root = await createTestTempDirectory("rea-release-exposure-wide-");
const source = join(root, "source");
await mkdir(source);
await writeFile(join(source, "main.js"), "console.log('app');\n");
const install = join(root, "install");
await mkdir(install);
const archive = join(install, "app.asar");
await createPackageWithOptions(source, archive, {});
await prependAsarJsonWhitespace(archive, " ".repeat(20 * 1024 * 1024));
const environment = {
REA_ASAR_MAX_HEADER_BYTES: String(32 * 1024 * 1024),
};
const admitted = createReleaseExposureService(environment);
try {
const result = await admitted.inspect({ path: install });
if (!result.ok) throw result.error;
expect(
releaseExposureReportSchema
.parse(result.value.normalized_result)
.checks.find((check) => check.id === "packaging.extractable_payload")
?.status,
).toBe("exposed");
} finally {
await admitted.close();
}
const lowered = createReleaseExposureService(environment, () => ({
revision: 1,
overrides: { "asar.max_header_bytes": DEFAULT_ASAR_MAX_HEADER_BYTES },
}));
try {
const result = await lowered.inspect({ path: install });
if (result.ok) throw new Error("Expected ASAR header admission refusal");
const error = result.error;
expect(error).toBeInstanceOf(AnalysisResourceConstraintError);
if (!(error instanceof AnalysisResourceConstraintError)) return;
expect(error.reportedLimits).toMatchObject({
asar_max_header_bytes: DEFAULT_ASAR_MAX_HEADER_BYTES,
});
expect(error.limit).toMatchObject({
setting: "asar.max_header_bytes",
effective_value: DEFAULT_ASAR_MAX_HEADER_BYTES,
source: "runtime",
});
} finally {
await lowered.close();
}
}, 60_000);
});
+4 -1
View File
@@ -158,7 +158,10 @@ it("does not skip malformed earlier metadata to report a later valid record", ()
);
fixture.bytes[512 + 15] = 0xff;
expect(() => readGoBinaryImage(fixture.bytes)).toThrow(
/unsupported format bit/,
expect.objectContaining({
message: expect.stringMatching(/unsupported format bit/u),
undecodedContent: true,
}),
);
});
@@ -0,0 +1,75 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { RELEASE_EXPOSURE_TOOL_CONTRACTS } from "../../../src/contracts/releaseExposureToolContracts.js";
import { createServer } from "../../../src/server/createServer.js";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { mcpTest } from "../../support/mcp/mcpFixture.js";
const PLANTED_SOURCE = "release-exposure-planted-secret-7c2e9a";
const releaseExposureContract = RELEASE_EXPOSURE_TOOL_CONTRACTS.find(
(contract) => contract.name === "audit_release_exposure",
);
if (releaseExposureContract === undefined)
throw new Error("Missing release exposure contract");
const outputSchema = releaseExposureContract.outputSchema;
mcpTest(
"advertises and reads release exposure without changing the artifact",
async ({ mcp }) => {
const session = createTestBinarySession(() => {
throw new Error("Must not start a deep provider");
});
const client = await mcp.connect(
createServer({ kind: "session", session }),
);
try {
const definition = (await client.listTools()).tools.find(
(tool) => tool.name === "audit_release_exposure",
);
if (definition === undefined)
throw new Error("Missing advertised contract");
expect(definition.annotations).toMatchObject({
readOnlyHint: false,
idempotentHint: true,
});
const root = await createTestTempDirectory("rea-release-exposure-mcp-");
await writeFile(
join(root, "app.js.map"),
JSON.stringify({
version: 3,
file: "app.js",
sources: ["app.js"],
names: [],
mappings: "",
sourcesContent: [PLANTED_SOURCE],
}),
);
const response = await client.callTool(
{ name: "audit_release_exposure", arguments: { path: root } },
{ toolDefinition: definition },
);
expect(response.isError, JSON.stringify(response.content)).not.toBe(true);
const evidence = outputSchema.parse(response.structuredContent);
expect(
evidence.normalized_result.checks.find(
(check) => check.id === "javascript.source_map_sources",
)?.status,
).toBe("exposed");
expect(JSON.stringify(evidence)).not.toContain(PLANTED_SOURCE);
const bad = await client.callTool(
{
name: "audit_release_exposure",
arguments: { path: "relative-dir" },
},
{ toolDefinition: definition },
);
expect(bad.isError).toBe(true);
} finally {
await session.close();
}
},
60_000,
);
@@ -1,4 +1,5 @@
import { PeLoadConfigProvider } from "../../src/native/pe/PeLoadConfigProvider.js";
import { ReleaseExposureReader } from "../../src/artifacts/ReleaseExposureReader.js";
import { BinaryHardeningProvider } from "../../src/native/hardening/BinaryHardeningProvider.js";
import { inspectPeLoadConfigInputSchema } from "../../src/domain/native/peLoadConfig.js";
import { inspectBinaryHardeningInputSchema } from "../../src/domain/native/binaryHardening.js";
@@ -1013,6 +1014,7 @@ const stableArtifactProviders = [
["kernel build config", () => new KernelBuildConfigProvider()],
["PE certificates", () => new PeCertificatesProvider()],
["PE load configuration", () => new PeLoadConfigProvider()],
["release exposure", () => new ReleaseExposureReader()],
["binary hardening", () => new BinaryHardeningProvider()],
["PE imports", () => new PeImportsProvider()],
["Windows shortcut", () => new WindowsShortcutProvider()],
@@ -1106,6 +1108,8 @@ const inspectFileFailure = (
inspectPeResourcesInputSchema.parse({ path }),
options,
);
if (provider instanceof ReleaseExposureReader)
return provider.inspect({ path }, options, () => undefined);
return provider.inspect({ path }, options);
};