Skip to main content

Session

Struct Session 

Source
pub struct Session { /* private fields */ }
Expand description

One node, one optional operator key file and one output format: the context every stratum command runs in.

Each command method writes its results through Output and returns the process exit code on success (see exit); failures are returned as CliError, whose exit_code gives theirs. Every authenticated request is signed with NostrSecretKey::sign_request_with_nonce over the exact URL, method and body bytes sent, with a fresh random nonce and fresh auxiliary randomness.

§Examples

use stratum_node_cli::{CliError, Output, OutputFormat, Session};

let session = Session::new("http://127.0.0.1:7460".parse()?, None, Output::new(OutputFormat::Json));
// Commands that need the operator key say so before touching the network.
assert!(matches!(session.audit_checkpoint(), Err(CliError::MissingKeyFile)));

Implementations§

Source§

impl Session

Source

pub fn invite_create(&self, options: &InviteOptions) -> Result<u8, CliError>

stratum invite create <did> [--expires-in <duration>]: issues an invitation for one identity and prints its identifier, subject, expiry, the canonical origin and node DID, and the stratum join command line the invitee runs. Signed by the administrator.

Without --expires-in the lifetime is the node’s configured membership.invitation_ttl_secs, read from the effective configuration. The response must name the requested subject and the node /readyz reported.

§Errors

CliError::Usage for a lifetime over 30 days or under one second, CliError::Refused when the response names another subject or node, and key, transport, protocol and server errors (invitations_disabled among them).

Source

pub fn invite_list(&self) -> Result<u8, CliError>

stratum invite list: lists invitations with their state. Signed.

§Errors

Key, transport, protocol and server errors.

Source

pub fn invite_revoke( &self, invitation: &InvitationId, operation_id_arg: Option<&str>, ) -> Result<u8, CliError>

stratum invite revoke <invitation>: revokes an invitation that is still issued. Signed.

§Errors

CliError::Refused when the response names another invitation or state, and key, transport, protocol and server errors.

Source

pub fn member_list(&self) -> Result<u8, CliError>

stratum member list: lists members with their state, pod URL and the last provisioning error, and the capacity in use. Signed.

§Errors

Key, transport, protocol and server errors.

Source

pub fn member_repair( &self, member: &DidNostr, operation_id_arg: Option<&str>, confirmation: Confirmation, ) -> Result<u8, CliError>

stratum member repair <did> [--yes]: runs provisioning again for a member, which restores a missing root ACL and leaves an existing one alone. Asks first. Signed.

§Errors

CliError::NotConfirmed, CliError::Refused when the response names another member, and key, transport, protocol and server errors.

Source

pub fn member_cancel( &self, member: &DidNostr, operation_id_arg: Option<&str>, confirmation: Confirmation, ) -> Result<u8, CliError>

stratum member cancel <did> [--yes]: cancels a reserved member, releasing its slot; the invitation stays used. Asks first. Signed.

§Errors

CliError::NotConfirmed, CliError::Refused when the response names another member or a state other than cancelled, and key, transport, protocol and server errors.

Source§

impl Session

Source

pub fn export( &self, target: &GateTarget, options: &ExportOptions, ) -> Result<u8, CliError>

stratum export -o <archive.tar.zst> [--force]: walks the caller’s own pod over signed requests and writes it as a tar archive compressed with zstd, with a manifest beside it.

The walk starts at the pod root /pods/<pk>/ and fetches the root ACL /pods/<pk>.acl. Each child a listing names under ldp:contains is resolved against the listing’s own address and followed only if the result is on the canonical origin, parses as a pod path under the Step 2 rules, is in the caller’s own pod and lies under the container listed; anything else is skipped and reported. Redirects are never followed. For every container and resource the ACL beside it is asked for (a 404 means none). No entry is fetched twice.

The archive holds pods/<pk>/… (containers as directories) and pods/<pk>.acl, so it unpacks to the bytes that were written. The manifest, <archive>.manifest.json, lists every entry’s path, kind, size, SHA-256 and content type, which ACLs exist, the archive’s own size and SHA-256, and what was skipped. The export is not a snapshot: after the walk each resource’s entity tag and each container’s listing is asked for again, and entries that changed or vanished are reported. The walk stops with an error at 100,000 entries or 64 GiB.

Both files are written under temporary names in the target directory (mode 0600) and moved into place only once complete, the archive first and the manifest last. A manifest present beside the archive therefore always describes that archive; an archive with no manifest is an export that did not finish and should not be trusted. Without force, nothing is ever replaced, including a file that appears at either name while the export runs: the export fails instead, and an archive it had already placed is withdrawn. With force, the old manifest is set aside before the archive is replaced, and put back if the archive cannot be moved; the limit is that a failure or crash between the two moves leaves the new (or old) archive with no manifest, never with a mismatched one. Concurrent forced exports to the same name are not coordinated.

§Errors

CliError::Local when a target exists without force (checked before the walk and again when the files are placed), a limit is reached or a file cannot be written; CliError::ExportIncomplete (after both files are written) when anything changed, vanished or was skipped; and key, transport and server errors.

Source§

impl Session

Source

pub fn join( &self, target: &GateTarget, options: &JoinOptions, ) -> Result<u8, CliError>

stratum join --invitation <id> --node <did> --origin … [--connect …]: redeems an invitation with the caller’s key and activates the pod.

The flow:

  1. Fetch the admission notice. The node DID it reports must be JoinOptions::node, its origin the canonical origin, and the SHA-256 of the notice text received must equal both the hash the node reports and the hash of the notice this client was built with (admission_notice_v1_sha256).
  2. Ask for the caller’s own operation. A caller who is already a member (reserved, provisioned or active) continues from where an earlier run stopped, without redeeming again.
  3. Otherwise show the notice and ask for confirmation (a terminal is required unless --yes), then redeem with the admission claim signed by the caller. If the connection fails after the request was sent, the identical signed request is resent once: the node returns the response it stored.
  4. Poll the operation until the member is provisioned, for at most JoinOptions::wait, showing the node’s last error when it reports one.
  5. Write a probe resource in the pod (create only), read it back and compare, and delete it.
  6. Confirm, and print the pod URL.

Every request is signed with a fresh event over the canonical URL; only the single resend reuses one. Every pod URL the node reports must be exactly <origin>/pods/<caller's key>/.

§Errors

CliError::Refused for a notice from another node or with another hash, a cancelled membership, a response naming another member or pod URL, or a probe that does not read back; CliError::NotConfirmed; CliError::TimedOut when provisioning does not finish in time (rerun join to continue); and key, transport and server errors (invitation_refused, invitations_disabled, capacity_exhausted, too_many_requests among them).

Source§

impl Session

Source

pub fn pod_ls(&self, target: &GateTarget, path: &str) -> Result<u8, CliError>

stratum pod ls [<path>]: lists a container in a pod. Signed by the caller’s key over the canonical URL.

path is relative to the caller’s own pod root (empty for the root itself) or absolute /pods/<pk>/…; a missing trailing / is added. Each listed child is resolved against the listing’s address and shown only if it lies under the container; anything else is reported as refused.

§Errors

CliError::Usage for a path the Step 2 rules refuse, and key, transport and server errors.

Source

pub fn pod_get( &self, target: &GateTarget, path: &str, output: Option<&Path>, ) -> Result<u8, CliError>

stratum pod get <path> [-o <file>]: reads a resource. Signed.

The body is written byte for byte to output, a new file created with mode 0600 (an existing file is never overwritten), or to standard output. On a terminal, control characters are escaped; in a pipe the bytes are written unchanged. Under --json an output file is required, and a report of the status, content type, entity tag, size and SHA-256 is printed.

§Errors

CliError::Usage for a refused path or --json without -o, CliError::File when the output file exists, and key, transport and server errors.

Source

pub fn pod_acl_get( &self, target: &GateTarget, path: &str, output: Option<&Path>, ) -> Result<u8, CliError>

stratum pod acl get <path> [-o <file>]: reads the ACL beside a resource or container, as pod_get does. For the pod root (an empty path) that is the root ACL /pods/<pk>.acl.

§Errors

As pod_get; CliError::Usage when the path is itself an ACL.

Source

pub fn pod_put( &self, target: &GateTarget, options: &PutOptions, ) -> Result<u8, CliError>

stratum pod put <path> <file> [--content-type …] [--if-match <etag> | --create-only]: writes a resource. Signed over the body, which is read whole (at most 1 GiB) and sent with Content-Length.

§Errors

CliError::Usage for a refused path or a container path, CliError::FileContents for an unreadable or oversized file, precondition_failed when the condition does not hold, and key, transport and server errors.

Source

pub fn pod_acl_put( &self, target: &GateTarget, options: &PutOptions, ) -> Result<u8, CliError>

stratum pod acl put <path> <file>: writes the ACL beside a resource or container (the root ACL for the pod root), as pod_put does, with content type text/turtle unless another is given.

§Errors

As pod_put; CliError::Usage when the path is itself an ACL.

Source

pub fn pod_rm( &self, target: &GateTarget, path: &str, confirmation: Confirmation, ) -> Result<u8, CliError>

stratum pod rm <path> [--yes]: deletes a resource or an empty container after confirmation. Signed. The root ACL cannot be deleted: that would lock the owner out of their own pod.

§Errors

CliError::Usage for a refused path or the root ACL, CliError::NotConfirmed, and key, transport and server errors.

Source§

impl Session

Source

pub fn new(url: LoopbackUrl, key_file: Option<PathBuf>, output: Output) -> Self

Creates a session for the node at url, signing with the key in key_file when a command needs it.

Source

pub fn key_generate(&self, out: &Path) -> Result<u8, CliError>

stratum key generate --out <file>: creates a new operator key file and prints the operator’s DID and npub.

§Errors

CliError::KeyFile when the file exists or cannot be created.

Source

pub fn key_show(&self) -> Result<u8, CliError>

stratum key show: prints the DID and npub of the operator key.

§Errors

CliError::MissingKeyFile or CliError::KeyFile.

Source

pub fn status(&self) -> Result<u8, CliError>

stratum status: reads /readyz and returns exit::OK when the node is ready, exit::UNCONFIGURED or exit::DEGRADED.

§Errors

CliError::Unreachable (exit 2) or CliError::Protocol.

Source

pub fn config_schema(&self) -> Result<u8, CliError>

stratum config schema: prints the node’s configuration schema.

§Errors

Transport, protocol and server errors.

Source

pub fn config_show(&self) -> Result<u8, CliError>

stratum config show: prints the node’s effective configuration, revisions and public-config hash. Signed.

§Errors

Key, transport, protocol and server errors.

Source

pub fn config_preview( &self, sets: &[String], base_revision: Option<u64>, ) -> Result<u8, CliError>

stratum config preview --set path=value …: shows what the change would do, without changing anything. Signed when a key file is given (the node requires it once an administrator is bound).

§Errors

CliError::Usage for bad --set arguments, CliError::InvalidPreview when the result would be invalid, and key, transport, protocol and server errors.

Source

pub fn config_apply(&self, options: &ApplyOptions) -> Result<u8, CliError>

stratum config apply --set path=value …: previews the change, prints the diff and the strictest apply class, and after confirmation applies it on the same base revision. Signed.

The operation ID is printed before the apply request is sent, so a retry after a lost response can pass it with --operation-id.

§Errors

CliError::NotConfirmed when not confirmed, CliError::InvalidPreview, CliError::Usage, and key, transport, protocol and server errors (conflict for a stale base revision, invalid for a rejected configuration).

Source

pub fn audit_checkpoint(&self) -> Result<u8, CliError>

stratum audit checkpoint: prints the audit checkpoint <seq>:<hex> and the node DID. Keep the checkpoint somewhere the node cannot write: it is what truncation of the audit log is detected against. Signed.

§Errors

Key, transport, protocol and server errors.

Source

pub fn backup( &self, operation_id_arg: Option<&str>, expect_node: Option<&DidNostr>, ) -> Result<u8, CliError>

stratum backup [--expect-node <did>]: asks the node for a backup and prints its directory, checkpoint and configuration revision. Signed.

Before anything is printed, the returned manifest event must verify (ID and signature), be of kind 30078 and be authored by the node DID reported by /readyz; its content must be a stratum-backup version 1 manifest naming that node and listing the three backup files in order; and its signed audit_checkpoint must equal the response’s checkpoint. Every printed fact except the backup directory therefore comes from the signed manifest; the directory is the node’s unsigned statement of where it wrote the files. When expect_node is given, /readyz must report it before any request is signed.

§Errors

CliError::Refused for a manifest that fails verification or a node other than expect_node, backup_refused when the node has no backup recipient, and key, transport, protocol and server errors.

Source

pub fn sign_challenge( &self, claim_body_file: &Path, expect_node: &DidNostr, ) -> Result<u8, CliError>

stratum sign-challenge --claim-body-file <file> --expect-node <did>: signs a claim body offline and prints the Authorization header value for it. No network.

Before signing, the body must name this key as claimant and expect_node as the node, and must not have expired. The expected node comes from the operator (stratumd prints its node DID at start), never from the file, so a substituted claim file for another node is refused. The configuration hash and base revision in the body cannot be checked offline: they are signed as the node issued them. stratum setup checks them against its own derivation; prefer it when the node is reachable.

The URL is the session URL: a bare origin gets /api/v1/bootstrap/claim appended, and a URL with a path must end in exactly that path, so no other route can be signed. It must equal the url the challenge response named. The file’s bytes are signed exactly as they are, so a trailing newline added by an editor makes the signature fail at the node; a warning is printed if one is present.

§Errors

CliError::Usage for a URL with another path, CliError::Refused when the body names another claimant or node or has expired, CliError::FileContents when it is not a claim body, and key and file errors.

Source§

impl Session

Source

pub fn setup(&self, options: &SetupOptions) -> Result<u8, CliError>

stratum setup --token-file <path> [--set path=value …]: claims an unconfigured node for the operator key and commits the initial configuration. With no --set, the node is claimed with its seed configuration unchanged.

The flow:

  1. Read the bootstrap token and /readyz, which must report unconfigured at revision 0, and take the node DID from it. With SetupOptions::expect_node, that DID must be the expected one, or setup stops before anything else is sent.
  2. Derive the initial configuration locally: the seed text of stratum-node-config (the text of revision 0) with the changes applied. Preview the same changes on the node; its text and diff must equal the local ones byte for byte. Show the local diff and change list (and with SetupOptions::show_text the whole text); stop if the result is invalid.
  3. Request a challenge for this key’s DID and the same changes.
  4. Check the returned claim body locally: it must name this claimant and the node from /readyz, must not have expired, must answer the challenge ID and base revision, its config_sha256 must be the SHA-256 of the locally derived text (so the hash covers exactly the text shown), and the claim URL must be this client’s own /api/v1/bootstrap/claim URL with method POST.
  5. Show the claim fields and ask for confirmation (or --yes).
  6. Sign the body verbatim, save the signed request with the token to the resume file (0600, created exclusively), then send it with the token in Stratum-Bootstrap-Token.
  7. Check that the response names this administrator and node, print the administrator DID, revision and public-config hash, and delete the resume file.

If a resume file exists, steps 1 to 6 are skipped and the saved request is resent byte for byte, so that a node which committed the claim but lost the response returns its stored result. With SetupOptions::expect_node, the saved body must name that node and /readyz must report it before the saved request is resent. The resume file is kept after a transport failure, a protocol error or a 5xx response, and deleted after success or any 4xx, which the identical request can never turn into a success.

§Errors

CliError::Refused for any failed local check (including a node other than the expected one, or a node preview that differs from the local derivation), CliError::NotConfirmed, CliError::InvalidPreview, token, key and resume-file errors, and transport, protocol and server errors.

Trait Implementations§

Source§

impl Clone for Session

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Session

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Forget for Session

§

impl Freeze for Session
where *const u8 is !null: Freeze, PhantomData<u8>: Freeze,

§

impl Move for Session

§

impl RefUnwindSafe for Session

§

impl Send for Session
where RawVecInner: Send,

§

impl Sync for Session
where RawVecInner: Sync,

§

impl Unpin for Session
where *const u8 is !null: Unpin,

§

impl UnsafeUnpin for Session

§

impl UnwindSafe for Session
where RawVecInner: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.