auths-id 0.1.2

Multi-device identity and attestation crate for Auths
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
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
//! Delegated device identifiers — a device as a KERI delegated AID.
//!
//! A device is a **delegated identifier** of the root identity: its KEL is
//! incepted with a `dip` naming the root as delegator (`di`), and the root
//! **anchors** the dip via an `ixn` whose `a[]` carries a `Seal::KeyEvent` for
//! the dip. The device holds its own key; the root never holds it. Verifiers
//! confirm authorization via [`auths_keri::validate_delegation`] (the delegator
//! anchored the delegated event).
//!
//! This is the keripy-native, single-author, device-bound replacement for
//! shared-`k[]` controllers — and the same `dip`/`drt` mechanism agents use.

use std::ops::ControlFlow;
use std::sync::Arc;

use auths_core::crypto::said::{compute_next_commitment, verify_commitment};
use auths_core::crypto::signer::{decrypt_keypair, encrypt_keypair};
use auths_core::signing::PassphraseProvider;
use auths_core::storage::keychain::{IdentityDID, KeyAlias, KeyRole, KeyStorage};
use auths_crypto::{CurveType, Pkcs8Der};
use ring::signature::KeyPair;

use crate::error::InitError;
use crate::identity::helpers::load_keypair_from_der_or_seed;
use crate::keri::inception::{generate_keypair_for_init, sign_with_pkcs8_for_init};
use crate::keri::{
    CesrKey, Event, KeriSequence, Prefix, Said, Seal, Threshold, VersionString, finalize_dip_event,
    finalize_drt_event, serialize_for_signing,
};
use crate::storage::registry::RegistryBackend;
use auths_keri::{
    AgentScope, DipEvent, DipEventInit, DrtEvent, DrtEventInit, IndexedSignature, IxnEvent,
    KeriPublicKey, SourceSeal, decode_agent_scope, encode_agent_scope, finalize_ixn_event,
    serialize_attachment, serialize_source_seal_couples,
};

/// A device incepted as a delegated identifier of a root identity.
pub struct DelegatedDevice {
    /// The device's `did:keri:` (self-addressing — derived from the dip SAID).
    pub device_did: IdentityDID,
    /// The device's KEL prefix.
    pub device_prefix: Prefix,
    /// The keychain alias the device's current key is stored under.
    pub device_alias: KeyAlias,
}

/// Incept a device as a delegated identifier of the root identity.
///
/// Builds the device's `dip` (delegated inception) naming `root_prefix` as
/// delegator, signs it with a freshly-generated **device** key, appends it to the
/// device KEL, then authors the root's anchoring `ixn` (a `Seal::KeyEvent` for the
/// dip) signed by the root's current key. The device's private key is stored only
/// under `device_alias` — never under the root's alias.
///
/// Args:
/// * `backend`: Registry backend holding the root KEL and the new device KEL.
/// * `root_prefix`: The root identity's KEL prefix (the delegator).
/// * `root_alias`: Keychain alias of the root's current signing key.
/// * `root_curve`: Curve of the root's current key (for the anchoring signature).
/// * `device_alias`: Keychain alias to store the new device key under.
/// * `device_curve`: Curve for the new device key.
/// * `passphrase_provider`: Passphrase source for key decrypt/encrypt.
/// * `keychain`: Key storage.
///
/// Usage:
/// ```ignore
/// let dev = incept_delegated_device(backend, &root_prefix, &root_alias,
///     CurveType::Ed25519, &device_alias, CurveType::Ed25519, &provider, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn incept_delegated_device(
    backend: Arc<dyn RegistryBackend + Send + Sync>,
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    device_alias: &KeyAlias,
    device_curve: CurveType,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<DelegatedDevice, InitError> {
    // Local add = build the device dip here (we generate the key) + anchor it +
    // store the keys. The remote path (pairing) calls the two halves separately.
    let bundle = build_device_dip(root_prefix, device_curve)?;
    let device_did = bundle.device_did.clone();
    let device_prefix = bundle.device_prefix.clone();

    anchor_received_dip(
        backend.as_ref(),
        root_prefix,
        root_alias,
        root_curve,
        &bundle.dip,
        &bundle.attachment,
        passphrase_provider,
        keychain,
    )?;

    let pass = passphrase_provider.get_passphrase(&format!(
        "Create passphrase for device key '{}':",
        device_alias
    ))?;
    let enc_cur = encrypt_keypair(bundle.current_pkcs8.as_ref(), &pass)?;
    keychain.store_key(device_alias, &device_did, KeyRole::Primary, &enc_cur)?;
    let next_alias = KeyAlias::new_unchecked(format!("{}--next-0", device_alias));
    let enc_next = encrypt_keypair(bundle.next_pkcs8.as_ref(), &pass)?;
    keychain.store_key(&next_alias, &device_did, KeyRole::NextRotation, &enc_next)?;

    Ok(DelegatedDevice {
        device_did,
        device_prefix,
        device_alias: device_alias.clone(),
    })
}

/// The joiner-side product of [`build_device_dip`]: a signed device `dip` plus the
/// device's own keys, ready to be anchored by the root — locally (same host) or
/// after transport (remote pairing). The dip names the root as delegator but is
/// not yet on any KEL and not yet anchored.
pub struct DeviceDipBundle {
    /// The finalized, device-signed delegated-inception event.
    pub dip: DipEvent,
    /// CESR attachment carrying the device's signature over the dip.
    pub attachment: Vec<u8>,
    /// The device's KEL prefix (self-addressing — equals the dip SAID).
    pub device_prefix: Prefix,
    /// The device's `did:keri:`.
    pub device_did: IdentityDID,
    /// The device's current private key (PKCS#8 DER) — the joiner stores this.
    pub current_pkcs8: Pkcs8Der,
    /// The device's pre-committed next private key (PKCS#8 DER).
    pub next_pkcs8: Pkcs8Der,
    /// Curve of the device's keys.
    pub device_curve: CurveType,
}

/// Build + sign a device's delegated-inception (`dip`) without touching any KEL.
///
/// This is the **joiner** half of delegation: the joining device generates its own
/// key, builds a `dip` naming `root_prefix` as delegator, and self-signs it. The
/// result is pure — no backend, no keychain — so it can be produced on a device
/// that has no registry and transmitted to the root for anchoring (see
/// [`anchor_received_dip`]). For same-host adds, [`incept_delegated_device`]
/// composes this with `anchor_received_dip` directly.
///
/// Args:
/// * `root_prefix`: The root identity's KEL prefix (becomes the dip's `di`).
/// * `device_curve`: Curve for the new device key.
///
/// Usage:
/// ```ignore
/// let bundle = build_device_dip(&root_prefix, CurveType::Ed25519)?;
/// // transmit bundle.dip + bundle.attachment to the root; store the keys locally
/// ```
pub fn build_device_dip(
    root_prefix: &Prefix,
    device_curve: CurveType,
) -> Result<DeviceDipBundle, InitError> {
    let device_cur =
        generate_keypair_for_init(device_curve).map_err(|e| InitError::Crypto(e.to_string()))?;
    let device_next =
        generate_keypair_for_init(device_curve).map_err(|e| InitError::Crypto(e.to_string()))?;
    let device_next_commitment = compute_next_commitment(&device_next.verkey());

    let dip = finalize_dip_event(DipEvent::new(DipEventInit {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: Prefix::default(),
        s: KeriSequence::new(0),
        kt: Threshold::Simple(1),
        k: vec![CesrKey::new_unchecked(device_cur.cesr_encoded.clone())],
        nt: Threshold::Simple(1),
        n: vec![device_next_commitment],
        bt: Threshold::Simple(0),
        b: vec![],
        c: vec![],
        a: vec![],
        di: root_prefix.clone(),
    }))
    .map_err(|e| InitError::Keri(e.to_string()))?;

    let device_prefix = dip.i.clone();
    let dip_canonical = serialize_for_signing(&Event::Dip(dip.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let dip_sig = sign_with_pkcs8_for_init(device_curve, &device_cur.pkcs8, &dip_canonical)
        .map_err(|e| InitError::Crypto(e.to_string()))?;
    let attachment = serialize_attachment(&[IndexedSignature {
        index: 0,
        prior_index: None,
        sig: dip_sig,
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;

    #[allow(clippy::disallowed_methods)]
    // INVARIANT: device_prefix is from finalize_dip_event, a valid did:keri prefix.
    let device_did = IdentityDID::new_unchecked(format!("did:keri:{}", device_prefix));

    Ok(DeviceDipBundle {
        dip,
        attachment,
        device_prefix,
        device_did,
        current_pkcs8: device_cur.pkcs8,
        next_pkcs8: device_next.pkcs8,
        device_curve,
    })
}

/// Anchor a received device `dip` on the root's registry: append the (already
/// device-signed) dip to the device KEL, then author the root's anchoring `ixn`.
///
/// This is the **initiator** half of delegation. The dip is taken as-is — its
/// signature is the device's, validated by the backend on append — so this never
/// needs the device's private key. Returns the now-delegated device's DID and the
/// root's anchoring `ixn` (remote pairing relays the `ixn` back to the joiner so it
/// can confirm the anchor via `validate_delegation`).
///
/// Args:
/// * `backend`: Registry holding the root KEL; the dip is appended to the device KEL here.
/// * `root_prefix`: The root identity's KEL prefix (the delegator).
/// * `root_alias`: Keychain alias of the root's current signing key.
/// * `root_curve`: Curve of the root's current key (for the anchoring signature).
/// * `dip`: The device-signed delegated-inception event (from [`build_device_dip`]).
/// * `dip_attachment`: The device's CESR signature attachment over the dip.
/// * `passphrase_provider`: Passphrase source for the root key.
/// * `keychain`: Key storage (the root's signing key).
///
/// Usage:
/// ```ignore
/// let device_did = anchor_received_dip(backend.as_ref(), &root_prefix, &root_alias,
///     CurveType::Ed25519, &bundle.dip, &bundle.attachment, &provider, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn anchor_received_dip(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    dip: &DipEvent,
    dip_attachment: &[u8],
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<(IdentityDID, IxnEvent), InitError> {
    let device_prefix = dip.i.clone();
    let dip_said = dip.d.clone();

    // Cooperative double-anchor: author the root's anchoring `ixn` FIRST so we
    // know its (sequence, SAID). Only then can the delegate's `-G` source seal
    // point back at the exact anchoring event (the dip's own SAID doesn't depend
    // on the anchor, so authoring the anchor before appending the dip is sound).
    let anchor_ixn = author_root_anchor_ixn(
        backend,
        root_prefix,
        root_alias,
        root_curve,
        vec![Seal::KeyEvent {
            i: device_prefix.clone(),
            s: KeriSequence::new(0),
            d: dip_said,
        }],
        passphrase_provider,
        keychain,
    )?;

    // Attach the delegate-side source seal (`-G`) and append the dip carrying it:
    // combined attachment = device signature group (`-A`) ++ source-seal group (`-G`).
    let source_seal = SourceSeal {
        s: anchor_ixn.s,
        d: anchor_ixn.d.clone(),
    };
    let mut anchored_dip = dip.clone();
    anchored_dip.source_seal = Some(source_seal.clone());
    let mut attachment = dip_attachment.to_vec();
    attachment.extend_from_slice(
        &serialize_source_seal_couples(&[source_seal])
            .map_err(|e| InitError::Keri(format!("source seal serialization: {e}")))?,
    );
    backend
        .append_signed_event(&device_prefix, &Event::Dip(anchored_dip), &attachment)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    #[allow(clippy::disallowed_methods)]
    // INVARIANT: device_prefix is from a validated dip, a valid did:keri prefix.
    let device_did = IdentityDID::new_unchecked(format!("did:keri:{}", device_prefix));
    Ok((device_did, anchor_ixn))
}

/// Build + sign an `ixn` on the root KEL anchoring the given seals, **staging** it
/// into `batch` rather than committing. Single-author — signed by the root's
/// current key. The caller commits the batch (alone or alongside other staged
/// writes that must land atomically with the anchor, e.g. a TEL event + ACDC blob).
///
/// Returns the finalized, signed `ixn` and its CESR signature attachment so callers
/// that relay the anchor (or need its `(sequence, SAID)`) can.
///
/// Args:
/// * `backend`: Registry holding the root KEL (read for the current key state).
/// * `root_prefix`: The root identity's KEL prefix (the anchoring controller).
/// * `root_alias`: Keychain alias of the root's current signing key.
/// * `root_curve`: Curve of the root's current key.
/// * `anchors`: The seals to carry in the `ixn`'s `a[]`.
/// * `passphrase_provider`: Passphrase source for the root key.
/// * `keychain`: Key storage (the root's signing key).
/// * `batch`: The atomic write batch the `ixn` is staged into.
///
/// Usage:
/// ```ignore
/// let mut batch = AtomicWriteBatch::new();
/// let ixn = stage_root_anchor_ixn(backend, &root, &alias, curve, seals, &provider, &keychain, &mut batch)?;
/// backend.commit_batch(&batch)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn stage_root_anchor_ixn(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    anchors: Vec<Seal>,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
    batch: &mut crate::storage::registry::backend::AtomicWriteBatch,
) -> Result<IxnEvent, InitError> {
    let root_state = backend
        .get_key_state(root_prefix)
        .map_err(|e| InitError::Registry(e.to_string()))?;
    if !root_state.can_emit_ixn() {
        return Err(InitError::InvalidData(
            "root identity cannot anchor (interaction events forbidden)".to_string(),
        ));
    }
    let ixn = finalize_ixn_event(IxnEvent {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: root_prefix.clone(),
        s: KeriSequence::new(root_state.sequence + 1),
        p: root_state.last_event_said.clone(),
        a: anchors,
    })
    .map_err(|e| InitError::Keri(e.to_string()))?;

    let canonical = serialize_for_signing(&Event::Ixn(ixn.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let (_did, _role, encrypted) = keychain.load_key(root_alias)?;
    let pass = passphrase_provider
        .get_passphrase(&format!("Enter passphrase for root key '{}':", root_alias))?;
    let pkcs8 = Pkcs8Der::new(decrypt_keypair(&encrypted, &pass)?.to_vec());
    let sig = sign_with_pkcs8_for_init(root_curve, &pkcs8, &canonical)
        .map_err(|e| InitError::Crypto(e.to_string()))?;
    let attachment = serialize_attachment(&[IndexedSignature {
        index: 0,
        prior_index: None,
        sig,
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;
    batch.stage_event(root_prefix.clone(), Event::Ixn(ixn.clone()), attachment);
    Ok(ixn)
}

/// Author an `ixn` on the root KEL anchoring the given seals, signed by the root's
/// current key, and commit it immediately. Single-author — no other identity's key
/// is required. Returns the finalized, signed `ixn` (callers that relay the anchor —
/// e.g. remote pairing — need its bytes; same-host callers may ignore it).
///
/// Thin wrapper over [`stage_root_anchor_ixn`] + `commit_batch` — use the staging
/// form directly when the anchor must commit atomically with other writes.
pub fn author_root_anchor_ixn(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    anchors: Vec<Seal>,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<IxnEvent, InitError> {
    let mut batch = crate::storage::registry::backend::AtomicWriteBatch::new();
    let ixn = stage_root_anchor_ixn(
        backend,
        root_prefix,
        root_alias,
        root_curve,
        anchors,
        passphrase_provider,
        keychain,
        &mut batch,
    )?;
    backend
        .commit_batch(&batch)
        .map_err(|e| InitError::Registry(e.to_string()))?;
    Ok(ixn)
}

/// The role a delegated identifier plays.
///
/// Agents and devices share the exact same `dip`/`drt` delegation mechanism; the
/// role is a presentation distinction so `agent list` and `device list` don't
/// intermix. It is carried by an `agent:{prefix}` `Seal::Digest` marker in the root
/// KEL (no new seal type) — devices are the unmarked default.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DelegatedRole {
    /// A device — the default delegated identifier (carries no role marker).
    Device,
    /// An AI agent — carries an `agent:{prefix}` role marker in the root KEL.
    Agent,
}

/// One identifier the root has delegated, with its role and revocation status.
pub struct DelegatedDeviceInfo {
    /// The delegated identifier's KEL prefix.
    pub device_prefix: Prefix,
    /// Whether the root has anchored a revocation for it.
    pub revoked: bool,
    /// Whether this delegation is an agent or a device.
    pub role: DelegatedRole,
}

/// The role-marker digest value for an agent prefix (`agent:{prefix}`).
fn agent_role_marker(agent_prefix: &Prefix) -> String {
    format!("agent:{}", agent_prefix.as_str())
}

/// Anchor an agent role marker for `agent_prefix` on the root KEL (single-author).
///
/// Anchors a `Seal::Digest{d: "agent:{prefix}"}` so [`list_delegated_devices`] can
/// classify this delegated identifier as an agent — distinguishing it from devices
/// without a new seal type. Distinct from the exact-prefix revocation digest, so it
/// never reads as a revocation.
///
/// Args:
/// * `backend`: Registry backend holding the root KEL.
/// * `root_prefix` / `root_alias` / `root_curve`: the delegator authoring the marker.
/// * `agent_prefix`: The agent's KEL prefix to mark.
/// * `passphrase_provider` / `keychain`: root key custody.
///
/// Usage:
/// ```ignore
/// mark_delegated_agent(&*backend, &root_prefix, &root_alias, curve, &agent_prefix, &provider, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn mark_delegated_agent(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    agent_prefix: &Prefix,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<(), InitError> {
    author_root_anchor_ixn(
        backend,
        root_prefix,
        root_alias,
        root_curve,
        vec![Seal::Digest {
            d: Said::new_unchecked(agent_role_marker(agent_prefix)),
        }],
        passphrase_provider,
        keychain,
    )
    .map(|_| ())
}

/// Anchor a delegator-anchored scope/expiry seal for an agent on the root KEL.
///
/// Authority comes from the party that controls the delegator key — the scope rides
/// in the delegator's own `ixn`, never in the agent's KEL (a compromised agent must
/// not widen its own scope). Advisory authorization (ACDC is the Epic-F upgrade).
///
/// Args:
/// * `backend`: Registry backend holding the root KEL.
/// * `root_prefix` / `root_alias` / `root_curve`: the delegator authoring the seal.
/// * `agent_prefix`: The agent's KEL prefix the scope applies to.
/// * `scope`: The granted capabilities + optional expiry.
/// * `passphrase_provider` / `keychain`: root key custody.
///
/// Usage:
/// ```ignore
/// mark_agent_scope(&*backend, &root_prefix, &root_alias, curve, &agent_prefix, &scope, &provider, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn mark_agent_scope(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    agent_prefix: &Prefix,
    scope: &AgentScope,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<(), InitError> {
    author_root_anchor_ixn(
        backend,
        root_prefix,
        root_alias,
        root_curve,
        vec![Seal::Digest {
            d: Said::new_unchecked(encode_agent_scope(agent_prefix.as_str(), scope)),
        }],
        passphrase_provider,
        keychain,
    )
    .map(|_| ())
}

/// Read the latest delegator-anchored scope for `agent_prefix` from a KEL slice,
/// or `None` if the delegator never anchored one. Pure — used by the verifier.
///
/// Args:
/// * `events`: The delegator's KEL events.
/// * `agent_prefix`: The agent prefix to resolve scope for.
pub fn read_agent_scope(events: &[Event], agent_prefix: &Prefix) -> Option<AgentScope> {
    let mut found: Option<AgentScope> = None;
    for event in events {
        for seal in event.anchors() {
            if let Seal::Digest { d } = seal
                && let Some((prefix, scope)) = decode_agent_scope(d.as_str())
                && prefix == agent_prefix.as_str()
            {
                found = Some(scope);
            }
        }
    }
    found
}

/// Marker prefix for an org-policy `Seal::Digest` value (`policy:{source_hash_hex}`).
///
/// Distinct from the `agent:` role marker, the `agentscope:` scope seal, and the
/// bare-prefix revocation digest, so an org-policy seal is never misread as any of
/// them by [`list_delegated_devices`], [`read_agent_scope`], or the revocation scan.
const ORG_POLICY_MARKER: &str = "policy:";

/// Anchor an org-policy seal on the org KEL: a `Seal::Digest{d: "policy:{hash}"}`
/// binding the KEL to the BLAKE3 source-hash of the org's compiled policy.
///
/// Only the hash rides the KEL — the policy bytes live in a content-addressed blob
/// (the registry credential store) — so the append-only log stays lean and the
/// binding is tamper-evident (loaders recompute the blob's hash and compare).
/// Single-author: the org's current key signs the `ixn`. Latest-anchored wins.
///
/// Args:
/// * `backend`: Registry backend holding the org KEL.
/// * `org_prefix` / `org_alias` / `org_curve`: the org authoring the seal.
/// * `source_hash_hex`: Lowercase-hex BLAKE3 hash of the compiled policy's source.
/// * `passphrase_provider` / `keychain`: org key custody.
///
/// Usage:
/// ```ignore
/// mark_org_policy(&*backend, &org_prefix, &org_alias, curve, &hash_hex, &provider, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn mark_org_policy(
    backend: &(dyn RegistryBackend + Send + Sync),
    org_prefix: &Prefix,
    org_alias: &KeyAlias,
    org_curve: CurveType,
    source_hash_hex: &str,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<(), InitError> {
    author_root_anchor_ixn(
        backend,
        org_prefix,
        org_alias,
        org_curve,
        vec![Seal::Digest {
            d: Said::new_unchecked(format!("{ORG_POLICY_MARKER}{source_hash_hex}")),
        }],
        passphrase_provider,
        keychain,
    )
    .map(|_| ())
}

/// Read the latest org-policy source-hash anchored on a KEL slice, or `None` if the
/// org never anchored one. Pure — the inverse of [`mark_org_policy`]'s marker.
///
/// Args:
/// * `events`: The org's KEL events (oldest first; the latest anchored policy wins).
pub fn read_org_policy_hash(events: &[Event]) -> Option<String> {
    let mut found: Option<String> = None;
    for event in events {
        for seal in event.anchors() {
            if let Seal::Digest { d } = seal
                && let Some(hash) = d.as_str().strip_prefix(ORG_POLICY_MARKER)
            {
                found = Some(hash.to_string());
            }
        }
    }
    found
}

/// List every device the root has delegated, each tagged with whether the root
/// has revoked it (walks the root KEL collecting delegation `KeyEvent` seals and
/// revocation digest seals). Order follows first delegation.
///
/// Args:
/// * `backend`: Registry backend holding the root KEL.
/// * `root_prefix`: The root identity's KEL prefix.
///
/// Usage:
/// ```ignore
/// let devices = list_delegated_devices(&*backend, &root_prefix)?;
/// let live = devices.iter().filter(|d| !d.revoked).count();
/// ```
pub fn list_delegated_devices(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
) -> Result<Vec<DelegatedDeviceInfo>, InitError> {
    let mut delegated: Vec<String> = Vec::new();
    let mut revoked: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut agents: std::collections::HashSet<String> = std::collections::HashSet::new();
    backend
        .visit_events(root_prefix, 0, &mut |event| {
            for seal in event.anchors() {
                match seal {
                    Seal::KeyEvent { i, .. } => {
                        let p = i.as_str().to_string();
                        if !delegated.contains(&p) {
                            delegated.push(p);
                        }
                    }
                    // An `agent:{prefix}` digest is a role marker; a bare-prefix
                    // digest is a revocation.
                    Seal::Digest { d } => match d.as_str().strip_prefix("agent:") {
                        Some(prefix) => {
                            agents.insert(prefix.to_string());
                        }
                        None => {
                            revoked.insert(d.as_str().to_string());
                        }
                    },
                    _ => {}
                }
            }
            ControlFlow::Continue(())
        })
        .map_err(|e| InitError::Registry(e.to_string()))?;
    Ok(delegated
        .into_iter()
        .map(|p| DelegatedDeviceInfo {
            revoked: revoked.contains(&p),
            role: if agents.contains(&p) {
                DelegatedRole::Agent
            } else {
                DelegatedRole::Device
            },
            device_prefix: Prefix::new_unchecked(p),
        })
        .collect())
}

/// Resolve `(delegated, revoked)` for `device_prefix` against the root KEL: the
/// root anchored its `dip` (KeyEvent seal) and/or revoked it (digest seal of the
/// device prefix).
fn delegation_status(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    device_prefix: &Prefix,
) -> Result<(bool, bool), InitError> {
    let mut delegated = false;
    let mut revoked = false;
    backend
        .visit_events(root_prefix, 0, &mut |event| {
            for seal in event.anchors() {
                match seal {
                    Seal::KeyEvent { i, .. } if i.as_str() == device_prefix.as_str() => {
                        delegated = true;
                    }
                    Seal::Digest { d } if d.as_str() == device_prefix.as_str() => {
                        revoked = true;
                    }
                    _ => {}
                }
            }
            ControlFlow::Continue(())
        })
        .map_err(|e| InitError::Registry(e.to_string()))?;
    Ok((delegated, revoked))
}

/// Revoke a delegated device: the root anchors a revocation marker (a digest seal
/// of the device's prefix) so verifiers stop treating it as authorized. Single-
/// author — the root's current key signs the `ixn`; the device's key is not needed.
/// Idempotent if the device is already revoked.
///
/// Args:
/// * `backend`: Registry backend holding the root KEL.
/// * `root_prefix`: The root identity's KEL prefix (the delegator).
/// * `root_alias`: Keychain alias of the root's current signing key.
/// * `root_curve`: Curve of the root's current key.
/// * `device_prefix`: The delegated device's KEL prefix to revoke.
/// * `passphrase_provider`: Passphrase source.
/// * `keychain`: Key storage.
///
/// Usage:
/// ```ignore
/// revoke_delegated_device(&*backend, &root_prefix, &root_alias, curve, &device_prefix, &provider, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn revoke_delegated_device(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    device_prefix: &Prefix,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<(), InitError> {
    if device_prefix.as_str() == root_prefix.as_str() {
        return Err(InitError::InvalidData(
            "cannot revoke the root identity's own controller".to_string(),
        ));
    }
    let (delegated, revoked) = delegation_status(backend, root_prefix, device_prefix)?;
    if !delegated {
        return Err(InitError::InvalidData(format!(
            "device {device_prefix} is not a delegated controller of the identity"
        )));
    }
    if revoked {
        return Ok(());
    }
    let revocation = Seal::Digest {
        d: Said::new_unchecked(device_prefix.as_str().to_string()),
    };
    author_root_anchor_ixn(
        backend,
        root_prefix,
        root_alias,
        root_curve,
        vec![revocation],
        passphrase_provider,
        keychain,
    )
    .map(|_| ())
}

/// Revoke an enumerated set of delegated devices in a **single** `ixn` — the org-wide
/// kill switch. Anchors one revocation `Seal::Digest` per still-live device in one
/// atomic event (an `ixn`'s `a[]` is a seal vector), so the whole set's authority ends
/// at the same KEL position. Idempotent: devices already revoked are skipped; if none
/// remain to revoke, no event is written (`Ok(None)`).
///
/// This is an atomic batch of N revocations, **not** a class abstraction — the caller
/// supplies the explicit membership. (Class-by-predicate revocation needs the policy
/// path; it is tracked as a follow-on.)
///
/// Args:
/// * `backend`: Registry backend holding the root KEL.
/// * `root_prefix` / `root_alias` / `root_curve`: the delegator authoring the batch.
/// * `device_prefixes`: The delegated devices to revoke.
/// * `passphrase_provider` / `keychain`: root key custody.
///
/// Returns the newly-revoked prefixes and the anchoring `ixn` (or `None` if every
/// listed device was already revoked).
///
/// Usage:
/// ```ignore
/// let (revoked, ixn) = revoke_delegated_devices_batch(&*backend, &root, &alias, curve, &prefixes, &p, &kc)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn revoke_delegated_devices_batch(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    device_prefixes: &[Prefix],
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<(Vec<Prefix>, Option<IxnEvent>), InitError> {
    let mut seals = Vec::new();
    let mut newly_revoked = Vec::new();
    for device_prefix in device_prefixes {
        if device_prefix.as_str() == root_prefix.as_str() {
            return Err(InitError::InvalidData(
                "cannot revoke the root identity's own controller".to_string(),
            ));
        }
        let (delegated, revoked) = delegation_status(backend, root_prefix, device_prefix)?;
        if !delegated {
            return Err(InitError::InvalidData(format!(
                "device {device_prefix} is not a delegated controller of the identity"
            )));
        }
        if revoked {
            continue; // already revoked — idempotent skip.
        }
        seals.push(Seal::Digest {
            d: Said::new_unchecked(device_prefix.as_str().to_string()),
        });
        newly_revoked.push(device_prefix.clone());
    }

    if seals.is_empty() {
        return Ok((newly_revoked, None));
    }
    let ixn = author_root_anchor_ixn(
        backend,
        root_prefix,
        root_alias,
        root_curve,
        seals,
        passphrase_provider,
        keychain,
    )?;
    Ok((newly_revoked, Some(ixn)))
}

/// Reveal and validate a delegated device's pre-committed next key (its new current
/// key) for a `drt`: loads `{device_alias}--next-{establishment_seq}`, decrypts it,
/// and checks it against the prior next-key commitment. Returns the next-key alias (so
/// the caller can retire it), the revealed PKCS#8, and its verkey.
fn reveal_pre_committed_next_key(
    keychain: &(dyn KeyStorage + Send + Sync),
    passphrase_provider: &dyn PassphraseProvider,
    device_alias: &KeyAlias,
    device_state: &auths_keri::KeyState,
) -> Result<(KeyAlias, Pkcs8Der, KeriPublicKey), InitError> {
    let next_alias = KeyAlias::new_unchecked(format!(
        "{}--next-{}",
        device_alias, device_state.last_establishment_sequence
    ));
    let (_did, _role, encrypted) = keychain.load_key(&next_alias)?;
    let pass = passphrase_provider.get_passphrase(&format!(
        "Enter passphrase for device next key '{}':",
        next_alias
    ))?;
    let revealed_pkcs8 = Pkcs8Der::new(decrypt_keypair(&encrypted, &pass)?.to_vec());
    let revealed_keypair = load_keypair_from_der_or_seed(revealed_pkcs8.as_ref())?;
    #[allow(clippy::expect_used)] // INVARIANT: ring Ed25519 public key is always 32 bytes
    let revealed_verkey = KeriPublicKey::ed25519(revealed_keypair.public_key().as_ref())
        .expect("ring Ed25519 public key is 32 bytes");
    if device_state.next_commitment.is_empty()
        || !verify_commitment(&revealed_verkey, &device_state.next_commitment[0])
    {
        return Err(InitError::InvalidData(
            "device next key does not match its prior commitment".to_string(),
        ));
    }
    Ok((next_alias, revealed_pkcs8, revealed_verkey))
}

/// Rotate a delegated device's own key (`drt`), anchored by the root.
///
/// The device reveals its pre-committed next key (its new current key), signs a
/// `drt` on its own KEL advancing to it, commits a fresh next key, and the root
/// anchors the `drt`. Single signer = the device; the root only anchors. (Local
/// case: the device's keys live in this keychain under `device_alias`; the remote
/// case runs the device half on the device.)
///
/// Args:
/// * `backend`: Registry backend holding the device + root KELs.
/// * `root_prefix` / `root_alias` / `root_curve`: the delegator (anchors the drt).
/// * `device_prefix`: the delegated device's KEL prefix.
/// * `device_alias`: keychain alias of the device's current key (its next key is
///   under `{device_alias}--next-{seq}`).
/// * `device_curve`: the device key's curve.
/// * `passphrase_provider` / `keychain`: key custody.
///
/// Usage:
/// ```ignore
/// rotate_delegated_device(&*backend, &root_prefix, &root_alias, root_curve,
///     &device_prefix, &device_alias, CurveType::Ed25519, &provider, &keychain)?;
/// ```
#[allow(clippy::too_many_arguments)]
pub fn rotate_delegated_device(
    backend: &(dyn RegistryBackend + Send + Sync),
    root_prefix: &Prefix,
    root_alias: &KeyAlias,
    root_curve: CurveType,
    device_prefix: &Prefix,
    device_alias: &KeyAlias,
    device_curve: CurveType,
    passphrase_provider: &dyn PassphraseProvider,
    keychain: &(dyn KeyStorage + Send + Sync),
) -> Result<(), InitError> {
    let device_state = backend
        .get_key_state(device_prefix)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    // Reveal the device's pre-committed next key (its new current key).
    let (next_alias, revealed_pkcs8, revealed_verkey) =
        reveal_pre_committed_next_key(keychain, passphrase_provider, device_alias, &device_state)?;

    // Commit a fresh next key for the device's subsequent rotation.
    let fresh_next =
        generate_keypair_for_init(device_curve).map_err(|e| InitError::Crypto(e.to_string()))?;
    let new_next_commitment = compute_next_commitment(&fresh_next.verkey());

    let new_sequence = device_state.sequence + 1;
    let revealed_cesr = revealed_verkey
        .to_qb64()
        .map_err(|e| InitError::InvalidData(e.to_string()))?;
    let drt = finalize_drt_event(DrtEvent::new(DrtEventInit {
        v: VersionString::placeholder(),
        d: Said::default(),
        i: device_prefix.clone(),
        s: KeriSequence::new(new_sequence),
        p: device_state.last_event_said.clone(),
        kt: Threshold::Simple(1),
        k: vec![CesrKey::new_unchecked(revealed_cesr)],
        nt: Threshold::Simple(1),
        n: vec![new_next_commitment],
        bt: Threshold::Simple(0),
        br: vec![],
        ba: vec![],
        c: vec![],
        a: vec![],
        di: root_prefix.clone(),
    }))
    .map_err(|e| InitError::Keri(e.to_string()))?;
    let drt_said = drt.d.clone();

    // The device signs the drt with its revealed (new current) key. The signature
    // is over the event body only; the `-G` source seal is an attachment added
    // after anchoring and never affects the SAID or the signed bytes.
    let canonical = serialize_for_signing(&Event::Drt(drt.clone()))
        .map_err(|e| InitError::Keri(e.to_string()))?;
    let sig = sign_with_pkcs8_for_init(device_curve, &revealed_pkcs8, &canonical)
        .map_err(|e| InitError::Crypto(e.to_string()))?;
    let mut attachment = serialize_attachment(&[IndexedSignature {
        index: 0,
        prior_index: None,
        sig,
    }])
    .map_err(|e| InitError::Keri(format!("attachment serialization: {e}")))?;

    // Cooperative double-anchor (as in `anchor_received_dip`): the root anchors
    // the drt first, then the delegate's `-G` source seal points back at it.
    let anchor_ixn = author_root_anchor_ixn(
        backend,
        root_prefix,
        root_alias,
        root_curve,
        vec![Seal::KeyEvent {
            i: device_prefix.clone(),
            s: KeriSequence::new(new_sequence),
            d: drt_said,
        }],
        passphrase_provider,
        keychain,
    )?;

    let source_seal = SourceSeal {
        s: anchor_ixn.s,
        d: anchor_ixn.d.clone(),
    };
    let mut anchored_drt = drt;
    anchored_drt.source_seal = Some(source_seal.clone());
    attachment.extend_from_slice(
        &serialize_source_seal_couples(&[source_seal])
            .map_err(|e| InitError::Keri(format!("source seal serialization: {e}")))?,
    );
    backend
        .append_signed_event(device_prefix, &Event::Drt(anchored_drt), &attachment)
        .map_err(|e| InitError::Registry(e.to_string()))?;

    // Persist the device's new current (the revealed key) + fresh next.
    #[allow(clippy::disallowed_methods)]
    // INVARIANT: device_prefix is a valid did:keri prefix.
    let device_did = IdentityDID::new_unchecked(format!("did:keri:{}", device_prefix));
    let store_pass = passphrase_provider.get_passphrase(&format!(
        "Create passphrase for rotated device key '{}':",
        device_alias
    ))?;
    let enc_cur = encrypt_keypair(revealed_pkcs8.as_ref(), &store_pass)?;
    keychain.store_key(device_alias, &device_did, KeyRole::Primary, &enc_cur)?;
    let new_next_alias =
        KeyAlias::new_unchecked(format!("{}--next-{}", device_alias, new_sequence));
    let enc_next = encrypt_keypair(fresh_next.pkcs8.as_ref(), &store_pass)?;
    keychain.store_key(
        &new_next_alias,
        &device_did,
        KeyRole::NextRotation,
        &enc_next,
    )?;
    let _ = keychain.delete_key(&next_alias);

    Ok(())
}