haps 0.1.12

Hashtree Package System: signed packages, content-addressed distribution, social discovery
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
use crate::{
    model::*,
    store::{VerifiedStore, download},
    transport::CatalogTransport,
};
use anyhow::{Context, Result, bail, ensure};
use hashtree_core::Cid;
use hashtree_index::{SearchIndex, SearchIndexOptions, SearchOptions};
use nostr::{Event, Keys};
use serde::{Deserialize, Serialize};
use std::{
    collections::{BTreeMap, BTreeSet},
    fs,
    path::{Path, PathBuf},
    sync::Arc,
    time::Duration,
};

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct CatalogRoot {
    pub schema: String,
    pub sequence: u64,
    pub root: String,
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Catalog {
    pub releases: Vec<String>,
    pub search: Option<String>,
    #[serde(default)]
    pub packages: BTreeMap<String, String>,
}

pub struct Snapshot {
    pub event: Event,
    pub head: CatalogRoot,
    pub catalog: Catalog,
}

pub struct Repository {
    location: Location,
    pub store: Arc<VerifiedStore>,
}

enum Location {
    Local(PathBuf),
    Http(reqwest::Url),
    Hashtree(Arc<CatalogTransport>),
}

impl Repository {
    pub fn local(path: PathBuf) -> Result<Self> {
        let store = VerifiedStore::new(&path.join("blobs"), None)?;
        Ok(Self {
            location: Location::Local(path),
            store,
        })
    }
    pub fn open(location: &str, cache: &Path) -> Result<Self> {
        if location.starts_with("htree://") {
            return Self::from_transport(Arc::new(CatalogTransport::new(location, cache)?), cache);
        }
        if location.starts_with("http://") || location.starts_with("https://") {
            let mut url = reqwest::Url::parse(location)?;
            ensure!(
                url.username().is_empty()
                    && url.password().is_none()
                    && url.query().is_none()
                    && url.fragment().is_none(),
                "repository URL cannot contain credentials, query, or fragment"
            );
            if !url.path().ends_with('/') {
                url.set_path(&format!("{}/", url.path()));
            }
            let store = VerifiedStore::new(cache, Some(url.clone()))?;
            Ok(Self {
                location: Location::Http(url),
                store,
            })
        } else {
            let path = Path::new(location)
                .canonicalize()
                .context("repository does not exist")?;
            Self::local(path)
        }
    }
    pub fn hashtree(
        location: &str,
        cache: &Path,
        config: hashtree_client::ClientConfig,
    ) -> Result<Self> {
        let transport = Arc::new(CatalogTransport::with_config(location, cache, config)?);
        Self::from_transport(transport, cache)
    }
    fn from_transport(transport: Arc<CatalogTransport>, cache: &Path) -> Result<Self> {
        Ok(Self {
            store: VerifiedStore::hashtree(cache, transport.clone())?,
            location: Location::Hashtree(transport),
        })
    }
    pub fn path(&self) -> Option<&Path> {
        match &self.location {
            Location::Local(p) => Some(p),
            _ => None,
        }
    }
    pub async fn catalog(&self, author: &str) -> Result<Snapshot> {
        let event: Event = self.metadata("catalog.json").await?;
        self.verify_catalog(event, author).await
    }
    /// Read bounded metadata from the same immutable directory as its blocks.
    pub async fn metadata<T: serde::de::DeserializeOwned>(&self, name: &str) -> Result<T> {
        safe_path(name)?;
        Ok(match &self.location {
            Location::Local(path) => read_json(&path.join(name))?,
            Location::Hashtree(transport) => {
                serde_json::from_slice(&transport.read(name, MAX_METADATA).await?)?
            }
            Location::Http(url) => {
                let client = reqwest::Client::builder()
                    .timeout(Duration::from_secs(30))
                    .redirect(reqwest::redirect::Policy::none())
                    .build()?;
                serde_json::from_slice(&download(&client, url.join(name)?, MAX_METADATA).await?)?
            }
        })
    }
    async fn verify_catalog(&self, event: Event, author: &str) -> Result<Snapshot> {
        verify_event(&event)?;
        ensure!(
            event.pubkey.to_hex() == author,
            "catalog publisher does not match pinned public key"
        );
        ensure!(
            tag_value(&event, "d")? == "haps/catalog/v1",
            "not a Haps catalog"
        );
        let head: CatalogRoot = serde_json::from_str(&event.content)?;
        ensure!(
            head.schema == "haps.catalog.v1",
            "unsupported catalog schema"
        );
        let catalog: Catalog = self.json(&head.root).await?;
        ensure!(catalog.releases.len() <= 10_000, "catalog is too large");
        Ok(Snapshot {
            event,
            head,
            catalog,
        })
    }
    pub async fn json<T: serde::de::DeserializeOwned>(&self, cid: &str) -> Result<T> {
        let bytes = self
            .store
            .tree()
            .get(&Cid::parse(cid)?, Some(MAX_METADATA as u64))
            .await?
            .context("metadata block unavailable")?;
        Ok(serde_json::from_slice(&bytes)?)
    }
    pub async fn put_json(&self, value: &impl Serialize) -> Result<String> {
        let bytes = serde_json::to_vec(value)?;
        ensure!(bytes.len() <= MAX_METADATA, "metadata is too large");
        Ok(self.store.tree().put(&bytes).await?.0.to_string())
    }
    pub async fn releases(&self, snapshot: &Snapshot) -> Result<Vec<Release>> {
        let mut results = Vec::new();
        let mut coordinates = BTreeSet::new();
        for cid in &snapshot.catalog.releases {
            let release = Release::verify(self.json(cid).await?)?;
            ensure!(
                coordinates.insert(release.coordinate()),
                "duplicate release coordinate in catalog"
            );
            results.push(release);
        }
        Ok(results)
    }
    pub async fn search(&self, snapshot: &Snapshot, query: &str) -> Result<Vec<Release>> {
        let index = SearchIndex::new(self.store.clone(), SearchIndexOptions::default());
        let root = snapshot
            .catalog
            .search
            .as_deref()
            .map(Cid::parse)
            .transpose()?;
        let results = index
            .search(
                root.as_ref(),
                "",
                query,
                SearchOptions {
                    limit: Some(100),
                    full_match: false,
                },
            )
            .await?;
        let allowed: BTreeSet<_> = snapshot.catalog.releases.iter().collect();
        let mut releases = Vec::new();
        for result in results {
            ensure!(
                allowed.contains(&result.value),
                "search index references a release outside its catalog"
            );
            let release = Release::verify(self.json(&result.value).await?)?;
            ensure!(
                result.id == release.coordinate(),
                "search identity mismatch"
            );
            releases.push(release);
        }
        Ok(releases)
    }
    /// Write a shareable repository. This does not upload or announce anything.
    pub async fn publish(&self, keys: &Keys, spec: PackageSpec, payload: &Path) -> Result<Release> {
        self.publish_inner(keys, spec, payload, false).await
    }

    /// A release flow may retry only when the entire package is byte-identical.
    pub async fn publish_reusable(
        &self,
        keys: &Keys,
        spec: PackageSpec,
        payload: &Path,
    ) -> Result<Release> {
        self.publish_inner(keys, spec, payload, true).await
    }

    async fn publish_inner(
        &self,
        keys: &Keys,
        spec: PackageSpec,
        payload: &Path,
        reuse: bool,
    ) -> Result<Release> {
        spec.validate()?;
        let path = self
            .path()
            .context("publish requires a local output directory")?;
        let _guard = lock(&path.join(".publish.lock"))?;
        let mut catalog = Catalog::default();
        let mut sequence = 1;
        let mut existing = None;
        if path.join("catalog.json").exists() {
            let previous = self.catalog(&keys.public_key().to_hex()).await?;
            for release in self.releases(&previous).await? {
                if release.author() == keys.public_key().to_hex()
                    && release.data.package.name == spec.name
                    && release.data.package.version == spec.version
                    && release.data.package.target == spec.target
                {
                    ensure!(reuse, "release already exists; publish a new version");
                    existing = Some(release);
                }
            }
            sequence = previous
                .head
                .sequence
                .checked_add(1)
                .context("catalog sequence overflow")?;
            catalog = previous.catalog;
        }
        ensure!(catalog.releases.len() < 10_000, "catalog is full");
        let manifest = self.pack_payload(&spec, payload).await?;
        let data = ReleaseData {
            schema: "haps.release.v1".into(),
            package: spec.clone(),
            manifest,
        };
        if let Some(existing) = existing {
            ensure!(
                existing.data.package == data.package && existing.data.manifest == data.manifest,
                "immutable release differs from its existing package; publish a new version"
            );
            return Ok(existing);
        }
        let event = sign(keys, &release_tag(&spec), &data)?;
        let release = Release::verify(event.clone())?;
        let cid = self.put_json(&event).await?;
        let card = sign(
            keys,
            &format!("haps/package/{}", spec.name),
            &serde_json::json!({
                "schema": "haps.package.v1", "name": spec.name, "description": spec.description,
            }),
        )?;
        catalog
            .packages
            .insert(release.identity(), self.put_json(&card).await?);
        let index = SearchIndex::new(self.store.clone(), SearchIndexOptions::default());
        let terms = index.parse_keywords(&format!("{} {}", spec.name, spec.description));
        let terms = if terms.is_empty() {
            vec![spec.name.clone()]
        } else {
            terms
        };
        let previous = catalog.search.as_deref().map(Cid::parse).transpose()?;
        catalog.search = Some(
            index
                .index(previous.as_ref(), "", &terms, &release.coordinate(), &cid)
                .await?
                .to_string(),
        );
        catalog.releases.push(cid);
        let head = CatalogRoot {
            schema: "haps.catalog.v1".into(),
            sequence,
            root: self.put_json(&catalog).await?,
        };
        let event = sign(keys, "haps/catalog/v1", &head)?;
        atomic_write(
            &path.join("catalog.json"),
            &serde_json::to_vec_pretty(&event)?,
        )?;
        Ok(release)
    }
    /// Validate and address a payload without creating any signed event.
    pub async fn pack_payload(&self, spec: &PackageSpec, payload: &Path) -> Result<String> {
        spec.validate()?;
        let payload = payload
            .canonicalize()
            .context("payload directory is missing")?;
        ensure!(payload.is_dir(), "payload must be a directory");
        let repo_path = self
            .path()
            .context("packing requires a local directory")?
            .canonicalize()?;
        ensure!(
            !repo_path.starts_with(&payload),
            "output repository must be outside payload"
        );
        let mut files = Vec::new();
        let mut total = 0u64;
        let tree = self.store.tree();
        let mut overrides = ignore::overrides::OverrideBuilder::new(&payload);
        for pattern in [
            "!**/.git",
            "!**/.DS_Store",
            "!**/._*",
            "!**/Thumbs.db",
            "!**/desktop.ini",
            "!**/__MACOSX",
            "!/node_modules",
            "!/target",
            "!/.venv",
            "!/venv",
            "!/__pycache__",
            "!/.pytest_cache",
            "!/.mypy_cache",
            "!/.ruff_cache",
            "!/.cache",
            "!/.env",
            "!/.env.local",
            "!/.env.*.local",
        ] {
            overrides.add(pattern)?;
        }
        let entries = ignore::WalkBuilder::new(&payload)
            .hidden(false)
            .parents(false)
            .git_global(false)
            .git_exclude(false)
            .require_git(false)
            .follow_links(false)
            .overrides(overrides.build()?)
            .sort_by_file_name(|a, b| a.cmp(b))
            .build();
        for entry in entries {
            let entry = entry?;
            if let Some(error) = entry.error() {
                bail!("cannot apply payload ignore rules: {error}");
            }
            if entry.file_type().is_some_and(|t| t.is_dir()) {
                continue;
            }
            // Never silently rewrite a signed application's filesystem layout.
            let source = if entry.file_type().is_some_and(|t| t.is_file()) {
                entry.path().to_path_buf()
            } else {
                bail!(
                    "symlinks and special files are not yet supported; payload must contain regular files"
                );
            };
            let relative = entry
                .path()
                .strip_prefix(&payload)?
                .to_str()
                .context("non-UTF8 package path")?;
            #[cfg(windows)]
            let relative = relative.replace('\\', "/");
            #[cfg(not(windows))]
            let relative = relative.to_string();
            safe_path(&relative)?;
            let metadata = fs::metadata(&source)?;
            total = total.checked_add(metadata.len()).context("size overflow")?;
            ensure!(
                total <= MAX_PACKAGE_BYTES && files.len() < MAX_FILES,
                "package exceeds size or file limit"
            );
            #[cfg(unix)]
            let executable = {
                use std::os::unix::fs::PermissionsExt;
                metadata.permissions().mode() & 0o111 != 0
            };
            #[cfg(not(unix))]
            let executable = false;
            let executable = executable || spec.commands.values().any(|p| p == &relative);
            let (cid, size) = tree
                .put_stream(futures::io::AllowStdIo::new(fs::File::open(&source)?))
                .await?;
            ensure!(size == metadata.len(), "payload changed while being packed");
            files.push(PackageFile {
                path: relative,
                cid: cid.to_string(),
                size,
                executable,
            });
        }
        let manifest = Manifest {
            schema: "haps.files.v1".into(),
            files,
        };
        manifest.validate(spec)?;
        self.put_json(&manifest).await
    }
}