vtc-service 0.12.0

Service for Verifiable Trust Communities
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
//! `POST /v1/invitations` — issue an **Invitation Credential** (VIC) to a
//! prospective member (the operator side of the VIC auto-join ceremony).
//!
//! The community admin enters an invitee DID; the VTC mints a short-lived,
//! revocable VIC bound to that DID and signed by the community key, and returns
//! the signed credential for **out-of-band delivery** (copy / QR) to the
//! invitee. The invitee later presents it inside a join VP and is auto-admitted
//! (`credentials::invitation_verify` + the default `join.rego`).
//!
//! Auth: Admin / Moderator / Issuer — the roles that grow + vouch for
//! membership. The issuance itself (slot allocation, signing, schema check)
//! lives in [`crate::credentials::invitation`]; this is the thin authenticated
//! REST surface over it.

use chrono::{Duration, Utc};
use serde::{Deserialize, Serialize};
use serde_json::Value as JsonValue;
use tracing::info;

use vti_common::audit::{
    AuditEvent, InvitationDeliveredData, InvitationIssuedData, InvitationRevokedData,
};
use vti_common::error::AppError;

use crate::acl::{VtcRole, get_acl_entry};
use crate::credentials::invitation::{DEFAULT_INVITATION_VALIDITY, issue_invitation};
use crate::credentials::invitation_registry::{
    InvitationRecord, get_invitation, list_invitations, store_invitation,
};
use crate::error::TaskError;
use crate::server::AppState;
use crate::status_list;

/// Upper bound on a caller-requested validity — an invite is a short-lived
/// onboarding artifact, not a standing credential.
const MAX_VALIDITY_DAYS: i64 = 90;

#[derive(Debug, Deserialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct IssueInvitationBody {
    /// The DID to invite (a prospective, non-member holder).
    pub subject_did: String,
    /// Optional validity in days (1..=90); defaults to the 7-day VIC default.
    #[serde(default)]
    pub validity_days: Option<u32>,
    /// Optional role to grant the invitee on join (e.g. `member`, `moderator`,
    /// `issuer`). Carried in the VIC's `credentialSubject.scopes` as
    /// `role:<name>` and honored by the join policy. `admin` is refused — the
    /// no-admin-via-join privilege ceiling would deny it anyway. Defaults to
    /// `member` (absent scope).
    #[serde(default)]
    pub role: Option<String>,
}

#[derive(Debug, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct IssueInvitationResponse {
    /// Echo of the invited DID.
    pub subject_did: String,
    /// The VIC's `validUntil` (RFC3339), for the operator UI to display.
    pub valid_until: Option<String>,
    /// The signed Invitation Credential — handed to the invitee out-of-band
    /// (copy / QR). The invitee presents it back in a join request.
    pub vic: JsonValue,
}

/// `vtc/invitations/issue/0.1`, by `actor`. A signed document served by the
/// spine (`trust_tasks::community_tasks`).
pub(crate) async fn issue(
    state: &AppState,
    actor: &str,
    body: IssueInvitationBody,
) -> Result<IssueInvitationResponse, TaskError> {
    let signer = state
        .credential_signer
        .as_ref()
        .ok_or_else(|| AppError::Internal("credential signer not configured".into()))?;

    // Auth: `vtc.invitations.manage`, read from the inviter's live entry
    // (vtc-admin-roles.md §4).
    let acl = crate::acl::require_capability(
        &state.acl_ks,
        actor,
        crate::acl::Capability::InvitationsManage,
        None,
    )
    .await?;

    // An invite is for a *prospective* member.
    if !body.subject_did.starts_with("did:") {
        return Err(AppError::Validation("subjectDid must be a DID".into()).into());
    }
    // "Already a member" means a *current* (ACL-present) member — not a departed
    // one whose tombstone Member row lingers after a Tombstone/Historical
    // removal. A departed member can be re-invited (re-join overwrites the
    // tombstone with a fresh membership), so gate on the ACL, not the Member row.
    if get_acl_entry(&state.acl_ks, &body.subject_did)
        .await?
        .is_some()
    {
        return Err(AppError::Conflict(format!(
            "{} is already a current member — no invitation needed",
            body.subject_did
        ))
        .into());
    }

    let validity = match body.validity_days {
        Some(d) if d == 0 || (d as i64) > MAX_VALIDITY_DAYS => {
            return Err(AppError::Validation(format!(
                "validityDays must be between 1 and {MAX_VALIDITY_DAYS}"
            ))
            .into());
        }
        Some(d) => Duration::days(d as i64),
        None => DEFAULT_INVITATION_VALIDITY,
    };

    // A role grant on the invite must parse to a known role and may never be
    // `admin` — a join can't grant admin (host privilege ceiling), so we refuse
    // it at issuance rather than mint an invite that would be denied on redeem.
    if let Some(role) = body.role.as_deref() {
        // Only an unparseable role is `unknownRole`. `admin` parses and is
        // refused below as the privilege ceiling, which the specification
        // does not describe, so it stays the framework's own refusal.
        //
        // "Not one this community defines" can mean no more than this today:
        // a community keeps no register of its `custom:<name>` roles — a
        // custom role is a name, granted whatever an operator's
        // `role_definitions.rego` grants it — so any well-formed custom name
        // is one this service can seat.
        let parsed = role.parse::<VtcRole>().map_err(|_| {
            TaskError::declared(
                INVITATION_ISSUE_ERR_UNKNOWN_ROLE,
                AppError::Validation(format!("unknown role `{role}`")),
            )
        })?;
        if !parsed.is_assignable() {
            return Err(TaskError::declared(
                INVITATION_ISSUE_ERR_UNKNOWN_ROLE,
                AppError::Validation(format!(
                    "`{role}` is not a role an invitation can seat — it marks a non-member \
                     holding git rights"
                )),
            ));
        }
        if matches!(parsed, VtcRole::Admin) {
            return Err(AppError::Validation(
                "an invitation may not grant `admin` (no admin via join)".into(),
            )
            .into());
        }
        // Conferring a role is assigning one (`vtc.roles.assign`), and a role
        // that implies administrative authority is a grant of it, bounded by
        // the inviter's own entry like any grant (VTI-ACL-071). An inviter
        // without it invites members only.
        if !matches!(parsed, VtcRole::Member) {
            if !acl.can_any(crate::acl::Capability::RolesAssign) {
                return Err(AppError::Forbidden(format!(
                    "inviting with the role `{role}` assigns a role, which takes \
                     vtc.roles.assign"
                ))
                .into());
            }
            let seated = crate::acl::VtcAclEntry::new(
                body.subject_did.clone(),
                parsed.clone(),
                parsed.implied_authority(),
                actor,
            );
            if let Err(refusal) =
                crate::acl::granting::check_write(&acl, &seated, crate::auth::session::now_epoch())
            {
                return Err(AppError::Forbidden(format!(
                    "an invitation with the role `{role}` grants what it implies: {refusal}"
                ))
                .into());
            }
        }
    }

    let vic = issue_invitation(
        signer,
        &state.status_lists_ks,
        &state.schemas_ks,
        &body.subject_did,
        validity,
        body.role.as_deref(),
    )
    .await?;
    let valid_until = vic
        .get("validUntil")
        .and_then(JsonValue::as_str)
        .map(str::to_string);

    // Record the issued VIC so it can be listed + revoked. The id + revocation
    // slot are read back from the freshly-signed credential.
    let id = vic
        .get("id")
        .and_then(JsonValue::as_str)
        .ok_or_else(|| AppError::Internal("issued VIC has no `id`".into()))?
        .to_string();
    let slot = vic
        .pointer("/credentialStatus/statusListIndex")
        .and_then(JsonValue::as_str)
        .and_then(|s| s.parse::<u32>().ok())
        .ok_or_else(|| AppError::Internal("issued VIC has no usable statusListIndex".into()))?;
    store_invitation(
        &state.invitations_ks,
        &InvitationRecord {
            id: id.clone(),
            subject_did: body.subject_did.clone(),
            slot,
            role: body.role.clone(),
            issued_by: actor.to_string(),
            issued_at: Utc::now(),
            valid_until: valid_until.clone(),
            revoked_at: None,
            // Kept for `deliver`, which offers it to the invitee later.
            credential: Some(vic.clone()),
            offer_code: None,
        },
    )
    .await?;

    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(
                actor,
                Some(&body.subject_did),
                AuditEvent::InvitationIssued(InvitationIssuedData {
                    invitation_id: id.clone(),
                    subject_did: body.subject_did.clone(),
                    role: body.role.clone(),
                    valid_until: valid_until.clone().unwrap_or_default(),
                    status_list_index: Some(slot),
                }),
            )
            .await?;
    }

    info!(
        actor = %actor,
        subject = %body.subject_did,
        vic_id = %id,
        "issued an invitation credential (VIC)"
    );

    Ok(IssueInvitationResponse {
        subject_did: body.subject_did,
        valid_until,
        vic,
    })
}

// ── List + revoke ─────────────────────────────────────────────────────────

/// One row of the invitation list (the registry record, body-free).
#[derive(Debug, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct InvitationListItem {
    pub id: String,
    pub subject_did: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub role: Option<String>,
    pub issued_by: String,
    pub issued_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub valid_until: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revoked_at: Option<String>,
}

impl From<InvitationRecord> for InvitationListItem {
    fn from(r: InvitationRecord) -> Self {
        // One timestamp form per row: `validUntil` is echoed from the signed
        // credential (`…Z`, whole seconds), so the record's own instants are
        // written the same way rather than chrono's default `+00:00` with
        // microseconds (OBS-04).
        let instant =
            |t: chrono::DateTime<chrono::Utc>| t.to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
        Self {
            id: r.id,
            subject_did: r.subject_did,
            role: r.role,
            issued_by: r.issued_by,
            issued_at: instant(r.issued_at),
            valid_until: r.valid_until,
            revoked_at: r.revoked_at.map(instant),
        }
    }
}

#[derive(Debug, Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct InvitationListResponse {
    pub invitations: Vec<InvitationListItem>,
}

/// What an inviter may manage: every invitation (an `Admin`), or only the
/// ones it issued itself (a `Moderator` or `Issuer`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InviterScope {
    All,
    OwnOnly,
}

impl InviterScope {
    fn covers(self, record: &InvitationRecord, actor: &str) -> bool {
        self == Self::All || record.issued_by == actor
    }
}

/// Auth gate shared by the invitation ops: `vtc.invitations.manage`, and how
/// far the caller's authority over issued invitations reaches.
///
/// An inviter grows the community; it does not manage the invitations other
/// inviters issued unless it also assigns roles (`vtc.roles.assign`, a
/// community administrator) — their invitees, revocations and offers are not
/// its to see or act on, so an invitation outside its scope answers exactly as
/// one that does not exist.
async fn require_inviter(state: &AppState, did: &str) -> Result<InviterScope, AppError> {
    let acl = crate::acl::require_capability(
        &state.acl_ks,
        did,
        crate::acl::Capability::InvitationsManage,
        None,
    )
    .await?;
    Ok(if acl.can(crate::acl::Capability::RolesAssign, None) {
        InviterScope::All
    } else {
        InviterScope::OwnOnly
    })
}

pub(crate) async fn list(
    state: &AppState,
    actor: &str,
) -> Result<InvitationListResponse, AppError> {
    let scope = require_inviter(state, actor).await?;
    let invitations = list_invitations(&state.invitations_ks)
        .await?
        .into_iter()
        .filter(|r| scope.covers(r, actor))
        .map(InvitationListItem::from)
        .collect();
    Ok(InvitationListResponse { invitations })
}

#[derive(Debug, Serialize, utoipa::ToSchema)]
#[schema(as = InvitationRevokeResponse)]
#[serde(rename_all = "camelCase")]
pub struct RevokeResponse {
    pub id: String,
    pub revoked_at: String,
    /// True if this call performed the revocation; false if it was already
    /// revoked (idempotent).
    pub newly_revoked: bool,
}

pub(crate) async fn revoke(
    state: &AppState,
    actor: &str,
    id: String,
) -> Result<RevokeResponse, TaskError> {
    let scope = require_inviter(state, actor).await?;

    let mut record = get_invitation(&state.invitations_ks, &id)
        .await?
        // One outside the caller's scope is as absent as one never issued: a
        // Moderator learns nothing of another inviter's invitations.
        .filter(|r| scope.covers(r, actor))
        .ok_or_else(|| {
            TaskError::declared(
                INVITATION_REVOKE_ERR_NOT_FOUND,
                AppError::NotFound(format!("no invitation with id {id}")),
            )
        })?;

    // Idempotent: an already-revoked invite reports its prior revocation.
    if let Some(revoked_at) = record.revoked_at {
        return Ok(RevokeResponse {
            id,
            revoked_at: revoked_at.to_rfc3339(),
            newly_revoked: false,
        });
    }

    // Flip the revocation status-list bit at the VIC's slot — locked RMW so a
    // concurrent allocate/flip can't clobber it (P0.1).
    let slot = record.slot;
    status_list::with_locked(
        &state.status_lists_ks,
        affinidi_status_list::StatusPurpose::Revocation,
        |sl| {
            status_list::flip(sl, slot, true)
                .map_err(|e| AppError::Internal(format!("flip revocation bit {slot}: {e}")))
        },
    )
    .await?;

    let now = Utc::now();
    record.revoked_at = Some(now);
    store_invitation(&state.invitations_ks, &record).await?;

    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(
                actor,
                Some(&record.subject_did),
                AuditEvent::InvitationRevoked(InvitationRevokedData {
                    invitation_id: id.clone(),
                    subject_did: Some(record.subject_did.clone()),
                    newly_revoked: true,
                }),
            )
            .await?;
    }

    info!(actor = %actor, vic_id = %id, slot, "revoked an invitation credential (VIC)");

    Ok(RevokeResponse {
        id,
        revoked_at: now.to_rfc3339(),
        newly_revoked: true,
    })
}

/// `vtc/invitations/issue:unknownRole`, read from the generated bindings.
pub const INVITATION_ISSUE_ERR_UNKNOWN_ROLE: &str =
    trust_tasks_rs::specs::vtc::invitations::issue::v0_1::error_codes::UNKNOWN_ROLE.code;
/// `vtc/invitations/revoke:notFound`, read from the generated bindings.
pub const INVITATION_REVOKE_ERR_NOT_FOUND: &str =
    trust_tasks_rs::specs::vtc::invitations::revoke::v0_1::error_codes::NOT_FOUND.code;

use trust_tasks_rs::specs::vtc::invitations::deliver::v0_1::error_codes as deliver_codes;

/// `vtc/invitations/deliver:notFound`, read from the generated bindings.
pub const INVITATION_DELIVER_ERR_NOT_FOUND: &str = deliver_codes::NOT_FOUND.code;
/// `vtc/invitations/deliver:revoked`, read from the generated bindings.
pub const INVITATION_DELIVER_ERR_REVOKED: &str = deliver_codes::REVOKED.code;
/// `vtc/invitations/deliver:noRoute`, read from the generated bindings.
pub const INVITATION_DELIVER_ERR_NO_ROUTE: &str = deliver_codes::NO_ROUTE.code;

/// A `deliver` refusal. The three the specification declares carry their code
/// beside the usual `error` member; anything else renders as every other VTC
/// error does. `expired` is the framework's standard code, reported as a 410.
pub enum DeliverError {
    NotFound(String),
    Revoked(String),
    NoRoute(String),
    Other(AppError),
}

impl From<AppError> for DeliverError {
    fn from(e: AppError) -> Self {
        Self::Other(e)
    }
}

impl From<DeliverError> for crate::error::TaskError {
    fn from(e: DeliverError) -> Self {
        use crate::error::TaskError;
        match e {
            DeliverError::NotFound(m) => {
                TaskError::declared(INVITATION_DELIVER_ERR_NOT_FOUND, AppError::NotFound(m))
            }
            DeliverError::Revoked(m) => {
                TaskError::declared(INVITATION_DELIVER_ERR_REVOKED, AppError::Conflict(m))
            }
            DeliverError::NoRoute(m) => {
                TaskError::declared(INVITATION_DELIVER_ERR_NO_ROUTE, AppError::Validation(m))
            }
            // A lapsed invitation is the framework's standard `expired`.
            DeliverError::Other(AppError::Gone(m)) => {
                TaskError::declared("expired", AppError::Gone(m))
            }
            DeliverError::Other(e) => TaskError::App(e),
        }
    }
}

/// The delivery channels this build implements.
#[derive(Clone, Copy)]
enum Channel {
    Message,
    Offer,
}

/// How long a delivery offer lives, at most: long enough for an invitee to
/// act on a pushed offer or a printed QR code, and never longer than the
/// invitation itself.
const DELIVERY_OFFER_TTL: Duration = Duration::days(7);

/// The OID4VCI credential configuration an invitation is offered under.
const VIC_CONFIGURATION: &str = "VIC";

/// Deliver an issued invitation to the DID it admits
/// (`vtc/invitations/deliver/0.1`, Keyring VTI-21 / VTI-32).
///
/// Records a single-use offer bound to the invited DID — withdrawing any
/// earlier one — and either pushes it to that DID as a
/// `credential-exchange/offer` (`message`) or returns it for a QR code
/// (`offer`). The invitation credential is released only by
/// `credential-exchange/request` with a key-binding proof by the invited
/// DID's key, so the offer itself admits no one else; it is never in this
/// response.
pub(crate) async fn deliver(
    state: &AppState,
    actor: &str,
    body: trust_tasks_rs::specs::vtc::invitations::deliver::v0_1::Payload,
) -> Result<trust_tasks_rs::specs::vtc::invitations::deliver::v0_1::Response, DeliverError> {
    use trust_tasks_rs::specs::vtc::invitations::deliver::v0_1 as spec;

    let scope = require_inviter(state, actor).await?;
    let payload = body;
    let id = payload.id.to_string();
    // The generated channel is `#[non_exhaustive]`: a channel a later
    // specification adds is refused here, not guessed at.
    let channel = match payload.channel {
        spec::PayloadChannel::Message => Channel::Message,
        spec::PayloadChannel::Offer => Channel::Offer,
        other => {
            return Err(AppError::Validation(format!(
                "this community does not deliver over channel {other:?}"
            ))
            .into());
        }
    };

    let mut record = get_invitation(&state.invitations_ks, &id)
        .await?
        .filter(|r| scope.covers(r, actor))
        .ok_or_else(|| DeliverError::NotFound(format!("no invitation with id {id}")))?;
    if record.is_revoked() {
        return Err(DeliverError::Revoked(format!(
            "invitation {id} has been revoked"
        )));
    }
    let now = Utc::now();
    let lapses = record
        .valid_until
        .as_deref()
        .and_then(|v| chrono::DateTime::parse_from_rfc3339(v).ok())
        .map(|t| t.with_timezone(&Utc));
    if lapses.is_some_and(|t| t <= now) {
        return Err(AppError::Gone(format!("expired: invitation {id} has lapsed")).into());
    }
    let credential = record.credential.clone().ok_or_else(|| {
        DeliverError::Other(AppError::Conflict(format!(
            "invitation {id} was issued before delivery existed, and its credential was \
             returned once and not kept. Issue a new invitation to {} and deliver that.",
            record.subject_did
        )))
    })?;
    let vtc_did = state
        .config
        .read()
        .await
        .vtc_did
        .clone()
        .ok_or_else(|| AppError::Internal("VTC DID not configured".into()))?;

    // `message` needs a route to the invitee before anything is recorded, so a
    // refusal leaves the live offer (if any) as it was.
    if matches!(channel, Channel::Message)
        && !can_authcrypt_to(state.did_resolver.as_ref(), &record.subject_did).await
    {
        return Err(DeliverError::NoRoute(format!(
            "{} does not resolve to a key this community can encrypt the offer to. \
             Deliver with channel `offer` and hand it over as a QR code.",
            record.subject_did
        )));
    }

    let ttl = match lapses {
        Some(t) => (t - now).min(DELIVERY_OFFER_TTL),
        None => DELIVERY_OFFER_TTL,
    };
    // At most one live offer per invitation: withdraw the last one first.
    if let Some(old) = record.offer_code.take() {
        crate::credentials::exchange::withdraw_offer(&state.join_requests_ks, &old).await?;
    }
    let (offer, code) = crate::credentials::exchange::make_offer(
        &state.join_requests_ks,
        &vtc_did,
        vec![VIC_CONFIGURATION.to_string()],
        credential,
        &record.subject_did,
        ttl,
        now,
    )
    .await?;
    record.offer_code = Some(code);
    store_invitation(&state.invitations_ks, &record).await?;
    let expires_at = now + ttl;

    let offer_json = serde_json::to_value(&offer)
        .map_err(|e| AppError::Internal(format!("serialise offer: {e}")))?;
    let returned_offer = match channel {
        Channel::Message => {
            // A signed `credential-exchange/offer`, over whichever transport
            // the invitee speaks. Its `request` answer threads on this id.
            if let Err(e) = crate::credentials::delivery::push_document(
                state,
                &record.subject_did,
                vta_sdk::protocols::credential_exchange::OFFER,
                serde_json::json!({ "credential_offer": offer_json }),
                crate::credentials::delivery::Thread::New,
            )
            .await
            {
                // Nothing went out, so no offer should be live for it.
                if let Some(code) = record.offer_code.take() {
                    crate::credentials::exchange::withdraw_offer(&state.join_requests_ks, &code)
                        .await?;
                    store_invitation(&state.invitations_ks, &record).await?;
                }
                return Err(e.into());
            }
            None
        }
        Channel::Offer => match offer_json {
            JsonValue::Object(map) => Some(map),
            _ => {
                return Err(
                    AppError::Internal("offer did not serialise to an object".into()).into(),
                );
            }
        },
    };

    let channel_name = match channel {
        Channel::Message => "message",
        Channel::Offer => "offer",
    };
    if let Some(writer) = state.audit_writer.as_ref() {
        writer
            .write(
                actor,
                Some(&record.subject_did),
                AuditEvent::InvitationDelivered(InvitationDeliveredData {
                    invitation_id: id.clone(),
                    subject_did: record.subject_did.clone(),
                    channel: channel_name.to_string(),
                    expires_at: expires_at.to_rfc3339(),
                }),
            )
            .await?;
    }
    // R1.1: over `message` the offer is only queued here — the push engine logs
    // `trust-task push delivered` when there is evidence the invitee collected
    // it. Over `offer` it is handed back to the caller for out-of-band hand-off.
    match channel {
        Channel::Message => info!(
            actor = %actor,
            vic_id = %id,
            channel = channel_name,
            "queued an invitation offer for delivery to the invitee"
        ),
        Channel::Offer => info!(
            actor = %actor,
            vic_id = %id,
            channel = channel_name,
            "returned an invitation offer for out-of-band hand-off"
        ),
    }

    let response: spec::Response = spec::Response::builder()
        .id(id)
        .channel(match channel {
            Channel::Message => spec::ResponseChannel::Message,
            Channel::Offer => spec::ResponseChannel::Offer,
        })
        // An absent offer is an empty map: the generated type omits it then.
        .offer(returned_offer.unwrap_or_default())
        .expires_at(expires_at)
        .try_into()
        .map_err(|e| AppError::Internal(format!("build deliver response: {e}")))?;
    Ok(response)
}

/// Whether an offer can be sent to `did` over DIDComm: it resolves, and names
/// a key-agreement key to encrypt to. An advertised service is not required —
/// a DID with none (a `did:peer:2` holding only keys) is reached through the
/// community's mediator, as members already are for credential delivery.
async fn can_authcrypt_to(
    resolver: Option<&affinidi_did_resolver_cache_sdk::DIDCacheClient>,
    did: &str,
) -> bool {
    let Some(resolver) = resolver else {
        return false;
    };
    let Ok(resolved) = resolver.resolve(did).await else {
        return false;
    };
    serde_json::to_value(&resolved.doc)
        .ok()
        .and_then(|doc| {
            doc.get("keyAgreement")
                .and_then(JsonValue::as_array)
                .map(|a| !a.is_empty())
        })
        .unwrap_or(false)
}