Connect two parties with an invitation

Let two parties who start without each other’s DIDs connect through an out-of-band invitation on your mediator, then exchange end-to-end encrypted messages in both directions, from a Rust or Dart application.

Connect two parties who start without each other’s DIDs through an out-of-band invitation on your DIDComm Mediator, then exchange messages in both directions, from a Rust or Dart application.

This guide adds first contact to your application. The inviter stores an out-of-band (OOB) invitation on the mediator and shares its URL as a link or QR code. The invitee reads the inviter’s decentralised identifier (DID) from the invitation and sends a first message, which gives the inviter the invitee’s DID, and each party then adds the other to its access list. For how access lists decide who may message a DID, see Supported ACLs.

A DID on an Affinidi-hosted mediator receives messages only from senders on its own access list, apart from anonymous messages where it accepts them, and a party can add a sender only once it knows the sender’s DID. Send and receive messages starts from two DIDs that already know each other. In a real application the parties start without each other’s DIDs, and the invitation is how each learns the other’s.

Use this guide when:

  • Your users connect with people or agents whose DIDs they learn only when they connect, for example by scanning a QR code or opening a link.
  • Each party should accept messages only from the parties it has connected with.
  • You have a mediator, Affinidi-hosted or self-hosted, and want your application to use it.

If you use the Meeting Place SDK, which runs the connection for you and lets the inviter approve each request, follow Connect two users and chat with Meeting Place instead.

The steps build one program that plays both parties, Alice the inviter and Bob the invitee, and passes only the invitation URL from one to the other:

  • Alice creates the invitation and switches her access list to Explicit Deny mode, so that Bob’s first message can reach her before she knows his DID.
  • Bob reads Alice’s DID from the invitation, adds Alice to his access list, and sends her a hello.
  • Alice reads Bob’s DID from the hello, adds Bob to her access list, switches it back to Explicit Allow mode, and deletes the invitation.
  • Alice replies, and Bob receives the reply.

While Alice’s list is in Explicit Deny mode, any DID can message her, and anyone with the invitation URL can read her DID. Keep that time short: the program closes it as soon as Bob’s hello arrives, and gives the invitation an expiry time one hour ahead.

Prerequisites

  • Your mediator’s DID: the Mediator DID on your mediator’s page in Affinidi Portal, or the DID you configured for a self-hosted mediator. See Affinidi Portal (Affinidi-hosted).
  • A mediator that lets new DIDs connect, because the program creates new DIDs on each run:
    • Affinidi-hosted: a mediator whose Mediator ACL mode is Explicit Deny. In your application on a mediator in Explicit Allow mode, add each party’s DID under Access Controls before it connects. The steps are then the same.
    • Self-hosted: mediator_acl_mode set to explicit_deny, and a global_acl_default that also grants CREATE_INVITES and MODE_SELF_CHANGE, besides the flags in the Test mediator connection prerequisites.
  • For Rust: Rust 1.95.0 or later.
  • For Dart: the Dart SDK 3.6.0 or later, and a mediator served over HTTPS, because the DIDComm library for Dart connects only to https:// endpoints.

Both parties use your mediator, as two users of one application usually do. The Rust program on this page was run against mediator release 0.55.0, the release that new Affinidi-hosted mediators run, in both Explicit Deny and Explicit Allow modes. The Dart program was run against a 0.55.0 mediator with trust_task_verification set to warn, in both modes.

Connect with Rust

The program uses the Affinidi Trust Development Kit (TDK) for Rust, which includes the Affinidi Messaging SDK.

Create the project

cargo new didcomm-invitation
cd didcomm-invitation

Replace the contents of Cargo.toml with the following. The affinidi-tdk requirement keeps the program on the 0.49 release line it was run with, and sha256 computes the DID hashes that access lists hold.

[package]
name = "didcomm-invitation"
version = "0.1.0"
edition = "2024"

[dependencies]
affinidi-tdk = "0.49"
serde_json = "1"
sha256 = "1"
tokio = { version = "1", features = ["full"] }
uuid = { version = "1", features = ["v4"] }

Start the TDK

Start the TDK with its messaging client, which manages each party’s connection to the mediator.

let tdk = TDK::new(
    TDKConfig::builder()
        .with_load_environment(false)
        .with_use_atm(true)
        .build()?,
    None,
)
.await?;
let atm = tdk.atm.clone().expect("messaging client is enabled");

Create a DID for each party and connect it

Create a did:peer DID whose service points at your mediator, then authenticate it and open a WebSocket connection for live delivery. Send and receive messages explains this function in detail.

async fn connect_party(
    tdk: &TDK,
    atm: &ATM,
    name: &str,
    mediator_did: &str,
) -> Result<Arc<ATMProfile>, ATMError> {
    let (did, secrets) = DID::generate_did_peer(
        vec![
            (PeerKeyRole::Verification, KeyType::Ed25519),
            (PeerKeyRole::Encryption, KeyType::X25519),
        ],
        Some(mediator_did.to_string()),
    )?;
    println!("{name} DID: {did}");

    let profile = TDKProfile::new(name, &did, Some(mediator_did), secrets);
    tdk.add_profile(&profile).await;
    atm.profile_add(&ATMProfile::from_tdk_profile(atm, &profile).await?, true)
        .await
}

In your application, each party creates its DID on its own device, so neither knows the other’s DID at this point.

Create the invitation and open the inviter’s access list

Alice stores an invitation on the mediator with create_invite, which returns the invitation’s ID. The invitation URL is the mediator’s REST endpoint, then /oob?_oobid=, then the ID. Share it as a link or a QR code: anyone with the URL can fetch the invitation without signing in.

Alice then switches her own access list to Explicit Deny mode. The SDK sends the change to the mediator as a Trust Task, a management message.

async fn create_invitation(
    atm: &ATM,
    inviter: &Arc<ATMProfile>,
) -> Result<(String, String), ATMError> {
    let invitation_id = atm
        .oob_discovery()
        .create_invite(inviter, Some(Duration::from_secs(3600)))
        .await?;
    let endpoint = inviter
        .get_mediator_rest_endpoint()
        .expect("the mediator has a REST endpoint");
    let invitation_url = format!("{endpoint}/oob?_oobid={invitation_id}");

    set_access_list_mode(atm, inviter, MediatorAclAccessListMode::ExplicitDeny).await?;
    Ok((invitation_url, invitation_id))
}
async fn set_access_list_mode(
    atm: &ATM,
    owner: &Arc<ATMProfile>,
    mode: MediatorAclAccessListMode,
) -> Result<(), ATMError> {
    let acl: MediatorAcl = MediatorAcl::builder()
        .access_list_mode(mode)
        .try_into()
        .map_err(|e| ATMError::ConfigError(format!("invalid access list mode: {e}")))?;
    atm.trust_tasks()
        .account_update(owner, None, None, Some(acl), None)
        .await?;
    Ok(())
}

Accept the invitation and say hello

Bob fetches the invitation and reads Alice’s DID from its from field. Before he messages Alice, he puts his own access list in Explicit Allow mode and adds Alice, so that her reply can reach him. Mediators differ in the mode they give a new DID, so Bob sets the mode himself rather than relying on the default. A self-hosted mediator that doesn’t let a DID change its own mode refuses this step, as Troubleshooting describes. Access lists hold the SHA-256 hash of each DID.

async fn accept_invitation(
    atm: &ATM,
    invitee: &Arc<ATMProfile>,
    invitation_url: &str,
) -> Result<String, ATMError> {
    let invitation = atm.oob_discovery().retrieve_invite(invitation_url).await?;
    let inviter_did = invitation
        .from
        .ok_or_else(|| ATMError::MsgReceiveError("invitation has no `from` DID".into()))?;
    allow_sender(atm, invitee, &inviter_did).await?;
    Ok(inviter_did)
}
async fn allow_sender(
    atm: &ATM,
    owner: &Arc<ATMProfile>,
    sender_did: &str,
) -> Result<(), ATMError> {
    set_access_list_mode(atm, owner, MediatorAclAccessListMode::ExplicitAllow).await?;
    // Access lists hold the SHA-256 hash of each DID.
    atm.trust_tasks()
        .access_list_update(owner, None, false, vec![sha256::digest(sender_did)], vec![])
        .await?;
    Ok(())
}

Bob then sends Alice a hello. The message is encrypted for Alice with authenticated encryption (authcrypt), which also tells Alice who sent it, and wrapped in a forward message for her mediator.

async fn send_message(
    atm: &ATM,
    sender: &Arc<ATMProfile>,
    recipient_did: &str,
    recipient_mediator_did: &str,
    content: &str,
) -> Result<(), ATMError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let message = Message::build(
        Uuid::new_v4().to_string(),
        BASIC_MESSAGE.to_string(),
        json!({ "content": content }),
    )
    .from(sender.inner.did.to_string())
    .to(recipient_did.to_string())
    .created_time(now)
    .expires_time(now + 60)
    .finalize();

    // Authenticated encryption: only the recipient can read the message, and
    // the recipient can confirm who sent it.
    let (packed, _) = atm
        .pack_encrypted(&message, recipient_did, Some(&sender.inner.did), None)
        .await?;
    let (_, forward) = atm
        .routing()
        .forward_message(
            sender,
            false,
            &packed,
            recipient_mediator_did,
            recipient_did,
            None,
            None,
        )
        .await?;
    atm.send_message(sender, &forward, &message.id, false, false)
        .await?;
    Ok(())
}

Receive the hello and close the invitation

Alice waits for the next message over her WebSocket connection. Its from field is Bob’s DID, which the SDK has checked against the key that encrypted the message. The mediator also sends its own status messages, which the function skips. Passing true as the last argument of live_stream_next deletes each message at the mediator once it is received.

async fn receive_message(
    atm: &ATM,
    recipient: &Arc<ATMProfile>,
) -> Result<(Message, String), ATMError> {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let wait = deadline.saturating_duration_since(Instant::now());
        let Some((message, metadata)) = atm
            .message_pickup()
            .live_stream_next(recipient, Some(wait), true)
            .await?
        else {
            return Err(ATMError::MsgReceiveError(
                "no message within 10 seconds".into(),
            ));
        };
        // The mediator sends its own status messages too: skip them.
        if message.typ != BASIC_MESSAGE {
            continue;
        }
        return match message.from.clone() {
            Some(sender_did) if metadata.authenticated => Ok((message, sender_did)),
            _ => Err(ATMError::MsgReceiveError(
                "the message's sender is not authenticated".into(),
            )),
        };
    }
}

In main, Alice receives the hello and adds Bob, which puts her list back in Explicit Allow mode. She then deletes the invitation so that nobody else can use it.

let (hello, bob_did) = receive_message(&atm, &alice).await?;
println!("Alice received from {bob_did}: {}", hello.body);
allow_sender(&atm, &alice, &bob_did).await?;
atm.oob_discovery()
    .delete_invite(&alice, &invitation_id)
    .await?;

Reply

Alice and Bob are now on each other’s access lists, so either can message the other.

send_message(&atm, &alice, &bob_did, &mediator_did, "Hello, Bob!").await?;
let (reply, _) = receive_message(&atm, &bob).await?;
println!("Bob received from Alice: {}", reply.body);

Run the program

Replace the contents of src/main.rs with the full Rust program, then run it with your mediator’s DID in place of <REPLACE_MEDIATOR_DID>:

cargo run -- "<REPLACE_MEDIATOR_DID>"

The first run downloads and compiles the dependencies, which takes a few minutes.

Full Rust program

use affinidi_tdk::{
    TDK,
    common::{config::TDKConfig, profiles::TDKProfile},
    didcomm::message::Message,
    dids::{DID, KeyType, PeerKeyRole},
    messaging::{
        ATM,
        errors::ATMError,
        profiles::ATMProfile,
        tasks::messaging::account::update::v0_2::{MediatorAcl, MediatorAclAccessListMode},
    },
};
use serde_json::json;
use std::{
    env,
    sync::Arc,
    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
use uuid::Uuid;

const BASIC_MESSAGE: &str = "https://didcomm.org/basicmessage/2.0/message";

#[tokio::main]
async fn main() -> Result<(), ATMError> {
    let mediator_did = env::args()
        .nth(1)
        .expect("Usage: cargo run -- <MEDIATOR_DID>");

    // Step 2: start the TDK with its messaging client.
    let tdk = TDK::new(
        TDKConfig::builder()
            .with_load_environment(false)
            .with_use_atm(true)
            .build()?,
        None,
    )
    .await?;
    let atm = tdk.atm.clone().expect("messaging client is enabled");

    // Step 3: create a DID for each party and connect it to the mediator.
    // Neither party knows the other's DID yet.
    let alice = connect_party(&tdk, &atm, "Alice", &mediator_did).await?;
    let bob = connect_party(&tdk, &atm, "Bob", &mediator_did).await?;

    // Step 4: Alice creates an invitation and opens her access list.
    let (invitation_url, invitation_id) = create_invitation(&atm, &alice).await?;
    println!("Invitation URL: {invitation_url}");

    // Step 5: Bob accepts the invitation and sends Alice a hello.
    let alice_did = accept_invitation(&atm, &bob, &invitation_url).await?;
    send_message(&atm, &bob, &alice_did, &mediator_did, "Hello, Alice!").await?;

    // Step 6: Alice receives the hello, adds Bob, and closes the invitation.
    let (hello, bob_did) = receive_message(&atm, &alice).await?;
    println!("Alice received from {bob_did}: {}", hello.body);
    allow_sender(&atm, &alice, &bob_did).await?;
    atm.oob_discovery()
        .delete_invite(&alice, &invitation_id)
        .await?;

    // Step 7: Alice replies, and Bob receives the reply.
    send_message(&atm, &alice, &bob_did, &mediator_did, "Hello, Bob!").await?;
    let (reply, _) = receive_message(&atm, &bob).await?;
    println!("Bob received from Alice: {}", reply.body);

    atm.graceful_shutdown().await;
    Ok(())
}

/// Creates a DID that uses the mediator, then authenticates it and opens a
/// WebSocket connection for live delivery.
async fn connect_party(
    tdk: &TDK,
    atm: &ATM,
    name: &str,
    mediator_did: &str,
) -> Result<Arc<ATMProfile>, ATMError> {
    let (did, secrets) = DID::generate_did_peer(
        vec![
            (PeerKeyRole::Verification, KeyType::Ed25519),
            (PeerKeyRole::Encryption, KeyType::X25519),
        ],
        Some(mediator_did.to_string()),
    )?;
    println!("{name} DID: {did}");

    let profile = TDKProfile::new(name, &did, Some(mediator_did), secrets);
    tdk.add_profile(&profile).await;
    atm.profile_add(&ATMProfile::from_tdk_profile(atm, &profile).await?, true)
        .await
}

/// Stores an invitation on the inviter's mediator and returns its URL and ID.
/// Then switches the inviter's access list to deny-list mode, so the first
/// message from whoever accepts the invitation can reach the inviter.
async fn create_invitation(
    atm: &ATM,
    inviter: &Arc<ATMProfile>,
) -> Result<(String, String), ATMError> {
    let invitation_id = atm
        .oob_discovery()
        .create_invite(inviter, Some(Duration::from_secs(3600)))
        .await?;
    let endpoint = inviter
        .get_mediator_rest_endpoint()
        .expect("the mediator has a REST endpoint");
    let invitation_url = format!("{endpoint}/oob?_oobid={invitation_id}");

    set_access_list_mode(atm, inviter, MediatorAclAccessListMode::ExplicitDeny).await?;
    Ok((invitation_url, invitation_id))
}

/// Fetches the invitation, lets the inviter message the invitee, and returns
/// the inviter's DID.
async fn accept_invitation(
    atm: &ATM,
    invitee: &Arc<ATMProfile>,
    invitation_url: &str,
) -> Result<String, ATMError> {
    let invitation = atm.oob_discovery().retrieve_invite(invitation_url).await?;
    let inviter_did = invitation
        .from
        .ok_or_else(|| ATMError::MsgReceiveError("invitation has no `from` DID".into()))?;
    allow_sender(atm, invitee, &inviter_did).await?;
    Ok(inviter_did)
}

/// Puts the owner's access list in allow-list mode, then adds the sender.
async fn allow_sender(
    atm: &ATM,
    owner: &Arc<ATMProfile>,
    sender_did: &str,
) -> Result<(), ATMError> {
    set_access_list_mode(atm, owner, MediatorAclAccessListMode::ExplicitAllow).await?;
    // Access lists hold the SHA-256 hash of each DID.
    atm.trust_tasks()
        .access_list_update(owner, None, false, vec![sha256::digest(sender_did)], vec![])
        .await?;
    Ok(())
}

/// Changes the mode of the owner's own access list.
async fn set_access_list_mode(
    atm: &ATM,
    owner: &Arc<ATMProfile>,
    mode: MediatorAclAccessListMode,
) -> Result<(), ATMError> {
    let acl: MediatorAcl = MediatorAcl::builder()
        .access_list_mode(mode)
        .try_into()
        .map_err(|e| ATMError::ConfigError(format!("invalid access list mode: {e}")))?;
    atm.trust_tasks()
        .account_update(owner, None, None, Some(acl), None)
        .await?;
    Ok(())
}

/// Encrypts a message from `sender` to `recipient_did`, wraps it in a forward
/// for the recipient's mediator, and sends it.
async fn send_message(
    atm: &ATM,
    sender: &Arc<ATMProfile>,
    recipient_did: &str,
    recipient_mediator_did: &str,
    content: &str,
) -> Result<(), ATMError> {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap()
        .as_secs();
    let message = Message::build(
        Uuid::new_v4().to_string(),
        BASIC_MESSAGE.to_string(),
        json!({ "content": content }),
    )
    .from(sender.inner.did.to_string())
    .to(recipient_did.to_string())
    .created_time(now)
    .expires_time(now + 60)
    .finalize();

    // Authenticated encryption: only the recipient can read the message, and
    // the recipient can confirm who sent it.
    let (packed, _) = atm
        .pack_encrypted(&message, recipient_did, Some(&sender.inner.did), None)
        .await?;
    let (_, forward) = atm
        .routing()
        .forward_message(
            sender,
            false,
            &packed,
            recipient_mediator_did,
            recipient_did,
            None,
            None,
        )
        .await?;
    atm.send_message(sender, &forward, &message.id, false, false)
        .await?;
    Ok(())
}

/// Waits up to 10 seconds for the recipient's next basic message, and returns
/// it with the sender's DID. Only an authenticated sender's DID is returned,
/// because that DID is what goes on the recipient's access list.
async fn receive_message(
    atm: &ATM,
    recipient: &Arc<ATMProfile>,
) -> Result<(Message, String), ATMError> {
    let deadline = Instant::now() + Duration::from_secs(10);
    loop {
        let wait = deadline.saturating_duration_since(Instant::now());
        let Some((message, metadata)) = atm
            .message_pickup()
            .live_stream_next(recipient, Some(wait), true)
            .await?
        else {
            return Err(ATMError::MsgReceiveError(
                "no message within 10 seconds".into(),
            ));
        };
        // The mediator sends its own status messages too: skip them.
        if message.typ != BASIC_MESSAGE {
            continue;
        }
        return match message.from.clone() {
            Some(sender_did) if metadata.authenticated => Ok((message, sender_did)),
            _ => Err(ATMError::MsgReceiveError(
                "the message's sender is not authenticated".into(),
            )),
        };
    }
}

Connect with Dart

The program uses the DIDComm library for Dart, Affinidi Dart SSI, which manages keys and DIDs, and Dio for HTTP requests.

Create the project

Create a folder for the program and go to it:

mkdir didcomm_invitation
cd didcomm_invitation

Create a pubspec.yaml file with the following content. The constraints keep each library on the major version the program was run with. didcomm 2.4.0 needs ssi 3.x.

name: didcomm_invitation
description: Connect two parties with an out-of-band invitation
version: 1.0.0

environment:
  sdk: ^3.6.0

dependencies:
  didcomm: ^2.4.0
  dio: ^5.9.0
  ssi: ^3.9.4
  uuid: ^4.5.1

Install the dependencies:

dart pub get

Create a DID for each party and connect it

Resolve the mediator’s DID, create a did:key DID for each party, and create a client that authenticates each one to the mediator. Send and receive messages explains these functions in detail.

final mediatorDidDocument =
    await UniversalDIDResolver.defaultResolver.resolveDid(mediatorDid);
final alice = await createDidManager('alice-key-1');
final bob = await createDidManager('bob-key-1');
final aliceDid = (await alice.getDidDocument()).id;
final bobDid = (await bob.getDidDocument()).id;
print('Alice DID: $aliceDid');
print('Bob DID: $bobDid');
final aliceClient = await connectToMediator(alice, mediatorDidDocument);
final bobClient = await connectToMediator(bob, mediatorDidDocument);
Future<DidKeyManager> createDidManager(String keyId) async {
  final wallet = PersistentWallet(InMemoryKeyStore());
  final didManager = DidKeyManager(wallet: wallet, store: InMemoryDidStore());
  await wallet.generateKey(keyId: keyId, keyType: KeyType.ed25519);
  await didManager.addVerificationMethod(keyId);
  return didManager;
}
Future<MediatorClient> connectToMediator(
  DidManager didManager,
  DidDocument mediatorDidDocument,
) async {
  return MediatorClient.init(
    mediatorDidDocument: mediatorDidDocument,
    didManager: didManager,
    authorizationProvider: await AffinidiAuthorizationProvider.init(
      mediatorDidDocument: mediatorDidDocument,
      didManager: didManager,
    ),
    forwardMessageOptions: const ForwardMessageOptions(
      shouldSign: true,
      keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdhEs,
      encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    ),
  );
}

In your application, each party creates its DID on its own device, so neither knows the other’s DID at this point.

Create the invitation and open the inviter’s access list

Alice stores an invitation on the mediator with createOob, which returns the invitation’s ID. The invitation URL is the mediator’s REST endpoint, then /oob?_oobid=, then the ID. Share it as a link or a QR code: anyone with the URL can fetch the invitation without signing in.

Alice then switches her own access list to Explicit Deny mode, with a Trust Task, a management message.

Future<(String, String)> createInvitation(
  MediatorClient inviterClient, {
  required String inviter,
}) async {
  final invitationId = await inviterClient.createOob(
    OutOfBandMessage(
      id: const Uuid().v4(),
      from: inviter,
      body: {
        'goal_code': 'connect',
        'accept': ['didcomm/v2'],
      },
      expiresTime: DateTime.now().toUtc().add(const Duration(hours: 1)),
    ),
  );
  final endpoint = mediatorRestClient(inviterClient).options.baseUrl;
  final invitationUrl = '$endpoint/oob?_oobid=$invitationId';

  await setAccessListMode(
    inviterClient,
    owner: inviter,
    mode: AccessListMode.explicitDeny,
  );
  return (invitationUrl, invitationId);
}
Dio mediatorRestClient(MediatorClient client) {
  return client.mediatorDidDocument.toDio(
    mediatorServiceType: DidDocumentServiceType.didCommMessaging,
  );
}
Future<void> setAccessListMode(
  MediatorClient ownerClient, {
  required String owner,
  required AccessListMode mode,
}) async {
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccountUpdateTask(
        issuer: owner,
        mediatorDid: ownerClient.mediatorDidDocument.id,
        acl: MediatorAcl(accessListMode: mode),
      ),
      expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    ),
  );
}

Accept the invitation and say hello

Bob fetches the invitation, which the mediator returns base64url-encoded, and reads Alice’s DID from its from field. Before he messages Alice, he puts his own access list in Explicit Allow mode and adds Alice, so that her reply can reach him. Mediators differ in the mode they give a new DID, so Bob sets the mode himself rather than relying on the default. A self-hosted mediator that doesn’t let a DID change its own mode refuses this step, as Troubleshooting describes.

Future<String> acceptInvitation(
  MediatorClient inviteeClient, {
  required String invitee,
  required String invitationUrl,
}) async {
  final response = await Dio().get<Map<String, dynamic>>(invitationUrl);
  final encoded = response.data!['data'] as String;
  final invitation =
      jsonDecode(utf8.decode(base64Url.decode(base64Url.normalize(encoded))))
          as Map<String, dynamic>;
  final inviterDid = invitation['from'] as String;
  await allowSender(inviteeClient, owner: invitee, sender: inviterDid);
  return inviterDid;
}
Future<void> allowSender(
  MediatorClient ownerClient, {
  required String owner,
  required String sender,
}) async {
  await setAccessListMode(
    ownerClient,
    owner: owner,
    mode: AccessListMode.explicitAllow,
  );
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccessListUpdateTask(
        issuer: owner,
        mediatorDid: ownerClient.mediatorDidDocument.id,
        add: [sender],
      ),
      expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    ),
  );
}

Bob then sends Alice a hello. The message is signed, encrypted for Alice with authenticated encryption (authcrypt), and wrapped in a forward message for her mediator.

Future<void> sendMessage(
  MediatorClient senderClient, {
  required DidManager sender,
  required String recipientDid,
  required String recipientMediatorDid,
  required String content,
}) async {
  final senderDidDocument = await sender.getDidDocument();
  final recipientDidDocument =
      await UniversalDIDResolver.defaultResolver.resolveDid(recipientDid);
  final message = PlainTextMessage(
    id: const Uuid().v4(),
    from: senderDidDocument.id,
    to: [recipientDid],
    type: basicMessageType,
    body: {'content': content},
  );
  final keyAgreementId = senderDidDocument.keyAgreement.first.id;
  final encrypted = await DidcommMessage.packIntoSignedAndEncryptedMessages(
    message,
    keyPair: await sender.getKeyPairByDidKeyId(keyAgreementId),
    didKeyId: keyAgreementId,
    recipientDidDocuments: [recipientDidDocument],
    keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdh1Pu,
    encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    signer: await sender.getSigner(
      senderDidDocument.assertionMethod.first.id,
    ),
  );

  final forward = ForwardMessage(
    id: const Uuid().v4(),
    to: [recipientMediatorDid],
    from: senderDidDocument.id,
    next: recipientDid,
    expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    attachments: [
      Attachment(
        mediaType: 'application/json',
        data: AttachmentData(
          base64: base64UrlEncodeNoPadding(encrypted.toJsonBytes()),
        ),
      ),
    ],
  );
  await senderClient.sendMessage(forward);
}

Receive the hello and close the invitation

Alice fetches her inbox until a basic message arrives. Its from field is Bob’s DID, which the library has checked against the key that encrypted the message. The inbox also holds the mediator’s responses to Alice’s Trust Tasks, which use a different message wrapping, so list both wrapping types. fetchMessages deletes the messages it returns at the mediator.

Future<PlainTextMessage> receiveMessage(
  MediatorClient client,
  DidManager recipient,
) async {
  for (var attempt = 0; attempt < 10; attempt++) {
    if (attempt > 0) await Future<void>.delayed(const Duration(seconds: 1));
    for (final message in await client.fetchMessages()) {
      final received = await DidcommMessage.unpackToPlainTextMessage(
        message: message,
        recipientDidManager: recipient,
        expectedMessageWrappingTypes: [
          // A message from another DID: signed, then encrypted.
          MessageWrappingType.authcryptSignPlaintext,
          // The mediator's responses to Trust Tasks.
          MessageWrappingType.authcryptPlaintext,
        ],
      );
      if (received.type == basicMessageType) return received;
    }
  }
  throw StateError('No message received within 10 seconds');
}

In main, Alice receives the hello and adds Bob, which puts her list back in Explicit Allow mode. She then deletes the invitation so that nobody else can use it.

final hello = await receiveMessage(aliceClient, alice);
final senderDid = hello.from!;
print('Alice received from $senderDid: ${hello.body}');
await allowSender(aliceClient, owner: aliceDid, sender: senderDid);
await deleteInvitation(aliceClient, invitationId);
Future<void> deleteInvitation(
  MediatorClient inviterClient,
  String invitationId,
) async {
  await mediatorRestClient(inviterClient).delete<Map<String, dynamic>>(
    '/oob',
    queryParameters: {'_oobid': invitationId},
    options: Options(headers: await inviterClient.getAuthorizationHeaders()),
  );
}

Reply

Alice and Bob are now on each other’s access lists, so either can message the other.

await sendMessage(
  aliceClient,
  sender: alice,
  recipientDid: senderDid,
  recipientMediatorDid: mediatorDidDocument.id,
  content: 'Hello, Bob!',
);
final reply = await receiveMessage(bobClient, bob);
print('Bob received from Alice: ${reply.body}');
exit(0);

Run the program

Create an invitation.dart file with the full Dart program, replace <REPLACE_MEDIATOR_DID> with your mediator’s DID, and run it:

dart run invitation.dart

Full Dart program

import 'dart:convert';
import 'dart:io';

import 'package:didcomm/didcomm.dart';
import 'package:dio/dio.dart';
import 'package:ssi/ssi.dart';
import 'package:uuid/uuid.dart';

final basicMessageType = Uri.parse(
  'https://didcomm.org/basicmessage/2.0/message',
);

void main() async {
  const mediatorDid = '<REPLACE_MEDIATOR_DID>';

  // Step 2: create a DID for each party and connect it to the mediator.
  // Neither party knows the other's DID yet.
  final mediatorDidDocument =
      await UniversalDIDResolver.defaultResolver.resolveDid(mediatorDid);
  final alice = await createDidManager('alice-key-1');
  final bob = await createDidManager('bob-key-1');
  final aliceDid = (await alice.getDidDocument()).id;
  final bobDid = (await bob.getDidDocument()).id;
  print('Alice DID: $aliceDid');
  print('Bob DID: $bobDid');
  final aliceClient = await connectToMediator(alice, mediatorDidDocument);
  final bobClient = await connectToMediator(bob, mediatorDidDocument);

  // Step 3: Alice creates an invitation and opens her access list.
  final (invitationUrl, invitationId) = await createInvitation(
    aliceClient,
    inviter: aliceDid,
  );
  print('Invitation URL: $invitationUrl');

  // Step 4: Bob accepts the invitation and sends Alice a hello.
  final inviterDid = await acceptInvitation(
    bobClient,
    invitee: bobDid,
    invitationUrl: invitationUrl,
  );
  await sendMessage(
    bobClient,
    sender: bob,
    recipientDid: inviterDid,
    recipientMediatorDid: mediatorDidDocument.id,
    content: 'Hello, Alice!',
  );

  // Step 5: Alice receives the hello, adds Bob, and closes the invitation.
  final hello = await receiveMessage(aliceClient, alice);
  final senderDid = hello.from!;
  print('Alice received from $senderDid: ${hello.body}');
  await allowSender(aliceClient, owner: aliceDid, sender: senderDid);
  await deleteInvitation(aliceClient, invitationId);

  // Step 6: Alice replies, and Bob receives the reply.
  await sendMessage(
    aliceClient,
    sender: alice,
    recipientDid: senderDid,
    recipientMediatorDid: mediatorDidDocument.id,
    content: 'Hello, Bob!',
  );
  final reply = await receiveMessage(bobClient, bob);
  print('Bob received from Alice: ${reply.body}');
  exit(0);
}

/// Creates a did:key identity from a new Ed25519 key. Its key agreement key
/// is X25519, which Affinidi mediators support.
Future<DidKeyManager> createDidManager(String keyId) async {
  final wallet = PersistentWallet(InMemoryKeyStore());
  final didManager = DidKeyManager(wallet: wallet, store: InMemoryDidStore());
  await wallet.generateKey(keyId: keyId, keyType: KeyType.ed25519);
  await didManager.addVerificationMethod(keyId);
  return didManager;
}

/// Authenticates to the mediator. Signing what the client sends is required,
/// because by default the mediator rejects anonymous messages.
Future<MediatorClient> connectToMediator(
  DidManager didManager,
  DidDocument mediatorDidDocument,
) async {
  return MediatorClient.init(
    mediatorDidDocument: mediatorDidDocument,
    didManager: didManager,
    authorizationProvider: await AffinidiAuthorizationProvider.init(
      mediatorDidDocument: mediatorDidDocument,
      didManager: didManager,
    ),
    forwardMessageOptions: const ForwardMessageOptions(
      shouldSign: true,
      keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdhEs,
      encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    ),
  );
}

/// Stores an invitation on the inviter's mediator and returns its URL and ID.
/// Then switches the inviter's access list to deny-list mode, so the first
/// message from whoever accepts the invitation can reach the inviter.
Future<(String, String)> createInvitation(
  MediatorClient inviterClient, {
  required String inviter,
}) async {
  final invitationId = await inviterClient.createOob(
    OutOfBandMessage(
      id: const Uuid().v4(),
      from: inviter,
      body: {
        'goal_code': 'connect',
        'accept': ['didcomm/v2'],
      },
      expiresTime: DateTime.now().toUtc().add(const Duration(hours: 1)),
    ),
  );
  final endpoint = mediatorRestClient(inviterClient).options.baseUrl;
  final invitationUrl = '$endpoint/oob?_oobid=$invitationId';

  await setAccessListMode(
    inviterClient,
    owner: inviter,
    mode: AccessListMode.explicitDeny,
  );
  return (invitationUrl, invitationId);
}

/// Fetches the invitation, lets the inviter message the invitee, and returns
/// the inviter's DID.
Future<String> acceptInvitation(
  MediatorClient inviteeClient, {
  required String invitee,
  required String invitationUrl,
}) async {
  final response = await Dio().get<Map<String, dynamic>>(invitationUrl);
  final encoded = response.data!['data'] as String;
  final invitation =
      jsonDecode(utf8.decode(base64Url.decode(base64Url.normalize(encoded))))
          as Map<String, dynamic>;
  final inviterDid = invitation['from'] as String;
  await allowSender(inviteeClient, owner: invitee, sender: inviterDid);
  return inviterDid;
}

/// Deletes an invitation the client's DID created.
Future<void> deleteInvitation(
  MediatorClient inviterClient,
  String invitationId,
) async {
  await mediatorRestClient(inviterClient).delete<Map<String, dynamic>>(
    '/oob',
    queryParameters: {'_oobid': invitationId},
    options: Options(headers: await inviterClient.getAuthorizationHeaders()),
  );
}

/// An HTTP client for the mediator's REST API.
Dio mediatorRestClient(MediatorClient client) {
  return client.mediatorDidDocument.toDio(
    mediatorServiceType: DidDocumentServiceType.didCommMessaging,
  );
}

/// Puts the owner's access list in allow-list mode, then adds the sender.
Future<void> allowSender(
  MediatorClient ownerClient, {
  required String owner,
  required String sender,
}) async {
  await setAccessListMode(
    ownerClient,
    owner: owner,
    mode: AccessListMode.explicitAllow,
  );
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccessListUpdateTask(
        issuer: owner,
        mediatorDid: ownerClient.mediatorDidDocument.id,
        add: [sender],
      ),
      expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    ),
  );
}

/// Changes the mode of the owner's own access list.
Future<void> setAccessListMode(
  MediatorClient ownerClient, {
  required String owner,
  required AccessListMode mode,
}) async {
  await ownerClient.sendTrustTask(
    TrustTaskMessage(
      id: const Uuid().v4(),
      document: AccountUpdateTask(
        issuer: owner,
        mediatorDid: ownerClient.mediatorDidDocument.id,
        acl: MediatorAcl(accessListMode: mode),
      ),
      expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    ),
  );
}

/// Signs a message, encrypts it for the recipient with authenticated
/// encryption, wraps it in a forward for the recipient's mediator, and sends it.
Future<void> sendMessage(
  MediatorClient senderClient, {
  required DidManager sender,
  required String recipientDid,
  required String recipientMediatorDid,
  required String content,
}) async {
  final senderDidDocument = await sender.getDidDocument();
  final recipientDidDocument =
      await UniversalDIDResolver.defaultResolver.resolveDid(recipientDid);
  final message = PlainTextMessage(
    id: const Uuid().v4(),
    from: senderDidDocument.id,
    to: [recipientDid],
    type: basicMessageType,
    body: {'content': content},
  );
  final keyAgreementId = senderDidDocument.keyAgreement.first.id;
  final encrypted = await DidcommMessage.packIntoSignedAndEncryptedMessages(
    message,
    keyPair: await sender.getKeyPairByDidKeyId(keyAgreementId),
    didKeyId: keyAgreementId,
    recipientDidDocuments: [recipientDidDocument],
    keyWrappingAlgorithm: KeyWrappingAlgorithm.ecdh1Pu,
    encryptionAlgorithm: EncryptionAlgorithm.a256cbc,
    signer: await sender.getSigner(
      senderDidDocument.assertionMethod.first.id,
    ),
  );

  final forward = ForwardMessage(
    id: const Uuid().v4(),
    to: [recipientMediatorDid],
    from: senderDidDocument.id,
    next: recipientDid,
    expiresTime: DateTime.now().toUtc().add(const Duration(seconds: 60)),
    attachments: [
      Attachment(
        mediaType: 'application/json',
        data: AttachmentData(
          base64: base64UrlEncodeNoPadding(encrypted.toJsonBytes()),
        ),
      ),
    ],
  );
  await senderClient.sendMessage(forward);
}

/// Fetches the inbox once a second, for up to 10 seconds, until a basic
/// message arrives. Unpacking checks that the message's `from` matches the key
/// that encrypted it, so `from` is the authenticated sender's DID.
Future<PlainTextMessage> receiveMessage(
  MediatorClient client,
  DidManager recipient,
) async {
  for (var attempt = 0; attempt < 10; attempt++) {
    if (attempt > 0) await Future<void>.delayed(const Duration(seconds: 1));
    for (final message in await client.fetchMessages()) {
      final received = await DidcommMessage.unpackToPlainTextMessage(
        message: message,
        recipientDidManager: recipient,
        expectedMessageWrappingTypes: [
          // A message from another DID: signed, then encrypted.
          MessageWrappingType.authcryptSignPlaintext,
          // The mediator's responses to Trust Tasks.
          MessageWrappingType.authcryptPlaintext,
        ],
      );
      if (received.type == basicMessageType) return received;
    }
  }
  throw StateError('No message received within 10 seconds');
}

Confirm

Test 1: Bob’s hello reaches Alice, and her reply reaches Bob

Run the program as its last step describes. It prints the DIDs it created, the invitation URL, the hello Alice received with Bob’s DID, and the reply Bob received.

Rust:

Alice DID: did:peer:2.Vz6Mk...
Bob DID: did:peer:2.Vz6Mk...
Invitation URL: https://.../oob?_oobid=2e58d278...
Alice received from did:peer:2.Vz6Mk...: {"content":"Hello, Alice!"}
Bob received from Alice: {"content":"Hello, Bob!"}

Dart:

Alice DID: did:key:z6Mk...
Bob DID: did:key:z6Mk...
Invitation URL: https://.../oob?_oobid=cbb22f71...
Alice received from did:key:z6Mk...: {content: Hello, Alice!}
Bob received from Alice: {content: Hello, Bob!}

Seeing both messages confirms that Bob read Alice’s DID from the invitation, that Alice’s access list let Bob’s first message in, and that each party’s list now admits the other. The DID after Alice received from is the same as the Bob DID line, which shows that Alice learned Bob’s DID from his message.

Test 2: the deleted invitation returns 404

Fetch the invitation URL the program printed:

curl -s "<INVITATION_URL>"

The mediator answers with HTTP status 404:

{"sessionId":"NA","httpCode":404,"errorCode":0,"errorCodeStr":"NA","message":"Not found","data":null}

This confirms that Alice deleted the invitation, so nobody else can read her DID from it.

Troubleshooting

SymptomLikely causeFix
Rust: Error: MsgReceiveError("no message within 10 seconds") after the invitation URL, with an e.p.delivery.refused problem report in Bob’s inbox. Dart: Status code: 403 with e.p.delivery.refused.The mediator refused delivery because the recipient hasn’t added the sender to its access list, and the list is in Explicit Allow mode.Check that Alice switched her list to Explicit Deny mode before Bob sent his hello, and that each party added the other before replying.
HTTP 404 with Not found when Bob fetches the invitation.The invitation expired, or Alice deleted it.Ask Alice for a new invitation. Give each invitation an expiry time that leaves the invitee enough time to accept it.
HTTP 403 with e.p.authorization.permission and “Not authorized to create OOB invitations”.The inviter’s DID doesn’t have permission to create invitations.On a self-hosted mediator, add CREATE_INVITES to global_acl_default and restart it, or have an administrator grant it to the DID. See Supported ACLs.
selfChangeDenied with “this account may not change accessListMode”.The inviter’s DID doesn’t have permission to change its own access list’s mode.On a self-hosted mediator, add MODE_SELF_CHANGE to global_acl_default and restart it.
Dart: Status code: 403 with e.p.proofRequired and “this Trust Task type requires a proof”. The program stops before it prints the invitation URL.The mediator’s trust_task_verification setting is enforce, for example on a self-hosted mediator set up with mediator-setup, and the DIDComm library for Dart sends Trust Tasks without a proof.Use the Rust program, which signs its Trust Tasks, or set trust_task_verification to warn and restart the mediator.
e.p.authentication.blocked with “DID is blocked”.The mediator is in Explicit Allow mode, so it accepts only DIDs on its allow list, and the program’s DIDs are new.For this program, use a mediator in Explicit Deny mode. In your application, add each party’s DID under Access Controls for an Affinidi-hosted mediator.

What’s next

  Deploy an Affinidi-hosted mediator

  Connect two users and chat with Meeting Place

  Send and receive messages through your mediator

  Supported ACLs

  How DIDComm works

  Test mediator connection