Skip to main content

adk_website/packs/
bundle.rs

1//! The capability pack bundle (spec 3.5 §7.23): one JSON document that carries a pack's
2//! capability declarations, the configuration of the handlers that serve them, its playbooks
3//! and its driver manifests, sealed with a content digest and its publisher's signature.
4//!
5//! ```json
6//! {
7//!   "format": "adk-website.pack/1",
8//!   "name": "waitlist",
9//!   "version": "1.0.0",
10//!   "publisher": { "id": "tables.example", "name": "Tables" },
11//!   "description": "A waiting list for fully booked evenings",
12//!   "capabilities": [ { "name": "join_waitlist", "effect": "non_idempotent", "…": "…" } ],
13//!   "handlers": { "join_waitlist": { "handler": "form" } },
14//!   "playbooks": [ { "id": "waitlist", "job": "capture", "agents": ["concierge"], "text": "---\nname: waitlist\n…" } ],
15//!   "drivers": [ { "id": "tables-pos", "manifest": "id = \"tables-pos\"\n…" } ],
16//!   "digest": "sha256:…",
17//!   "proof": { "alg": "EdDSA", "kid": "tables-2026", "jws": "<detached JWS>" }
18//! }
19//! ```
20//!
21//! | Member | Holds |
22//! |---|---|
23//! | `digest` | The content digest: the SHA-256 of the JCS form of the bundle without `digest` and `proof` (AWP 2.0 §1.2) |
24//! | `proof` | The publisher's detached JWS (EdDSA) over the JCS form of the bundle without `proof`, so it covers the digest (AWP 2.0 §5.4) |
25//!
26//! A pack runs no code in the site's process: each capability is served by a built-in handler
27//! its [`HandlerConfig`] names, and a pack's drivers are MCP servers the kernel runs sandboxed
28//! once the owner mounts them. [`PackBundle::verify`] authenticates a bundle against a
29//! [`TrustList`] before [`PackBundle::check`] judges its content; installation refuses a
30//! bundle that is unsigned, tampered, from an unknown publisher, invalid, or in conflict with
31//! the site's packs.
32
33use std::collections::BTreeSet;
34use std::sync::Arc;
35
36use adk_awp::signing::jws::{DocumentSigner, document_digest, jwk_thumbprint, sign, verify};
37use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler, CapabilityTool};
38use adk_core::{AdkError, ErrorCategory, ErrorComponent};
39use adk_kernel::drivers::{DriverManifest, DriverSandbox, EffectClass};
40use async_trait::async_trait;
41use awp_types::{CapabilityEffect, CapabilityV2, ContentKind, Digest, Proof};
42use serde::{Deserialize, Serialize};
43use serde_json::Value;
44
45use super::trust::TrustList;
46use crate::team::AgentRole;
47
48/// The bundle format this release writes and reads (spec 3.5 §7.23).
49pub const PACK_FORMAT: &str = "adk-website.pack/1";
50
51/// The largest bundle file installation reads.
52pub const MAX_BUNDLE_BYTES: usize = 4 * 1024 * 1024;
53
54const MAX_PLAYBOOK_BYTES: usize = 64 * 1024;
55const MAX_CAPABILITIES: usize = 256;
56const MAX_PLAYBOOKS: usize = 64;
57const MAX_DRIVERS: usize = 32;
58const MAX_DESCRIPTION_CHARS: usize = 2_000;
59
60/// Why a pack is refused (spec 3.5 §7.23). [`code`](Self::code) names each refusal for
61/// scripts and conformance vectors.
62#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
63#[non_exhaustive]
64pub enum PackError {
65    /// The file is not a pack bundle.
66    #[error("not a capability pack bundle: {0}")]
67    Malformed(String),
68    /// The bundle's format is not one this release reads.
69    #[error("the bundle's format is `{0}`; this release reads `{PACK_FORMAT}`")]
70    Format(String),
71    /// The bundle carries no signature.
72    #[error(
73        "the pack is not signed: a pack installs only with its publisher's signature over its \
74         content digest; ask the publisher for the signed bundle"
75    )]
76    Unsigned,
77    /// The content does not match its digest, or the signature does not verify.
78    #[error(
79        "the pack's content is not what its publisher signed: {0}; get the pack again from \
80         its publisher"
81    )]
82    Tampered(String),
83    /// No trusted key of the trust list belongs to the bundle's publisher and key id.
84    #[error(
85        "the pack's publisher `{publisher}` (key `{kid}`) is not in the trust list; add the \
86         publisher's public key with `adk-rust site packs trust` only if you trust them"
87    )]
88    UnknownPublisher {
89        /// The publisher the bundle names.
90        publisher: String,
91        /// The key id its proof names.
92        kid: String,
93    },
94    /// The offered version is older than the installed one.
95    #[error(
96        "`{name}` {installed} is installed and {offered} is older; a pack is never downgraded \
97         in place: remove it first to go back"
98    )]
99    Downgrade {
100        /// The pack.
101        name: String,
102        /// The installed version.
103        installed: String,
104        /// The offered version.
105        offered: String,
106    },
107    /// The offered version is installed with other content.
108    #[error(
109        "`{name}` {version} is installed with other content; a published version never \
110         changes, so its publisher must release a new version"
111    )]
112    Republished {
113        /// The pack.
114        name: String,
115        /// The version.
116        version: String,
117    },
118    /// The content breaks a rule of the format.
119    #[error("the pack is invalid: {0}")]
120    Invalid(String),
121    /// The pack takes a name, capability, playbook or driver another pack holds.
122    #[error("the pack conflicts with the site's packs: {0}")]
123    Conflict(String),
124    /// No installed pack has the name.
125    #[error("no installed pack is named `{0}`; `adk-rust site packs list` shows the site's packs")]
126    NotInstalled(String),
127    /// Built-in packs are not installed or removed.
128    #[error(
129        "`{0}` is a built-in pack: it ships with adk-website, and the site's kind chooses which \
130         of its capabilities the site offers"
131    )]
132    BuiltIn(String),
133    /// A file could not be read or written.
134    #[error("{0}")]
135    Io(String),
136}
137
138impl PackError {
139    /// The refusal's code: `malformed`, `format`, `unsigned`, `tampered`, `unknown_publisher`,
140    /// `downgrade`, `republished`, `invalid`, `conflict`, `not_installed`, `built_in` or `io`.
141    pub fn code(&self) -> &'static str {
142        match self {
143            Self::Malformed(_) => "malformed",
144            Self::Format(_) => "format",
145            Self::Unsigned => "unsigned",
146            Self::Tampered(_) => "tampered",
147            Self::UnknownPublisher { .. } => "unknown_publisher",
148            Self::Downgrade { .. } => "downgrade",
149            Self::Republished { .. } => "republished",
150            Self::Invalid(_) => "invalid",
151            Self::Conflict(_) => "conflict",
152            Self::NotInstalled(_) => "not_installed",
153            Self::BuiltIn(_) => "built_in",
154            Self::Io(_) => "io",
155        }
156    }
157}
158
159impl From<PackError> for AdkError {
160    fn from(error: PackError) -> Self {
161        let (category, code) = match &error {
162            PackError::Malformed(_) => (ErrorCategory::InvalidInput, "website.pack.malformed"),
163            PackError::Format(_) => (ErrorCategory::Unsupported, "website.pack.format"),
164            PackError::Unsigned => (ErrorCategory::Forbidden, "website.pack.unsigned"),
165            PackError::Tampered(_) => (ErrorCategory::Forbidden, "website.pack.tampered"),
166            PackError::UnknownPublisher { .. } => {
167                (ErrorCategory::Forbidden, "website.pack.unknown_publisher")
168            }
169            PackError::Downgrade { .. } => (ErrorCategory::Conflict, "website.pack.downgrade"),
170            PackError::Republished { .. } => (ErrorCategory::Conflict, "website.pack.republished"),
171            PackError::Invalid(_) => (ErrorCategory::InvalidInput, "website.pack.invalid"),
172            PackError::Conflict(_) => (ErrorCategory::Conflict, "website.pack.conflict"),
173            PackError::NotInstalled(_) => (ErrorCategory::NotFound, "website.pack.not_installed"),
174            PackError::BuiltIn(_) => (ErrorCategory::InvalidInput, "website.pack.built_in"),
175            PackError::Io(_) => (ErrorCategory::Internal, "website.pack.io"),
176        };
177        AdkError::new(ErrorComponent::Deploy, category, code, error.to_string())
178    }
179}
180
181/// Who publishes a pack (spec 3.5 §7.23): the id a trust list names and a display name.
182#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(rename_all = "camelCase", deny_unknown_fields)]
184pub struct PackPublisher {
185    /// The publisher's id: lowercase letters, digits, `.` and `-`, such as `tables.example`.
186    pub id: String,
187    /// The publisher's name, for people.
188    #[serde(default, skip_serializing_if = "Option::is_none")]
189    pub name: Option<String>,
190}
191
192impl PackPublisher {
193    /// The publisher `id`.
194    pub fn new(id: impl Into<String>) -> Self {
195        Self { id: id.into(), name: None }
196    }
197
198    /// With a display name.
199    #[must_use]
200    pub fn named(mut self, name: impl Into<String>) -> Self {
201        self.name = Some(name.into());
202        self
203    }
204}
205
206/// What an order handler does with a call (spec 3.5 §7.16 `order`).
207#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
208#[serde(rename_all = "snake_case")]
209pub enum OrderOperation {
210    /// Places an order against an open quote, as `place_order` does.
211    Place,
212    /// Reports an order's status, as `order_status` does.
213    Status,
214    /// Requests a return, as `request_return` does.
215    Return,
216}
217
218/// What a booking handler does with a call (spec 3.5 §7.16 `booking`).
219#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
220#[serde(rename_all = "snake_case")]
221pub enum BookingOperation {
222    /// Lists open slots, as `check_availability` does.
223    Availability,
224    /// Takes a slot and keeps the contact, as `book` does.
225    Book,
226}
227
228/// The built-in handler that serves a capability, with its configuration (spec 3.5 §7.23
229/// "handlers"). A pack configures handlers and ships no handler code: the edge serves each
230/// capability with the handler named here, over the site's own stores, calendar and payment
231/// desk, after its governed path has decided the call.
232///
233/// | Handler | Serves | Effect at least | Input members it reads |
234/// |---|---|---|---|
235/// | `form` | Enquiries and sign-ups: the contact, a lead and a `lead_captured` signal | `idempotent` | — |
236/// | `quote` | Quotes at the release's prices | `idempotent` | `items` |
237/// | `order` with `operation` `place`, `status` or `return` | Orders against quotes | `non_idempotent`; `read_only` for `status` | `quoteId`; `orderId` |
238/// | `payment` | Payments through the owner's payment desk | `non_idempotent` | — |
239/// | `booking` with `operation` `availability` or `book` | The owner's calendar | `read_only`; `non_idempotent` for `book` | —; `slot` |
240/// | `search` | The release's index | `read_only` | `query` |
241/// | `listing` with `content` | The published items of a content kind | `read_only` | — |
242/// | `status` | An application's status by its reference | `read_only` | `reference` |
243///
244/// # Example
245///
246/// ```rust
247/// use adk_website::packs::bundle::{BookingOperation, HandlerConfig};
248///
249/// let config: HandlerConfig =
250///     serde_json::from_str(r#"{"handler": "booking", "operation": "book"}"#).unwrap();
251/// assert_eq!(config, HandlerConfig::Booking { operation: BookingOperation::Book });
252/// assert_eq!(config.reads(), ["slot"]);
253/// ```
254#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
255#[serde(tag = "handler", rename_all = "snake_case")]
256#[non_exhaustive]
257pub enum HandlerConfig {
258    /// The forms handler.
259    Form,
260    /// The quotes handler.
261    Quote,
262    /// The orders handler.
263    Order {
264        /// What it does with the call.
265        operation: OrderOperation,
266    },
267    /// The payments handler.
268    Payment,
269    /// The bookings handler.
270    Booking {
271        /// What it does with the call.
272        operation: BookingOperation,
273    },
274    /// The search handler.
275    Search,
276    /// The listings handler.
277    Listing {
278        /// The content kind it lists.
279        content: ContentKind,
280    },
281    /// The application status handler.
282    Status,
283}
284
285impl HandlerConfig {
286    /// The handler's name, with its operation or content kind, such as `order/place`.
287    pub fn label(&self) -> String {
288        match self {
289            Self::Form => "form".into(),
290            Self::Quote => "quote".into(),
291            Self::Order { operation } => format!("order/{}", json_name(operation)),
292            Self::Payment => "payment".into(),
293            Self::Booking { operation } => format!("booking/{}", json_name(operation)),
294            Self::Search => "search".into(),
295            Self::Listing { content } => format!("listing/{}", json_name(content)),
296            Self::Status => "status".into(),
297        }
298    }
299
300    /// The least strict effect a capability this handler serves may declare: a handler that
301    /// writes never serves a capability declared read-only.
302    pub fn minimum_effect(&self) -> CapabilityEffect {
303        match self {
304            Self::Form | Self::Quote => CapabilityEffect::Idempotent,
305            Self::Order { operation: OrderOperation::Place | OrderOperation::Return }
306            | Self::Payment
307            | Self::Booking { operation: BookingOperation::Book } => {
308                CapabilityEffect::NonIdempotent
309            }
310            Self::Order { operation: OrderOperation::Status }
311            | Self::Booking { operation: BookingOperation::Availability }
312            | Self::Search
313            | Self::Listing { .. }
314            | Self::Status => CapabilityEffect::ReadOnly,
315        }
316    }
317
318    /// The input members the handler reads, which the capability's input schema must declare.
319    pub fn reads(&self) -> &'static [&'static str] {
320        match self {
321            Self::Quote => &["items"],
322            Self::Order { operation: OrderOperation::Place } => &["quoteId"],
323            Self::Order { operation: OrderOperation::Status | OrderOperation::Return } => {
324                &["orderId"]
325            }
326            Self::Booking { operation: BookingOperation::Book } => &["slot"],
327            Self::Search => &["query"],
328            Self::Status => &["reference"],
329            Self::Form
330            | Self::Payment
331            | Self::Booking { operation: BookingOperation::Availability }
332            | Self::Listing { .. } => &[],
333        }
334    }
335
336    /// The built-in capability whose name the shared handler dispatches on, when a pack's
337    /// capability of another name must reach it as that one: the order operations and
338    /// availability.
339    pub fn dispatches_as(&self) -> Option<&'static str> {
340        match self {
341            Self::Order { operation: OrderOperation::Place } => Some("place_order"),
342            Self::Order { operation: OrderOperation::Status } => Some("order_status"),
343            Self::Order { operation: OrderOperation::Return } => Some("request_return"),
344            Self::Booking { operation: BookingOperation::Availability } => {
345                Some("check_availability")
346            }
347            Self::Form
348            | Self::Quote
349            | Self::Payment
350            | Self::Booking { operation: BookingOperation::Book }
351            | Self::Search
352            | Self::Listing { .. }
353            | Self::Status => None,
354        }
355    }
356}
357
358/// A playbook a pack adds (spec 3.5 §7.15, §7.23): a skill file for a job's agents.
359#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
360#[serde(rename_all = "camelCase", deny_unknown_fields)]
361pub struct PackPlaybook {
362    /// The skill's name, which its front matter's `name` repeats.
363    pub id: String,
364    /// The job it changes how is done (spec 3.5 §7.20).
365    pub job: String,
366    /// The agents that use it; each runs the job.
367    pub agents: Vec<AgentRole>,
368    /// The skill file: YAML front matter with `name` and `description`, then the body.
369    pub text: String,
370}
371
372/// A driver manifest a pack ships (spec 3.5 §7.13, §7.23): the kernel's TOML manifest of an
373/// MCP server, mounted only by the owner (`adk-rust drivers mount`).
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375#[serde(rename_all = "camelCase", deny_unknown_fields)]
376pub struct PackDriver {
377    /// The driver's id, which the manifest's `id` repeats.
378    pub id: String,
379    /// The manifest, as `adk-rust drivers mount` reads it.
380    pub manifest: String,
381}
382
383/// A capability pack bundle (spec 3.5 §7.23).
384///
385/// # Example
386///
387/// ```rust
388/// use adk_awp::signing::jws::{DocumentSigner, Ed25519DocumentSigner};
389/// use adk_website::packs::bundle::{HandlerConfig, PackBundle, PackPublisher};
390/// use adk_website::packs::trust::{TrustList, TrustedKey};
391/// use awp_types::{CapabilityEffect, CapabilityV2, ContentKind};
392///
393/// # #[tokio::main(flavor = "current_thread")]
394/// # async fn main() {
395/// let key = Ed25519DocumentSigner::from_seed("tables-2026", [4; 32]).unwrap();
396/// let menu = CapabilityV2::new("list_menu", "Tonight's menu", CapabilityEffect::ReadOnly);
397/// let bundle = PackBundle::new("menu", "1.0.0", PackPublisher::new("tables.example"), "The menu")
398///     .capability(menu, HandlerConfig::Listing { content: ContentKind::Product });
399/// bundle.check().unwrap();
400/// let sealed = bundle.seal(&key).await.unwrap();
401///
402/// let trust = TrustList::new().with(TrustedKey::new("tables.example", "tables-2026", key.public_key()));
403/// let verified = PackBundle::verify(&sealed.to_json().unwrap(), &trust).unwrap();
404/// assert_eq!(verified.bundle.name, "menu");
405/// assert!(PackBundle::verify(&sealed.to_json().unwrap(), &TrustList::new()).is_err());
406/// # }
407/// ```
408#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
409#[serde(rename_all = "camelCase", deny_unknown_fields)]
410pub struct PackBundle {
411    /// The bundle format, [`PACK_FORMAT`].
412    pub format: String,
413    /// The pack's name: lowercase letters, digits and `-`.
414    pub name: String,
415    /// The pack's version (Semantic Versioning, no build metadata).
416    pub version: String,
417    /// Its publisher.
418    pub publisher: PackPublisher,
419    /// What it adds, for the person installing it.
420    pub description: String,
421    /// The capabilities it declares (spec 3.5 §7.4).
422    #[serde(default)]
423    pub capabilities: Vec<CapabilityV2>,
424    /// The handler serving each capability, by capability name.
425    #[serde(default)]
426    pub handlers: std::collections::BTreeMap<String, HandlerConfig>,
427    /// The playbooks it adds.
428    #[serde(default, skip_serializing_if = "Vec::is_empty")]
429    pub playbooks: Vec<PackPlaybook>,
430    /// The driver manifests it ships.
431    #[serde(default, skip_serializing_if = "Vec::is_empty")]
432    pub drivers: Vec<PackDriver>,
433    /// The content digest: SHA-256 of the JCS form without `digest` and `proof`.
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    pub digest: Option<Digest>,
436    /// The publisher's detached JWS over the JCS form without `proof`.
437    #[serde(default, skip_serializing_if = "Option::is_none")]
438    pub proof: Option<Proof>,
439}
440
441/// A bundle whose digest and publisher signature verified against a trust list, and whose
442/// content passed [`PackBundle::check`].
443#[derive(Debug, Clone, PartialEq)]
444pub struct VerifiedPack {
445    /// The bundle.
446    pub bundle: PackBundle,
447    /// Its content digest.
448    pub digest: Digest,
449    /// The publisher's key id.
450    pub kid: String,
451    /// The RFC 7638 thumbprint of the publisher's key.
452    pub thumbprint: String,
453}
454
455impl VerifiedPack {
456    /// The pack's version.
457    pub fn version(&self) -> semver::Version {
458        // `check` parsed it before the pack was verified.
459        semver::Version::parse(&self.bundle.version)
460            .unwrap_or_else(|_| semver::Version::new(0, 0, 0))
461    }
462}
463
464fn valid_slug(text: &str, max: usize, extra: &[u8]) -> bool {
465    let bytes = text.as_bytes();
466    !bytes.is_empty()
467        && bytes.len() <= max
468        && (bytes[0].is_ascii_lowercase() || bytes[0].is_ascii_digit())
469        && bytes.iter().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || extra.contains(b))
470}
471
472/// Whether `name` is a pack, playbook or driver name: 1–64 lowercase letters, digits and `-`,
473/// starting with a letter or digit.
474pub fn is_valid_pack_name(name: &str) -> bool {
475    valid_slug(name, 64, b"-")
476}
477
478/// Whether `id` is a publisher id: 1–128 lowercase letters, digits, `.` and `-`, starting with
479/// a letter or digit.
480pub fn is_valid_publisher_id(id: &str) -> bool {
481    valid_slug(id, 128, b".-")
482}
483
484fn strictness(effect: CapabilityEffect) -> u8 {
485    match effect {
486        CapabilityEffect::ReadOnly => 0,
487        CapabilityEffect::Idempotent => 1,
488        // `NonIdempotent`, and any effect a later release adds, is the strictest.
489        _ => 2,
490    }
491}
492
493/// The JSON name of an enum value, such as `non_idempotent`.
494fn json_name<T: Serialize + std::fmt::Debug>(value: &T) -> String {
495    match serde_json::to_value(value) {
496        Ok(Value::String(name)) => name,
497        _ => format!("{value:?}"),
498    }
499}
500
501/// The front matter's `name`, when the text opens with front matter holding a `name` and a
502/// `description`.
503fn front_matter_name(text: &str) -> Option<&str> {
504    let rest = text.strip_prefix("---\n")?;
505    let end = rest.find("\n---")?;
506    let header = &rest[..end];
507    if !header.lines().any(|line| line.starts_with("description:")) {
508        return None;
509    }
510    header.lines().find_map(|line| {
511        line.strip_prefix("name:").map(|value| value.trim().trim_matches('"').trim_matches('\''))
512    })
513}
514
515/// A handler that refuses every call: [`PackBundle::check`] compiles each declaration with it.
516struct Unserved;
517
518#[async_trait]
519impl CapabilityHandler for Unserved {
520    async fn handle(&self, _call: CapabilityCall) -> Result<Value, CapabilityError> {
521        Err(CapabilityError::Failed("not served".into()))
522    }
523}
524
525impl PackBundle {
526    /// An unsigned bundle with no content yet.
527    pub fn new(
528        name: impl Into<String>,
529        version: impl Into<String>,
530        publisher: PackPublisher,
531        description: impl Into<String>,
532    ) -> Self {
533        Self {
534            format: PACK_FORMAT.into(),
535            name: name.into(),
536            version: version.into(),
537            publisher,
538            description: description.into(),
539            capabilities: Vec::new(),
540            handlers: std::collections::BTreeMap::new(),
541            playbooks: Vec::new(),
542            drivers: Vec::new(),
543            digest: None,
544            proof: None,
545        }
546    }
547
548    /// Adds `declaration`, served by `handler`.
549    #[must_use]
550    pub fn capability(mut self, declaration: CapabilityV2, handler: HandlerConfig) -> Self {
551        self.handlers.insert(declaration.name.clone(), handler);
552        self.capabilities.push(declaration);
553        self
554    }
555
556    /// Adds `playbook`.
557    #[must_use]
558    pub fn playbook(mut self, playbook: PackPlaybook) -> Self {
559        self.playbooks.push(playbook);
560        self
561    }
562
563    /// Adds `driver`.
564    #[must_use]
565    pub fn driver(mut self, driver: PackDriver) -> Self {
566        self.drivers.push(driver);
567        self
568    }
569
570    /// The pack's version.
571    ///
572    /// # Errors
573    ///
574    /// [`PackError::Invalid`] when it is not a Semantic Version without build metadata.
575    pub fn semver(&self) -> Result<semver::Version, PackError> {
576        let version = semver::Version::parse(&self.version).map_err(|error| {
577            PackError::Invalid(format!(
578                "version `{}` is not a Semantic Version such as 1.2.0: {error}",
579                self.version
580            ))
581        })?;
582        if !version.build.is_empty() {
583            return Err(PackError::Invalid(format!(
584                "version `{}` carries build metadata, which orders no versions; drop the `+…`",
585                self.version
586            )));
587        }
588        Ok(version)
589    }
590
591    /// The content digest: the SHA-256 of the JCS form of the bundle without `digest` and
592    /// `proof`.
593    ///
594    /// # Errors
595    ///
596    /// [`PackError::Malformed`] when the bundle is not I-JSON.
597    pub fn content_digest(&self) -> Result<Digest, PackError> {
598        let value =
599            serde_json::to_value(self).map_err(|error| PackError::Malformed(error.to_string()))?;
600        content_digest(&value)
601    }
602
603    /// Seals the bundle: sets its content digest and signs it with the publisher's `signer`
604    /// (spec 3.5 §7.23, AWP 2.0 §5.4). Sealing judges nothing; [`check`](Self::check) does,
605    /// and installation refuses a sealed bundle that fails it.
606    ///
607    /// # Errors
608    ///
609    /// [`PackError::Malformed`] when the bundle is not I-JSON; [`PackError::Io`] when the key
610    /// cannot sign.
611    pub async fn seal(mut self, signer: &dyn DocumentSigner) -> Result<Self, PackError> {
612        self.digest = None;
613        self.proof = None;
614        self.digest = Some(self.content_digest()?);
615        let proof = sign(&self, signer).await.map_err(|error| PackError::Io(error.to_string()))?;
616        self.proof = Some(proof);
617        Ok(self)
618    }
619
620    /// The bundle as its file: pretty JSON ending in a newline.
621    ///
622    /// # Errors
623    ///
624    /// [`PackError::Malformed`] when the bundle is not I-JSON.
625    pub fn to_json(&self) -> Result<Vec<u8>, PackError> {
626        let mut bytes = serde_json::to_vec_pretty(self)
627            .map_err(|error| PackError::Malformed(error.to_string()))?;
628        bytes.push(b'\n');
629        Ok(bytes)
630    }
631
632    /// Reads a bundle file without verifying it.
633    ///
634    /// # Errors
635    ///
636    /// [`PackError::Malformed`] for a file over [`MAX_BUNDLE_BYTES`] or that is not a bundle;
637    /// [`PackError::Format`] for another format.
638    pub fn parse(bytes: &[u8]) -> Result<Self, PackError> {
639        Ok(Self::parse_value(bytes)?.0)
640    }
641
642    fn parse_value(bytes: &[u8]) -> Result<(Self, Value), PackError> {
643        if bytes.len() > MAX_BUNDLE_BYTES {
644            return Err(PackError::Malformed(format!(
645                "the file is {} bytes; a bundle is at most {MAX_BUNDLE_BYTES}",
646                bytes.len()
647            )));
648        }
649        let value: Value = serde_json::from_slice(bytes)
650            .map_err(|error| PackError::Malformed(format!("not JSON: {error}")))?;
651        if let Some(format) = value.get("format").and_then(Value::as_str)
652            && format != PACK_FORMAT
653        {
654            return Err(PackError::Format(format.to_string()));
655        }
656        let bundle: Self = serde_json::from_value(value.clone())
657            .map_err(|error| PackError::Malformed(error.to_string()))?;
658        Ok((bundle, value))
659    }
660
661    /// Verifies a bundle file against `trust` (spec 3.5 §7.23): it must carry a proof, its
662    /// content must match its digest, its publisher's key must be in `trust`, the proof must
663    /// verify with that key, and the content must pass [`check`](Self::check). The digest and
664    /// signature are checked over the file's own JSON, so nothing the publisher did not sign
665    /// is read.
666    ///
667    /// # Errors
668    ///
669    /// The [`PackError`] naming the first check that fails.
670    pub fn verify(bytes: &[u8], trust: &TrustList) -> Result<VerifiedPack, PackError> {
671        let (bundle, value) = Self::parse_value(bytes)?;
672        let Some(proof) = bundle.proof.clone() else {
673            return Err(PackError::Unsigned);
674        };
675        let Some(digest) = bundle.digest.clone() else {
676            return Err(PackError::Malformed(
677                "the bundle has a proof but no content digest".into(),
678            ));
679        };
680        let computed = content_digest(&value)?;
681        if computed != digest {
682            return Err(PackError::Tampered(format!(
683                "its content digest is {computed}, not the {digest} it names"
684            )));
685        }
686        let key = trust.key(&bundle.publisher.id, &proof.kid).ok_or_else(|| {
687            PackError::UnknownPublisher {
688                publisher: bundle.publisher.id.clone(),
689                kid: proof.kid.clone(),
690            }
691        })?;
692        verify(&value, &proof, key).map_err(|error| {
693            PackError::Tampered(format!(
694                "the signature does not verify with key `{}`: {error}",
695                proof.kid
696            ))
697        })?;
698        bundle.check()?;
699        Ok(VerifiedPack { thumbprint: jwk_thumbprint(key), kid: proof.kid, digest, bundle })
700    }
701
702    /// Checks the content against the format's rules (spec 3.5 §7.23): names and version;
703    /// every capability declared once, compiling, served by a handler whose effect it does not
704    /// understate and whose input it declares, asking for consent where it takes an email
705    /// (A-I8) under the site's policy version; every playbook a skill file for a job its
706    /// agents run, not one of the product's own; every driver manifest sandboxed, serving the
707    /// public or back-office partition, with an effect class for every tool. Neither the
708    /// signature nor the site's other packs are checked here.
709    ///
710    /// # Errors
711    ///
712    /// [`PackError::Format`], [`PackError::Invalid`] or, for a playbook the product holds,
713    /// [`PackError::Conflict`], naming the first rule broken.
714    pub fn check(&self) -> Result<(), PackError> {
715        let invalid = |reason: String| Err(PackError::Invalid(reason));
716        if self.format != PACK_FORMAT {
717            return Err(PackError::Format(self.format.clone()));
718        }
719        if !is_valid_pack_name(&self.name) {
720            return invalid(format!(
721                "name `{}` is not 1–64 lowercase letters, digits and `-`",
722                self.name
723            ));
724        }
725        self.semver()?;
726        if !is_valid_publisher_id(&self.publisher.id) {
727            return invalid(format!(
728                "publisher `{}` is not 1–128 lowercase letters, digits, `.` and `-`",
729                self.publisher.id
730            ));
731        }
732        let description = self.description.trim();
733        if description.is_empty() || description.chars().count() > MAX_DESCRIPTION_CHARS {
734            return invalid(format!(
735                "the description must say what the pack adds, in at most {MAX_DESCRIPTION_CHARS} characters"
736            ));
737        }
738        if self.capabilities.is_empty() && self.playbooks.is_empty() && self.drivers.is_empty() {
739            return invalid("the pack adds no capability, playbook or driver".into());
740        }
741        if self.capabilities.len() > MAX_CAPABILITIES
742            || self.playbooks.len() > MAX_PLAYBOOKS
743            || self.drivers.len() > MAX_DRIVERS
744        {
745            return invalid(format!(
746                "a pack holds at most {MAX_CAPABILITIES} capabilities, {MAX_PLAYBOOKS} playbooks and {MAX_DRIVERS} drivers"
747            ));
748        }
749        self.check_capabilities()?;
750        self.check_playbooks()?;
751        self.check_drivers()
752    }
753
754    fn check_capabilities(&self) -> Result<(), PackError> {
755        let invalid = |reason: String| Err(PackError::Invalid(reason));
756        let mut names = BTreeSet::new();
757        for declaration in &self.capabilities {
758            let name = declaration.name.as_str();
759            if !names.insert(name) {
760                return invalid(format!("capability `{name}` is declared twice"));
761            }
762            CapabilityTool::new("pack.invalid", declaration.clone(), Arc::new(Unserved))
763                .map_err(|error| PackError::Invalid(format!("capability `{name}`: {error}")))?;
764            let Some(handler) = self.handlers.get(name) else {
765                return invalid(format!(
766                    "capability `{name}` names no handler; add it to `handlers`"
767                ));
768            };
769            let least = handler.minimum_effect();
770            if strictness(declaration.effect) < strictness(least) {
771                return invalid(format!(
772                    "capability `{name}` is declared `{}`, but the `{}` handler's calls are at \
773                     least `{}`; declare the effect the handler has",
774                    json_name(&declaration.effect),
775                    handler.label(),
776                    json_name(&least)
777                ));
778            }
779            let properties = declaration
780                .input_schema
781                .as_ref()
782                .and_then(|schema| schema.get("properties"))
783                .and_then(Value::as_object);
784            for member in handler.reads() {
785                if !properties.is_some_and(|properties| properties.contains_key(*member)) {
786                    return invalid(format!(
787                        "capability `{name}`'s input schema declares no `{member}`, which the \
788                         `{}` handler reads",
789                        handler.label()
790                    ));
791                }
792            }
793            if properties.is_some_and(|properties| properties.contains_key("email"))
794                && declaration.consent.is_none()
795            {
796                return invalid(format!(
797                    "capability `{name}` takes an email address without asking for consent; \
798                     declare `consent` (spec 3.5 A-I8)"
799                ));
800            }
801            if let Some(consent) = &declaration.consent
802                && consent.policy_version != super::POLICY_VERSION
803            {
804                return invalid(format!(
805                    "capability `{name}`'s consent names policy version `{}`; the site's \
806                     policy, its public terms, is version `{}`",
807                    consent.policy_version,
808                    super::POLICY_VERSION
809                ));
810            }
811        }
812        if let Some(stray) = self.handlers.keys().find(|name| !names.contains(name.as_str())) {
813            return invalid(format!("handler for `{stray}`, which the pack does not declare"));
814        }
815        Ok(())
816    }
817
818    fn check_playbooks(&self) -> Result<(), PackError> {
819        let invalid = |reason: String| Err(PackError::Invalid(reason));
820        let mut ids = BTreeSet::new();
821        for playbook in &self.playbooks {
822            let id = playbook.id.as_str();
823            if !is_valid_pack_name(id) {
824                return invalid(format!(
825                    "playbook `{id}` is not named with 1–64 lowercase letters, digits and `-`"
826                ));
827            }
828            if !ids.insert(id) {
829                return invalid(format!("playbook `{id}` appears twice"));
830            }
831            if crate::playbooks::playbook(id).is_some() {
832                return Err(PackError::Conflict(format!(
833                    "playbook `{id}` is the product's own; name the pack's playbook differently"
834                )));
835            }
836            if playbook.text.len() > MAX_PLAYBOOK_BYTES {
837                return invalid(format!("playbook `{id}` is over {MAX_PLAYBOOK_BYTES} bytes"));
838            }
839            if front_matter_name(&playbook.text) != Some(id) {
840                return invalid(format!(
841                    "playbook `{id}` must open with front matter naming it (`---\\nname: {id}\\n\
842                     description: …\\n---`)"
843                ));
844            }
845            let Some(job) = crate::jobs::job(&playbook.job) else {
846                return invalid(format!(
847                    "playbook `{id}` names job `{}`, which is not a job of spec 3.5 §7.20",
848                    playbook.job
849                ));
850            };
851            if playbook.agents.is_empty() {
852                return invalid(format!("playbook `{id}` names no agent"));
853            }
854            if let Some(agent) = playbook.agents.iter().find(|agent| !job.agents.contains(agent)) {
855                return invalid(format!(
856                    "playbook `{id}` is for {agent}, who does not run the `{}` job",
857                    job.id
858                ));
859            }
860        }
861        Ok(())
862    }
863
864    fn check_drivers(&self) -> Result<(), PackError> {
865        let invalid = |reason: String| Err(PackError::Invalid(reason));
866        let mut ids = BTreeSet::new();
867        for driver in &self.drivers {
868            let id = driver.id.as_str();
869            if !is_valid_pack_name(id) {
870                return invalid(format!(
871                    "driver `{id}` is not named with 1–64 lowercase letters, digits and `-`"
872                ));
873            }
874            if !ids.insert(id) {
875                return invalid(format!("driver `{id}` appears twice"));
876            }
877            let manifest = DriverManifest::from_toml(&driver.manifest)
878                .map_err(|error| PackError::Invalid(format!("driver `{id}`: {error}")))?;
879            if manifest.id != id {
880                return invalid(format!("driver `{id}`'s manifest is for `{}`", manifest.id));
881            }
882            if manifest.sandbox == DriverSandbox::Unsandboxed {
883                return invalid(format!(
884                    "driver `{id}` runs unsandboxed; a pack's drivers run in the OS sandbox or a \
885                     container"
886                ));
887            }
888            let partitions = [adk_drivers::PUBLIC_PARTITION, adk_drivers::BACK_OFFICE_PARTITION];
889            if manifest.partitions.is_empty()
890                || manifest.partitions.iter().any(|p| !partitions.contains(&p.as_str()))
891            {
892                return invalid(format!(
893                    "driver `{id}` must serve the `{}` or `{}` partition",
894                    partitions[0], partitions[1]
895                ));
896            }
897            if manifest.tools.is_empty() {
898                return invalid(format!("driver `{id}` lists no tools with their effect classes"));
899            }
900            if let Some((tool, _)) =
901                manifest.tools.iter().find(|(_, class)| **class == EffectClass::Other)
902            {
903                return invalid(format!(
904                    "driver `{id}`'s tool `{tool}` is classed `other`; declare its effect class"
905                ));
906            }
907        }
908        Ok(())
909    }
910}
911
912/// The SHA-256 of the JCS form of `value` without `digest` and `proof`.
913fn content_digest(value: &Value) -> Result<Digest, PackError> {
914    let mut content = value.clone();
915    if let Some(object) = content.as_object_mut() {
916        object.remove("digest");
917        object.remove("proof");
918    }
919    document_digest(&content).map_err(|error| PackError::Malformed(error.to_string()))
920}
921
922#[cfg(test)]
923mod tests {
924    use super::*;
925    use adk_awp::signing::jws::Ed25519DocumentSigner;
926    use awp_types::{ConsentRequirement, ConsentScope};
927    use serde_json::json;
928
929    use crate::packs::trust::TrustedKey;
930
931    fn key() -> Ed25519DocumentSigner {
932        Ed25519DocumentSigner::from_seed("tables-2026", [4; 32]).unwrap()
933    }
934
935    fn trust() -> TrustList {
936        TrustList::new().with(TrustedKey::new("tables.example", "tables-2026", key().public_key()))
937    }
938
939    fn waitlist() -> PackBundle {
940        let join = CapabilityV2 {
941            consent: Some(ConsentRequirement {
942                scope: ConsentScope::Custom("contact".into()),
943                policy_version: "1".into(),
944            }),
945            input_schema: Some(json!({
946                "type": "object",
947                "properties": { "email": { "type": "string", "maxLength": 254 }, "party": { "type": "integer" } },
948                "required": ["email"],
949                "additionalProperties": false
950            })),
951            ..CapabilityV2::new(
952                "join_waitlist",
953                "Join tonight's waiting list",
954                CapabilityEffect::NonIdempotent,
955            )
956        };
957        PackBundle::new(
958            "waitlist",
959            "1.0.0",
960            PackPublisher::new("tables.example").named("Tables"),
961            "A waiting list for fully booked evenings",
962        )
963        .capability(join, HandlerConfig::Form)
964        .playbook(PackPlaybook {
965            id: "waitlist-capture".into(),
966            job: "capture".into(),
967            agents: vec![AgentRole::Concierge],
968            text: "---\nname: waitlist-capture\ndescription: Offer the waiting list.\n---\n\nOffer it.\n".into(),
969        })
970        .driver(PackDriver {
971            id: "tables-pos".into(),
972            manifest: "id = \"tables-pos\"\ncommand = \"mcp-tables\"\npartitions = [\"back-office\"]\n\n[tools]\ntables_list = \"read\"\n".into(),
973        })
974    }
975
976    async fn sealed(bundle: PackBundle) -> Vec<u8> {
977        bundle.seal(&key()).await.unwrap().to_json().unwrap()
978    }
979
980    fn refused(bytes: &[u8]) -> String {
981        PackBundle::verify(bytes, &trust()).unwrap_err().code().to_string()
982    }
983
984    #[tokio::test]
985    async fn a_sealed_bundle_verifies_and_reports_its_publisher_key() {
986        let verified = PackBundle::verify(&sealed(waitlist()).await, &trust()).unwrap();
987        assert_eq!(verified.bundle.name, "waitlist");
988        assert_eq!(verified.kid, "tables-2026");
989        assert_eq!(verified.thumbprint, jwk_thumbprint(&key().public_key()));
990        assert_eq!(Some(verified.digest), verified.bundle.digest);
991    }
992
993    #[tokio::test]
994    async fn unsigned_unknown_and_tampered_bundles_are_refused() {
995        assert_eq!(refused(&waitlist().to_json().unwrap()), "unsigned");
996        let bytes = sealed(waitlist()).await;
997        assert_eq!(
998            PackBundle::verify(&bytes, &TrustList::new()).unwrap_err().code(),
999            "unknown_publisher"
1000        );
1001        let other = TrustList::new().with(TrustedKey::new(
1002            "tables.example",
1003            "tables-2027",
1004            key().public_key(),
1005        ));
1006        assert_eq!(PackBundle::verify(&bytes, &other).unwrap_err().code(), "unknown_publisher");
1007
1008        let mut value: Value = serde_json::from_slice(&bytes).unwrap();
1009        value["capabilities"][0]["effect"] = json!("read_only");
1010        assert_eq!(refused(&serde_json::to_vec(&value).unwrap()), "tampered");
1011
1012        // The digest made to match the change, the signature still covers the old one.
1013        let digest = content_digest(&value).unwrap();
1014        value["digest"] = json!(digest);
1015        assert_eq!(refused(&serde_json::to_vec(&value).unwrap()), "tampered");
1016
1017        // Another key under the trusted publisher's id.
1018        let thief = Ed25519DocumentSigner::from_seed("tables-2026", [5; 32]).unwrap();
1019        let forged = waitlist().seal(&thief).await.unwrap().to_json().unwrap();
1020        assert_eq!(refused(&forged), "tampered");
1021    }
1022
1023    #[tokio::test]
1024    async fn verification_reads_the_signed_json_not_a_reformatting() {
1025        let bytes = sealed(waitlist()).await;
1026        let value: Value = serde_json::from_slice(&bytes).unwrap();
1027        assert!(PackBundle::verify(&serde_json::to_vec(&value).unwrap(), &trust()).is_ok());
1028        let mut extra = value.clone();
1029        extra["capabilities"][0]["x-note"] = json!("added");
1030        assert_eq!(refused(&serde_json::to_vec(&extra).unwrap()), "tampered");
1031        let mut top = value;
1032        top["note"] = json!("added");
1033        assert_eq!(refused(&serde_json::to_vec(&top).unwrap()), "malformed");
1034        assert_eq!(refused(b"[1, 2"), "malformed");
1035        let mut later = serde_json::from_slice::<Value>(&bytes).unwrap();
1036        later["format"] = json!("adk-website.pack/2");
1037        assert_eq!(refused(&serde_json::to_vec(&later).unwrap()), "format");
1038    }
1039
1040    fn invalid(bundle: PackBundle) -> String {
1041        bundle.check().unwrap_err().to_string()
1042    }
1043
1044    #[test]
1045    fn handlers_must_fit_their_capabilities() {
1046        let mut weak = waitlist();
1047        weak.capabilities[0].effect = CapabilityEffect::ReadOnly;
1048        assert!(invalid(weak).contains("at least `idempotent`"));
1049
1050        let mut unhandled = waitlist();
1051        unhandled.handlers.clear();
1052        assert!(invalid(unhandled).contains("names no handler"));
1053
1054        let mut stray = waitlist();
1055        stray.handlers.insert("other_thing".into(), HandlerConfig::Search);
1056        assert!(invalid(stray).contains("does not declare"));
1057
1058        let booking =
1059            CapabilityV2::new("reserve_table", "Reserve", CapabilityEffect::NonIdempotent);
1060        let unread = waitlist()
1061            .capability(booking, HandlerConfig::Booking { operation: BookingOperation::Book });
1062        assert!(invalid(unread).contains("declares no `slot`"));
1063
1064        let mut no_consent = waitlist();
1065        no_consent.capabilities[0].consent = None;
1066        assert!(invalid(no_consent).contains("A-I8"));
1067
1068        let mut policy = waitlist();
1069        policy.capabilities[0].consent.as_mut().unwrap().policy_version = "7".into();
1070        assert!(invalid(policy).contains("policy version"));
1071
1072        let mut twice = waitlist();
1073        twice.capabilities.push(twice.capabilities[0].clone());
1074        assert!(invalid(twice).contains("declared twice"));
1075
1076        let mut bad_name = waitlist();
1077        bad_name.capabilities[0].name = "Join".into();
1078        bad_name.handlers = [("Join".to_string(), HandlerConfig::Form)].into();
1079        assert!(invalid(bad_name).contains("capability `Join`"));
1080    }
1081
1082    #[test]
1083    fn names_versions_and_publishers_are_checked() {
1084        let mut named = waitlist();
1085        named.name = "Wait List".into();
1086        assert!(invalid(named).contains("lowercase"));
1087        for version in ["1.0", "v1.0.0", "1.0.0+build.7"] {
1088            let mut versioned = waitlist();
1089            versioned.version = version.into();
1090            assert_eq!(versioned.check().unwrap_err().code(), "invalid", "{version}");
1091        }
1092        let mut publisher = waitlist();
1093        publisher.publisher.id = "Tables Ltd".into();
1094        assert!(invalid(publisher).contains("publisher"));
1095        let empty =
1096            PackBundle::new("empty", "1.0.0", PackPublisher::new("tables.example"), "Nothing");
1097        assert!(invalid(empty).contains("adds no"));
1098        let mut quiet = waitlist();
1099        quiet.description = " ".into();
1100        assert!(invalid(quiet).contains("description"));
1101    }
1102
1103    #[test]
1104    fn playbooks_are_skill_files_for_a_job_their_agents_run() {
1105        let with = |change: &dyn Fn(&mut PackPlaybook)| {
1106            let mut bundle = waitlist();
1107            change(&mut bundle.playbooks[0]);
1108            bundle.check().unwrap_err()
1109        };
1110        assert!(with(&|p| p.text = "Offer it.".into()).to_string().contains("front matter"));
1111        assert!(
1112            with(&|p| p.text = "---\nname: other\ndescription: x\n---\n".into())
1113                .to_string()
1114                .contains("front matter")
1115        );
1116        assert!(with(&|p| p.job = "world-domination".into()).to_string().contains("not a job"));
1117        assert!(
1118            with(&|p| p.agents = vec![AgentRole::Finance]).to_string().contains("does not run")
1119        );
1120        assert!(with(&|p| p.agents.clear()).to_string().contains("names no agent"));
1121        let product = with(&|p| {
1122            p.id = "sell".into();
1123            p.text = "---\nname: sell\ndescription: x\n---\n".into();
1124        });
1125        assert_eq!(product.code(), "conflict");
1126    }
1127
1128    #[test]
1129    fn drivers_are_sandboxed_and_declare_every_effect() {
1130        let with = |manifest: &str| {
1131            let mut bundle = waitlist();
1132            bundle.drivers[0].manifest = manifest.into();
1133            bundle.check().unwrap_err().to_string()
1134        };
1135        let base =
1136            "id = \"tables-pos\"\ncommand = \"mcp-tables\"\npartitions = [\"back-office\"]\n";
1137        assert!(
1138            with(&format!("{base}sandbox = \"unsandboxed\"\n[tools]\ntables_list = \"read\"\n"))
1139                .contains("unsandboxed")
1140        );
1141        assert!(
1142            with(&format!("{base}[tools]\ntables_list = \"other\"\n")).contains("classed `other`")
1143        );
1144        assert!(with(base).contains("lists no tools"));
1145        assert!(
1146            with("id = \"tables-pos\"\ncommand = \"mcp-tables\"\n[tools]\nx = \"read\"\n")
1147                .contains("partition")
1148        );
1149        assert!(with("id = \"till\"\ncommand = \"mcp-tables\"\npartitions = [\"public\"]\n[tools]\nx = \"read\"\n").contains("is for `till`"));
1150        assert!(with("not toml at all = = =").contains("driver `tables-pos`"));
1151    }
1152
1153    #[test]
1154    fn handler_configuration_reads_as_json() {
1155        for (text, config) in [
1156            (r#"{"handler":"form"}"#, HandlerConfig::Form),
1157            (
1158                r#"{"handler":"order","operation":"return"}"#,
1159                HandlerConfig::Order { operation: OrderOperation::Return },
1160            ),
1161            (
1162                r#"{"handler":"listing","content":"notice"}"#,
1163                HandlerConfig::Listing { content: ContentKind::Notice },
1164            ),
1165        ] {
1166            assert_eq!(serde_json::from_str::<HandlerConfig>(text).unwrap(), config);
1167            assert_eq!(serde_json::to_string(&config).unwrap(), text);
1168        }
1169        assert_eq!(HandlerConfig::Listing { content: ContentKind::Event }.label(), "listing/event");
1170        assert!(serde_json::from_str::<HandlerConfig>(r#"{"handler":"shell"}"#).is_err());
1171    }
1172
1173    #[test]
1174    fn refusals_map_to_adk_errors() {
1175        let error: AdkError = PackError::Unsigned.into();
1176        assert_eq!(error.category, ErrorCategory::Forbidden);
1177        assert_eq!(error.code, "website.pack.unsigned");
1178    }
1179}