monetize-embed 0.1.3

The thin client a monetized product compiles in: an Ed25519-verified entitlement cache with nanosecond verdicts that keeps answering while the licence server is unreachable. No network, no ledger — the product feeds it signed facts and asks.
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
//! **The one canonical form** an entitlement is signed over, and the verify side.
//!
//! Signing lives in `monetize` (it has the key); verifying lives here because a product
//! must check a fact without linking the core (redb, vendors). Core depends on this
//! crate for [`fact_message`] so there is exactly one canonical form.
//!
//! Canonical JSON: the fact's fields minus `signature`, objects with keys sorted
//! bytewise, no whitespace. `serde_json`'s map is sorted by default but that is a cargo
//! feature (`preserve_order`) any crate in the build could flip, so the sort is done
//! here, explicitly, and does not depend on it.

use ed25519_dalek::{Signature, Verifier, VerifyingKey};
use monetize_product::EntitlementFact;
use serde_json::Value;

/// A signed set of facts, the file monetize hands a product so it can start (or
/// restart) with the full picture before any push arrives.
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct Snapshot {
    /// Monotonic: a cache refuses a snapshot older than the one it holds (replay).
    pub issued_unix_ms: u64,
    pub facts: Vec<EntitlementFact>,
    /// Ed25519 over [`snapshot_message`], by monetize's key.
    pub signature: Vec<u8>,
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum SignatureError {
    #[error("signature is not 64 bytes")]
    Malformed,
    #[error("signature does not verify for tenant {0}")]
    Fact(String),
    /// The fact's ISSUE TIME is not signed by the same key, or the fact carries
    /// one half of the stamp without the other. Told apart from [`Self::Fact`]
    /// on purpose: the six fields were genuine and the monotonic half was not,
    /// which is a tampering attempt with a different shape and a different
    /// remedy from a wholly forged fact.
    #[error("the issue time on the fact for tenant {0} is not signed by the same key")]
    Issued(String),
    #[error("snapshot envelope signature does not verify")]
    Envelope,
    #[error("go-ahead signature does not verify for nonce {0}")]
    GoAhead(String),
    /// An actor ticket was refused. The string is the OPERATOR's reason and may
    /// name the ticket's own fields; see `crate::ticket::verify_ticket` for why
    /// none of them is a customer's to read.
    #[error("the actor ticket was refused: {0}")]
    Ticket(String),
}

/// Write `value` as canonical JSON: keys sorted, no whitespace.
pub fn canonical_json(value: &Value, out: &mut String) {
    match value {
        Value::Object(map) => {
            let mut keys: Vec<&String> = map.keys().collect();
            keys.sort();
            out.push('{');
            for (i, k) in keys.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                out.push_str(&serde_json::to_string(k).expect("string"));
                out.push(':');
                canonical_json(&map[*k], out);
            }
            out.push('}');
        }
        Value::Array(items) => {
            out.push('[');
            for (i, v) in items.iter().enumerate() {
                if i > 0 {
                    out.push(',');
                }
                canonical_json(v, out);
            }
            out.push(']');
        }
        other => out.push_str(&other.to_string()),
    }
}

/// Canonical JSON of the fact with `drop` removed. The ONE writer of a fact's
/// signed bytes; the two forms below differ only in what they drop, so they
/// cannot drift apart.
fn fact_form(fact: &EntitlementFact, drop: &[&str]) -> Vec<u8> {
    let mut v = serde_json::to_value(fact).expect("fact serializes");
    let object = v.as_object_mut().expect("fact is an object");
    for key in drop {
        object.remove(*key);
    }
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

/// **The V1 form**: every field except `signature`, `issued_unix_ms` and
/// `issued_signature`.
///
/// This is byte for byte what it was before the issue time existed, and it must
/// stay that way for ever: it is the form an appliance built before 2026-09-17
/// computes from the seven proto fields it knows, and every fact ever signed
/// carries a signature over it. Adding the issue time HERE instead of in a
/// second form would have invalidated every one of them at once.
pub fn fact_message(fact: &EntitlementFact) -> Vec<u8> {
    fact_form(fact, &["signature", "issued_unix_ms", "issued_signature"])
}

/// **The V2 form**: [`fact_message`] plus `issued_unix_ms`. What
/// [`EntitlementFact::issued_signature`] covers, and the reason the issue time
/// cannot be added, moved or bumped by anyone but monetize.
pub fn fact_message_issued(fact: &EntitlementFact) -> Vec<u8> {
    fact_form(fact, &["signature", "issued_signature"])
}

/// The bytes a snapshot's envelope signature covers. The facts inside keep their own
/// signatures (they are part of the message), so a snapshot vouches for the *set*.
pub fn snapshot_message(issued_unix_ms: u64, facts: &[EntitlementFact]) -> Vec<u8> {
    let v = serde_json::json!({ "issued_unix_ms": issued_unix_ms, "facts": facts });
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

pub(crate) fn check(key: &VerifyingKey, msg: &[u8], sig: &[u8]) -> Result<bool, SignatureError> {
    let sig = Signature::from_slice(sig).map_err(|_| SignatureError::Malformed)?;
    Ok(key.verify(msg, &sig).is_ok())
}

/// **Both halves.** The V1 signature always, and the V2 signature whenever the
/// fact carries an issue time.
///
/// The two are checked together and never apart, which is what stops the issue
/// time being editable in transit. Three shapes are refused here and not later:
///
/// * a stamped fact whose `issued_signature` does not verify — someone ADDED or
///   BUMPED an issue time. Bumping matters as much as adding: a fact stamped
///   far in the future would latch a product's high-water mark past every
///   legitimate fact monetize will ever mint for that tenant, which is a lasting
///   denial of service dressed as a plan change;
/// * `issued_signature` with no `issued_unix_ms`, and
/// * `issued_unix_ms` with no `issued_signature` — an unsigned issue time is not
///   a weaker fact, it is a forged one.
pub fn verify_fact(fact: &EntitlementFact, key: &VerifyingKey) -> Result<(), SignatureError> {
    if !check(key, &fact_message(fact), &fact.signature)? {
        return Err(SignatureError::Fact(fact.tenant.0.clone()));
    }
    match (fact.issued_unix_ms, fact.issued_signature.is_empty()) {
        // Unstamped: a fact signed before the issue time existed. Legal.
        (None, true) => Ok(()),
        (Some(_), false) => {
            if check(key, &fact_message_issued(fact), &fact.issued_signature)? {
                Ok(())
            } else {
                Err(SignatureError::Issued(fact.tenant.0.clone()))
            }
        }
        (None, false) | (Some(_), true) => Err(SignatureError::Issued(fact.tenant.0.clone())),
    }
}

/// Envelope first, then every fact: one forged fact rejects the whole snapshot.
pub fn verify_snapshot(snap: &Snapshot, key: &VerifyingKey) -> Result<(), SignatureError> {
    if !check(key, &snapshot_message(snap.issued_unix_ms, &snap.facts), &snap.signature)? {
        return Err(SignatureError::Envelope);
    }
    snap.facts.iter().try_for_each(|f| verify_fact(f, key))
}

// ── the growth go-ahead (`DATA-SET-GROWTH-FLOW.md` D3 / T14) ───────────────

/// **The go-ahead a data-set growth is started on**, as gunnar's
/// `gunnar_server::grow::go_ahead::GoAhead` parses it:
///
/// ```json
/// {"v":1,"signer":"monetize","target_sectors":<u64>,"nonce":"<one line ≤256 B>",
///  "issued_unix_ms":<i64>,"signature":"<base64, standard alphabet, padded>"}
/// ```
///
/// The signature is Ed25519 by monetize's signing key over
/// [`go_ahead_message`]: the canonical JSON (keys sorted bytewise, no
/// whitespace) of the object MINUS `signature` — the same form and the same
/// key an [`EntitlementFact`] is signed with, so a metered gunnar verifies it
/// with the `--monetize-pubkey` it already holds. gunnar checks the structure
/// (`v`, a known `signer`, a non-empty nonce, `target_sectors` equal to the
/// request's, the nonce unspent on that box); a `monetize` policy plugged into
/// its `GoAheadPolicy` calls [`verify_go_ahead`].
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct GoAhead {
    pub v: u32,
    pub signer: String,
    pub target_sectors: u64,
    pub nonce: String,
    pub issued_unix_ms: i64,
    #[serde(default)]
    pub signature: String,
}

/// The signer word a monetize-minted go-ahead carries.
pub const GO_AHEAD_SIGNER_MONETIZE: &str = "monetize";

/// The bytes a go-ahead's signature covers: every field except `signature`,
/// canonical.
pub fn go_ahead_message(go: &GoAhead) -> Vec<u8> {
    let mut v = serde_json::to_value(go).expect("go-ahead serializes");
    v.as_object_mut().expect("go-ahead is an object").remove("signature");
    let mut s = String::new();
    canonical_json(&v, &mut s);
    s.into_bytes()
}

/// Parse the bytes handed on the wire and verify the signature under `key`.
/// Structure first (so a refusal names what is wrong), then the signature.
pub fn verify_go_ahead(bytes: &[u8], key: &VerifyingKey) -> Result<GoAhead, SignatureError> {
    let go: GoAhead = serde_json::from_slice(bytes).map_err(|_| SignatureError::Malformed)?;
    if go.v != 1 || go.signer != GO_AHEAD_SIGNER_MONETIZE || go.nonce.trim().is_empty() {
        return Err(SignatureError::Malformed);
    }
    let sig = base64_decode(&go.signature).ok_or(SignatureError::Malformed)?;
    if check(key, &go_ahead_message(&go), &sig)? {
        Ok(go)
    } else {
        Err(SignatureError::GoAhead(go.nonce.clone()))
    }
}

const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

/// Standard base64, padded — the alphabet `GoAhead.signature` is written in.
/// Twenty lines here rather than a dependency the two crates that need it
/// (this one and `monetize`) would otherwise add for one field.
pub fn base64_encode(bytes: &[u8]) -> String {
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
        let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
        out.push(B64[(n >> 18) as usize & 63] as char);
        out.push(B64[(n >> 12) as usize & 63] as char);
        out.push(if chunk.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' });
        out.push(if chunk.len() > 2 { B64[n as usize & 63] as char } else { '=' });
    }
    out
}

/// The inverse; `None` on anything that is not padded standard base64.
pub fn base64_decode(text: &str) -> Option<Vec<u8>> {
    let text = text.trim();
    if text.len() % 4 != 0 {
        return None;
    }
    let val = |c: u8| B64.iter().position(|b| *b == c).map(|p| p as u32);
    let mut out = Vec::with_capacity(text.len() / 4 * 3);
    for chunk in text.as_bytes().chunks(4) {
        let pad = chunk.iter().rev().take_while(|c| **c == b'=').count();
        if pad > 2 || chunk[..4 - pad].iter().any(|c| *c == b'=') {
            return None;
        }
        let mut n = 0u32;
        for (i, c) in chunk.iter().enumerate() {
            let v = if i >= 4 - pad { 0 } else { val(*c)? };
            n = (n << 6) | v;
        }
        out.push((n >> 16) as u8);
        if pad < 2 {
            out.push((n >> 8) as u8);
        }
        if pad < 1 {
            out.push(n as u8);
        }
    }
    Some(out)
}

#[cfg(test)]
mod go_ahead_tests {
    use super::*;

    #[test]
    fn base64_round_trips_every_padding_shape_and_refuses_junk() {
        for n in 0..10 {
            let bytes: Vec<u8> = (0..n).map(|i| (i * 37 + 11) as u8).collect();
            let enc = base64_encode(&bytes);
            assert_eq!(enc.len() % 4, 0);
            assert_eq!(base64_decode(&enc).unwrap(), bytes, "{enc}");
        }
        assert_eq!(base64_encode(b"Man"), "TWFu");
        assert_eq!(base64_encode(b"Ma"), "TWE=");
        assert_eq!(base64_encode(b"M"), "TQ==");
        assert_eq!(base64_decode("TQ="), None);
        assert_eq!(base64_decode("T@=="), None);
        assert_eq!(base64_decode("TQ=x"), None);
    }

    #[test]
    fn the_go_ahead_message_is_canonical_and_excludes_the_signature() {
        let go = GoAhead { v: 1, signer: "monetize".into(), target_sectors: 134_217_728, nonce: "n-1".into(), issued_unix_ms: 1_800_000_000_000, signature: "zzz".into() };
        let msg = String::from_utf8(go_ahead_message(&go)).unwrap();
        assert_eq!(msg, r#"{"issued_unix_ms":1800000000000,"nonce":"n-1","signer":"monetize","target_sectors":134217728,"v":1}"#);
    }
}

// ── the two compatibility directions ───────────────────────────────────────

/// **The issue time was added on 2026-09-17, and nothing signed before it may
/// break.** These tests are the promise, written down where the forms are.
///
/// The two directions a change to a signed form has to answer:
///
/// * an OLD fact meeting NEW code — every signature ever minted still verifies,
///   because the V1 form is untouched;
/// * a NEW fact meeting an OLD appliance — it reads seven proto fields, computes
///   the V1 form and checks `signature`, which is exactly what
///   [`v1_of_a_stamped_fact_is_byte_for_byte_the_old_form`] measures.
///
/// Neither direction ends in service withdrawn from a paying customer. The
/// guard itself is the product's (gunnar's `EntitlementSlot::set`); what is
/// promised here is only that both generations can still read the fact.
#[cfg(test)]
mod stamp_tests {
    use super::*;
    use ed25519_dalek::{Signer as _, SigningKey};
    use monetize_product::{State, TenantId};

    fn key() -> SigningKey {
        SigningKey::from_bytes(&[3u8; 32])
    }

    fn bare() -> EntitlementFact {
        EntitlementFact {
            tenant: TenantId("team/sub".into()),
            plan: "gunnar/team/sub/2026-09-03".into(),
            state: State::Paid,
            paid_until_unix_ms: Some(1_790_812_800_000),
            caps: [("pack_bytes".to_string(), 10u64 << 30)].into(),
            source: "payment:invoice:ocr-42".into(),
            signature: vec![],
            issued_unix_ms: None,
            issued_signature: vec![],
        }
    }

    /// A fact as it was signed before the field existed: V1 only.
    fn v1(k: &SigningKey) -> EntitlementFact {
        let mut f = bare();
        f.signature = k.sign(&fact_message(&f)).to_bytes().to_vec();
        f
    }

    /// A fact as monetize mints one now: both signatures, stamped.
    fn stamped(k: &SigningKey, issued: u64) -> EntitlementFact {
        let mut f = bare();
        f.issued_unix_ms = Some(issued);
        f.signature = k.sign(&fact_message(&f)).to_bytes().to_vec();
        f.issued_signature = k.sign(&fact_message_issued(&f)).to_bytes().to_vec();
        f
    }

    /// **The old form is frozen.** The bytes below are what `fact_message`
    /// produced before the stamp existed, written out in full rather than
    /// computed, so a future field that forgets to exclude itself fails HERE
    /// and not on a customer's appliance.
    const V1_BYTES: &str = concat!(
        r#"{"caps":{"pack_bytes":10737418240},"paid_until_unix_ms":1790812800000,"#,
        r#""plan":"gunnar/team/sub/2026-09-03","source":"payment:invoice:ocr-42","#,
        r#""state":"Paid","tenant":"team/sub"}"#
    );

    #[test]
    fn v1_of_a_stamped_fact_is_byte_for_byte_the_old_form() {
        let k = key();
        assert_eq!(String::from_utf8(fact_message(&bare())).unwrap(), V1_BYTES);
        let stamped = stamped(&k, 1_789_000_000_000);
        assert_eq!(
            String::from_utf8(fact_message(&stamped)).unwrap(),
            V1_BYTES,
            "an appliance that has never heard of the stamp computes exactly this"
        );
        // …and therefore the V1 signature on a stamped fact is the one such an
        // appliance checks, and it passes. This is the NEW-fact-meets-OLD-box
        // direction, and it must never become a refusal.
        assert!(check(&k.verifying_key(), V1_BYTES.as_bytes(), &stamped.signature).unwrap());
    }

    #[test]
    fn the_v2_form_is_the_v1_form_plus_the_issue_time_and_nothing_else() {
        let stamped = stamped(&key(), 1_789_000_000_000);
        assert_eq!(
            String::from_utf8(fact_message_issued(&stamped)).unwrap(),
            concat!(
                r#"{"caps":{"pack_bytes":10737418240},"issued_unix_ms":1789000000000,"#,
                r#""paid_until_unix_ms":1790812800000,"plan":"gunnar/team/sub/2026-09-03","#,
                r#""source":"payment:invoice:ocr-42","state":"Paid","tenant":"team/sub"}"#
            )
        );
    }

    #[test]
    fn a_fact_signed_before_the_stamp_existed_still_verifies() {
        let k = key();
        verify_fact(&v1(&k), &k.verifying_key()).expect("OLD fact, NEW code: accepted");
    }

    #[test]
    fn a_stamped_fact_verifies_both_halves() {
        let k = key();
        verify_fact(&stamped(&k, 1_789_000_000_000), &k.verifying_key()).unwrap();
    }

    /// **The issue time cannot be added, moved or bumped in transit.**
    ///
    /// Bumping is the one that would hurt most: a fact stamped far in the future
    /// moves a product's high-water mark past every fact monetize will ever mint
    /// for that tenant, so the tenant's plan can never be changed again. That is
    /// a lasting denial of service, and it is refused here, at the signature.
    #[test]
    fn refuse_twin_an_unsigned_or_bumped_issue_time_is_refused_by_its_own_name() {
        let k = key();
        let who = || SignatureError::Issued("team/sub".into());

        // Added to a fact that never had one.
        let mut added = v1(&k);
        added.issued_unix_ms = Some(u64::MAX);
        assert_eq!(verify_fact(&added, &k.verifying_key()), Err(who()));

        // Bumped on a genuinely stamped fact: the V1 signature still passes
        // (it never covered the field), and the V2 one does not.
        let mut bumped = stamped(&k, 1_789_000_000_000);
        bumped.issued_unix_ms = Some(u64::MAX);
        assert!(check(&k.verifying_key(), &fact_message(&bumped), &bumped.signature).unwrap());
        assert_eq!(verify_fact(&bumped, &k.verifying_key()), Err(who()));

        // Half a stamp, either way round.
        let mut no_sig = stamped(&k, 1_789_000_000_000);
        no_sig.issued_signature.clear();
        assert_eq!(verify_fact(&no_sig, &k.verifying_key()), Err(who()));
        let mut no_time = stamped(&k, 1_789_000_000_000);
        no_time.issued_unix_ms = None;
        assert_eq!(verify_fact(&no_time, &k.verifying_key()), Err(who()));

        // A stamp lifted off another fact for the same tenant.
        let mut moved = stamped(&k, 1_789_000_000_000);
        moved.issued_signature = stamped(&k, 1_789_000_000_001).issued_signature;
        assert_eq!(verify_fact(&moved, &k.verifying_key()), Err(who()));
    }

    /// A snapshot of stamped facts verifies whole, and one bumped stamp inside
    /// it rejects the whole snapshot — the envelope vouches for the SET.
    #[test]
    fn a_snapshot_carries_stamped_facts_and_one_bad_stamp_rejects_the_set() {
        let k = key();
        let good = stamped(&k, 1_789_000_000_000);
        let facts = vec![good.clone()];
        let signature = k.sign(&snapshot_message(9, &facts)).to_bytes().to_vec();
        let snap = Snapshot { issued_unix_ms: 9, facts, signature };
        verify_snapshot(&snap, &k.verifying_key()).unwrap();

        let mut bumped = good;
        bumped.issued_unix_ms = Some(u64::MAX);
        let facts = vec![bumped];
        let signature = k.sign(&snapshot_message(9, &facts)).to_bytes().to_vec();
        let snap = Snapshot { issued_unix_ms: 9, facts, signature };
        assert_eq!(
            verify_snapshot(&snap, &k.verifying_key()),
            Err(SignatureError::Issued("team/sub".into()))
        );
    }
}