Skip to content

Commit 3fc7cc3

Browse files
jfblaaclaude
andcommitted
feat(scan): scan jar, war and ear targets by their bundled Maven metadata
`socket scan create` now accepts a .jar, .war or .ear as a target (not with --reach). A small Java 8 loader walks the archive and its nested archives with java.util.zip and reads each META-INF/maven/*/*/pom.properties with java.util.Properties; the CLI then writes `<archive>.socket.facts.json` next to the archive and uploads it with the scan. - The archive is the project; every library it ships is a direct dependency. - A nested archive is identified by the pom.properties its file name spells out (classifiers and timestamped snapshots included). - Libraries bundled inside a dependency jar are not reported until the SBOM schema can mark bundled libraries. - --exclude-paths applies; .gitignore and projectIgnorePaths do not hide an archive the user named. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 74de5be commit 3fc7cc3

18 files changed

Lines changed: 1221 additions & 45 deletions

‎.config/rollup.dist.config.mjs‎

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -105,14 +105,15 @@ async function copyInitGradle() {
105105
}
106106

107107
// Copy the build-tool resolution assets (Gradle init script, sbt plugin,
108-
// Maven extension jar, dotnet tool) into dist/manifest-scripts, where run.mts resolves them
108+
// Maven extension and archive loader jars, dotnet tool) into dist/manifest-scripts, where run.mts resolves them
109109
// at runtime. The Maven jar is compiled by maven-extension/build-jar.sh (run in
110110
// CI / local dev) and is absent from a fresh checkout — copy it only if present;
111111
// run.mts surfaces a build hint when it's missing.
112112
async function copyManifestScripts() {
113113
const srcDir = path.join(constants.srcPath, 'commands/manifest/scripts')
114114
const destDir = path.join(constants.distPath, 'manifest-scripts')
115115
await fs.mkdir(path.join(destDir, 'maven-extension'), { recursive: true })
116+
await fs.mkdir(path.join(destDir, 'archive-loader'), { recursive: true })
116117
await Promise.all([
117118
fs.copyFile(
118119
path.join(srcDir, 'socket-facts.init.gradle'),
@@ -145,25 +146,34 @@ async function copyManifestScripts() {
145146
' for a published build. Build it first: pnpm run build:dotnet-tool',
146147
)
147148
}
148-
const jarPath = path.join(
149-
srcDir,
150-
'maven-extension',
151-
'coana-maven-extension.jar',
149+
await copyBuiltJar(
150+
'Archive loader jar',
151+
path.join('archive-loader', 'archive-loader.jar'),
152+
'build:archive-loader',
152153
)
153-
if (existsSync(jarPath)) {
154+
await copyBuiltJar(
155+
'Maven manifest extension jar',
156+
path.join('maven-extension', 'coana-maven-extension.jar'),
157+
'build:maven-extension',
158+
)
159+
}
160+
161+
// Absent from a fresh checkout: a published build fails closed rather than ship
162+
// a feature that silently produces nothing; run.mts hints for a dev build.
163+
async function copyBuiltJar(description, relativePath, buildScript) {
164+
const srcPath = path.join(
165+
constants.srcPath,
166+
'commands/manifest/scripts',
167+
relativePath,
168+
)
169+
if (existsSync(srcPath)) {
154170
await fs.copyFile(
155-
jarPath,
156-
path.join(destDir, 'maven-extension', 'coana-maven-extension.jar'),
171+
srcPath,
172+
path.join(constants.distPath, 'manifest-scripts', relativePath),
157173
)
158174
} else if (constants.ENV[INLINED_SOCKET_CLI_PUBLISHED_BUILD]) {
159-
// Fail closed: a published build without the jar would ship a package whose
160-
// `socket manifest maven` / Maven reachability silently produces an empty
161-
// SBOM. Run `pnpm run build:maven-extension` before `build:dist`. (A local
162-
// dev build tolerates a missing jar; run.mts surfaces a hint at runtime.)
163175
throw new Error(
164-
'Maven manifest extension jar not found at ' +
165-
jarPath +
166-
' for a published build. Build it first: pnpm run build:maven-extension',
176+
`${description} not found at ${srcPath} for a published build. Build it first: pnpm run ${buildScript}`,
167177
)
168178
}
169179
}

‎.github/workflows/publish-npm.yml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -379,12 +379,13 @@ jobs:
379379
# download outside the shimmed process tree. The org action allowlist forbids
380380
# actions/setup-java, so use a JDK pre-installed on the runner image
381381
# (JAVA_HOME_17_X64), falling back to the runner's default `java`.
382-
- name: Build Maven manifest extension jar
382+
- name: Build Maven manifest extension and archive loader jars
383383
run: |
384384
if [ -n "${JAVA_HOME_17_X64:-}" ]; then
385385
export JAVA_HOME="$JAVA_HOME_17_X64"
386386
fi
387387
bash src/commands/manifest/scripts/maven-extension/build-jar.sh
388+
bash src/commands/manifest/scripts/archive-loader/build-jar.sh
388389
389390
# Same for the dotnet manifest tool: built here, bundled into
390391
# dist/manifest-scripts, never committed. The runner image's preinstalled

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
44

55
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
66

7+
## [Unreleased]
8+
9+
### Added
10+
- `socket scan create` now scans a `.jar`, `.war` or `.ear` you pass as a target, reporting the Maven libraries it ships as identified by their bundled `pom.properties` (requires Java 8 or newer).
11+
712
## [1.14.0](https://github.com/SocketDev/socket-cli/releases/tag/v1.14.0) - 2026-11-05
813

914
### Added

‎package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
},
3737
"scripts": {
3838
"build": "pnpm build:dist",
39+
"build:archive-loader": "bash src/commands/manifest/scripts/archive-loader/build-jar.sh",
3940
"build:dist": "pnpm build:dist:src && pnpm build:dist:types",
4041
"build:dist:src": "run-p -c clean:dist clean:external && dotenvx -q run -f .env.local -- rollup -c .config/rollup.dist.config.mjs",
4142
"build:dist:types": "pnpm clean:dist:types && tsgo --project tsconfig.dts.json",
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
archive-loader.jar
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env bash
2+
# Compile the archive loader to a Java 8 jar at the path the TS runner resolves:
3+
# manifest-scripts/archive-loader/archive-loader.jar. Needs a JDK 9+ for --release 8.
4+
set -euo pipefail
5+
6+
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7+
out="$(mktemp -d)"
8+
trap 'rm -rf "$out"' EXIT
9+
javac --release 8 -Xlint:-options -d "$out" "$here/src/ArchiveLoader.java"
10+
jar --create --file "$here/archive-loader.jar" --main-class ArchiveLoader -C "$out" .
11+
echo "Archive loader jar: $here/archive-loader.jar"
Lines changed: 171 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,171 @@
1+
import java.io.BufferedInputStream;
2+
import java.io.BufferedWriter;
3+
import java.io.File;
4+
import java.io.FileOutputStream;
5+
import java.io.IOException;
6+
import java.io.InputStream;
7+
import java.io.OutputStreamWriter;
8+
import java.io.Writer;
9+
import java.nio.charset.StandardCharsets;
10+
import java.util.Arrays;
11+
import java.util.Enumeration;
12+
import java.util.HashSet;
13+
import java.util.Properties;
14+
import java.util.Set;
15+
import java.util.zip.ZipEntry;
16+
import java.util.zip.ZipException;
17+
import java.util.zip.ZipFile;
18+
import java.util.zip.ZipInputStream;
19+
20+
/**
21+
* Walks a Java archive and every archive nested in it, writing what it finds as records for
22+
* generate-archive-facts.mts, which decides what they mean.
23+
*
24+
* <p>Records, one per line, tab-separated, fields escaped like records.mts ({@code \\ \t \n \r}).
25+
* An archive path is the chain of entry names from the scanned archive, joined by {@code !/};
26+
* the scanned archive itself is the empty path.
27+
*
28+
* <pre>
29+
* archive path
30+
* pom archivePath entry groupId artifactId version (absent keys are empty)
31+
* malformed archivePath entry detail
32+
* unreadable archivePath detail
33+
* </pre>
34+
*/
35+
public final class ArchiveLoader {
36+
private final Set<String> archiveExtensions;
37+
private final Writer out;
38+
39+
private ArchiveLoader(Set<String> archiveExtensions, Writer out) {
40+
this.archiveExtensions = archiveExtensions;
41+
this.out = out;
42+
}
43+
44+
public static void main(String[] args) throws IOException {
45+
if (args.length != 3) {
46+
System.err.println("Usage: java -jar archive-loader.jar <archive> <recordsFile> <ext,ext,...>");
47+
System.exit(64);
48+
}
49+
Set<String> extensions = new HashSet<>(Arrays.asList(args[2].split(",")));
50+
ZipFile zip;
51+
try {
52+
zip = new ZipFile(new File(args[0]));
53+
} catch (ZipException e) {
54+
// generate-archive-facts.mts reports this exit as "not a zip archive".
55+
System.err.println(e.getMessage());
56+
System.exit(2);
57+
return;
58+
}
59+
try (ZipFile root = zip;
60+
Writer out =
61+
new BufferedWriter(
62+
new OutputStreamWriter(new FileOutputStream(args[1]), StandardCharsets.UTF_8))) {
63+
ArchiveLoader loader = new ArchiveLoader(extensions, out);
64+
Enumeration<? extends ZipEntry> entries = root.entries();
65+
while (entries.hasMoreElements()) {
66+
ZipEntry entry = entries.nextElement();
67+
if (!entry.isDirectory() && loader.wants(entry.getName())) {
68+
try (InputStream in = root.getInputStream(entry)) {
69+
loader.visit("", entry.getName(), in);
70+
}
71+
}
72+
}
73+
}
74+
}
75+
76+
// The same escaping as SocketSupport.escapeField in the Maven extension.
77+
private static String escape(String s) {
78+
return s.replace("\\", "\\\\").replace("\t", "\\t").replace("\n", "\\n").replace("\r", "\\r");
79+
}
80+
81+
// ZipInputStream reads a non-zip as an empty archive. A zip starts with a local file header, or
82+
// when empty with its (zip64) end of central directory record (APPNOTE.TXT 4.3.6).
83+
private static boolean startsLikeZip(BufferedInputStream in) throws IOException {
84+
byte[] signature = new byte[4];
85+
in.mark(signature.length);
86+
int read = 0;
87+
while (read < signature.length) {
88+
int n = in.read(signature, read, signature.length - read);
89+
if (n < 0) {
90+
break;
91+
}
92+
read += n;
93+
}
94+
in.reset();
95+
return read == signature.length
96+
&& signature[0] == 'P'
97+
&& signature[1] == 'K'
98+
&& ((signature[2] == 3 && signature[3] == 4)
99+
|| (signature[2] == 5 && signature[3] == 6)
100+
|| (signature[2] == 6 && signature[3] == 6));
101+
}
102+
103+
// maven-archiver writes META-INF/maven/<groupId>/<artifactId>/pom.properties.
104+
private static boolean isPomProperties(String entryName) {
105+
String[] segments = entryName.split("/", -1);
106+
return segments.length == 5
107+
&& segments[0].equals("META-INF")
108+
&& segments[1].equals("maven")
109+
&& segments[4].equals("pom.properties");
110+
}
111+
112+
private boolean isArchive(String entryName) {
113+
int dot = entryName.lastIndexOf('.');
114+
return dot > entryName.lastIndexOf('/')
115+
&& archiveExtensions.contains(entryName.substring(dot + 1));
116+
}
117+
118+
private boolean wants(String entryName) {
119+
return isPomProperties(entryName) || isArchive(entryName);
120+
}
121+
122+
private void record(String... fields) throws IOException {
123+
for (int i = 0; i < fields.length; i++) {
124+
if (i > 0) {
125+
out.write('\t');
126+
}
127+
out.write(escape(fields[i]));
128+
}
129+
out.write('\n');
130+
}
131+
132+
// `in` is positioned at the entry's data and is not closed here.
133+
private void visit(String archivePath, String entryName, InputStream in) throws IOException {
134+
if (isPomProperties(entryName)) {
135+
Properties properties = new Properties();
136+
try {
137+
properties.load(in);
138+
} catch (IllegalArgumentException | IOException e) {
139+
record("malformed", archivePath, entryName, String.valueOf(e.getMessage()));
140+
return;
141+
}
142+
record(
143+
"pom",
144+
archivePath,
145+
entryName,
146+
properties.getProperty("groupId", ""),
147+
properties.getProperty("artifactId", ""),
148+
properties.getProperty("version", ""));
149+
} else if (isArchive(entryName)) {
150+
String nestedPath = archivePath.isEmpty() ? entryName : archivePath + "!/" + entryName;
151+
record("archive", nestedPath);
152+
BufferedInputStream buffered = new BufferedInputStream(in);
153+
if (!startsLikeZip(buffered)) {
154+
record("unreadable", nestedPath, "not a zip archive");
155+
return;
156+
}
157+
// Not closed: closing a ZipInputStream closes the stream it reads from.
158+
ZipInputStream nested = new ZipInputStream(buffered, StandardCharsets.UTF_8);
159+
try {
160+
ZipEntry entry;
161+
while ((entry = nested.getNextEntry()) != null) {
162+
if (!entry.isDirectory()) {
163+
visit(nestedPath, entry.getName(), nested);
164+
}
165+
}
166+
} catch (IOException | IllegalArgumentException e) {
167+
record("unreadable", nestedPath, String.valueOf(e));
168+
}
169+
}
170+
}
171+
}

‎src/commands/manifest/scripts/records.mts‎

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,18 @@ export type ParsedRecords = {
145145
unscannable: Unscannable[]
146146
}
147147

148+
// One field array per non-empty line; tolerates an emitter that writes CRLF.
149+
export function splitRecords(text: string): string[][] {
150+
const records: string[][] = []
151+
for (const line of text.split('\n')) {
152+
const rawLine = line.endsWith('\r') ? line.slice(0, -1) : line
153+
if (rawLine) {
154+
records.push(rawLine.split('\t').map(unescapeField))
155+
}
156+
}
157+
return records
158+
}
159+
148160
export function unescapeField(s: string): string {
149161
if (!s.includes('\\')) {
150162
return s
@@ -233,13 +245,7 @@ export function parseRecords(text: string): ParsedRecords {
233245
return b
234246
}
235247

236-
for (const line of text.split('\n')) {
237-
// Tolerates an emitter that writes CRLF line endings.
238-
const rawLine = line.endsWith('\r') ? line.slice(0, -1) : line
239-
if (!rawLine) {
240-
continue
241-
}
242-
const f = rawLine.split('\t').map(unescapeField)
248+
for (const f of splitRecords(text)) {
243249
switch (f[0]) {
244250
case 'meta':
245251
result.tool = f[1] ?? ''

‎src/commands/manifest/scripts/run.mts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ export type WorkspaceEnumerationResult = {
8888
}
8989

9090
// Bundled emitter assets, copied into dist by the rollup build.
91-
function manifestScriptsPath(...parts: string[]): string {
91+
export function manifestScriptsPath(...parts: string[]): string {
9292
return path.join(constants.distPath, 'manifest-scripts', ...parts)
9393
}
9494

@@ -185,7 +185,7 @@ function assembleRecords(
185185

186186
// Missing only in an unbuilt local checkout. Fail loudly: without the
187187
// extension, Maven silently emits an empty SBOM.
188-
function assertBundledAssetBuilt(
188+
export function assertBundledAssetBuilt(
189189
assetPath: string,
190190
description: string,
191191
// The package.json script that builds it, as the dist build names it too.

‎src/commands/scan/cmd-scan-create.mts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import path from 'node:path'
44
import { logger } from '@socketsecurity/registry/lib/logger'
55

66
import { assertValidExcludePaths } from './exclude-paths.mts'
7+
import { findArchiveTargets } from './generate-archive-facts.mts'
78
import {
89
generateUvMemberSboms,
910
resolveUvMemberDirs,
@@ -44,6 +45,7 @@ import {
4445
getFlagApiRequirementsOutput,
4546
getFlagListOutput,
4647
} from '../../utils/output-formatting.mts'
48+
import { isPathInside } from '../../utils/path-resolve.mts'
4749
import { hasDefaultApiToken } from '../../utils/sdk.mts'
4850
import { readOrDefaultSocketJsonUp } from '../../utils/socket-json.mts'
4951
import { socketDashboardLink } from '../../utils/terminal-link.mts'
@@ -240,6 +242,9 @@ async function run(
240242
- Defaults to the current dir (cwd) if none given
241243
- Multiple targets can be specified
242244
- If a target is a file, only that file is checked
245+
- If it is a .jar, .war or .ear, the Maven libraries identified by the
246+
pom.properties bundled in it are written to "<archive>.socket.facts.json"
247+
next to it and scanned (needs Java 8+; not with --reach)
243248
- If it is a dir, the dir is scanned for any supported manifest files
244249
- Dirs MUST be within the current dir (cwd), you can use --cwd to change it
245250
- Supports globbing such as "**/package.json", "**/${REQUIREMENTS_TXT}", etc.
@@ -665,6 +670,15 @@ async function run(
665670
'Target directory must be inside the current working directory when --reach is enabled',
666671
fail: 'provide a path inside the working directory',
667672
},
673+
{
674+
nook: true,
675+
test: findArchiveTargets(targets, cwd).every(archive =>
676+
isPathInside(archive, cwd),
677+
),
678+
message:
679+
'A .jar, .war or .ear target must be inside the current working directory',
680+
fail: 'provide a path inside the working directory, or use --cwd',
681+
},
668682
)
669683
if (!wasValidInput) {
670684
return

0 commit comments

Comments
 (0)