saferskills 0.2.0

Every AI capability, independently scanned — install Skills & MCP servers with a verified SaferSkills trust score.
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//! Hand-written wire DTOs for the SaferSkills public API.
//!
//! These mirror the snake_case JSON the API emits (`OrmBaseModel.model_dump
//! (by_alias=false)`); paginated lists deserialize the `data` envelope key (NOT
//! `items`, per `naming-conventions.md`). There is **no** typify/codegen here —
//! the CLI is an API consumer, not part of the repo's 8-generator pipeline. A
//! contract test (`tests/contract.rs`) deserializes `services/api/openapi.json`
//! component examples into these structs and fails on drift, which is the
//! honest schema-fidelity gate.
//!
//! Resilience (prime invariant: never panic on malformed input): unknown enum
//! values fall through to an `Unknown` variant, optional/extra fields default,
//! and unknown object keys are ignored (no `deny_unknown_fields`).

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// Finding-severity ladder. `info` carries weight 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Info,
    Low,
    Medium,
    High,
    Critical,
    /// Forward-compat catch-all for a severity this CLI build doesn't know.
    #[serde(other)]
    Unknown,
}

impl Severity {
    /// Ordering rank for "highest severity wins" gating. `Unknown`
    /// sorts at the bottom so it never silently escalates a gate.
    pub fn rank(self) -> u8 {
        match self {
            Severity::Critical => 4,
            Severity::High => 3,
            Severity::Medium => 2,
            Severity::Low => 1,
            Severity::Info | Severity::Unknown => 0,
        }
    }
}

/// Score-tier band. `unscoped` = never scanned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Tier {
    Green,
    Yellow,
    Orange,
    Red,
    Unscoped,
    /// Forward-compat catch-all for a tier this CLI build doesn't know.
    #[serde(other)]
    Unknown,
}

impl Tier {
    /// Human label for a tier (e.g. `"Green"`), for plain-text contexts like
    /// did-you-mean suggestions that render without ANSI color.
    pub fn label(self) -> &'static str {
        match self {
            Tier::Green => "Green",
            Tier::Yellow => "Yellow",
            Tier::Orange => "Orange",
            Tier::Red => "Red",
            Tier::Unscoped => "Unscoped",
            Tier::Unknown => "Unknown",
        }
    }
}

/// One line of a finding's matched-content evidence window (report-DTO only,
/// snapshot-sourced — never a trace field).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct EvidenceLine {
    pub line_no: u32,
    pub text: String,
    pub hit: bool,
}

/// The matched-line window shown verbatim on a finding card.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct EvidenceExcerpt {
    pub file: String,
    #[serde(default)]
    pub lang: Option<String>,
    #[serde(default)]
    pub lines: Vec<EvidenceLine>,
    #[serde(default)]
    pub truncated: bool,
}

impl EvidenceExcerpt {
    /// The first matched (`hit`) line, for a single-line evidence summary.
    pub fn hit_line(&self) -> Option<&EvidenceLine> {
        self.lines
            .iter()
            .find(|l| l.hit)
            .or_else(|| self.lines.first())
    }
}

/// A single rule fire on a scanned artifact (report DTO, snake_case).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FindingResponse {
    pub id: String,
    pub rule_id: String,
    pub severity: Severity,
    pub sub_score: String,
    pub penalty: i32,
    pub status_at_scan: String,
    pub file_path: String,
    pub line_start: u32,
    #[serde(default)]
    pub line_end: Option<u32>,
    pub matched_content_sha256: String,
    pub remediation_link: String,
    pub rubric_version: String,
    #[serde(default)]
    pub evidence_excerpt: Option<EvidenceExcerpt>,
    // Explainable-finding prose, inlined server-side onto the report — the CLI
    // renders straight from the finding, no rule corpus fetch. All
    // `#[serde(default)]` for forward-compat: a degraded finding (no
    // content entry) carries None and the CLI falls back to rule_id +
    // remediation_link.
    #[serde(default)]
    pub title: Option<String>,
    #[serde(default)]
    pub explanation: Option<String>,
    #[serde(default)]
    pub category_label: Option<String>,
    #[serde(default)]
    pub severity_rationale: Option<String>,
    #[serde(default)]
    pub remediation: Option<FindingRemediation>,
}

/// An Avoid → Safer before/after pair on an inlined finding remediation.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SaferPattern {
    pub before: String,
    pub after: String,
}

/// How to fix a finding — inlined onto the report finding (snake_case).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct FindingRemediation {
    pub action: String,
    #[serde(default)]
    pub steps: Option<Vec<String>>,
    #[serde(default)]
    pub safer_pattern: Option<SaferPattern>,
}

/// A catalog item as it appears in list responses + `item` on the detail page.
/// (The API's `CatalogItemDetail` is a superset — its extra keys are ignored.)
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CatalogItemSummary {
    pub id: String,
    pub slug: String,
    pub kind: String,
    pub display_name: String,
    #[serde(default)]
    pub description: Option<String>,
    #[serde(default)]
    pub github_url: Option<String>,
    #[serde(default)]
    pub github_org: Option<String>,
    #[serde(default)]
    pub github_repo: Option<String>,
    #[serde(default)]
    pub source_kind: Option<String>,
    pub popularity_tier: String,
    #[serde(default)]
    pub popularity_score: i64,
    #[serde(default)]
    pub latest_scan_score: Option<u8>,
    #[serde(default)]
    pub latest_scan_tier: Option<Tier>,
    #[serde(default)]
    pub latest_scan_at: Option<String>,
    #[serde(default)]
    pub findings_count: i64,
    #[serde(default)]
    pub registries: Vec<String>,
    #[serde(default)]
    pub agent_compatibility: Vec<String>,
    #[serde(default)]
    pub updated_at: Option<String>,
}

/// Paginated catalog list envelope. The array key is `data` (NOT `items`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CatalogListEnvelope {
    #[serde(default)]
    pub data: Vec<CatalogItemSummary>,
    #[serde(default)]
    pub next_cursor: Option<String>,
    #[serde(default)]
    pub total_count: i64,
    #[serde(default)]
    pub page: i64,
    #[serde(default)]
    pub total_pages: i64,
    #[serde(default)]
    pub page_size: i64,
}

/// The install descriptor the CLI consumes to install/uninstall/update a
/// capability across compatible agents (mirrors `app/scan/discovery.py::
/// build_install_spec`; snake_case keys). Every field `#[serde(default)]` for
/// forward-compat — a pre-feature scan carries `install_spec: null` and the CLI
/// falls back to its legacy behaviour.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct InstallSpec {
    #[serde(default)]
    pub kind: Option<String>,
    /// The MCP launch object to merge (`{command,args,env}` or `{url}`).
    #[serde(default)]
    pub mcp_entry: Option<serde_json::Value>,
    /// The hook event names this hook registers (`PreToolUse`, …).
    #[serde(default)]
    pub hook_events: Option<Vec<String>>,
    /// Source rules files (path + source format).
    #[serde(default)]
    pub rules_files: Option<Vec<RulesFile>>,
    /// Plugin coordinates (name/version/marketplace).
    #[serde(default)]
    pub plugin_ref: Option<PluginRef>,
}

/// One rules file in an `install_spec` — its repo path + source format.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RulesFile {
    pub path: String,
    #[serde(default)]
    pub target: Option<String>,
}

/// Plugin coordinates carried on an `install_spec`.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct PluginRef {
    #[serde(default)]
    pub name: Option<String>,
    #[serde(default)]
    pub version: Option<String>,
    #[serde(default)]
    pub marketplace_git: Option<String>,
}

/// A per-capability scan report (`GET /scans/{scan_id}`, and `latest_scan` on
/// the item detail).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ScanReportDetail {
    pub id: String,
    #[serde(default)]
    pub github_url: Option<String>,
    pub slug: String,
    pub display_name: String,
    pub aggregate_score: u8,
    pub tier: Tier,
    #[serde(default)]
    pub sub_scores: BTreeMap<String, i64>,
    #[serde(default)]
    pub findings: Vec<FindingResponse>,
    #[serde(default)]
    pub scanned_at: Option<String>,
    #[serde(default)]
    pub rubric_version: Option<String>,
    #[serde(default)]
    pub engine_version: Option<String>,
    #[serde(default)]
    pub ref_sha: Option<String>,
    #[serde(default)]
    pub component_path: Option<String>,
    #[serde(default)]
    pub scan_run_id: Option<String>,
    /// Per-capability install descriptor (null for skill + pre-feature scans).
    #[serde(default)]
    pub install_spec: Option<InstallSpec>,
}

/// The item-detail response (`GET /items/{slug}`). Only the fields the CLI
/// reads are modeled; the rest of the rich page payload is ignored.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ItemDetailResponse {
    pub item: CatalogItemSummary,
    #[serde(default)]
    pub latest_scan: Option<ScanReportDetail>,
}

/// One capability within a repo scan run (`GET /scans/runs/{run_id}`).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct CapabilityRow {
    pub kind: String,
    pub name: String,
    #[serde(default)]
    pub component_path: Option<String>,
    pub aggregate_score: u8,
    pub tier: Tier,
    pub scan_id: String,
    pub catalog_slug: String,
    #[serde(default)]
    pub sub_scores: BTreeMap<String, i64>,
    #[serde(default)]
    pub findings: Vec<FindingResponse>,
}

/// A repo scan run — the roll-up the CLI's `capability` scan / audit reports (the
/// run report IS the roll-up).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ScanRunReportDetail {
    pub id: String,
    #[serde(default)]
    pub github_url: Option<String>,
    pub repo_aggregate_score: u8,
    pub repo_tier: Tier,
    #[serde(default)]
    pub kind_tally: BTreeMap<String, i64>,
    #[serde(default)]
    pub capability_count: i64,
    #[serde(default)]
    pub capabilities: Vec<CapabilityRow>,
    /// `pending` | `running` | `completed` | `failed`. Free-form so an unknown
    /// status never breaks polling; absent on older servers.
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub visibility: Option<String>,
    #[serde(default)]
    pub source_kind: Option<String>,
    #[serde(default)]
    pub share_url: Option<String>,
    /// Canonical public report URL on the webapp, built server-side from
    /// `public_base_url` — the client need not know the webapp origin (which
    /// differs from the API origin in local dev). Absent on older servers.
    #[serde(default)]
    pub report_url: Option<String>,
    #[serde(default)]
    pub expires_at: Option<String>,
}

/// `GET /api/v1/scans/cli-challenge` — a stateless Proof-of-Work challenge for
/// the CLI scan-submit gate. `status` of a submit stays `String` so an
/// unknown value never panics.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ChallengeResponse {
    pub challenge: String,
    pub difficulty: u32,
    #[serde(default)]
    pub expires_at: Option<String>,
}

/// 202 result of `POST /api/v1/scans` (a GitHub-URL submit).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ScanSubmitResponse {
    pub id: String,
    /// Free-form so an unknown status never breaks deserialization.
    pub status: String,
    #[serde(default)]
    pub cached: bool,
    #[serde(default)]
    pub rubric_version: Option<String>,
    /// Present (non-null) only for an `unlisted` submission.
    #[serde(default)]
    pub share_url: Option<String>,
}

/// 202 result of `POST /api/v1/scans/upload` (a local-content submit).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ScanUploadResponse {
    pub id: String,
    pub status: String,
    #[serde(default)]
    pub source_kind: Option<String>,
    #[serde(default)]
    pub visibility: Option<String>,
    #[serde(default)]
    pub slug: Option<String>,
    /// Present (non-null) only for an `unlisted` upload.
    #[serde(default)]
    pub share_url: Option<String>,
}

// ─── Agent Scan ──────────────────────────────────────────────

/// `POST|GET /api/v1/agent-scans/bootstrap` — the minted run + the rendered
/// bootstrap prompt the user pastes into their agent (canaries are NOT in it).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BootstrapResponse {
    pub run_id: String,
    pub prompt: String,
    pub consent_notice: String,
    pub pack_url: String,
    pub submit_token: String,
    pub poll_url: String,
    /// Present (non-null) only for an `unlisted` run.
    #[serde(default)]
    pub share_token: Option<String>,
}

/// `GET /api/v1/agent-scans/{run_id}/status` — the token-authed lightweight poll.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgentStatusResponse {
    /// `created` | `fetched` | `submitted` | `graded` | `published` | `aborted`.
    pub status: String,
    #[serde(default)]
    pub score: Option<i64>,
    #[serde(default)]
    pub band: Option<String>,
    #[serde(default)]
    pub report_url: Option<String>,
    #[serde(default)]
    pub share_url: Option<String>,
}

/// An Avoid → Safer before/after pair on an agent-finding remediation.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgentSaferPattern {
    pub before: String,
    pub after: String,
}

/// How to fix an agent finding (pack-sourced prose).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgentRemediation {
    pub action: String,
    #[serde(default)]
    pub steps: Option<Vec<String>>,
    #[serde(default)]
    pub safer_pattern: Option<AgentSaferPattern>,
}

/// One proof-of-tests row — every executed test, not just the vulnerable ones.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgentCheckRow {
    pub test_id: String,
    pub family: String,
    pub title: String,
    /// `vulnerable` | `not_observed` | `n_a` | `error` (free-form for forward-compat).
    pub verdict: String,
    pub severity: Severity,
}

/// One observed-vulnerable agent finding (report DTO, snake_case).
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgentFindingDto {
    pub id: String,
    pub test_id: String,
    pub severity: Severity,
    pub verdict: String,
    pub family: String,
    #[serde(default)]
    pub owasp_refs: Vec<String>,
    #[serde(default)]
    pub atlas_refs: Vec<String>,
    #[serde(default)]
    pub nist_refs: Vec<String>,
    pub score_delta: i64,
    /// `substring` | `normalized_substring` | `transform` | `tool_arg` | `forbidden_tool_presence`.
    pub detection_rule: String,
    #[serde(default)]
    pub leaked_canary_slot: Option<String>,
    pub title: String,
    pub explanation: String,
    #[serde(default)]
    pub severity_rationale: Option<String>,
    #[serde(default)]
    pub category_label: Option<String>,
    pub remediation: AgentRemediation,
    /// Report-DTO-only redacted transcript window — present only on the private
    /// (unlisted token-route) projection; `None` on the public report.
    #[serde(default)]
    pub evidence_excerpt: Option<EvidenceExcerpt>,
}

/// The full agent-scan report (`GET /agent-scans/{id}` and `.../r/{token}`). Mirrors
/// the backend `AgentScanReportDetail` snake_case wire shape. Every field
/// `#[serde(default)]` where the schema allows, for forward-compat.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AgentScanReport {
    pub id: String,
    pub status: String,
    pub agent_name: String,
    pub runtime: String,
    #[serde(default)]
    pub score: Option<u8>,
    pub band: Tier,
    #[serde(default)]
    pub verdict_label: Option<String>,
    #[serde(default)]
    pub cap_callout: Option<String>,
    #[serde(default)]
    pub confidence: Option<String>,
    #[serde(default)]
    pub score_breakdown: Option<serde_json::Value>,
    #[serde(default)]
    pub trust_labels: Vec<String>,
    pub pack_id: String,
    pub pack_version: String,
    #[serde(default)]
    pub pack_signature_verified: Option<bool>,
    #[serde(default)]
    pub capabilities_present: Vec<String>,
    #[serde(default)]
    pub capabilities_absent: Vec<String>,
    #[serde(default)]
    pub family_tally: BTreeMap<String, i64>,
    #[serde(default)]
    pub checks: Vec<AgentCheckRow>,
    #[serde(default)]
    pub findings: Vec<AgentFindingDto>,
    /// Contributing component scores — context only, never rendered by the CLI.
    #[serde(default)]
    pub component_scores: Vec<serde_json::Value>,
    pub visibility: String,
    #[serde(default)]
    pub expires_at: Option<String>,
    #[serde(default)]
    pub share_url: Option<String>,
    #[serde(default)]
    pub report_url: Option<String>,
    pub rubric_version: String,
    pub engine_version: String,
    #[serde(default)]
    pub latency_ms: i64,
    #[serde(default)]
    pub scanned_at: Option<String>,
}

/// `GET /health`.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct HealthResponse {
    pub status: String,
    pub version: String,
    pub git_sha: String,
    #[serde(default)]
    pub migrations_ok: bool,
    #[serde(default)]
    pub migrations_error: Option<String>,
}

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

    #[test]
    fn severity_deserializes_lowercase() {
        let s: Severity = serde_json::from_str("\"critical\"").unwrap();
        assert_eq!(s, Severity::Critical);
    }

    #[test]
    fn unknown_severity_falls_through() {
        let s: Severity = serde_json::from_str("\"apocalyptic\"").unwrap();
        assert_eq!(s, Severity::Unknown);
        assert_eq!(s.rank(), 0);
    }

    #[test]
    fn unknown_tier_falls_through() {
        let t: Tier = serde_json::from_str("\"plaid\"").unwrap();
        assert_eq!(t, Tier::Unknown);
    }

    #[test]
    fn severity_rank_orders_correctly() {
        assert!(Severity::Critical.rank() > Severity::High.rank());
        assert!(Severity::High.rank() > Severity::Low.rank());
        assert_eq!(Severity::Info.rank(), 0);
    }

    #[test]
    fn list_envelope_uses_data_key() {
        let json = r#"{"data":[],"total_count":0,"page":1,"total_pages":0,"page_size":24}"#;
        let env: CatalogListEnvelope = serde_json::from_str(json).unwrap();
        assert_eq!(env.total_count, 0);
        assert!(env.data.is_empty());
    }

    #[test]
    fn evidence_excerpt_hit_line() {
        let json = r#"{"file":"a.py","lines":[{"line_no":1,"text":"ok","hit":false},{"line_no":2,"text":"BAD","hit":true}],"truncated":false}"#;
        let ex: EvidenceExcerpt = serde_json::from_str(json).unwrap();
        assert_eq!(ex.hit_line().unwrap().line_no, 2);
        assert_eq!(ex.hit_line().unwrap().text, "BAD");
    }

    #[test]
    fn unknown_object_keys_are_ignored() {
        // The API's CatalogItemDetail is a superset of CatalogItemSummary;
        // extra keys must not break deserialization.
        let json = r#"{"id":"x","slug":"a--b--skill-c","kind":"skill","display_name":"C","popularity_tier":"emerging","item_metadata":{"z":1},"sources":[]}"#;
        let item: CatalogItemSummary = serde_json::from_str(json).unwrap();
        assert_eq!(item.slug, "a--b--skill-c");
    }
}