mid_issuer/types.rs
1//! Wire-format types for the mID JWT, locked by ADR 0005 Decision 1.
2//!
3//! Every field name here MUST exactly match the JSON serialization the
4//! verifier (`mid-verify`) and the JS SDK (`@mata/mid`) expect. Changing
5//! a field name here is a wire-format break that requires a follow-on ADR.
6
7use std::collections::BTreeMap;
8
9use serde::{Deserialize, Serialize};
10
11// ─── Request side ──────────────────────────────────────────────────────────
12
13/// The relying party's sign-in request, posted into the wallet by the
14/// `@mata/mid` SDK on the RP page.
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct RpRequest {
17 /// The RP's bare origin, e.g. `"https://acme.com"`. The wallet verifies
18 /// this matches the page's actual origin before issuing.
19 pub rp_origin: String,
20 /// RP-issued single-use nonce. The wallet echoes it in the JWT for
21 /// replay defense.
22 pub nonce: String,
23 /// Per-claim categorization (required/optional/custom).
24 pub claims: ClaimRequest,
25}
26
27/// Categorized claim request from the RP.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29pub struct ClaimRequest {
30 /// Claims that block sign-in if denied. Almost always just `["did"]`.
31 pub required: Vec<String>,
32 /// Claims the user can include or skip.
33 #[serde(default)]
34 pub optional: Vec<String>,
35 /// Arbitrary keys outside the standard catalog — looked up in the
36 /// wallet's local `profile_kv`.
37 #[serde(default)]
38 pub custom: BTreeMap<String, CustomClaimRequest>,
39}
40
41/// Per-key custom-claim metadata.
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct CustomClaimRequest {
44 /// Always true in v1 — custom claims cannot be required (the wallet
45 /// doesn't know what they mean to the RP).
46 pub optional: bool,
47 /// Optional human-readable description the consent UI surfaces.
48 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub description: Option<String>,
50}
51
52// ─── Identity snapshot ─────────────────────────────────────────────────────
53
54/// The wallet's identity state at the moment of sign-in, assembled by the
55/// caller from `mata-identity` plus the `mid_user_consents` Y-CRDT lookup.
56///
57/// This crate consumes the snapshot read-only — it never mutates wallet
58/// state.
59#[derive(Debug, Clone)]
60pub struct IdentitySnapshot {
61 /// The user's DID, e.g. `"did:mata:p3k7q...8x2h"`.
62 pub did: String,
63 /// The genesis roster envelope, self-signed at signup by the genesis
64 /// device's key. Held in wallet storage forever.
65 pub genesis_roster: EmbeddedGenesisRoster,
66 /// The wallet-signed roster mutations from genesis to current. May be
67 /// empty if the user has only ever had the genesis device.
68 pub roster_chain: Vec<EmbeddedRosterChainEntry>,
69 /// The verification method for the device that's about to sign this
70 /// mID JWT. MUST appear in either the genesis roster (if `roster_chain`
71 /// is empty) or in the head roster chain entry.
72 pub current_verification_method: EmbeddedVerificationMethod,
73 /// Pre-built claim values keyed by claim name. The caller looks each
74 /// claim up against the wallet's local stores (profile, achievements,
75 /// computed level ratings) and populates this map BEFORE calling
76 /// [`crate::build_mid_jwt`].
77 ///
78 /// Claims the user denied at the consent screen MUST be absent from
79 /// this map — the issuer trusts the caller's filtering.
80 pub approved_claims: BTreeMap<String, ClaimValue>,
81}
82
83// ─── JWT payload ───────────────────────────────────────────────────────────
84
85/// The mID JWT payload — the JSON object that's base64url-encoded as the
86/// second segment of the JWS compact-form token.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct MidJwtPayload {
89 /// Issuer — the user's DID.
90 pub iss: String,
91 /// Subject — same as `iss` for self-issued tokens.
92 pub sub: String,
93 /// Audience — the RP's bare origin from the request.
94 pub aud: String,
95 /// Issued-at, Unix seconds.
96 pub iat: u64,
97 /// Expiry, Unix seconds. v1 ships short-lived (~1 hour) tokens.
98 pub exp: u64,
99 /// RP-supplied nonce, echoed for replay defense.
100 pub nonce: String,
101 /// Claim values approved by the user, keyed by claim name.
102 pub claims: BTreeMap<String, ClaimValue>,
103 /// Self-signed genesis roster (signed by the key encoded in the DID).
104 pub embedded_genesis_roster: EmbeddedGenesisRoster,
105 /// Chain of wallet-signed roster mutations from genesis to current.
106 pub embedded_roster_chain: Vec<EmbeddedRosterChainEntry>,
107 /// The device key signing this JWT — must appear in the head roster.
108 pub embedded_verification_method: EmbeddedVerificationMethod,
109}
110
111/// A single claim value with provenance metadata.
112#[derive(Debug, Clone, Serialize, Deserialize)]
113pub struct ClaimValue {
114 /// The claim's value. Free-form per RFC 7519; common shapes are
115 /// strings, numbers, booleans.
116 pub value: serde_json::Value,
117 /// Provenance — `self` in v1; v2 may add `third_party_vc`.
118 pub attested_by: AttestedBy,
119 /// Only set on the `email` claim if the user completed signup OTP.
120 /// Historical fact, not a MATA signature.
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub verified_at_signup: Option<bool>,
123 /// Only set on derived claims (level ratings) — the wall-clock the
124 /// wallet computed the score at.
125 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub computed_at: Option<u64>,
127 /// Only set on derived claims — pins the formula generation. RPs can
128 /// reject older versions.
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub formula_version: Option<String>,
131}
132
133/// Attestation provenance for a claim.
134///
135/// v1 ships only `self`. The enum is open for future provenance categories
136/// without breaking the wire format.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
138pub enum AttestedBy {
139 /// User-supplied, signed by the user's M5 device key as part of the
140 /// outer JWT signature. MATA never witnessed this value.
141 #[serde(rename = "self")]
142 SelfAttested,
143}
144
145// ─── Embedded roster + verification method ─────────────────────────────────
146
147/// The genesis roster envelope — version 1, self-signed by the genesis
148/// device's signing key (the key whose public form is encoded in the DID
149/// identifier).
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct EmbeddedGenesisRoster {
152 /// Always 1 for the genesis envelope.
153 pub version: u64,
154 /// The DID this roster belongs to.
155 pub did: String,
156 /// Verification methods present in the genesis roster. v1 wallets ship
157 /// a one-entry genesis roster (just the genesis device); future
158 /// versions could initialize multi-device genesis.
159 pub verification_methods: Vec<VerificationMethod>,
160 /// When the genesis roster was signed, Unix seconds.
161 pub signed_at: u64,
162 /// Signature by the genesis key over the canonical envelope bytes.
163 /// Verifiable against the public key recovered from the DID.
164 /// base64url-encoded `r || s` (64 bytes total).
165 pub self_signed_by_genesis_key: String,
166}
167
168/// One entry in the wallet-signed roster chain. Each entry is signed by a
169/// verification method present in the prior entry's roster.
170#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct EmbeddedRosterChainEntry {
172 /// Monotonically increasing across the chain. genesis is version 1; the
173 /// first chain entry is version 2.
174 pub version: u64,
175 /// The DID this roster belongs to.
176 pub did: String,
177 /// Verification methods after this mutation.
178 pub verification_methods: Vec<VerificationMethod>,
179 /// When this mutation was signed, Unix seconds.
180 pub signed_at: u64,
181 /// Signature by a verification method present in the PRIOR roster.
182 /// base64url-encoded `r || s` (64 bytes total).
183 pub signed_by_signer_in_prior_roster: String,
184 /// The `kid` of the verification method in the prior roster that
185 /// produced this signature. Lets the verifier skip a scan.
186 pub signer_kid: String,
187}
188
189/// A verification method = a public key bound to a DID. Same shape as the
190/// W3C DID document `verificationMethod[]` entry, minimum-fields form.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct VerificationMethod {
193 /// Fully-qualified ID, e.g. `"did:mata:abc...#dev-laptop"`.
194 pub id: String,
195 /// Always `"EcdsaSecp256r1VerificationKey2019"` in v1.
196 #[serde(rename = "type")]
197 pub vm_type: String,
198 /// The DID that controls this verification method.
199 pub controller: String,
200 /// Multibase-encoded public key. v1 wallets use `z6Mk...` base58btc
201 /// per the multibase spec.
202 pub public_key_multibase: String,
203}
204
205/// The current device's verification method — the key that's about to sign
206/// the JWT. Slim form (just the key + identity), no extra DID-document
207/// metadata. Must appear in the head roster of the chain.
208#[derive(Debug, Clone, Serialize, Deserialize)]
209pub struct EmbeddedVerificationMethod {
210 /// Fully-qualified ID, e.g. `"did:mata:abc...#dev-laptop"`.
211 pub id: String,
212 /// Always `"EcdsaSecp256r1VerificationKey2019"` in v1.
213 #[serde(rename = "type")]
214 pub vm_type: String,
215 /// The DID that controls this verification method.
216 pub controller: String,
217 /// Multibase-encoded public key.
218 pub public_key_multibase: String,
219}
220
221#[cfg(test)]
222mod tests {
223 use super::*;
224
225 #[test]
226 fn attested_by_serializes_as_lowercase_self() {
227 let cv = ClaimValue {
228 value: serde_json::Value::String("tim@example.com".into()),
229 attested_by: AttestedBy::SelfAttested,
230 verified_at_signup: Some(true),
231 computed_at: None,
232 formula_version: None,
233 };
234 let json = serde_json::to_string(&cv).unwrap();
235 assert!(
236 json.contains(r#""attested_by":"self""#),
237 "attested_by must serialize as the lowercase string 'self' per ADR 0005 Decision 1, got: {json}"
238 );
239 assert!(
240 json.contains(r#""verified_at_signup":true"#),
241 "verified_at_signup must be present when Some, got: {json}"
242 );
243 }
244
245 #[test]
246 fn claim_value_omits_optional_fields_when_none() {
247 let cv = ClaimValue {
248 value: serde_json::Value::String("Tim".into()),
249 attested_by: AttestedBy::SelfAttested,
250 verified_at_signup: None,
251 computed_at: None,
252 formula_version: None,
253 };
254 let json = serde_json::to_string(&cv).unwrap();
255 assert!(!json.contains("verified_at_signup"), "absent when None");
256 assert!(!json.contains("computed_at"), "absent when None");
257 assert!(!json.contains("formula_version"), "absent when None");
258 }
259
260 #[test]
261 fn verification_method_type_field_serializes_as_type() {
262 let vm = VerificationMethod {
263 id: "did:mata:abc#dev".into(),
264 vm_type: "EcdsaSecp256r1VerificationKey2019".into(),
265 controller: "did:mata:abc".into(),
266 public_key_multibase: "z6Mk...".into(),
267 };
268 let json = serde_json::to_string(&vm).unwrap();
269 assert!(
270 json.contains(r#""type":"EcdsaSecp256r1VerificationKey2019""#),
271 "vm_type must serialize as JSON field 'type' per the DID document standard, got: {json}"
272 );
273 }
274}