silicon-accounts-cli 0.6.0

The `silicon-accounts` command line for Silicon Accounts: sign Carbons and Silicons in, manage accounts, Silicons and apps
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
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
//! A small stateful mock of the Silicon Accounts API on its own thread, plus helpers to
//! run the `silicon-accounts` binary in an isolated home.

#![allow(dead_code, clippy::unwrap_used)]

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};

use axum::body::{Body, to_bytes};
use axum::extract::{Request, State};
use axum::http::StatusCode;
use axum::response::Response;
use serde_json::{Value, json};

pub const SILICON_ID: &str = "si:scout";
pub const SILICON_UUID: &str = "b9Z";
pub const STK: &str = "stk-0123456789ab";
pub const CARBON_ID: &str = "c:saket";
pub const CARBON_UUID: &str = "a8K";
pub const CARBON_EMAIL: &str = "saket@example.com";
pub const CARBON_TOKEN: &str = "at-carbon";
pub const APP_ID: &str = "briefcase";
pub const APP_SECRET: &str = "sa_app_briefcase_test_secret";

#[derive(Default)]
pub struct MockState {
    /// (method, path, authorization, body)
    pub requests: Vec<(String, String, Option<String>, String)>,
    /// (method, path, query)
    pub queries: Vec<(String, String, String)>,
    /// Anything an older CLI would have sent to the removed telemetry route (must stay empty).
    pub telemetry_batches: Vec<Value>,
    /// The Silicon's currently valid access and refresh tokens (rotated on refresh).
    pub access_token: String,
    pub refresh_token: String,
    pub generation: u32,
    /// Device polls before approval.
    pub device_polls: u32,
    /// Custodian request polls; the request is accepted from this poll number on.
    pub request_polls: u32,
    pub accept_on_poll: u32,
    /// The Silicon's current STK (a test rotates it by changing this).
    pub stk: String,
    /// The Carbon's currently valid access token (a test revokes the session by changing it).
    pub carbon_token: String,
    /// The app's sign-in setup version and redirect URIs (PATCH signin-config changes them).
    pub config_version: i64,
    pub redirect_uris: Value,
    /// The app's webhook URL (`PUT /v1/apps/briefcase/webhook` sets it).
    pub app_webhook_url: Option<String>,
}

pub struct Mock {
    pub url: String,
    pub state: Arc<Mutex<MockState>>,
}

impl Mock {
    pub fn start() -> Self {
        Self::start_with(2)
    }

    /// `accept_on_poll`: the custodian request reads `accepted` from this poll on.
    pub fn start_with(accept_on_poll: u32) -> Self {
        let state = Arc::new(Mutex::new(MockState {
            access_token: "at-1".into(),
            refresh_token: "sar_1".into(),
            generation: 1,
            accept_on_poll,
            stk: STK.into(),
            carbon_token: CARBON_TOKEN.into(),
            config_version: 4,
            redirect_uris: json!(["http://127.0.0.1:8593/briefcase/callback"]),
            ..MockState::default()
        }));
        let shared = state.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let runtime = tokio::runtime::Builder::new_current_thread()
                .enable_all()
                .build()
                .unwrap();
            runtime.block_on(async move {
                let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
                tx.send(listener.local_addr().unwrap()).unwrap();
                let app = axum::Router::new().fallback(handle).with_state(shared);
                axum::serve(listener, app).await.unwrap();
            });
        });
        let addr = rx.recv().unwrap();
        Self {
            url: format!("http://{addr}"),
            state,
        }
    }

    pub fn count(&self, method: &str, path: &str) -> usize {
        self.requests(method, path).len()
    }

    /// (authorization, body) of every request to `method path`.
    pub fn requests(&self, method: &str, path: &str) -> Vec<(Option<String>, String)> {
        self.state
            .lock()
            .unwrap()
            .requests
            .iter()
            .filter(|r| r.0 == method && r.1 == path)
            .map(|r| (r.2.clone(), r.3.clone()))
            .collect()
    }

    pub fn telemetry(&self) -> Vec<Value> {
        self.state.lock().unwrap().telemetry_batches.clone()
    }

    /// Revokes every session of the Silicon and makes `stk` its STK, as a custodian's
    /// `rotate-stk` does: the stored access and refresh tokens stop working.
    pub fn rotate_stk(&self, stk: &str) {
        let mut st = self.state.lock().unwrap();
        st.stk = stk.to_owned();
        st.generation += 10;
        st.access_token = format!("at-{}", st.generation);
        st.refresh_token = format!("sar_{}", st.generation);
    }

    /// Revokes the Carbon's session (as `silicon-accounts sessions revoke` from another terminal).
    pub fn revoke_carbon_session(&self) {
        let mut st = self.state.lock().unwrap();
        st.carbon_token = format!("{CARBON_TOKEN}-{}", st.requests.len());
    }

    /// The query string of every request to `method path`.
    pub fn queries(&self, method: &str, path: &str) -> Vec<String> {
        self.state
            .lock()
            .unwrap()
            .queries
            .iter()
            .filter(|r| r.0 == method && r.1 == path)
            .map(|r| r.2.clone())
            .collect()
    }
}

fn subscription(delivery: &str, updates: Value) -> Value {
    json!({
        "id": "sub-1", "app_id": APP_ID, "delivery": delivery, "status": "active",
        "url": null, "secret_set": delivery == "webhook", "updates": updates,
        "event_types": ["account.id_changed", "ping"],
        "stream_url": if delivery == "stream" { json!("http://127.0.0.1/v1/events/stream") } else { Value::Null },
        "created_at": "2026-10-09T00:00:00.000Z", "updated_at": "2026-10-09T00:00:00.000Z"
    })
}

fn error(status: u16, code: &str, message: &str, hint: &str) -> (u16, Value) {
    (
        status,
        json!({ "error": { "code": code, "message": message, "hint": hint } }),
    )
}

fn silicon_tokens(state: &MockState) -> Value {
    json!({
        "access_token": state.access_token,
        "token_type": "Bearer",
        "expires_in": 1800,
        "refresh_token": state.refresh_token,
        "refresh_token_expires_at": "2029-03-24T12:00:00.000Z",
        "scope": "profile",
        "membership_id": format!("silicon-accounts:{SILICON_UUID}"),
        "account": {
            "uuid": SILICON_UUID, "membership_id": format!("silicon-accounts:{SILICON_UUID}"), "kind": "silicon",
            "id": SILICON_ID, "display_name": "Scout", "pfp_url": "https://iris.example/pfp/silicon?id=b9Z",
            "custodian": { "uuid": CARBON_UUID, "id": CARBON_ID }, "updated_at": "2026-10-06T12:00:00.000Z", "version": 3
        }
    })
}

fn carbon_tokens(state: &MockState) -> Value {
    json!({
        "access_token": state.carbon_token,
        "token_type": "Bearer",
        "expires_in": 1800,
        "refresh_token": "sar_carbon",
        "refresh_token_expires_at": "2029-03-24T12:00:00.000Z",
        "scope": "profile email",
        "membership_id": format!("silicon-accounts:{CARBON_UUID}"),
        "account": {
            "uuid": CARBON_UUID, "membership_id": format!("silicon-accounts:{CARBON_UUID}"), "kind": "carbon",
            "id": CARBON_ID, "display_name": "Saket", "pfp_url": "https://iris.example/pfp/carbon?id=a8K",
            "email": CARBON_EMAIL, "email_verified": true, "updated_at": "2026-10-06T12:00:00.000Z", "version": 5
        }
    })
}

fn silicon_me() -> Value {
    json!({
        "uuid": SILICON_UUID, "kind": "silicon", "id": SILICON_ID, "display_name": "Scout",
        "pfp_url": "https://iris.example/pfp/silicon?id=b9Z", "dob": "2026-10-06", "timezone": "UTC",
        "status": "active", "created_at": "2026-10-06T12:00:00.000Z", "updated_at": "2026-10-06T12:00:00.000Z",
        "version": 3, "custodian": { "uuid": CARBON_UUID, "kind": "carbon", "id": CARBON_ID, "display_name": "Saket",
        "pfp_url": "", "status": "active" }, "webhook_url": null, "stk_rotated_at": null
    })
}

fn carbon_me() -> Value {
    json!({
        "uuid": CARBON_UUID, "kind": "carbon", "id": CARBON_ID, "display_name": "Saket",
        "pfp_url": "https://iris.example/pfp/carbon?id=a8K", "dob": "2000-01-01", "timezone": "Asia/Kolkata",
        "status": "active", "created_at": "2026-10-06T12:00:00.000Z", "updated_at": "2026-10-06T12:00:00.000Z",
        "version": 5, "emails": [{ "email": CARBON_EMAIL, "is_primary": true, "verified_at": "2026-10-06T12:00:00.000Z", "verified_via": "code" }],
        "phones": [], "identities": [], "custodian_of": 1
    })
}

fn new_silicon(status: &str) -> Value {
    json!({
        "uuid": SILICON_UUID, "kind": "silicon", "id": SILICON_ID, "display_name": "Scout",
        "pfp_url": "https://iris.example/pfp/silicon?id=b9Z", "dob": "2026-10-06", "timezone": "UTC",
        "status": status, "created_at": "2026-10-06T12:00:00.000Z", "updated_at": "2026-10-06T12:00:00.000Z",
        "version": 1, "custodian": null, "webhook_url": null, "stk_rotated_at": null
    })
}

fn import_job(status: &str, processed: u64) -> Value {
    json!({
        "id": "job-1", "status": status, "format": "csv", "total_rows": 3, "processed_rows": processed,
        "counts": { "created": 1, "matched": 1, "updated": 0, "skipped": 0, "error": 1, "warnings": 1 },
        "created_at": "2026-10-06T12:00:00.000Z", "started_at": "2026-10-06T12:00:00.000Z",
        "finished_at": null, "error": null
    })
}

fn app_details(state: &MockState) -> Value {
    json!({ "app_id": APP_ID, "name": "Briefcase", "description": "", "status": "active", "source": "fake",
            "owner": { "uuid": CARBON_UUID, "kind": "carbon", "id": CARBON_ID, "display_name": "Saket", "pfp_url": "", "status": "active" },
            "signin_config": { "methods": { "email": true, "google": true, "apple": false, "phone": false },
                "method_order": ["google", "apple", "email", "phone"], "redirect_uris": state.redirect_uris,
                "required_fields": ["email"], "optional_fields": [], "allow_signup": true },
            "config_version": state.config_version, "webhook": { "url": null, "secret_set": false },
            "stats": { "users": 2, "active_last_30d": 1, "imported_unclaimed": 0 } })
}

fn delivery(id: &str, status: &str) -> Value {
    json!({ "id": id, "event_id": "e-1", "type": "silicon.updated", "account_uuid": SILICON_UUID,
            "url": "https://scout.example/hooks", "status": status, "attempts": 12, "last_status": 503,
            "last_error": null, "next_attempt_at": null, "last_attempt_at": "2026-10-06T12:00:00.000Z",
            "delivered_at": null, "created_at": "2026-10-03T12:00:00.000Z", "manual_replays": 0 })
}

fn delivery_detail() -> Value {
    let mut detail = delivery("d-1", "failed");
    detail["attempt_count"] = json!(12);
    detail["attempts"] = json!([{ "attempted_at": "2026-10-06T12:00:00.000Z", "status_code": 503, "error": null, "duration_ms": 41 }]);
    detail["payload"] = json!({ "event_id": "e-1", "type": "silicon.updated", "silicon": SILICON_UUID, "data": { "uuid": SILICON_UUID } });
    detail["payload_redacted"] = json!(false);
    detail
}

fn replay_result(body: &Value) -> Value {
    let replayed = match body.get("delivery_ids") {
        Some(Value::Array(ids)) => ids
            .iter()
            .filter(|id| *id != "d-pending")
            .cloned()
            .collect(),
        _ => vec![json!("d-1")],
    };
    let skipped: Vec<Value> = match body.get("delivery_ids") {
        Some(Value::Array(ids)) if ids.iter().any(|id| id == "d-pending") => vec![json!({
            "delivery_id": "d-pending", "reason": "already_pending",
            "message": "Delivery d-pending is still being retried; it is not replayed."
        })],
        _ => Vec::new(),
    };
    json!({ "replayed": replayed, "skipped": skipped, "remaining": if body.get("status").is_some() { 3 } else { 0 },
            "not_replayable": 1, "url": "https://scout.example/hooks" })
}

fn form(body: &str) -> HashMap<String, String> {
    url::form_urlencoded::parse(body.as_bytes())
        .into_owned()
        .collect()
}

async fn handle(State(state): State<Arc<Mutex<MockState>>>, request: Request) -> Response {
    let (parts, body) = request.into_parts();
    let body = String::from_utf8(to_bytes(body, 1 << 20).await.unwrap_or_default().to_vec())
        .unwrap_or_default();
    let method = parts.method.to_string();
    let path = parts.uri.path().to_owned();
    let query = parts.uri.query().unwrap_or("").to_owned();
    let auth = parts
        .headers
        .get("authorization")
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);
    let mut st = state.lock().unwrap();
    st.requests
        .push((method.clone(), path.clone(), auth.clone(), body.clone()));
    st.queries
        .push((method.clone(), path.clone(), query.clone()));
    let silicon_bearer = auth.as_deref() == Some(&format!("Bearer {}", st.access_token));
    let carbon_bearer = auth.as_deref() == Some(&format!("Bearer {}", st.carbon_token));
    let basic = format!("Basic {}", base64_encode(&format!("{APP_ID}:{APP_SECRET}")));
    let app_auth = auth.as_deref() == Some(basic.as_str());
    let json_body: Value = serde_json::from_str(&body).unwrap_or(Value::Null);

    let (status, value): (u16, Value) = match (method.as_str(), path.as_str()) {
        ("GET", "/v1/meta") => (
            200,
            json!({"name": "Silicon Accounts", "public_url": "http://accounts.test"}),
        ),
        ("POST", "/v1/silicons/login") if json_body.get("assertion").is_some() => {
            let parts: Vec<&str> = json_body["assertion"]
                .as_str()
                .unwrap_or("")
                .split('.')
                .collect();
            let payload = parts
                .get(1)
                .map(|p| base64url_decode(p))
                .and_then(|b| serde_json::from_slice::<Value>(&b).ok())
                .unwrap_or(Value::Null);
            if parts.len() == 3
                && payload["iss"] == SILICON_ID
                && payload["sub"] == SILICON_ID
                && payload["aud"] == "http://accounts.test/v1/oauth/token"
                && payload["jti"].is_string()
            {
                (200, silicon_tokens(&st))
            } else {
                error(
                    401,
                    "invalid_assertion",
                    "No live key of this Silicon signed the assertion.",
                    "Sign a fresh one.",
                )
            }
        }
        ("POST", "/v1/silicons/si:scout/keys") if carbon_bearer || silicon_bearer => (
            201,
            json!({"id": "key-1", "name": json_body["name"].as_str().unwrap_or("key"), "algorithm": "EdDSA",
                "public_key": json_body["public_key"], "fingerprint": "SHA256:abc", "created_by": "a8K",
                "created_at": "2026-10-09T00:00:00.000Z", "last_used_at": null, "revoked_at": null}),
        ),
        ("GET", "/v1/silicons/si:scout/keys") if carbon_bearer || silicon_bearer => (
            200,
            json!({"items": [{"id": "key-1", "name": "laptop", "algorithm": "EdDSA", "public_key": "x",
                "fingerprint": "SHA256:abc", "created_by": "a8K", "created_at": "2026-10-09T00:00:00.000Z",
                "last_used_at": null, "revoked_at": null}], "next_cursor": null}),
        ),
        ("DELETE", "/v1/silicons/si:scout/keys/key-1") if carbon_bearer || silicon_bearer => {
            (204, Value::Null)
        }
        ("POST", "/v1/silicons/login") => {
            if json_body["id"] == SILICON_ID && json_body["stk"] == st.stk.as_str() {
                (200, silicon_tokens(&st))
            } else {
                error(
                    401,
                    "invalid_credentials",
                    "The si:id or STK is wrong.",
                    "Check both; ask the custodian to rotate the STK if it was lost.",
                )
            }
        }
        ("GET", "/v1/me") if silicon_bearer => (200, silicon_me()),
        ("GET", "/v1/me") if carbon_bearer => (200, carbon_me()),
        ("GET", "/v1/me") => error(
            401,
            "unauthenticated",
            "The access token is missing, expired or revoked.",
            "Sign in again.",
        ),
        ("GET", "/github-oidc")
            if auth.as_deref() == Some("bearer gh-request-token")
                && query.contains("audience=") =>
        {
            (200, json!({ "count": 1, "value": "eyJ.ci.ok" }))
        }
        ("POST", "/v1/me/identity-tokens") if silicon_bearer => (
            201,
            json!({ "identity_token": "eyJ.identity.sig", "token_type": "urn:ietf:params:oauth:token-type:id_token",
                    "issuer": "http://accounts.test", "subject": SILICON_UUID, "audience": json_body["audience"],
                    "jti": "j-1", "kid": "rsa-kid", "issued_at": "2026-10-09T00:00:00.000Z",
                    "expires_at": "2026-10-09T00:05:00.000Z", "expires_in": json_body["ttl_seconds"] }),
        ),
        ("POST", "/v1/me/short-lived-tokens") if silicon_bearer || carbon_bearer => (
            201,
            json!({ "slt": "slt_test_token", "app_id": json_body["app_id"], "expires_at": "2099-01-01T00:02:00.000Z" }),
        ),
        ("POST", "/v1/device/authorize") => (
            200,
            json!({ "device_code": "sad_device", "user_code": "WDJB-MJHT",
                    "verification_uri": "http://127.0.0.1/device", "verification_uri_complete": "http://127.0.0.1/device?code=WDJB-MJHT",
                    "expires_in": 600, "interval": 1 }),
        ),
        ("POST", "/v1/cli/login/start") => {
            if json_body["email"] == CARBON_EMAIL {
                (
                    200,
                    json!({ "challenge_id": "ch-1", "destination": "s***@example.com", "expires_at": "2099-01-01T00:10:00.000Z" }),
                )
            } else {
                error(
                    404,
                    "account_not_found",
                    "No Carbon account has that email or phone.",
                    "Sign up at accounts.teamofsilicons.com first.",
                )
            }
        }
        ("POST", "/v1/cli/login/verify") => {
            if json_body["challenge_id"] == "ch-1" && json_body["code"] == "123456" {
                (200, carbon_tokens(&st))
            } else {
                let (status, mut value) = error(
                    422,
                    "invalid_code",
                    "That code is wrong.",
                    "Check the latest code we sent; 9 attempts left.",
                );
                value["error"]["details"] = json!({ "remaining_attempts": 9 });
                (status, value)
            }
        }
        ("POST", "/v1/oauth/token") => {
            let f = form(&body);
            match f.get("grant_type").map(String::as_str) {
                Some("refresh_token") if f.get("refresh_token") == Some(&st.refresh_token) => {
                    st.generation += 1;
                    st.access_token = format!("at-{}", st.generation);
                    st.refresh_token = format!("sar_{}", st.generation);
                    (200, silicon_tokens(&st))
                }
                Some("refresh_token") => (
                    400,
                    json!({ "error": "invalid_grant", "error_description": "The refresh token was already used; the whole session was revoked." }),
                ),
                Some("authorization_code")
                    if f.get("code").map(String::as_str) == Some("sac_good") =>
                {
                    (200, carbon_tokens(&st))
                }
                Some("urn:ietf:params:oauth:grant-type:token-exchange")
                    if f.get("subject_token").map(String::as_str) == Some("eyJ.ci.ok")
                        && f.get("silicon").map(String::as_str) == Some(SILICON_ID)
                        && f.get("subject_token_type").map(String::as_str)
                            == Some("urn:ietf:params:oauth:token-type:jwt") =>
                {
                    let mut tokens = silicon_tokens(&st);
                    if let Some(t) = tokens.as_object_mut() {
                        t.insert(
                            "refresh_token_expires_at".into(),
                            json!("2026-10-09T01:00:00.000Z"),
                        );
                        t.insert(
                            "issued_token_type".into(),
                            json!("urn:ietf:params:oauth:token-type:access_token"),
                        );
                    }
                    (200, tokens)
                }
                Some("urn:ietf:params:oauth:grant-type:token-exchange") => (
                    400,
                    json!({ "error": "invalid_grant", "error_description": "si:scout trusts the issuer, but not this token: a trust wants other values for 'repository' (the token has 'mallory/scout'). (no_matching_trust)" }),
                ),
                Some("urn:ietf:params:oauth:grant-type:device_code") => {
                    st.device_polls += 1;
                    if st.device_polls < 2 {
                        (400, json!({ "error": "authorization_pending" }))
                    } else {
                        (200, carbon_tokens(&st))
                    }
                }
                _ => (400, json!({ "error": "unsupported_grant_type" })),
            }
        }
        ("POST", "/v1/oauth/revoke") => (200, json!({})),
        ("GET", "/v1/ids/available") => {
            let q = form(&query);
            let id = q.get("id").cloned().unwrap_or_default();
            if let Some(silicon) = q.get("for") {
                if !carbon_bearer {
                    error(
                        401,
                        "unauthenticated",
                        "?for= needs the custodian's session.",
                        "Sign in as the custodian.",
                    )
                } else if silicon == SILICON_ID || silicon == SILICON_UUID {
                    (
                        200,
                        json!({ "id": id, "available": true, "reason": null, "message": format!("{id} was an id of {SILICON_ID}; you can take it back for it."), "reclaimable": true }),
                    )
                } else {
                    error(
                        404,
                        "silicon_not_found",
                        &format!("You are not the custodian of a Silicon '{silicon}'."),
                        "List your Silicons with `silicon-accounts silicon list`.",
                    )
                }
            } else if id == "c:taken" {
                (
                    200,
                    json!({ "id": id, "available": false, "reason": "taken", "message": "c:taken belongs to another account.", "reclaimable": false }),
                )
            } else if id.contains(' ') {
                (
                    200,
                    json!({ "id": id, "available": false, "reason": "invalid", "message": "Ids can't contain spaces.", "reclaimable": false }),
                )
            } else {
                (
                    200,
                    json!({ "id": id, "available": true, "reason": null, "message": null, "reclaimable": false }),
                )
            }
        }
        ("POST", "/v1/silicons") => (
            201,
            json!({
                "silicon": new_silicon("pending_custodian"),
                "stk": STK,
                "request": { "id": "req-1", "status": "pending", "expires_at": "2099-01-01T00:00:00.000Z", "custodian": json_body["custodian"] },
                "request_token": "sarq_poll",
                "webhook_secret": null
            }),
        ),
        ("GET", "/v1/silicons/requests/req-1") if auth.as_deref() == Some("Bearer sarq_poll") => {
            st.request_polls += 1;
            let status = if st.request_polls >= st.accept_on_poll {
                "accepted"
            } else {
                "pending"
            };
            (
                200,
                json!({ "id": "req-1", "status": status, "expires_at": "2099-01-01T00:00:00.000Z",
                        "decided_at": if status == "accepted" { json!("2026-10-06T12:05:00.000Z") } else { Value::Null },
                        "silicon": { "uuid": SILICON_UUID, "id": SILICON_ID, "status": if status == "accepted" { "active" } else { "pending_custodian" } } }),
            )
        }
        ("POST", "/v1/me/silicons") if carbon_bearer => (
            201,
            json!({ "silicon": new_silicon("active"), "stk": STK, "webhook_secret": null }),
        ),
        // Like the service: a new secret only when the app has none; saving again keeps it.
        ("PUT", "/v1/apps/briefcase/webhook") if app_auth => {
            let first = st.app_webhook_url.is_none();
            st.app_webhook_url = json_body["url"].as_str().map(str::to_owned);
            (
                200,
                json!({
                    "url": json_body["url"],
                    "secret": if first { json!("whsec_first") } else { Value::Null },
                    "events": null,
                }),
            )
        }
        ("GET", "/v1/apps/briefcase/subscriptions") if app_auth => (
            200,
            json!({"items": [subscription("webhook", Value::Null)], "next_cursor": null}),
        ),
        ("POST", "/v1/apps/briefcase/subscriptions") if app_auth => {
            let delivery = json_body["delivery"].as_str().unwrap_or("").to_string();
            let mut s = subscription(
                &delivery,
                json_body.get("updates").cloned().unwrap_or(json!([
                    "id_change",
                    "display_name_change",
                    "pfp_change",
                    "access_removed",
                    "account_deleted"
                ])),
            );
            if json_body["status"] == "paused" {
                s["status"] = json!("paused");
            }
            if delivery == "webhook" {
                s["url"] = json_body["url"].clone();
                s["secret"] = json!("whsec_sub");
            }
            (201, s)
        }
        ("GET", "/v1/apps/briefcase/subscriptions/sub-1") if app_auth => {
            (200, subscription("stream", Value::Null))
        }
        ("PATCH", "/v1/apps/briefcase/subscriptions/sub-1") if app_auth => {
            let mut s = subscription("stream", Value::Null);
            if let Some(u) = json_body.get("updates") {
                s["updates"] = u.clone();
            }
            if let Some(st) = json_body.get("status") {
                s["status"] = st.clone();
            }
            (200, s)
        }
        ("DELETE", "/v1/apps/briefcase/subscriptions/sub-1") if app_auth => (204, Value::Null),
        ("POST", "/v1/apps/briefcase/subscriptions/sub-1/test") if app_auth => (
            202,
            json!({"subscription_id": "sub-1", "event_id": "ev-ping", "delivery_id": null, "type": "ping"}),
        ),
        ("GET", "/v1/apps/briefcase") if app_auth => (200, app_details(&st)),
        ("GET", "/v1/apps/briefcase") => error(
            401,
            "invalid_client",
            "The app credentials were rejected.",
            "Check the app id and secret.",
        ),
        ("POST", "/v1/apps/briefcase/imports") if app_auth => {
            (202, json!({ "job": import_job("queued", 0) }))
        }
        ("GET", "/v1/apps/briefcase/imports/job-1") if app_auth => {
            (200, json!({ "job": import_job("completed", 3) }))
        }
        ("GET", "/v1/apps/briefcase/imports/job-1/rows") if app_auth => (
            200,
            json!({ "items": [{ "row_number": 3, "outcome": "error", "account_uuid": null, "id": null,
                "messages": [{ "level": "error", "code": "missing_identifier", "message": "Row 3 has no valid email or phone.", "field": null }],
                "input": { "name": "Nobody" } }], "next_cursor": null }),
        ),
        ("POST", "/v1/proofs/app-verification") if app_auth => {
            if json_body.get("audiences").is_some() {
                error(
                    422,
                    "app_verification_single_app",
                    "An app verification is for exactly one app; ask for one proof per app.",
                    "Send {\"receiving_app\": \"remind\"} to POST /v1/proofs/app-verification instead of \"audiences\".",
                )
            } else {
                (
                    201,
                    json!({ "proof_id": "p-app_verification", "kind": "app_verification", "proof_token": "sap_app_verification", "expires_at": "2099-01-01T00:30:00.000Z",
                        "proof_refresh_token": "sapr_app_verification", "refresh_expires_at": "2099-06-01T00:00:00.000Z",
                        "issuing_app": APP_ID, "receiving_app": json_body["receiving_app"], "user": null,
                        "scopes": json_body.get("scopes").cloned().unwrap_or_else(|| json!([])) }),
                )
            }
        }
        ("POST", "/v1/proofs/verify") if app_auth => {
            if json_body["proof_token"] == "sap_valid" {
                (
                    200,
                    json!({ "valid": true, "proof_id": "p1", "kind": "user_verification", "expires_at": "2099-01-01T00:30:00.000Z",
                    "issuing_app": { "app_id": "dm", "name": "DM" }, "receiving_app": { "app_id": APP_ID, "name": "Briefcase" },
                    "user": { "uuid": CARBON_UUID, "id": CARBON_ID, "kind": "carbon", "membership_id": "dm:a8K" }, "scopes": ["files.write"] }),
                )
            } else {
                (200, json!({ "valid": false, "expires_at": null }))
            }
        }
        ("POST", "/v1/proofs/verify") => error(
            401,
            "invalid_client",
            "The app credentials were rejected.",
            "Check the app id and secret.",
        ),
        ("POST", "/v1/reports") => {
            if json_body["message"]
                .as_str()
                .unwrap_or_default()
                .chars()
                .count()
                > 10_000
            {
                error(
                    422,
                    "validation_failed",
                    "The report message is longer than 10000 characters.",
                    "Shorten it.",
                )
            } else {
                (
                    201,
                    json!({ "report_id": "rep-1", "status": "queued", "recipients": 3 }),
                )
            }
        }
        // A Silicon's own webhook deliveries, and its custodian's view of them.
        ("GET", "/v1/me/webhook/deliveries") if silicon_bearer => (
            200,
            json!({ "items": [delivery("d-1", "failed")], "next_cursor": null }),
        ),
        ("GET", "/v1/me/silicons/si:scout/apps") if carbon_bearer => (
            200,
            json!({"items": [{"app": {"app_id": "briefcase", "name": "Briefcase"}, "membership_id": "briefcase:b9Z",
                "status": "active", "source": "slt", "granted_scopes": ["profile"]}], "next_cursor": null}),
        ),
        ("DELETE", "/v1/me/silicons/si:scout/apps/briefcase") if carbon_bearer => {
            (204, Value::Null)
        }
        ("GET", "/v1/me/silicons/si:scout/signins") if carbon_bearer => (
            200,
            json!({"items": [{"at": "2026-10-09T00:00:00.000Z", "app": {"app_id": "briefcase", "name": "Briefcase"},
                "method": "slt", "outcome": "success", "ip": "203.0.113.9", "user_agent": "scout/1.0"}], "next_cursor": "c-9"}),
        ),
        ("PUT", "/v1/me/silicons/si:scout/allowed-apps") if carbon_bearer => {
            (200, json!({"allowed_apps": json_body["allowed_apps"]}))
        }
        ("GET", "/v1/me/silicons/si:scout/allowed-apps") if carbon_bearer => {
            (200, json!({"allowed_apps": ["briefcase"]}))
        }
        ("GET", "/v1/me/silicons/b9Z/webhook/deliveries") if carbon_bearer => (
            200,
            json!({ "items": [delivery("d-1", "failed")], "next_cursor": "c-2" }),
        ),
        ("GET", "/v1/me/webhook/deliveries/d-1") if silicon_bearer => (200, delivery_detail()),
        ("GET", "/v1/me/silicons/b9Z/webhook/deliveries/d-1") if carbon_bearer => {
            (200, delivery_detail())
        }
        ("POST", "/v1/me/webhook/replay") if silicon_bearer => (200, replay_result(&json_body)),
        ("POST", "/v1/me/silicons/b9Z/webhook/replay") if carbon_bearer => {
            (200, replay_result(&json_body))
        }
        ("GET", "/v1/me/silicons") if carbon_bearer => (
            200,
            json!({ "items": [{ "silicon": new_silicon("active"), "pending_transfer": null }], "next_cursor": null }),
        ),
        ("GET", "/v1/apps/briefcase/imports/job-failed") if app_auth => {
            let mut job = import_job("failed", 1);
            job["id"] = json!("job-failed");
            job["error"] = json!(
                "The worker processing this import stopped (the server restarted or crashed) more than twice."
            );
            (200, json!({ "job": job }))
        }
        ("GET", "/v1/apps/briefcase/imports/job-dry") if app_auth => {
            let mut job = import_job("completed", 3);
            job["id"] = json!("job-dry");
            job["dry_run"] = json!(true);
            (200, json!({ "job": job }))
        }
        ("PATCH", "/v1/apps/briefcase/signin-config") if app_auth => {
            // Like the service: a patch that changes nothing makes no new version.
            if let Some(uris) = json_body.get("redirect_uris")
                && *uris != st.redirect_uris
            {
                st.redirect_uris = uris.clone();
                st.config_version += 1;
            }
            (200, app_details(&st))
        }
        ("GET", "/v1/apps/briefcase/signin-config/history") if app_auth => (
            200,
            json!({ "items": [{ "version": st.config_version, "actor": CARBON_UUID,
                "actor_account": { "uuid": CARBON_UUID, "kind": "carbon", "id": CARBON_ID, "display_name": "Saket", "pfp_url": "", "status": "active" },
                "changes": [{ "path": "redirect_uris", "before": [], "after": st.redirect_uris }],
                "at": "2026-10-06T12:00:00.000Z" }], "next_cursor": null }),
        ),
        ("POST", "/v1/telemetry/events") => {
            st.telemetry_batches
                .push(serde_json::from_str(&body).unwrap_or(Value::Null));
            (202, json!({}))
        }
        // Like the service: a revoked or unknown access token is refused on every account route.
        (_, p)
            if p.starts_with("/v1/me")
                && auth.as_deref().is_some_and(|a| a.starts_with("Bearer "))
                && !silicon_bearer
                && !carbon_bearer =>
        {
            error(
                401,
                "unauthenticated",
                "The access token is missing, expired or revoked.",
                "Sign in again.",
            )
        }
        _ => error(
            404,
            "not_found",
            &format!("mock has no route for {method} {path}"),
            "Register it in the test.",
        ),
    };
    let mut response = Response::new(Body::from(value.to_string()));
    *response.status_mut() = StatusCode::from_u16(status).unwrap();
    response
        .headers_mut()
        .insert("content-type", "application/json".parse().unwrap());
    response
        .headers_mut()
        .insert("x-request-id", "req-test-1".parse().unwrap());
    response
}

fn base64url_decode(text: &str) -> Vec<u8> {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut bits: u32 = 0;
    let mut count = 0;
    let mut out = Vec::new();
    for c in text.bytes() {
        let Some(v) = ALPHABET.iter().position(|a| *a == c) else {
            continue;
        };
        bits = (bits << 6) | v as u32;
        count += 6;
        if count >= 8 {
            count -= 8;
            out.push((bits >> count) as u8);
        }
    }
    out
}

fn base64_encode(text: &str) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let bytes = text.as_bytes();
    let mut out = String::new();
    for chunk in bytes.chunks(3) {
        let b = [
            chunk[0],
            *chunk.get(1).unwrap_or(&0),
            *chunk.get(2).unwrap_or(&0),
        ];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        for i in 0..4 {
            if i <= chunk.len() {
                out.push(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize] as char);
            } else {
                out.push('=');
            }
        }
    }
    out
}

/// An isolated environment for one test: its own HOME, no inherited ACCOUNTS_* settings.
pub struct Env {
    pub home: tempfile::TempDir,
}

impl Env {
    pub fn new() -> Self {
        Self {
            home: tempfile::tempdir().unwrap(),
        }
    }

    pub fn path(&self) -> &Path {
        self.home.path()
    }

    pub fn state_file(&self, name: &str) -> PathBuf {
        self.home.path().join(".accounts").join(name)
    }

    /// The same isolated command as [`Env::cmd`], as a `std::process::Command` (for a test that
    /// chooses where stdout goes).
    pub fn std_cmd(&self) -> std::process::Command {
        let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_silicon-accounts"));
        for var in [
            "SILICON_HOME",
            "ACCOUNTS_HOME",
            "ACCOUNTS_URL",
            "ACCOUNTS_SILICON",
            "ACCOUNTS_STK",
            "ACCOUNTS_APP_ID",
            "ACCOUNTS_APP_SECRET",
            "ACCOUNTS_TIMEOUT_SECONDS",
            "ACCOUNTS_ALLOW_INSECURE_HTTP",
            "ACTIONS_ID_TOKEN_REQUEST_URL",
            "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
            "TZ",
        ] {
            cmd.env_remove(var);
        }
        cmd.env("HOME", self.home.path())
            .env("ACCOUNTS_NO_BROWSER", "1")
            .env("NO_COLOR", "1")
            .env("HOSTNAME", "test-host");
        cmd
    }

    pub fn cmd(&self) -> assert_cmd::Command {
        let mut cmd = assert_cmd::Command::new(env!("CARGO_BIN_EXE_silicon-accounts"));
        for var in [
            "SILICON_HOME",
            "ACCOUNTS_HOME",
            "ACCOUNTS_URL",
            "ACCOUNTS_SILICON",
            "ACCOUNTS_STK",
            "ACCOUNTS_APP_ID",
            "ACCOUNTS_APP_SECRET",
            "ACCOUNTS_TIMEOUT_SECONDS",
            "ACCOUNTS_ALLOW_INSECURE_HTTP",
            "ACTIONS_ID_TOKEN_REQUEST_URL",
            "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
            "TZ",
        ] {
            cmd.env_remove(var);
        }
        cmd.env("HOME", self.home.path())
            .env("ACCOUNTS_NO_BROWSER", "1")
            .env("NO_COLOR", "1")
            .env("HOSTNAME", "test-host")
            .timeout(std::time::Duration::from_secs(60));
        cmd
    }
}

/// Parses stdout as JSON.
pub fn stdout_json(output: &std::process::Output) -> Value {
    serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!(
            "stdout is not JSON ({e}):\n{}\nstderr:\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr)
        )
    })
}