Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions crates/socket-patch-cli/CLI_CONTRACT.md

Large diffs are not rendered by default.

9 changes: 9 additions & 0 deletions crates/socket-patch-cli/src/commands/vex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2381,6 +2381,15 @@ fn omission_phrase(reason: &str) -> &'static str {
"go_vendor_content_mismatch" => "the native Go vendor tree does not contain the patch; run go mod vendor (or go work vendor for a workspace)",
"vendor_artifact_missing" => "the vendored artifact is missing",
"vendor_artifact_unreadable" => "the vendored artifact cannot be read",
"vendor_artifact_non_canonical" => {
"the vendored tarball holds a second entry the package manager would extract \
over a patched file (another top-level directory, a second spelling of the \
name, or a link), so what installs is not what was checked"
}
"vendor_lock_pin_mismatch" => {
"the lockfile pins the vendored tarball to a sha512 that is not that file's, so \
an install does not deliver it; re-run socket-patch scan --mode vendored"
}
"vendor_path_unsafe" => "the vendored artifact path is unsafe",
"vendor_uuid_mismatch" => "the vendored artifact belongs to a different patch",
"vendor_inventory_mismatch" => {
Expand Down
18 changes: 13 additions & 5 deletions crates/socket-patch-cli/tests/e2e_bun_lockb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1742,7 +1742,11 @@ async fn vendored_text_migration_rerun_and_supersede_revert() {
/// an unfrozen one drops the pin. A hosted re-run must restore the
/// manifest's `workspace:*`, after which a fresh frozen install from the
/// text lock gets the patched bytes. Needs a Bun >= 1.4 reader (the only
/// releases whose text reader re-resolves on the path literal). Not named
/// releases whose text reader re-resolves on the path literal). Bun 1.4.4
/// writes the manifest's `workspace:*` itself when it migrates (1.4.2
/// carries the path), so there the re-run has nothing to heal and must
/// leave the lock alone; the fresh frozen install is checked either way.
/// Not named
/// `native_binary_*`: scripts/backtest-bun-lockb.py runs exactly those
/// three tests per writer/reader cell; this one has its own 1.4.2 CI leg.
#[tokio::test(flavor = "multi_thread")]
Expand Down Expand Up @@ -1788,22 +1792,26 @@ async fn workspace_text_migration_heals_on_rerun() {
.unwrap();
require_success(output, "bun.lockb -> bun.lock migration");
let migrated = std::fs::read_to_string(project.join("bun.lock")).unwrap();
let carries_path = migrated.contains("\"consumer\": \"packages/consumer\"");
assert!(
migrated.contains("\"consumer\": \"packages/consumer\""),
"the migration carries the normalized path literal:\n{migrated}"
carries_path || migrated.contains("\"consumer\": \"workspace:*\""),
"the migration carries the normalized path literal (Bun 1.4.2) or the manifest's \
own spelling (Bun 1.4.4):\n{migrated}"
);
assert!(migrated.contains("/patch/npm/minimist/"), "{migrated}");

let rerun = scan(project, &server, "hosted", &[]);
assert_eq!(rerun["summary"]["applied"], 1, "{rerun}");
let healed = std::fs::read_to_string(project.join("bun.lock")).unwrap();
if carries_path {
assert_eq!(rerun["summary"]["applied"], 1, "{rerun}");
}
assert_eq!(
healed,
migrated.replace(
"\"consumer\": \"packages/consumer\"",
"\"consumer\": \"workspace:*\""
),
"only the literal changes"
"only the literal changes, and nothing when Bun wrote `workspace:*` itself"
);

// A fresh checkout of the healed text lock installs frozen, patched.
Expand Down
53 changes: 50 additions & 3 deletions crates/socket-patch-cli/tests/in_process_redirect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1934,20 +1934,67 @@ async fn scan_redirect_rewrites_bun_lock_v2() {
bun_manifestless_vex(tmp.path(), &lock_before, "bun-v2");
}

/// A future `lockfileVersion` (3) has no byte-exact fixtures: the rewrite
/// `"lockfileVersion": 3` is what bun 1.4 writes when package.json has a
/// nested override or a yarn-style path resolution. Only the lock's head
/// differs (its `overrides` object nests); the packages grammar is the v2
/// one, so the rewrite proceeds exactly like v2 and keeps the version line
/// and the nested head verbatim.
#[tokio::test]
#[serial]
async fn scan_redirect_rewrites_bun_lock_v3() {
let server = MockServer::start().await;
mock_discovery(&server).await;
mock_reference(&server).await;
mock_view(&server).await;

let tmp = tempfile::tempdir().unwrap();
write_bun_project(tmp.path(), 3);
const NESTED_OVERRIDES: &str =
" \"overrides\": {\n \"rc\": {\n \"ini\": \"1.3.5\",\n },\n },\n";
let lock_path = tmp.path().join("bun.lock");
let with_head = std::fs::read_to_string(&lock_path).unwrap().replacen(
" \"packages\": {",
&format!("{NESTED_OVERRIDES} \"packages\": {{"),
1,
);
assert!(with_head.contains(NESTED_OVERRIDES));
std::fs::write(&lock_path, &with_head).unwrap();
let lock_before = std::fs::read(&lock_path).unwrap();

let code = run(redirect_args(tmp.path(), server.uri())).await;
assert_eq!(code, 0, "scan --mode hosted (bun, lock v3) should succeed");

let lock = std::fs::read_to_string(&lock_path).unwrap();
assert!(
lock.contains("\"lockfileVersion\": 3,") && lock.contains(NESTED_OVERRIDES),
"the version line and the nested overrides head must be preserved verbatim; got:\n{lock}"
);
assert!(
lock.contains(&format!("\"{NAME}@{HOSTED_URL}\"")),
"the tuple's spec must be name@<hosted url>; got:\n{lock}"
);
assert!(
lock.contains(PATCHED_SHA512),
"integrity must be the patched sha512"
);
vlt_hosted_common::assert_no_ledger(tmp.path());
bun_manifestless_vex(tmp.path(), &lock_before, "bun-v3");
}

/// A future `lockfileVersion` (4) has no byte-exact fixtures: the rewrite
/// must refuse whole (fail closed), leave the lock byte-identical, count
/// nothing redirected, and surface `redirect_bun_lock_unsupported` in the
/// `--json` envelope. Subprocess so `redirected` and `warnings[]` can be
/// read back.
#[tokio::test]
#[serial]
async fn scan_redirect_refuses_bun_lock_v3() {
async fn scan_redirect_refuses_bun_lock_v4() {
let server = MockServer::start().await;
mock_discovery(&server).await;
mock_reference(&server).await;

let tmp = tempfile::tempdir().unwrap();
write_bun_project(tmp.path(), 3);
write_bun_project(tmp.path(), 4);
let before = std::fs::read_to_string(tmp.path().join("bun.lock")).unwrap();

let env = run_redirect_subprocess(tmp.path(), &server.uri());
Expand Down
12 changes: 6 additions & 6 deletions crates/socket-patch-cli/tests/vendor/in_process_vendor_bun.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
//! the 2-tuple `["consumer@workspace:packages/consumer", { "dependencies":
//! { … } }]`;
//! * a malformed `bun.lockb` with no text lock;
//! * a malformed lock (`lockfileVersion` 3, non-canonical `"packages" : {`
//! * a malformed lock (`lockfileVersion` 4, non-canonical `"packages" : {`
//! header, unterminated entry) and — on Unix — a FIFO squatting
//! `bun.lock`.
//!
Expand Down Expand Up @@ -158,9 +158,9 @@ const DIRECT_V1_TEMPLATE: &str = r#"{
}
"#;

/// A future/hand-edited lock the version gate refuses: lockfileVersion 3,
/// A future/hand-edited lock the version gate refuses: lockfileVersion 4,
/// a non-canonical `"packages" : {` header and an unterminated entry.
const MALFORMED_V3_LOCK: &str = "{\n \"lockfileVersion\": 3,\n \"packages\" : {\n \"left-pad\": [\"left-pad@1.3.0\", \"\",\n }\n}\n";
const MALFORMED_V4_LOCK: &str = "{\n \"lockfileVersion\": 4,\n \"packages\" : {\n \"left-pad\": [\"left-pad@1.3.0\", \"\",\n }\n}\n";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LockShape {
Expand All @@ -170,7 +170,7 @@ enum LockShape {
V0Direct,
V1Direct,
MalformedLockb,
MalformedV3,
MalformedV4,
}

impl LockShape {
Expand All @@ -190,7 +190,7 @@ impl LockShape {
LockShape::V0Workspace => WS_V0_TEMPLATE.to_string(),
LockShape::V0Direct => DIRECT_V0_TEMPLATE.to_string(),
LockShape::V1Direct => DIRECT_V1_TEMPLATE.to_string(),
LockShape::MalformedV3 => return Some(MALFORMED_V3_LOCK.to_string()),
LockShape::MalformedV4 => return Some(MALFORMED_V4_LOCK.to_string()),
LockShape::MalformedLockb => return None,
};
Some(text.replace("{REGISTRY}", &registry))
Expand Down Expand Up @@ -550,7 +550,7 @@ async fn scan_vendored_refuses_malformed_bun_lockb_before_download() {

#[tokio::test]
async fn scan_vendored_refuses_malformed_v3_lock_before_download() {
assert_scan_refuses(LockShape::MalformedV3, VERSION_CODE).await;
assert_scan_refuses(LockShape::MalformedV4, VERSION_CODE).await;
}

/// A refused scan on a project with a legacy (agent-mode) manifest: the
Expand Down
5 changes: 3 additions & 2 deletions crates/socket-patch-core/src/crawlers/npm_crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,8 @@ fn skipped_members_of(root: &Path) -> Vec<PathBuf> {

let Some(patterns) = crate::utils::fs::read_regular_to_string_sync(&root.join("package.json"))
.ok()
.and_then(|text| crate::formats::package_json::Workspaces::listed_patterns(&text))
// As Bun reads it too: an extra root can only keep a copy.
.and_then(|text| crate::formats::package_json::Workspaces::listed_patterns_as_bun(&text))
else {
return Vec::new();
};
Expand Down Expand Up @@ -998,7 +999,7 @@ fn bun_workspace_pattern_members_sync(root: &Path) -> Option<Vec<PathBuf>> {

// Bun refuses to install from a malformed field (#1900), so it names
// no member set.
let patterns = match Workspaces::parse(&text)? {
let patterns = match Workspaces::parse_as_bun(&text)? {
Workspaces::None => Vec::new(),
Workspaces::Patterns(patterns) => patterns,
Workspaces::Malformed(_) => return None,
Expand Down
127 changes: 126 additions & 1 deletion crates/socket-patch-core/src/formats/package_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,72 @@

use serde_json::Value;

/// A `package.json` parsed the way Bun reads it: a leading BOM is skipped,
/// and when the text is not strict JSON, the comments and trailing commas
/// Bun accepts are removed first ([`strip_jsonc`]). npm, yarn, pnpm and vlt
/// refuse such a file outright, so this is for readers that know Bun is the
/// installer (or that only widen): reading it is what keeps a Bun
/// workspace root from looking like no workspace at all. `None` when Bun
/// could not parse the text either.
pub(crate) fn parse(text: &str) -> Option<Value> {
let text = super::text::strip_bom(text);
serde_json::from_str(text)
.or_else(|_| serde_json::from_str(&strip_jsonc(text)))
.ok()
}

/// `text` with the JSONC Bun accepts in a `package.json` removed: `//` and
/// `/* */` comments and a comma before a closing `}` or `]`, all outside
/// strings. Everything else, strings included, is kept byte for byte.
pub(crate) fn strip_jsonc(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut chars = text.chars().peekable();
let mut in_string = false;
while let Some(c) = chars.next() {
if in_string {
out.push(c);
if c == '\\' {
if let Some(escaped) = chars.next() {
out.push(escaped);
}
} else if c == '"' {
in_string = false;
}
continue;
}
match c {
'"' => {
in_string = true;
out.push(c);
}
'/' if chars.peek() == Some(&'/') => {
while chars.peek().is_some_and(|&n| n != '\n') {
chars.next();
}
}
'/' if chars.peek() == Some(&'*') => {
chars.next();
let mut prev = '\0';
for n in chars.by_ref() {
if prev == '*' && n == '/' {
break;
}
prev = n;
}
}
'}' | ']' => {
let kept = out.trim_end_matches(char::is_whitespace).len();
if out[..kept].ends_with(',') {
out.remove(kept - 1);
}
out.push(c);
}
_ => out.push(c),
}
}
out
}

/// What a `package.json` `workspaces` field declares.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Workspaces {
Expand Down Expand Up @@ -68,13 +134,22 @@ impl Workspaces {
}

/// The field of a `package.json` text (a leading BOM is ignored);
/// `None` when the text is not JSON.
/// `None` when the text is not JSON. Strict, as npm, yarn, pnpm and
/// vlt read it: a manifest with comments is one they cannot install
/// from, so it names no workspace of theirs.
pub(crate) fn parse(package_json: &str) -> Option<Self> {
serde_json::from_str(super::text::strip_bom(package_json))
.ok()
.map(|doc| Self::of(&doc))
}

/// [`Self::parse`] as Bun reads the manifest ([`parse`]): comments and
/// trailing commas allowed. For a root Bun installs, and for readers
/// that only widen.
pub(crate) fn parse_as_bun(package_json: &str) -> Option<Self> {
parse(package_json).map(|doc| Self::of(&doc))
}

/// The patterns a widening reader takes: every string item of a
/// declared field, well-formed or not; `None` when no field is
/// declared. A refusal, an extra crawl root or a warning that reads a
Expand All @@ -93,6 +168,12 @@ impl Workspaces {
Self::parse(package_json)?.into_listed()
}

/// [`Self::listed_patterns`] as Bun reads the manifest
/// ([`Self::parse_as_bun`]).
pub(crate) fn listed_patterns_as_bun(package_json: &str) -> Option<Vec<String>> {
Self::parse_as_bun(package_json)?.into_listed()
}

/// Whether the field names at least one pattern ([`Self::into_listed`]
/// non-empty).
pub(crate) fn lists_any(&self) -> bool {
Expand All @@ -111,6 +192,50 @@ mod tests {
items.iter().map(|s| s.to_string()).collect()
}

/// Bun installs from a `package.json` with comments and trailing
/// commas (measured on Bun 1.1.45 to 1.4.4), so its workspace root must
/// read as one: a strict reader saw no workspace, which let a member's
/// stray lock be attested and left members in pruned directories
/// uncrawled.
#[test]
fn reads_the_comments_and_trailing_commas_bun_accepts() {
let jsonc = "{\n // workspace root\n \"name\": \"mono\", /* private */\n \
\"workspaces\": [\"packages/*\", \"vendor/lib\",],\n}\n";
assert!(serde_json::from_str::<Value>(jsonc).is_err());
assert_eq!(
Workspaces::listed_patterns_as_bun(jsonc),
Some(strings(&["packages/*", "vendor/lib"]))
);
assert_eq!(parse(jsonc).unwrap()["name"], "mono");
// npm, yarn, pnpm and vlt cannot install from it: no workspace of
// theirs.
assert_eq!(Workspaces::listed_patterns(jsonc), None);
assert_eq!(Workspaces::parse(jsonc), None);
// The object form, behind a BOM.
let object = "\u{feff}{\"workspaces\": {\"packages\": [\"a\",], }, }";
assert_eq!(
Workspaces::listed_patterns_as_bun(object),
Some(strings(&["a"]))
);
// Comment markers and commas inside strings are content.
let strings_kept = r#"{"name": "a//b /* c */", "workspaces": ["x,]", "y,}"],}"#;
assert_eq!(parse(strings_kept).unwrap()["name"], "a//b /* c */");
assert_eq!(
Workspaces::listed_patterns_as_bun(strings_kept),
Some(strings(&["x,]", "y,}"]))
);
// Strict JSON reads the same either way.
let plain = r#"{"workspaces": ["a/*"]}"#;
assert_eq!(
Workspaces::listed_patterns_as_bun(plain),
Workspaces::listed_patterns(plain)
);
// Still not JSON: unreadable, as before.
for broken in ["{\"workspaces\": [}", "{\"workspaces\": [\"a\"]", ""] {
assert_eq!(Workspaces::parse_as_bun(broken), None, "{broken:?}");
}
}

#[test]
fn classifies_every_shape() {
let cases: &[(&str, Workspaces)] = &[
Expand Down
Loading
Loading