bevy-dlc 1.18.25

DLC (downloadable content) management for Bevy games
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use bevy::prelude::*;
use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey};

#[allow(unused_imports)]
use secure_gate::{CloneableSecret, RevealSecret, dynamic_alias, fixed_alias};

mod asset_loader;
pub mod encrypt_key_registry;
mod ext;

#[macro_use]
mod macros;

mod pack_format;

pub use asset_loader::{
    DlcLoader, DlcPack, DlcPackLoader, DlcPackLoaderSettings, EncryptedAsset, parse_encrypted,
};

pub use pack_format::{
    BlockMetadata, CompressionLevel, DEFAULT_BLOCK_SIZE, DLC_PACK_MAGIC, DLC_PACK_VERSION_LATEST,
    ManifestEntry, PackMetadata, ParsedDlcPack, V4ManifestEntry, V5ManifestEntry,
    is_data_executable, pack_encrypted_pack, pack_encrypted_pack_with_metadata,
    parse_encrypted_pack, parse_encrypted_pack_info,
};

use serde::{Deserialize, Serialize};

use thiserror::Error;

use crate::asset_loader::DlcPackLoaded;

#[doc(hidden)]
pub use crate::macros::__decode_embedded_signed_license_aes;
#[allow(unused_imports)]
pub use bevy_dlc_macro::include_signed_license_aes;

pub use crate::ext::AppExt;

/// Register an encryption key for a DLC ID in the global registry.
/// This is used internally by the plugin and can be called by tools/CLI for key management.
///
/// # Arguments
/// * `dlc_id` - The DLC identifier to associate with the key
/// * `key` - The encryption key to register
pub fn register_encryption_key(dlc_id: &str, key: EncryptionKey) {
    encrypt_key_registry::insert(dlc_id, key);
}

pub mod prelude {
    pub use crate::ext::*;
    pub use crate::include_dlc_key_and_license_aes;
    pub use crate::{
        DlcError, DlcId, DlcKey, DlcLoader, DlcPack, DlcPackLoader, DlcPackLoaderSettings,
        DlcPackMetadataError, DlcPlugin, EncryptedAsset, PackItem, PackMetadata, Product,
        SignedLicense, asset_loader::DlcPackEntry, asset_loader::DlcPackLoaded,
        is_dlc_entry_loaded, is_dlc_loaded,
    };
    pub use bevy_dlc_macro::include_signed_license_aes;
}

pub struct DlcPlugin {
    dlc_key: DlcKey,

    signed_license: SignedLicense,
}

impl DlcPlugin {
    /// Create the plugin from a `DlcKey` and a `SignedLicense`.
    ///
    /// The plugin will extract the encryption key from the signed license
    /// during `build` and register it in the global key registry.
    pub fn new(dlc_key: DlcKey, signed_license: SignedLicense) -> Self {
        Self {
            dlc_key,
            signed_license,
        }
    }
}

impl From<(DlcKey, SignedLicense)> for DlcPlugin {
    /// Create the plugin from a tuple of `(DlcKey, SignedLicense)`, for ergonomic construction using the `include_dlc_key_and_license_aes!` macro.
    fn from(tuple: (DlcKey, SignedLicense)) -> Self {
        DlcPlugin::new(tuple.0, tuple.1)
    }
}

impl Plugin for DlcPlugin {
    fn build(&self, app: &mut App) {
        if let Some(encrypt_key) = extract_encrypt_key_from_license(&self.signed_license) {
            let dlcs = extract_dlc_ids_from_license(&self.signed_license);
            for dlc_id in dlcs {
                // asset sources should already have been registered by PreDlcPlugin;
                // only insert the encryption keys here so later runtime behaviour
                // still works if user accidentally omitted the pre-plugin.
                let key_for_dlc = encrypt_key.with_secret(|kb| EncryptionKey::new(*kb));
                encrypt_key_registry::insert(&dlc_id, key_for_dlc);
            }
        }

        app.init_resource::<asset_loader::DlcPackRegistrarFactories>();

        app.insert_resource(self.dlc_key.clone())
            .init_asset_loader::<asset_loader::DlcLoader<Image>>()
            .init_asset_loader::<asset_loader::DlcLoader<Scene>>()
            .init_asset_loader::<asset_loader::DlcLoader<Mesh>>()
            .init_asset_loader::<asset_loader::DlcLoader<Font>>()
            .init_asset_loader::<asset_loader::DlcLoader<AudioSource>>()
            .init_asset_loader::<asset_loader::DlcLoader<ColorMaterial>>()
            .init_asset_loader::<asset_loader::DlcLoader<StandardMaterial>>()
            .init_asset_loader::<asset_loader::DlcLoader<Gltf>>()
            .init_asset_loader::<asset_loader::DlcLoader<bevy::gltf::GltfMesh>>()
            .init_asset_loader::<asset_loader::DlcLoader<Shader>>()
            .init_asset_loader::<asset_loader::DlcLoader<DynamicScene>>()
            .init_asset_loader::<asset_loader::DlcLoader<AnimationClip>>()
            .init_asset_loader::<asset_loader::DlcLoader<AnimationGraph>>();

        let factories = app
            .world()
            .get_resource::<asset_loader::DlcPackRegistrarFactories>()
            .cloned();
        let pack_loader = asset_loader::DlcPackLoader {
            registrars: asset_loader::collect_pack_registrars(factories.as_ref()),
            factories,
        };

        app.register_asset_loader(pack_loader);
        app.init_asset::<asset_loader::DlcPack>();

        app.add_systems(Update, trigger_dlc_events);
    }
}

/// System that monitors `AssetEvent<DlcPack>` and triggers observer-friendly events.
fn trigger_dlc_events(
    mut events: MessageReader<AssetEvent<DlcPack>>,
    packs: Res<Assets<DlcPack>>,
    mut commands: Commands,
) {
    for event in events.read() {
        match event {
            AssetEvent::Added { id } => {
                if let Some(pack) = packs.get(*id) {
                    let dlc_id = pack.id().clone();
                    commands.trigger(DlcPackLoaded::new(dlc_id.clone(), pack.clone()));
                }
            }
            _ => {}
        }
    }
}

/// A Bevy system condition that returns `true` when a DLC pack has been loaded.
///
/// A DLC is considered loaded when `DlcPackLoader` has successfully loaded a `.dlcpack` file
/// containing that `DlcId`.
///
/// This is useful for gating systems that should only run when specific DLC content is actually
/// available.
///
/// # Example
/// ```ignore
/// use bevy::prelude::*;
/// use bevy_dlc::is_dlc_loaded;
///
/// fn spawn_dlc_content() {}
///
/// let mut app = App::new();
/// app.add_systems(Update, spawn_dlc_content.run_if(is_dlc_loaded("dlcA")));
/// ```
pub fn is_dlc_loaded(dlc_id: impl Into<DlcId>) -> impl Fn() -> bool + Send + Sync + 'static {
    let id_string = dlc_id.into().0;
    move || !encrypt_key_registry::asset_path_for(&id_string).is_none()
}

/// A Bevy system condition that returns `true` when a specific DLC pack entry is loaded.
pub fn is_dlc_entry_loaded(
    dlc_id: impl Into<DlcId>,
    entry: impl Into<String>,
) -> impl Fn(Res<Assets<DlcPack>>) -> bool + Send + Sync + 'static {
    let id_string = dlc_id.into().0;
    let entry_name = entry.into();
    move |dlc_packs: Res<Assets<DlcPack>>| {
        if !encrypt_key_registry::asset_path_for(&id_string).is_none() {
            dlc_packs
                .iter()
                .filter(|p| p.1.id() == &DlcId::from(id_string.clone()))
                .any(|pack| pack.1.find_entry(&entry_name).is_some())
        } else {
            false
        }
    }
}

/// Strongly-typed DLC identifier (string-backed).
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[serde(transparent)]
pub struct DlcId(pub String);

impl std::fmt::Display for DlcId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl Clone for DlcId {
    fn clone(&self) -> Self {
        DlcId(self.0.clone())
    }
}

impl DlcId {
    /// Return the underlying string slice.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl From<&str> for DlcId {
    fn from(s: &str) -> Self {
        DlcId(s.to_owned())
    }
}

impl From<String> for DlcId {
    fn from(s: String) -> Self {
        DlcId(s)
    }
}

impl AsRef<str> for DlcId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

fixed_alias!(pub PrivateKey, 32, "A secure wrapper for a 32-byte Ed25519 signing seed (private key) used to create signed licenses. This should be protected and never exposed in logs or error messages.");

/// PublicKey wrapper (32 bytes)
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct PublicKey(pub [u8; 32]);

impl AsRef<[u8]> for PublicKey {
    fn as_ref(&self) -> &[u8] {
        &self.0
    }
}

impl std::fmt::Debug for PublicKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "PublicKey({} bytes)", 32)
    }
}

dynamic_alias!(pub SignedLicense, String, "A compact offline-signed token containing DLC ids and an optional embedded encrypt key. Treat as sensitive and do not leak raw secrets in logs.  This ");

/// Extract the embedded encryption key from a signed license's payload (base64url-encoded).
/// Returns `None` if the token is malformed or contains no encrypt_key.
pub fn extract_encrypt_key_from_license(license: &SignedLicense) -> Option<EncryptionKey> {
    license.with_secret(|token_str| {
        let parts: Vec<&str> = token_str.split('.').collect();
        if parts.len() != 2 {
            return None;
        }
        let payload = URL_SAFE_NO_PAD.decode(parts[0].as_bytes()).ok()?;
        let payload_json: serde_json::Value = serde_json::from_slice(&payload).ok()?;
        let key_b64 = payload_json.get("encrypt_key").and_then(|v| v.as_str())?;
        URL_SAFE_NO_PAD
            .decode(key_b64.as_bytes())
            .ok()
            .and_then(|key_bytes| Some(EncryptionKey::new(key_bytes.try_into().ok()?)))
    })
}

/// Extract the DLC IDs from a signed license's payload.
/// Returns an empty vec if the token is malformed or contains no dlcs array.
pub fn extract_dlc_ids_from_license(license: &SignedLicense) -> Vec<String> {
    license.with_secret(|token_str| {
        let parts: Vec<&str> = token_str.split('.').collect();
        if parts.len() != 2 {
            return Vec::new();
        }
        if let Ok(payload) = URL_SAFE_NO_PAD.decode(parts[0].as_bytes()) {
            if let Ok(payload_json) = serde_json::from_slice::<serde_json::Value>(&payload) {
                if let Some(dlcs_array) = payload_json.get("dlcs").and_then(|v| v.as_array()) {
                    let mut dlcs = Vec::new();
                    for dlc in dlcs_array {
                        if let Some(dlc_id) = dlc.as_str() {
                            dlcs.push(dlc_id.to_string());
                        }
                    }
                    return dlcs;
                }
            }
        }
        Vec::new()
    })
}

/// Extract the `product` field from a signed license's payload.
/// Returns `None` if the token is malformed or the field is missing.
pub fn extract_product_from_license(license: &SignedLicense) -> Option<String> {
    license.with_secret(|token_str| {
        let parts: Vec<&str> = token_str.split('.').collect();
        if parts.len() != 2 {
            return None;
        }
        if let Ok(payload) = URL_SAFE_NO_PAD.decode(parts[0].as_bytes()) {
            if let Ok(payload_json) = serde_json::from_slice::<serde_json::Value>(&payload) {
                if let Some(prod) = payload_json.get("product").and_then(|v| v.as_str()) {
                    return Some(prod.to_string());
                }
            }
        }
        None
    })
}
/// Product: non-secret identifier wrapper (keeps same API surface)
#[derive(Resource, Clone, PartialEq, Eq, Debug)]
pub struct Product(String);

impl std::fmt::Display for Product {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl AsRef<str> for Product {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Product {
    /// Return the underlying string slice.
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }
}

impl From<String> for Product {
    fn from(s: String) -> Self {
        Product(s)
    }
}
impl From<&str> for Product {
    fn from(s: &str) -> Self {
        Product(s.to_owned())
    }
}

fixed_alias!(pub EncryptionKey, 32, "A secure encrypt key (symmetric key for encrypting DLC pack entries). This should be protected and never exposed in logs or error messages.");

/// Client-side wrapper for Ed25519 key operations: verify tokens and (when
/// private) create compact signed tokens.
#[derive(Resource)]
pub enum DlcKey {
    /// Private key (protected seed + public bytes + public key tag)
    Private {
        /// Protected signing seed (secure wrapper)
        privkey: PrivateKey,
        /// Public key bytes (wrapped)
        pubkey: PublicKey,
    },

    /// Public-only key (public bytes)
    Public {
        /// Public key bytes (wrapped)
        pubkey: PublicKey,
    },
}

impl DlcKey {
    pub fn new(pubkey: &str, privkey: &str) -> Result<Self, DlcError> {
        let decoded_pub = URL_SAFE_NO_PAD
            .decode(pubkey.as_bytes())
            .map_err(|e| DlcError::CryptoError(format!("invalid pubkey base64: {}", e)))?;
        if decoded_pub.len() != 32 {
            return Err(DlcError::CryptoError("public key must be 32 bytes".into()));
        }
        let mut pub_bytes = [0u8; 32];
        pub_bytes.copy_from_slice(&decoded_pub);

        let decoded_priv = URL_SAFE_NO_PAD
            .decode(privkey.as_bytes())
            .map_err(|e| DlcError::CryptoError(format!("invalid privkey base64: {}", e)))?;
        if decoded_priv.len() != 32 {
            return Err(DlcError::CryptoError("private key must be 32 bytes".into()));
        }
        let mut priv_bytes = [0u8; 32];
        priv_bytes.copy_from_slice(&decoded_priv);

        Self::from_priv_and_pub(PrivateKey::from(priv_bytes), PublicKey(pub_bytes))
    }

    /// Construct a `DlcKey::Public` from a base64url-encoded public key string.
    pub fn public(pubkey: &str) -> Result<Self, DlcError> {
        let decoded_pub = URL_SAFE_NO_PAD
            .decode(pubkey.as_bytes())
            .map_err(|e| DlcError::CryptoError(format!("invalid pubkey base64: {}", e)))?;
        if decoded_pub.len() != 32 {
            return Err(DlcError::CryptoError("public key must be 32 bytes".into()));
        }
        let mut pub_bytes = [0u8; 32];
        pub_bytes.copy_from_slice(&decoded_pub);

        Ok(DlcKey::Public {
            pubkey: PublicKey(pub_bytes),
        })
    }

    /// Construct a `DlcKey::Private` from a private key and public key.
    pub(crate) fn from_priv_and_pub(
        privkey: PrivateKey,
        publickey: PublicKey,
    ) -> Result<Self, DlcError> {
        let kp = privkey
            .with_secret(|priv_bytes| {
                Ed25519KeyPair::from_seed_and_public_key(priv_bytes, &publickey.0)
            })
            .map_err(|e| DlcError::CryptoError(format!("invalid seed: {:?}", e)))?;
        let mut pub_bytes = [0u8; 32];
        pub_bytes.copy_from_slice(kp.public_key().as_ref());

        privkey
            .with_secret(|priv_bytes| {
                Ed25519KeyPair::from_seed_and_public_key(priv_bytes, &pub_bytes)
            })
            .map_err(|e| DlcError::CryptoError(format!("keypair validation failed: {:?}", e)))?;

        Ok(DlcKey::Private {
            privkey,
            pubkey: PublicKey(pub_bytes),
        })
    }

    /// Generate a new `DlcKey::Private` with a random seed and derived public key.
    ///
    /// The public key is derived from the generated seed so the keypair is valid.
    pub fn generate_random() -> Self {
        let privkey: PrivateKey = PrivateKey::new(rand::random());

        let pair = privkey
            .with_secret(|priv_bytes| Ed25519KeyPair::from_seed_unchecked(priv_bytes))
            .expect("derive public key from seed");
        let mut pub_bytes = [0u8; 32];
        pub_bytes.copy_from_slice(pair.public_key().as_ref());

        Self::from_priv_and_pub(privkey, PublicKey(pub_bytes))
            .unwrap_or_else(|e| panic!("generate_complete failed: {:?}", e))
    }

    pub fn get_public_key(&self) -> &PublicKey {
        match self {
            DlcKey::Private { pubkey, .. } => pubkey,
            DlcKey::Public { pubkey: public } => public,
        }
    }

    /// Sign data using the private key.
    /// Returns a 64-byte signature.
    pub fn sign(&self, data: &[u8]) -> Result<[u8; 64], DlcError> {
        match self {
            DlcKey::Private { privkey, pubkey } => privkey.with_secret(|seed| {
                let pair = Ed25519KeyPair::from_seed_and_public_key(seed, pubkey.as_ref())
                    .map_err(|e| DlcError::CryptoError(e.to_string()))?;
                let sig = pair.sign(data);
                let mut sig_bytes = [0u8; 64];
                sig_bytes.copy_from_slice(sig.as_ref());
                Ok(sig_bytes)
            }),
            DlcKey::Public { .. } => Err(DlcError::PrivateKeyRequired),
        }
    }

    /// Verify a 64-byte Ed25519 signature against provided data.
    pub fn verify(&self, data: &[u8], signature: &[u8; 64]) -> Result<(), DlcError> {
        let pubkey = self.get_public_key();
        ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, pubkey.as_ref())
            .verify(data, signature.as_ref())
            .map_err(|_| DlcError::SignatureInvalid)
    }

    /// Create a compact offline-signed token that can be verified by this key's public key.
    ///
    /// Returns a `SignedLicense` (zeroized on drop). The license payload includes
    /// the provided DLC ids and product binding.
    /// Create a compact offline-signed token (SignedLicense).
    pub fn create_signed_license<D>(
        &self,
        dlcs: impl IntoIterator<Item = D>,
        product: Product,
    ) -> Result<SignedLicense, DlcError>
    where
        D: std::fmt::Display,
    {
        let mut payload = serde_json::Map::new();
        payload.insert(
            "dlcs".to_string(),
            serde_json::Value::Array(
                dlcs.into_iter()
                    .map(|s| serde_json::Value::String(s.to_string()))
                    .collect(),
            ),
        );

        payload.insert(
            "product".to_string(),
            serde_json::Value::String(product.as_ref().to_string()),
        );

        match self {
            DlcKey::Private { privkey, .. } => {
                let sig_token = privkey.with_secret(
                    |encrypt_key_bytes| -> Result<SignedLicense, DlcError> {
                        payload.insert(
                            "encrypt_key".to_string(),
                            serde_json::Value::String(URL_SAFE_NO_PAD.encode(encrypt_key_bytes)),
                        );

                        let payload_value = serde_json::Value::Object(payload);
                        let payload_bytes = serde_json::to_vec(&payload_value)
                            .map_err(|e| DlcError::TokenCreationFailed(e.to_string()))?;

                        let sig = self.sign(&payload_bytes)?;
                        Ok(SignedLicense::from(format!(
                            "{}.{}",
                            URL_SAFE_NO_PAD.encode(&payload_bytes),
                            URL_SAFE_NO_PAD.encode(sig.as_ref())
                        )))
                    },
                )?;
                Ok(sig_token)
            }
            DlcKey::Public { .. } => Err(DlcError::PrivateKeyRequired),
        }
    }

    /// Extend an existing signed license by merging additional DLC ids while preserving backwards compatibility.
    ///
    /// Extracts the DLC ids from an existing (unsigned or unverified) license payload, merges them
    /// with the provided new DLC ids (with deduplication), and creates a fresh signed license
    /// with the combined list. The product must match this key's current product.
    ///
    /// **Important**: This creates a NEW signed token with a potentially different signature,
    /// but the payload contains all previous DLC ids plus the new ones. Existing DLC packs
    /// remain unlocked by the new license.
    ///
    /// # Example
    /// ```ignore
    /// use bevy_dlc::{DlcKey, SignedLicense, Product};
    ///
    /// // in a real program you would obtain a key and product from your build
    /// // process or configuration.  we use simple constructors here so the
    /// // example compiles without panicking.
    /// let dlc_key: DlcKey = DlcKey::generate_random();
    /// let product: Product = Product::from("my_game");
    ///
    /// let old_license = SignedLicense::from("...existing token...");
    /// let _new_license = dlc_key
    ///     .extend_signed_license(&old_license, &["new_expansion"], product)
    ///     .unwrap();
    /// ```
    pub fn extend_signed_license<D>(
        &self,
        existing: &SignedLicense,
        new_dlcs: impl IntoIterator<Item = D>,
        product: Product,
    ) -> Result<SignedLicense, DlcError>
    where
        D: std::fmt::Display,
    {
        let mut combined_dlcs: Vec<String> = existing.with_secret(|token_str| {
            let parts: Vec<&str> = token_str.split('.').collect();
            if parts.len() != 2 {
                return Vec::new();
            }
            if let Ok(payload) = URL_SAFE_NO_PAD.decode(parts[0].as_bytes()) {
                if let Ok(payload_json) = serde_json::from_slice::<serde_json::Value>(&payload) {
                    if let Some(dlcs_array) = payload_json.get("dlcs").and_then(|v| v.as_array()) {
                        let mut dlcs = Vec::new();
                        for dlc in dlcs_array {
                            if let Some(dlc_id) = dlc.as_str() {
                                dlcs.push(dlc_id.to_string());
                            }
                        }
                        return dlcs;
                    }
                }
            }
            Vec::new()
        });

        for new_dlc in new_dlcs {
            let dlc_str = new_dlc.to_string();
            if !combined_dlcs.contains(&dlc_str) {
                combined_dlcs.push(dlc_str);
            }
        }

        self.create_signed_license(combined_dlcs, product)
    }

    /// Verify a compact signed-license (signature + payload) using this key's public key
    /// Verify a compact signed-license using this key's public key.
    ///
    /// Returns `true` if the signature is valid and the token is well-formed,
    /// `false` otherwise.  No further payload validation is performed.
    pub fn verify_signed_license(&self, license: &SignedLicense) -> bool {
        license.with_secret(|full_token| {
            let parts: Vec<&str> = full_token.split('.').collect();
            if parts.len() != 2 {
                return false;
            }

            let payload = URL_SAFE_NO_PAD.decode(parts[0]);
            let sig_bytes = URL_SAFE_NO_PAD.decode(parts[1]);
            if payload.is_err() || sig_bytes.is_err() {
                return false;
            }
            let payload = payload.unwrap();
            let sig_bytes = sig_bytes.unwrap();

            if sig_bytes.len() != 64 {
                return false;
            }

            let public = self.get_public_key().0;
            let public_key = UnparsedPublicKey::new(&ED25519, public);
            public_key.verify(&payload, &sig_bytes).is_ok()
        })
    }
}

impl Clone for DlcKey {
    fn clone(&self) -> Self {
        match self {
            DlcKey::Private { privkey, pubkey } => privkey.with_secret(|s| DlcKey::Private {
                privkey: PrivateKey::new(*s),
                pubkey: *pubkey,
            }),
            DlcKey::Public { pubkey } => DlcKey::Public { pubkey: *pubkey },
        }
    }
}

impl std::fmt::Display for DlcKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", URL_SAFE_NO_PAD.encode(self.get_public_key().0))
    }
}

impl From<&DlcKey> for String {
    fn from(k: &DlcKey) -> Self {
        k.to_string()
    }
}

/// Helper struct for building DLC pack entries with optional metadata.
/// Provides a builder pattern for creating entries to pack into a `.dlcpack` container.
#[derive(Clone, Debug)]
pub struct PackItem {
    path: String,
    original_extension: Option<String>,
    type_path: Option<String>,
    plaintext: Vec<u8>,
}

#[allow(dead_code)]
impl PackItem {
    pub fn new(path: impl Into<String>, plaintext: impl Into<Vec<u8>>) -> Result<Self, DlcError> {
        let path = path.into();
        let bytes = plaintext.into();

        if bytes.len() >= 4 && bytes.starts_with(DLC_PACK_MAGIC) {
            return Err(DlcError::Other(format!(
                "cannot pack existing dlcpack container as an item: {}",
                path
            )));
        }

        if pack_format::is_data_executable(&bytes) {
            return Err(DlcError::Other(format!(
                "input data looks like an executable payload, which is not allowed: {}",
                path
            )));
        }

        let ext_str = std::path::Path::new(&path)
            .extension()
            .and_then(|e| e.to_str());

        Ok(Self {
            path: path.clone(),
            original_extension: ext_str.map(|s| s.to_string()),
            type_path: None,
            plaintext: bytes,
        })
    }

    pub fn with_extension(mut self, ext: impl Into<String>) -> Result<Self, DlcError> {
        let ext_s = ext.into();
        self.original_extension = Some(ext_s);
        Ok(self)
    }

    pub fn with_type_path(mut self, type_path: impl Into<String>) -> Self {
        self.type_path = Some(type_path.into());
        self
    }

    pub fn with_type<T: Asset>(self) -> Self {
        self.with_type_path(T::type_path())
    }

    /// Return the relative path for this item within the pack. This is used by the loader to determine how to register the decrypted asset.
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Return the plaintext bytes for this item. This is the data that will be encrypted and stored in the pack.
    pub fn plaintext(&self) -> &[u8] {
        &self.plaintext
    }

    pub fn ext(&self) -> Option<String> {
        if let Some(ext) = std::path::Path::new(&self.path)
            .extension()
            .and_then(|e| e.to_str())
            .and_then(|s| {
                if s.is_empty() {
                    None
                } else {
                    Some(s.to_string())
                }
            })
        {
            Some(ext)
        } else {
            self.original_extension.clone()
        }
    }

    pub fn type_path(&self) -> Option<String> {
        self.type_path.clone()
    }
}

impl From<PackItem> for (String, Option<String>, Option<String>, Vec<u8>) {
    fn from(item: PackItem) -> Self {
        (
            item.path,
            item.original_extension,
            item.type_path,
            item.plaintext,
        )
    }
}

/// Parse a `.dlcpack` container and return product, embedded dlc_id, and a list
/// of `(path, EncryptedAsset)` pairs. For v3 format, also validates the signature
/// against the authorized product public key.
///
/// Returns: (product, dlc_id, entries, signature_bytes_if_v3)

#[derive(Error, Debug, Clone)]
pub enum DlcError {
    #[error("invalid public key: {0}")]
    InvalidPublicKey(String),
    #[error("malformed private key: {0}")]
    MalformedLicense(String),
    #[error("signature verification failed")]
    SignatureInvalid,
    #[error("payload parse failed: {0}")]
    PayloadInvalid(String),

    #[error("private key creation failed: {0}")]
    TokenCreationFailed(String),
    #[error("private key required for this operation")]
    PrivateKeyRequired,
    #[error("invalid public key")]
    InvalidPassphrase,
    #[error("crypto error: {0}")]
    CryptoError(String),

    #[error("encryption failed: {0}")]
    EncryptionFailed(String),
    #[error("{0}")]
    DecryptionFailed(String),
    #[error("invalid encrypt key: {0}")]
    InvalidEncryptKey(String),
    #[error("invalid nonce: {0}")]
    InvalidNonce(String),

    #[error("dlc locked: {0}")]
    DlcLocked(String),
    #[error("no encrypt key for dlc: {0}")]
    NoEncryptKey(String),

    /// The DLC pack being loaded is cryptographically valid but the product it is bound to does not match the expected product. This indicates a mismatch between the pack and the game's registered product key.
    #[error("private key product does not match")]
    TokenProductMismatch,

    /// The version of the pack being loaded is older than the minimum supported version. The string contains the minimum supported version (e.g. "3").
    #[error("deprecated version: v{0}")]
    DeprecatedVersion(String),

    #[error("{0}")]
    Other(String),
}

#[derive(Error, Debug)]
pub enum DlcPackMetadataError {
    #[error("pack metadata is encrypted and unavailable without the DLC encryption key")]
    Locked,

    #[error("failed to deserialize metadata key '{key}': {source}")]
    Deserialize {
        key: String,
        #[source]
        source: serde_json::Error,
    },
}

// convenience conversions to reduce boilerplate
impl From<std::io::Error> for DlcError {
    fn from(e: std::io::Error) -> Self {
        DlcError::Other(e.to_string())
    }
}

impl From<ring::error::Unspecified> for DlcError {
    fn from(e: ring::error::Unspecified) -> Self {
        DlcError::CryptoError(format!("crypto error: {:?}", e))
    }
}

#[cfg(test)]
mod tests {
    use crate::ext::*;

    use super::*;

    #[test]
    fn pack_encrypted_pack_rejects_nested_dlc() {
        let mut v = Vec::new();
        v.extend_from_slice(DLC_PACK_MAGIC);
        v.extend_from_slice(b"inner");
        let err = PackItem::new("a.txt", v).unwrap_err();
        assert!(err.to_string().contains("cannot pack existing dlcpack"));
    }

    #[test]
    fn pack_encrypted_pack_rejects_nested_dlcpack() {
        let mut v = Vec::new();
        v.extend_from_slice(DLC_PACK_MAGIC);
        v.extend_from_slice(b"innerpack");
        let err = PackItem::new("b.dlcpack", v);
        assert!(err.is_err());
    }

    #[test]
    fn is_data_executable_detects_pe_header() {
        assert!(is_data_executable(&[0x4D, 0x5A, 0, 0]));
    }

    #[test]
    fn is_data_executable_detects_shebang() {
        assert!(is_data_executable(b"#! /bin/sh"));
    }

    #[test]
    fn is_data_executable_ignores_plain_text() {
        assert!(!is_data_executable(b"hello"));
    }

    #[test]
    fn packitem_rejects_binary_data() {
        let mut v = Vec::new();
        v.extend_from_slice(&[0x4D, 0x5A, 0, 0]);

        let pack_item = PackItem::new("evil.dat", v);
        assert!(pack_item.is_err());
    }

    #[test]
    fn dlc_id_serde_roundtrip() {
        let id = DlcId::from("expansion_serde");
        let s = serde_json::to_string(&id).expect("serialize dlc id");
        assert_eq!(s, "\"expansion_serde\"");
        let decoded: DlcId = serde_json::from_str(&s).expect("deserialize dlc id");
        assert_eq!(decoded.to_string(), "expansion_serde");
    }

    #[test]
    fn extend_signed_license_merges_dlc_ids() {
        let product = Product::from("test_product");
        let dlc_key = DlcKey::generate_random();

        let initial = dlc_key
            .create_signed_license(&["expansion_a", "expansion_b"], product.clone())
            .expect("create initial license");

        let extended = dlc_key
            .extend_signed_license(&initial, &["expansion_c"], product.clone())
            .expect("extend license");

        assert!(dlc_key.verify_signed_license(&extended));
        let verified_dlcs = extract_dlc_ids_from_license(&extended);
        assert_eq!(verified_dlcs.len(), 3);
        assert!(verified_dlcs.contains(&"expansion_a".to_string()));
        assert!(verified_dlcs.contains(&"expansion_b".to_string()));
        assert!(verified_dlcs.contains(&"expansion_c".to_string()));
    }

    #[test]
    fn extend_signed_license_deduplicates() {
        let product = Product::from("test_product");
        let dlc_key = DlcKey::generate_random();

        let initial = dlc_key
            .create_signed_license(&["expansion_a"], product.clone())
            .expect("create initial license");

        let extended = dlc_key
            .extend_signed_license(&initial, &["expansion_a"], product.clone())
            .expect("extend license");

        assert!(dlc_key.verify_signed_license(&extended));
        let verified_dlcs = extract_dlc_ids_from_license(&extended);
        let count = verified_dlcs.iter().filter(|d| d == &"expansion_a").count();
        assert_eq!(count, 1, "Should not duplicate dlc_ids");
    }

    #[test]
    #[serial_test::serial]
    fn register_dlc_type_adds_pack_registrar_factory() {
        let mut app = App::new();
        app.add_plugins(AssetPlugin::default());
        #[derive(Asset, TypePath)]
        struct TestAsset;
        app.init_asset::<TestAsset>();
        app.register_dlc_type::<TestAsset>();

        let factories = app
            .world()
            .get_resource::<asset_loader::DlcPackRegistrarFactories>()
            .expect("should have factories resource");
        assert!(
            factories
                .0
                .read()
                .unwrap()
                .iter()
                .any(|f| asset_loader::fuzzy_type_path_match(
                    f.type_name(),
                    TestAsset::type_path()
                ))
        );
    }

    #[test]
    #[serial_test::serial]
    fn register_dlc_type_is_idempotent_for_pack_factories() {
        let mut app = App::new();
        app.add_plugins(AssetPlugin::default());
        #[derive(Asset, TypePath)]
        struct TestAsset2;
        app.init_asset::<TestAsset2>();
        app.register_dlc_type::<TestAsset2>();
        app.register_dlc_type::<TestAsset2>();

        let factories = app
            .world()
            .get_resource::<asset_loader::DlcPackRegistrarFactories>()
            .expect("should have factories resource");
        let count = factories
            .0
            .read()
            .unwrap()
            .iter()
            .filter(|f| asset_loader::fuzzy_type_path_match(f.type_name(), TestAsset2::type_path()))
            .count();
        assert_eq!(count, 1);
    }
}

/// Test helpers for integration tests. These provide controlled access to the
/// internal registry to support test scenarios. Do not use in production code.
///
/// The registry should only be updated by `DlcPackLoader` when assets are loaded
/// or by systems processing `SignedLicense` tokens in production. This module
/// allows integration tests to bypass normal flow by directly registering keys.
#[cfg(test)]
#[allow(dead_code)]
pub mod test_helpers {
    use crate::{EncryptionKey, encrypt_key_registry};

    /// Insert a test encryption key into the registry for a given DLC id.
    ///
    /// **Test-only**: This bypasses normal production flows and should only be used
    /// in integration tests that need to load assets without processing signed licenses.
    pub fn register_test_encryption_key(dlc_id: &str, key: EncryptionKey) {
        encrypt_key_registry::insert(dlc_id, key);
    }

    /// Register an asset path in the test registry.
    ///
    /// **Test-only**: Used to simulate what `DlcPackLoader` does during asset loading.
    pub fn register_test_asset_path(dlc_id: &str, path: &str) {
        encrypt_key_registry::register_asset_path(dlc_id, path);
    }

    /// Clear the entire test registry.
    ///
    /// **Test-only**: Call this in test cleanup to reset state.
    pub fn clear_test_registry() {
        encrypt_key_registry::clear_all();
    }

    pub fn is_malicious_data(data: &[u8]) -> bool {
        crate::pack_format::is_data_executable(data)
    }
}