socket-patch-core 3.3.0

Core library for socket-patch: manifest, hash, crawlers, patch engine, API client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/// Package manager type for selecting the correct command prefix.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PackageManager {
    Npm,
    Pnpm,
}

/// Get the socket-patch apply command for the given package manager.
fn socket_patch_command(pm: PackageManager) -> &'static str {
    match pm {
        PackageManager::Npm => "npx @socketsecurity/socket-patch apply --silent --ecosystems npm",
        PackageManager::Pnpm => {
            "pnpm dlx @socketsecurity/socket-patch apply --silent --ecosystems npm"
        }
    }
}

/// Legacy command patterns to detect existing configurations.
const LEGACY_PATCH_PATTERNS: &[&str] = &[
    "socket-patch apply",
    "npx @socketsecurity/socket-patch apply",
    "socket patch apply",
];

/// Check if a script string contains any known socket-patch apply pattern.
fn script_is_configured(script: &str) -> bool {
    LEGACY_PATCH_PATTERNS
        .iter()
        .any(|pattern| script.contains(pattern))
}

/// Status of setup script configuration (both postinstall and dependencies).
#[derive(Debug, Clone)]
pub struct ScriptSetupStatus {
    pub postinstall_configured: bool,
    pub postinstall_script: String,
    pub dependencies_configured: bool,
    pub dependencies_script: String,
    pub needs_update: bool,
}

/// Check if package.json scripts are properly configured for socket-patch.
/// Checks both the postinstall and dependencies lifecycle scripts.
pub fn is_setup_configured(package_json: &serde_json::Value) -> ScriptSetupStatus {
    let scripts = package_json.get("scripts");

    let postinstall_script = scripts
        .and_then(|s| s.get("postinstall"))
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let postinstall_configured = script_is_configured(&postinstall_script);

    let dependencies_script = scripts
        .and_then(|s| s.get("dependencies"))
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let dependencies_configured = script_is_configured(&dependencies_script);

    ScriptSetupStatus {
        postinstall_configured,
        postinstall_script,
        dependencies_configured,
        dependencies_script,
        needs_update: !postinstall_configured || !dependencies_configured,
    }
}

/// Check if a package.json content string is properly configured.
pub fn is_setup_configured_str(content: &str) -> ScriptSetupStatus {
    match serde_json::from_str::<serde_json::Value>(content) {
        Ok(val) => is_setup_configured(&val),
        Err(_) => ScriptSetupStatus {
            postinstall_configured: false,
            postinstall_script: String::new(),
            dependencies_configured: false,
            dependencies_script: String::new(),
            needs_update: true,
        },
    }
}

/// Generate an updated script that includes the socket-patch apply command.
/// If already configured, returns unchanged. Otherwise prepends the command.
pub fn generate_updated_script(current_script: &str, pm: PackageManager) -> String {
    let command = socket_patch_command(pm);
    let trimmed = current_script.trim();

    // If empty, just add the socket-patch command.
    if trimmed.is_empty() {
        return command.to_string();
    }

    // If any socket-patch variant is already present, return unchanged.
    if script_is_configured(trimmed) {
        return trimmed.to_string();
    }

    // Prepend socket-patch command so it runs first.
    format!("{command} && {trimmed}")
}

/// Update a package.json Value with socket-patch in both postinstall and
/// dependencies scripts.
/// Returns (modified, new_postinstall, new_dependencies).
pub fn update_package_json_object(
    package_json: &mut serde_json::Value,
    pm: PackageManager,
) -> (bool, String, String) {
    let status = is_setup_configured(package_json);

    if !status.needs_update {
        return (false, status.postinstall_script, status.dependencies_script);
    }

    // We can only attach scripts to an object root. Anything else (array,
    // string, number, bool, null) cannot hold a "scripts" key, so indexing it
    // below would panic. Bail out as a no-op instead.
    if !package_json.is_object() {
        return (false, status.postinstall_script, status.dependencies_script);
    }

    // Ensure `scripts` exists *and* is an object. A present-but-non-object
    // `scripts` (e.g. a string or array) would otherwise panic when indexed.
    if !package_json
        .get("scripts")
        .map(serde_json::Value::is_object)
        .unwrap_or(false)
    {
        package_json["scripts"] = serde_json::json!({});
    }

    let mut modified = false;

    let new_postinstall = if !status.postinstall_configured {
        modified = true;
        let s = generate_updated_script(&status.postinstall_script, pm);
        package_json["scripts"]["postinstall"] = serde_json::Value::String(s.clone());
        s
    } else {
        status.postinstall_script
    };

    let new_dependencies = if !status.dependencies_configured {
        modified = true;
        let s = generate_updated_script(&status.dependencies_script, pm);
        package_json["scripts"]["dependencies"] = serde_json::Value::String(s.clone());
        s
    } else {
        status.dependencies_script
    };

    (modified, new_postinstall, new_dependencies)
}

/// Parse package.json content and update it with socket-patch scripts.
/// Returns (modified, new_content, old_postinstall, new_postinstall,
/// old_dependencies, new_dependencies).
pub fn update_package_json_content(
    content: &str,
    pm: PackageManager,
) -> Result<(bool, String, String, String, String, String), String> {
    let mut package_json: serde_json::Value =
        serde_json::from_str(content).map_err(|e| format!("Invalid package.json: {e}"))?;

    // A package.json must be a JSON object; otherwise there is nowhere to add
    // lifecycle scripts.
    if !package_json.is_object() {
        return Err("Invalid package.json: root is not a JSON object".to_string());
    }

    // Refuse to clobber a malformed (present but non-object) `scripts` value.
    // `null` is treated as absent and replaced with a fresh object downstream.
    if let Some(scripts) = package_json.get("scripts") {
        if !scripts.is_null() && !scripts.is_object() {
            return Err("Invalid package.json: \"scripts\" is not a JSON object".to_string());
        }
    }

    let status = is_setup_configured(&package_json);

    if !status.needs_update {
        return Ok((
            false,
            content.to_string(),
            status.postinstall_script.clone(),
            status.postinstall_script,
            status.dependencies_script.clone(),
            status.dependencies_script,
        ));
    }

    let old_postinstall = status.postinstall_script.clone();
    let old_dependencies = status.dependencies_script.clone();

    let (_, new_postinstall, new_dependencies) = update_package_json_object(&mut package_json, pm);
    let new_content = serde_json::to_string_pretty(&package_json).unwrap() + "\n";

    Ok((
        true,
        new_content,
        old_postinstall,
        new_postinstall,
        old_dependencies,
        new_dependencies,
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── is_setup_configured ─────────────────────────────────────────

    #[test]
    fn test_not_configured() {
        let pkg: serde_json::Value = serde_json::json!({
            "name": "test",
            "scripts": {
                "build": "tsc"
            }
        });
        let status = is_setup_configured(&pkg);
        assert!(!status.postinstall_configured);
        assert!(!status.dependencies_configured);
        assert!(status.needs_update);
    }

    #[test]
    fn test_postinstall_configured_dependencies_not() {
        let pkg: serde_json::Value = serde_json::json!({
            "name": "test",
            "scripts": {
                "postinstall": "npx @socketsecurity/socket-patch apply --silent --ecosystems npm"
            }
        });
        let status = is_setup_configured(&pkg);
        assert!(status.postinstall_configured);
        assert!(!status.dependencies_configured);
        assert!(status.needs_update);
    }

    #[test]
    fn test_both_configured() {
        let pkg: serde_json::Value = serde_json::json!({
            "name": "test",
            "scripts": {
                "postinstall": "npx @socketsecurity/socket-patch apply --silent --ecosystems npm",
                "dependencies": "npx @socketsecurity/socket-patch apply --silent --ecosystems npm"
            }
        });
        let status = is_setup_configured(&pkg);
        assert!(status.postinstall_configured);
        assert!(status.dependencies_configured);
        assert!(!status.needs_update);
    }

    #[test]
    fn test_legacy_socket_patch_apply_recognized() {
        let pkg: serde_json::Value = serde_json::json!({
            "scripts": {
                "postinstall": "socket patch apply --silent --ecosystems npm",
                "dependencies": "socket-patch apply"
            }
        });
        let status = is_setup_configured(&pkg);
        assert!(status.postinstall_configured);
        assert!(status.dependencies_configured);
        assert!(!status.needs_update);
    }

    #[test]
    fn test_no_scripts() {
        let pkg: serde_json::Value = serde_json::json!({"name": "test"});
        let status = is_setup_configured(&pkg);
        assert!(!status.postinstall_configured);
        assert!(status.postinstall_script.is_empty());
        assert!(!status.dependencies_configured);
        assert!(status.dependencies_script.is_empty());
    }

    #[test]
    fn test_no_postinstall() {
        let pkg: serde_json::Value = serde_json::json!({
            "scripts": {"build": "tsc"}
        });
        let status = is_setup_configured(&pkg);
        assert!(!status.postinstall_configured);
        assert!(status.postinstall_script.is_empty());
    }

    // ── is_setup_configured_str ─────────────────────────────────────

    #[test]
    fn test_configured_str_invalid_json() {
        let status = is_setup_configured_str("not json");
        assert!(!status.postinstall_configured);
        assert!(status.needs_update);
    }

    #[test]
    fn test_configured_str_legacy_npx_pattern() {
        let content =
            r#"{"scripts":{"postinstall":"npx @socketsecurity/socket-patch apply --silent"}}"#;
        let status = is_setup_configured_str(content);
        assert!(status.postinstall_configured);
    }

    #[test]
    fn test_configured_str_socket_dash_patch() {
        let content =
            r#"{"scripts":{"postinstall":"socket-patch apply --silent --ecosystems npm"}}"#;
        let status = is_setup_configured_str(content);
        assert!(status.postinstall_configured);
    }

    #[test]
    fn test_configured_str_pnpm_dlx_pattern() {
        let content = r#"{"scripts":{"postinstall":"pnpm dlx @socketsecurity/socket-patch apply --silent --ecosystems npm"}}"#;
        let status = is_setup_configured_str(content);
        // "pnpm dlx @socketsecurity/socket-patch apply" contains "socket-patch apply"
        assert!(status.postinstall_configured);
    }

    // ── generate_updated_script ─────────────────────────────────────

    #[test]
    fn test_generate_empty_npm() {
        assert_eq!(
            generate_updated_script("", PackageManager::Npm),
            "npx @socketsecurity/socket-patch apply --silent --ecosystems npm"
        );
    }

    #[test]
    fn test_generate_empty_pnpm() {
        assert_eq!(
            generate_updated_script("", PackageManager::Pnpm),
            "pnpm dlx @socketsecurity/socket-patch apply --silent --ecosystems npm"
        );
    }

    #[test]
    fn test_generate_prepend_npm() {
        assert_eq!(
            generate_updated_script("echo done", PackageManager::Npm),
            "npx @socketsecurity/socket-patch apply --silent --ecosystems npm && echo done"
        );
    }

    #[test]
    fn test_generate_prepend_pnpm() {
        assert_eq!(
            generate_updated_script("echo done", PackageManager::Pnpm),
            "pnpm dlx @socketsecurity/socket-patch apply --silent --ecosystems npm && echo done"
        );
    }

    #[test]
    fn test_generate_already_configured() {
        let current = "socket-patch apply && echo done";
        assert_eq!(
            generate_updated_script(current, PackageManager::Npm),
            current
        );
    }

    #[test]
    fn test_generate_whitespace_only() {
        let result = generate_updated_script("  \t  ", PackageManager::Npm);
        assert_eq!(
            result,
            "npx @socketsecurity/socket-patch apply --silent --ecosystems npm"
        );
    }

    // ── update_package_json_object ──────────────────────────────────

    #[test]
    fn test_update_object_creates_scripts() {
        let mut pkg: serde_json::Value = serde_json::json!({"name": "test"});
        let (modified, new_postinstall, new_dependencies) =
            update_package_json_object(&mut pkg, PackageManager::Npm);
        assert!(modified);
        assert!(new_postinstall.contains("npx @socketsecurity/socket-patch apply"));
        assert!(new_dependencies.contains("npx @socketsecurity/socket-patch apply"));
        assert!(pkg.get("scripts").is_some());
        assert!(pkg["scripts"]["postinstall"].is_string());
        assert!(pkg["scripts"]["dependencies"].is_string());
    }

    #[test]
    fn test_update_object_creates_scripts_pnpm() {
        let mut pkg: serde_json::Value = serde_json::json!({"name": "test"});
        let (modified, new_postinstall, new_dependencies) =
            update_package_json_object(&mut pkg, PackageManager::Pnpm);
        assert!(modified);
        assert!(new_postinstall.contains("pnpm dlx @socketsecurity/socket-patch apply"));
        assert!(new_dependencies.contains("pnpm dlx @socketsecurity/socket-patch apply"));
    }

    #[test]
    fn test_update_object_noop_when_both_configured() {
        let mut pkg: serde_json::Value = serde_json::json!({
            "scripts": {
                "postinstall": "npx @socketsecurity/socket-patch apply --silent --ecosystems npm",
                "dependencies": "npx @socketsecurity/socket-patch apply --silent --ecosystems npm"
            }
        });
        let (modified, _, _) = update_package_json_object(&mut pkg, PackageManager::Npm);
        assert!(!modified);
    }

    #[test]
    fn test_update_object_adds_dependencies_when_postinstall_exists() {
        let mut pkg: serde_json::Value = serde_json::json!({
            "scripts": {
                "postinstall": "npx @socketsecurity/socket-patch apply --silent --ecosystems npm"
            }
        });
        let (modified, _, new_dependencies) =
            update_package_json_object(&mut pkg, PackageManager::Npm);
        assert!(modified);
        assert!(new_dependencies.contains("npx @socketsecurity/socket-patch apply"));
        // postinstall should remain unchanged
        assert_eq!(
            pkg["scripts"]["postinstall"].as_str().unwrap(),
            "npx @socketsecurity/socket-patch apply --silent --ecosystems npm"
        );
    }

    // ── update_package_json_content ─────────────────────────────────

    #[test]
    fn test_update_content_roundtrip_no_scripts() {
        let content = r#"{"name": "test"}"#;
        let (modified, new_content, old_pi, new_pi, old_dep, new_dep) =
            update_package_json_content(content, PackageManager::Npm).unwrap();
        assert!(modified);
        assert!(old_pi.is_empty());
        assert!(new_pi.contains("npx @socketsecurity/socket-patch apply"));
        assert!(old_dep.is_empty());
        assert!(new_dep.contains("npx @socketsecurity/socket-patch apply"));
        let parsed: serde_json::Value = serde_json::from_str(&new_content).unwrap();
        assert!(parsed["scripts"]["postinstall"].is_string());
        assert!(parsed["scripts"]["dependencies"].is_string());
    }

    #[test]
    fn test_update_content_already_configured() {
        let content = r#"{"scripts":{"postinstall":"socket patch apply --silent --ecosystems npm","dependencies":"socket patch apply --silent --ecosystems npm"}}"#;
        let (modified, _, _, _, _, _) =
            update_package_json_content(content, PackageManager::Npm).unwrap();
        assert!(!modified);
    }

    #[test]
    fn test_update_content_invalid_json() {
        let result = update_package_json_content("not json", PackageManager::Npm);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("Invalid package.json"));
    }

    #[test]
    fn test_update_object_scripts_is_string_does_not_panic() {
        // Regression: a present-but-non-object `scripts` previously panicked
        // when indexed (`cannot access key "postinstall" in JSON string`).
        let mut pkg: serde_json::Value = serde_json::json!({
            "name": "test",
            "scripts": "build"
        });
        let (modified, _, _) = update_package_json_object(&mut pkg, PackageManager::Npm);
        // Root is an object but `scripts` is malformed; the object-level helper
        // replaces it rather than panicking.
        assert!(modified);
        assert!(pkg["scripts"]["postinstall"].is_string());
        assert!(pkg["scripts"]["dependencies"].is_string());
    }

    #[test]
    fn test_update_object_scripts_is_array_does_not_panic() {
        let mut pkg: serde_json::Value = serde_json::json!({
            "name": "test",
            "scripts": ["build"]
        });
        let (modified, _, _) = update_package_json_object(&mut pkg, PackageManager::Npm);
        assert!(modified);
        assert!(pkg["scripts"].is_object());
    }

    #[test]
    fn test_update_object_scripts_is_null() {
        // `null` scripts is treated as absent and replaced with an object.
        let mut pkg: serde_json::Value = serde_json::json!({
            "name": "test",
            "scripts": null
        });
        let (modified, _, _) = update_package_json_object(&mut pkg, PackageManager::Npm);
        assert!(modified);
        assert!(pkg["scripts"]["postinstall"].is_string());
    }

    #[test]
    fn test_update_object_non_object_root_is_noop() {
        // Regression: a non-object root previously panicked on `["scripts"] = ...`.
        let mut arr: serde_json::Value = serde_json::json!([1, 2, 3]);
        let (modified, _, _) = update_package_json_object(&mut arr, PackageManager::Npm);
        assert!(!modified);
        assert_eq!(arr, serde_json::json!([1, 2, 3]));
    }

    #[test]
    fn test_update_content_non_object_root_errors() {
        // Regression: valid JSON that is not an object must error, not panic.
        for content in ["[1,2,3]", "42", "\"hello\"", "true", "null"] {
            let result = update_package_json_content(content, PackageManager::Npm);
            assert!(result.is_err(), "expected error for content {content:?}");
            assert!(result.unwrap_err().contains("root is not a JSON object"));
        }
    }

    #[test]
    fn test_update_content_non_object_scripts_errors() {
        // Regression: a present-but-non-object `scripts` must error rather than
        // silently clobbering the user's value or panicking.
        let content = r#"{"name":"test","scripts":"build"}"#;
        let result = update_package_json_content(content, PackageManager::Npm);
        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .contains("\"scripts\" is not a JSON object"));
    }

    #[test]
    fn test_update_content_null_scripts_creates_object() {
        // `null` scripts is benign: treated as absent and populated.
        let content = r#"{"name":"test","scripts":null}"#;
        let (modified, new_content, _, new_pi, _, new_dep) =
            update_package_json_content(content, PackageManager::Npm).unwrap();
        assert!(modified);
        assert!(new_pi.contains("npx @socketsecurity/socket-patch apply"));
        assert!(new_dep.contains("npx @socketsecurity/socket-patch apply"));
        let parsed: serde_json::Value = serde_json::from_str(&new_content).unwrap();
        assert!(parsed["scripts"]["postinstall"].is_string());
        assert!(parsed["scripts"]["dependencies"].is_string());
    }

    #[test]
    fn test_update_content_pnpm() {
        let content = r#"{"name": "test"}"#;
        let (modified, new_content, _, new_pi, _, new_dep) =
            update_package_json_content(content, PackageManager::Pnpm).unwrap();
        assert!(modified);
        assert!(new_pi.contains("pnpm dlx @socketsecurity/socket-patch apply"));
        assert!(new_dep.contains("pnpm dlx @socketsecurity/socket-patch apply"));
        let parsed: serde_json::Value = serde_json::from_str(&new_content).unwrap();
        assert!(parsed["scripts"]["postinstall"]
            .as_str()
            .unwrap()
            .contains("pnpm dlx"));
        assert!(parsed["scripts"]["dependencies"]
            .as_str()
            .unwrap()
            .contains("pnpm dlx"));
    }
}