### Getting Started with Pubky SDK Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Complete example showing how to initialize the SDK, create a signer, sign up, sign in, and perform public storage operations. ```javascript import { Pubky, PublicKey, Keypair, AuthFlowKind } from "@synonymdev/pubky"; // Initiate a Pubky SDK facade wired for default mainnet Pkarr relays. const pubky = new Pubky(); // or: const pubky = Pubky.testnet(); for localhost testnet. // 1) Create random user keys and bind to a new Signer. const keypair = Keypair.random(); const signer = pubky.signer(keypair); // 2) Sign up at a homeserver (optionally with an invite) const homeserver = PublicKey.from( "8pinxxgqs41n4aididenw5apqp1urfmzdztr8jt4abrkdn435ewo" ); const signupToken = ""; await signer.signup(homeserver, signupToken); // 3a) Signin with the signer directly. let session = await signer.signin("example.com"); // 3b) Or, if you do not have the keypair available, authenticate on a 3rd-party app // by delegating the authentication to a signer with a QR code. const authFlow = await pubky.startGrantAuthFlow( "/pub/my-cool-app/:rw", AuthFlowKind.signin(), { clientId: "my-cool-app.example" }, ); renderQr(authFlow.authorizationUrl); // Show to user the signin deeplink via a QR code session = await authFlow.awaitApproval(); // 4) Write a public JSON file const path = "/pub/my-cool-app/hello.json"; await session.storage.putJson(path, { hello: "world" }); // 5) Read it publicly (no auth needed) const userPk = session.info.publicKey.toString(); const addr = `${userPk}/pub/my-cool-app/hello.json`; const json = await pubky.publicStorage.getJson(addr); // -> { hello: "world" } ``` -------------------------------- ### Install SDK and examples Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/README.md Build the local JS SDK package and install example dependencies. Requires Node 20+, npm, and Rust toolchain. ```bash cd pubky-sdk/bindings/js/pkg npm install npm run build cd ../../../../examples/javascript npm install ``` -------------------------------- ### Examples: GET, JSON POST, and --testnet requests with request binary Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/4-request/README.md Three sample invocations: a GET to the _pubky homeserver subdomain using the raw z-base32 key, a JSON POST with Content-Type and Accept headers, and a GET with --testnet for local testnet resolution. The --testnet example requires a running local testnet. ```bash # HTTPS to the _pubky (homeserver) subdomain form (use the raw z-base32 key) cargo run --bin request -- GET https://_pubky./pub/my-cool-app/info.json # JSON POST with headers cargo run --bin request -- \ -H "Content-Type: application/json" \ -H "Accept: application/json" \ -d '{"msg":"hello"}' \ POST https://example.com/data.json # Use local testnet endpoints cargo run --bin request -- --testnet GET https://_pubky./pub/my-cool-app/hello.txt ``` -------------------------------- ### Start Pubky testnet with Docker and PostgreSQL Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/README.md Start a disposable PostgreSQL container and then launch the Pubky testnet. The testnet requires PostgreSQL and these commands are run from the examples/rust directory. Wait for 'Testnet running' before running examples. ```bash docker run --name pubky-postgres \ -e POSTGRES_USER=postgres \ -e POSTGRES_PASSWORD=postgres \ -p 127.0.0.1:5432:5432 \ -d postgres:18 ``` ```bash TEST_PUBKY_CONNECTION_STRING='postgres://postgres:postgres@localhost:5432/postgres' \ cargo run -p pubky-testnet ``` -------------------------------- ### Grant authorization flow - browser app setup (2-auth-flow) Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/README.md Starts the browser app for the two-process grant authorization example. Requires npm install and npm run dev in the 2-auth-flow directory. ```bash cd 2-auth-flow npm install npm run dev ``` -------------------------------- ### Quick start: full Pubky workflow Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/README.md Demonstrates the core Pubky API: creating a signer, signing up and in, storage read/write, public read, keyless auth flow, and PKDNS operations. Uses a no_run Rust example. ```rust use pubky::prelude::*; use pubky::ClientId; # async fn run() -> pubky::Result<()> { let pubky = Pubky::new()?; // or Pubky::testnet() for local testnet. // 1) Create a new random key user and bound to a Signer let keypair = Keypair::random(); let signer = pubky.signer(keypair); // 2) Sign up on a homeserver (identified by its public key) let homeserver = PublicKey::try_from("o4dksf...uyy").unwrap(); signer.signup(&homeserver, None).await?; let session = signer.signin(ClientId::new("my-cool-app").unwrap()).await?; // 3) Read/Write as the signed-in user session.storage().put("/pub/my-cool-app/hello.txt", "hello").await?; let body = session.storage().get("/pub/my-cool-app/hello.txt").await?.text().await?; assert_eq!(&body, "hello"); // 4) Public read of another user’s file let txt = pubky .public_storage() .get(format!( "{}/pub/my-cool-app/hello.txt", session.info().public_key() )) .await? .text().await?; assert_eq!(txt, "hello"); // 5) Keyless app flow (QR/deeplink) let caps = Capabilities::builder() .write("/pub/example.com/") .expect("static scope is canonical") .finish(); let flow = pubky.start_grant_auth_flow( &caps, AuthFlowKind::signin(), ClientId::new("my-cool-app").unwrap(), )?; println!("Scan to sign in: {}", flow.authorization_url()); let app_session = flow.await_approval().await?; // 6) Optional (advanced): publish or resolve PKDNS (_pubky) records signer.pkdns().publish_homeserver_if_stale(None).await?; let resolved = signer.pkdns().get_homeserver().await; println!("Your current homeserver: {:?}", resolved); # Ok(()) } ``` -------------------------------- ### Install Rust toolchain with rustup Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Quick setup of the Rust toolchain using rustup, recommended for building with Cargo. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source ~/.cargo/env ``` -------------------------------- ### signup-tokens generate examples Source: https://github.com/pubky/pubky-homeserver/blob/main/homeservercli/README.md Two examples: one with unlimited storage and default rates, and one with 500 MB storage and custom read/write rates. ```sh # Unlimited storage, default rates homeservercli signup-tokens generate --storage-quota-mb unlimited ``` ```sh # 500 MB storage, 10 MB/s read, 1 MB/s write homeservercli signup-tokens generate \ --storage-quota-mb 500 \ --rate-read 10mb/s \ --rate-write 1mb/s ``` -------------------------------- ### Run storage example against local testnet Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/3-storage/README.md Runs the storage example with default settings against a local testnet. Requires a running local testnet as described in the examples README. ```bash cargo run --bin storage -- --testnet ``` -------------------------------- ### Run signup example with --testnet Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/README.md Run the signup example against a local testnet. Execute this in another terminal after the testnet reports 'Testnet running'. The --testnet flag expects a local testnet to be available. ```bash cd examples/rust cargo run --bin signup -- --testnet ``` -------------------------------- ### Start browser app Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/5-browser-session-persistence/README.md Run these commands in another terminal to install dependencies and start the Vite development server. ```bash cd examples/javascript/5-browser-session-persistence npm install npm run dev ``` -------------------------------- ### Run storage example with custom path and content Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/3-storage/README.md Runs the storage example with a custom path and content. The path and content are passed as command-line arguments. ```bash cargo run --bin storage -- --testnet /pub/my-app/data.json --content "my data" ``` -------------------------------- ### Run testnet with Dockerized PostgreSQL Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/8-testnet/README.md Runs the testnet example with a Dockerized PostgreSQL instance. Docker must be running on the host for this default setup. ```bash cargo run --bin testnet ``` -------------------------------- ### Install with cargo install Source: https://github.com/pubky/pubky-homeserver/blob/main/homeservercli/README.md Installs the Homeserver CLI from the current directory using Cargo. ```sh cargo install --path . ``` -------------------------------- ### Start homeserver as a library with HomeserverApp Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-homeserver/README.md Starts the full server stack (client server, admin server, metrics server, DHT republishers) using HomeserverApp::start_with_persistent_data_dir_path. Prints the HTTP and Pubky TLS URLs, and the admin server address if available. ```rust use pubky_homeserver::HomeserverApp; use std::path::PathBuf; #[tokio::main] async fn main() -> anyhow::Result<()> { let app = HomeserverApp::start_with_persistent_data_dir_path( PathBuf::from("~/.pubky") ).await?; println!("Homeserver HTTP: {}", app.icann_http_url()); println!("Homeserver Pubky TLS: {}", app.pubky_url()); if let Some(admin) = app.admin_server() { println!("Admin server: http://{}", admin.listen_socket()); } tokio::signal::ctrl_c().await?; Ok(()) } ``` -------------------------------- ### users quota-set examples Source: https://github.com/pubky/pubky-homeserver/blob/main/homeservercli/README.md Examples for setting storage limit, removing limit, resetting to default, setting read rate, and restricting write paths. ```sh # Set storage limit to 1 GB homeservercli users quota-set --storage-quota-mb 1024 ``` ```sh # Remove storage limit homeservercli users quota-set --storage-quota-mb unlimited ``` ```sh # Reset the storage override back to the system default homeservercli users quota-set --storage-quota-mb default ``` ```sh # Set read rate to 5 MB/s homeservercli users quota-set --rate-read 5mb/s ``` ```sh # Restrict writes to specific paths (repeatable) homeservercli users quota-set \ --allowed-write-paths /pub/tokens/ \ --allowed-write-paths /pub/profile.json ``` -------------------------------- ### Start PostgreSQL container with Docker Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Starts a PostgreSQL 18 container with the pubky_homeserver database, using a simple password for local setup. The container is set to restart unless stopped and exposes port 5432 on localhost. ```bash docker run --name pubky-postgres \ --restart unless-stopped \ -e POSTGRES_USER=postgres \ -e POSTGRES_PASSWORD=postgres \ -e POSTGRES_DB=pubky_homeserver \ -p 127.0.0.1:5432:5432 \ -v postgres-data:/var/lib/postgresql \ -d postgres:18 ``` -------------------------------- ### Run logging example with debug level Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/7-logging/README.md Runs the logging example with verbose tracing. Requires Docker to be running on the host. ```bash cargo run --bin logging -- --level debug ``` -------------------------------- ### Config file example (config.toml) Source: https://github.com/pubky/pubky-homeserver/blob/main/homeservercli/README.md Example configuration file for the CLI, compatible with the pubky-homeserver config format. The listen_socket accepts a bare socket address or a full URL. ```toml [admin] admin_password = "your-admin-password" listen_socket = "127.0.0.1:6288" ``` -------------------------------- ### Install and run pubky-testnet Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Installs and runs the local testnet homeserver. Use this for local test and development. ```bash cargo install pubky-testnet pubky-testnet ``` -------------------------------- ### Enable and start systemd service Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Enable and start the systemd service after creating the service file. ```bash sudo systemctl daemon-reload sudo systemctl enable pubky-homeserver sudo systemctl start pubky-homeserver ``` -------------------------------- ### Start the testnet Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/README.md Run the Pubky testnet from the repository root. Wait for 'Testnet running' before proceeding. ```bash cargo run -p pubky-testnet ``` -------------------------------- ### Install PostgreSQL natively Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Installs PostgreSQL using apt on Ubuntu-based systems. ```bash sudo apt update && sudo apt install -y postgresql ``` -------------------------------- ### Build binary with Cargo and install Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Builds the pubky-homeserver binary in release mode and copies it to /usr/local/bin. ```bash cargo build --release -p pubky-homeserver cp ./target/release/pubky-homeserver /usr/local/bin ``` -------------------------------- ### Run logging example with custom connection string Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/7-logging/README.md Runs the logging example with a custom PostgreSQL connection string via the TEST_PUBKY_CONNECTION_STRING environment variable. ```bash TEST_PUBKY_CONNECTION_STRING=postgres://user:pass@localhost:5432/mydb cargo run --bin logging -- --level debug --external-postgres ``` -------------------------------- ### Example output Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/5-events_stream/README.md Example output showing PUT and DEL events. ```text [PUT] pubky://o1gg96ewuojmopcjbz8895478wdtxtzzuxnfjjz8o8e77csa1ngo/pub/posts/123 (cursor: 42, hash: abc123...) [DEL] pubky://o1gg96ewuojmopcjbz8895478wdtxtzzuxnfjjz8o8e77csa1ngo/pub/posts/456 (cursor: 43, hash: -) ``` -------------------------------- ### Install SDK dependencies (npm install) Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/README.md Installs the local SDK package dependencies, including fetch-cookie. Run this when the module fetch-cookie cannot be found. ```bash cd pubky-sdk/bindings/js/pkg npm install ``` -------------------------------- ### Run testnet with custom PostgreSQL connection string Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/8-testnet/README.md Runs the testnet example with a custom PostgreSQL connection string via the TEST_PUBKY_CONNECTION_STRING environment variable. Each testnet automatically gets its own ephemeral pubky_test_{uuid} database on the configured server. ```bash TEST_PUBKY_CONNECTION_STRING=postgres://user:pass@localhost:5432/mydb cargo run --bin testnet -- --external-postgres ``` -------------------------------- ### Verify release binary install Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Checks that the homeserver binary is installed and prints its version. ```bash pubky-homeserver --version ``` -------------------------------- ### Install Rust Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Installs Rust, required for building wasm and testnet binaries. Run this before installing the local testnet. ```bash curl https://sh.rustup.rs -sSf | sh ``` -------------------------------- ### Run storage example with custom recovery file Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/3-storage/README.md Runs the storage example with a custom recovery file. The recovery file path is provided via the --recovery-file flag. ```bash cargo run --bin storage -- --testnet --recovery-file ``` -------------------------------- ### Start local testnet Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/5-browser-session-persistence/README.md Run this command in a terminal to start a local testnet for the browser app. ```bash cd pubky-sdk/bindings/js/pkg npm run testnet ``` -------------------------------- ### Run logging example with external PostgreSQL Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/7-logging/README.md Runs the logging example using an external PostgreSQL instance. Uses the default connection string postgres://postgres:postgres@localhost:5432/postgres unless overridden. ```bash # Uses postgres://postgres:postgres@localhost:5432/postgres by default cargo run --bin logging -- --level debug --external-postgres ``` -------------------------------- ### Initialize data directory with pubky-homeserver init Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Creates the data directory, default config.toml, and server keypair without starting the server or connecting to PostgreSQL. Available from v0.10 onwards. ```bash pubky-homeserver init ``` -------------------------------- ### Start PostgreSQL with Docker Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/TESTING.md Starts a local PostgreSQL 18 container named 'pubky-postgres' with user and password 'postgres', listening on localhost:5432. Required for many homeserver and testnet tests. ```bash docker run --name pubky-postgres \ -e POSTGRES_USER=postgres \ -e POSTGRES_PASSWORD=postgres \ -p 127.0.0.1:5432:5432 \ -d postgres:18 ``` -------------------------------- ### Install Pubky SDK with npm Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Install the Pubky SDK package using npm. Requires Node v20+. ```bash npm install @synonymdev/pubky ``` -------------------------------- ### Development quick start commands Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/README.md Run from pubky-sdk/bindings/js/pkg. Requires Rust toolchain, wasm-pack, and Node.js v20+. The build step produces an isomorphic bundle (index.js / index.cjs) and TypeScript definitions under pkg/. ```bash npm install # grab JS deps once npm run build # compile wasm + patch bundle npm run testnet # start local DHT + relay + homeserver (in another terminal) npm run test # run tape tests against the testnet + browser harness ``` -------------------------------- ### Run auth_client for sign-in Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/2-auth_flow/README.md Starts the auth_client CLI against a local testnet to begin a sign-in grant flow. The optional flags customize the client ID and requested capabilities. Requires a running local testnet. ```bash cargo run --bin auth_client -- --testnet # with a custom client ID or capabilities cargo run --bin auth_client -- --testnet \ --client-id my-app.example \ --capabilities /pub/my-app/:rw ``` -------------------------------- ### Checkout and pull main Source: https://github.com/pubky/pubky-homeserver/blob/main/RELEASING.md Start from the most recent main branch before bumping versions. Run these commands first to ensure you are up to date. ```bash git checkout main git pull origin main ``` -------------------------------- ### Run homeserver natively in foreground Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Start the homeserver in the foreground for testing. Press Ctrl+C to stop; it does not survive reboots. For production, use a systemd service instead. ```bash pubky-homeserver ``` -------------------------------- ### Run the homeserver binary Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-homeserver/README.md Runs the installed pubky-homeserver binary with a specified data directory. ```bash pubky-homeserver --data-dir ~/.pubky ``` -------------------------------- ### Use MockDataDir for testing Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-homeserver/README.md Creates a temporary directory that is cleaned up on drop using MockDataDir, then starts the homeserver with it. Requires the testing feature. ```rust use pubky_homeserver::{HomeserverApp, MockDataDir, ConfigToml}; let config = ConfigToml::default_test_config(); let mock_dir = MockDataDir::new(config, None).unwrap(); let app = HomeserverApp::start_with_mock_data_dir(mock_dir).await.unwrap(); ``` -------------------------------- ### Start grant auth flow with Pubky.startGrantAuthFlow Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Starts a grant auth flow with a comma-separated capabilities string and optional relay. The relay defaults to a Synonym-hosted relay if omitted. The flow returns an authorization URL to render as a QR code, and awaitApproval() blocks until the signer approves, returning a ready Session. ```js import { Pubky, AuthFlowKind } from "@synonymdev/pubky"; const pubky = new Pubky(); // Comma-separated capabilities string const caps = "/pub/my-cool-app/:rw,/pub/another-app/folder/:w"; // Optional relay; defaults to Synonym-hosted relay if omitted const relay = "https://httprelay.pubky.app/inbox/"; // optional (defaults to this) // Start grant auth polling const flow = await pubky.startGrantAuthFlow( caps, AuthFlowKind.signin(), { clientId: "my-cool-app.example", relay, xCallback: { xSource: "My Cool App", xSuccess: "my-cool-app://auth/success?nonce=unique", xError: "my-cool-app://auth/error?nonce=unique", xCancel: "my-cool-app://auth/cancel?nonce=unique", }, }, ); renderQr(flow.authorizationUrl); // show to user // Blocks until the signer approves; returns a ready Session const session = await flow.awaitApproval(); ``` -------------------------------- ### Check testnet availability Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/README.md Run the check-testnet example to verify the basic flow. Expected output includes 'Testnet is available, roundtrip succeeded.' ```bash cd examples/javascript node 6-check-testnet.mjs ``` -------------------------------- ### Pubky QR auth: start grant flow and await approval Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/README.md Start a grant auth flow with `start_grant_auth_flow`, print the authorization URL for QR/deeplink, and await approval to get a `PubkySession`. Uses default relay; for custom relay see the next example. ```rust # use pubky::{AuthFlowKind, Capabilities, ClientId, Keypair, Pubky}; # async fn auth() -> pubky::Result<()> { let pubky = Pubky::new()?; // Read/Write capabilities for acme.app route let caps = Capabilities::builder() .read_write("/pub/example.com/") .expect("static scope is canonical") .finish(); // Start the flow using the default relay (see “Relay & reliability” below) let flow = pubky.start_grant_auth_flow( &caps, AuthFlowKind::signin(), ClientId::new("example.com").expect("static client id is valid"), )?; println!("Scan to sign in: {}", flow.authorization_url()); // On the signing device, approve with: signer.approve_auth(flow.authorization_url()).await?; # pubky.signer(Keypair::random()).approve_auth(flow.authorization_url()).await?; let session = flow.await_approval().await?; # Ok(()) } ``` -------------------------------- ### Signup with testnet and sample recovery file Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/1-signup/README.md Runs the signup binary against a local testnet homeserver using the default sample recovery file. Requires a running local testnet. ```bash # use the local testnet homeserver and sample recovery file cargo run --bin signup -- --testnet ``` -------------------------------- ### Set log level with setLogLevel Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Call once at application start, before constructing Pubky or other SDK actors. If the logger is already initialized, calling setLogLevel again will throw. Use "debug" or "trace" while developing to see pkarr resolution, network requests, and storage operations. ```js import { setLogLevel } from "@synonymdev/pubky"; setLogLevel("debug"); // "error" | "warn" | "info" | "debug" | "trace" ``` -------------------------------- ### PublicStorage read-only operations Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Read-only access to public storage. Use `get()` when you need the raw `Response` for streaming or custom parsing. The addressed path must include a trailing slash for `list()`. ```js const pub = pubky.publicStorage; // Reads const response = await pub.get( `${userPk}/pub/example.com/data.json` ); // -> Response (stream it) await pub.getJson(`${userPk}/pub/example.com/data.json`); await pub.getText(`${userPk}/pub/example.com/readme.txt`); await pub.getBytes(`${userPk}/pub/example.com/icon.png`); // Uint8Array // Metadata await pub.exists(`${userPk}/pub/example.com/foo`); // boolean await pub.stats(`${userPk}/pub/example.com/foo`); // { content_length, content_type, etag, last_modified } | null // List directory (addressed path "/pub/.../") must include trailing `/`. // list(addr, cursor=null|suffix|fullUrl, reverse=false, limit?, shallow=false) await pub.list( `${userPk}/pub/example.com/`, null, false, 100, false ); ``` -------------------------------- ### SessionStorage read/write operations Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Read/write access to session storage. `get()` exposes the underlying `Response`, handy for streaming bodies or inspecting headers. Session storage uses absolute paths under `/pub/` or `/priv/`. ```js const s = session.storage; // Writes await s.putJson("/pub/example.com/data.json", { ok: true }); await s.putText("/pub/example.com/note.txt", "hello"); await s.putBytes("/pub/example.com/img.bin", new Uint8Array([1, 2, 3])); // Reads const response = await s.get("/pub/example.com/data.json"); // -> Response (stream it) await s.getJson("/pub/example.com/data.json"); await s.getText("/pub/example.com/note.txt"); await s.getBytes("/pub/example.com/img.bin"); // Metadata await s.exists("/pub/example.com/data.json"); await s.stats("/pub/example.com/data.json"); // Listing (session-scoped absolute dir) await s.list("/pub/example.com/", null, false, 100, false); // Delete await s.delete("/pub/example.com/data.json"); ``` -------------------------------- ### Run auth_client for sign-up and sign-in Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/2-auth_flow/README.md Starts the auth_client CLI with the --signup flag to sign up and sign in in one flow. The first command uses the local testnet; the second targets a non-testnet homeserver, requiring its public key and an optional signup code. The signup URL uses the signup_grant intent. ```bash cargo run --bin auth_client -- --testnet --signup ``` ```bash cargo run --bin auth_client -- --signup \ --homeserver \ --signup-code ``` -------------------------------- ### Validate and normalize capabilities with validateCapabilities Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/bindings/js/pkg/README.md Validates and normalizes user-supplied capability strings with validateCapabilities before starting a grant auth flow. On invalid input, validateCapabilities throws a PubkyError with data.invalidEntries containing the first malformed entry; catch InvalidInput to surface precise feedback. Capability scopes must be canonical absolute paths; repeated separators and '.' or '..' segments are rejected. ```js import { Pubky, validateCapabilities, AuthFlowKind } from "@synonymdev/pubky"; const pubky = new Pubky(); const rawCaps = formData.get("caps"); try { const caps = validateCapabilities(rawCaps ?? ""); const flow = await pubky.startGrantAuthFlow(caps, AuthFlowKind.signin(), { clientId: "my-cool-app.example", }); renderQr(flow.authorizationUrl); const session = await flow.awaitApproval(); // ... } catch (error) { if (error.name === "InvalidInput") { surfaceValidationError(error.message); return; } throw error; } ``` -------------------------------- ### Example: GET a user's social post from pubky homeserver Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/4-request/README.md Concrete GET command that returns the content of a user's social post from their pubky homeserver. Uses a real _pubky host key in the URL. ```bash cargo run --bin request -- GET https://_pubky.operrr8wsbpr3ue9d4qj41ge1kcc6r7fdiy6o3ugjrrhi4y77rdo/pub/pubky.app/posts/0033X02JAN0SG ``` -------------------------------- ### Public storage get and list with Pubky Source: https://github.com/pubky/pubky-homeserver/blob/main/pubky-sdk/README.md Unauthenticated public storage reads: get a file and list entries under a user's /pub/ path. Uses addressed form pubky/pub/app/file.txt. See the Public Storage example for more. ```rust use pubky::{Pubky, PublicKey}; # async fn run(user_id: PublicKey) -> pubky::Result<()> { let pubky = Pubky::new()?; let public = pubky.public_storage(); let file = public .get(format!("{user_id}/pub/example.com/file.bin")) .await? .bytes() .await?; let entries = public .list(format!("{user_id}/pub/example.com/"))? .limit(10) .send() .await?; for entry in entries { println!("{}", entry.to_pubky_url()); } # Ok(()) } ``` -------------------------------- ### Signup with custom recovery file and signup code Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/1-signup/README.md Runs the signup binary against a mainnet homeserver with a custom recovery file and a signup code. ```bash # With a custom recovery file and signup code cargo run --bin signup --recovery-file --signup-code ``` -------------------------------- ### Check PostgreSQL is running (native or Docker) Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Checks whether PostgreSQL is running. Use the first command for a native install, the second for Docker. If it reports "no response", start or restart PostgreSQL. ```bash pg_isready ``` ```bash docker exec pubky-postgres pg_isready ``` -------------------------------- ### Run logging example with debug level Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/README.md Uses setLogLevel() to surface the SDK's internal tracing while performing a quick storage roundtrip. Override --homeserver for mainnet infrastructure or change --level to reduce noise. ```bash node 7-logging.mjs --testnet --level debug ``` -------------------------------- ### Start PostgreSQL cluster Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Starts the PostgreSQL cluster. Not needed on systems with systemd where PostgreSQL starts automatically. ```bash pg_ctlcluster $(pg_lsclusters -h | awk '{print $1, $2}') start ``` -------------------------------- ### Signup to mainnet homeserver Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/1-signup/README.md Runs the signup binary against a mainnet homeserver by providing the homeserver pubky as an argument. ```bash # Signup to a mainnet homeserver cargo run --bin signup ``` -------------------------------- ### Signup with recovery file (1-signup.mjs) Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/javascript/README.md Runs the signup script with optional homeserver, recovery file, signup code, and testnet flag. Defaults to ../sample_recovery.key with empty passphrase; prompts for passphrase if encrypted. ```bash node 1-signup.mjs [homeserver_pubky] [--recovery-file ] [--signup-code ] [--testnet] # use the local testnet homeserver and sample recovery file node 1-signup.mjs --testnet # with a custom recovery file and signup code node 1-signup.mjs --recovery-file ./alice.recovery --signup-code INVITE-123 ``` -------------------------------- ### Install build dependencies Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Installs packages required to build from source on Debian-based systems. ```bash sudo apt update && sudo apt install -y build-essential pkg-config libssl-dev git curl ``` -------------------------------- ### Start from specific cursors for multiple users Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/5-events_stream/README.md Fetches events starting from specific cursors for two users. ```bash cargo run --bin events_stream -- \ o1gg96ewuojmopcjbz8895478wdtxtzzuxnfjjz8o8e77csa1ngo \ pxnu33x7jtpx9ar1ytsi4yxbp6a5o36gwhffs8zoxmbuptici1jy \ --cursors "1234567890,9876543210" \ --limit 50 ``` -------------------------------- ### Pubky Auth URL example Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/AUTH.md Example of a Pubky Auth URL with a specific relay, capabilities, and secret. ```text pubkyauth:/// ?relay=https://httprelay.pubky.app/inbox &caps=/pub/pubky.app/:rw,/pub/example.com/nested:rw &secret=mAa8kGmlrynGzQLteDVW6-WeUGnfvHTpEmbNerbWfPI ``` -------------------------------- ### Initialize data directory with Docker Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Runs the init command inside a Docker container, mounting the local ~/.pubky directory to /root/.pubky. ```bash docker run -it -v ~/.pubky:/root/.pubky pubky-homeserver homeserver init ``` -------------------------------- ### Path filter matching examples Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/v0.10-migration/README.md Examples showing how trailing slashes determine whether a path matches a single file or a directory tree. ```text /pub/my-app/profile matches only /pub/my-app/profile /pub/my-app/ matches everything under /pub/my-app/ ``` -------------------------------- ### Signup with testnet and custom recovery file Source: https://github.com/pubky/pubky-homeserver/blob/main/examples/rust/1-signup/README.md Runs the signup binary against a local testnet homeserver with a custom recovery file specified via --recovery-file. ```bash # with a custom recovery file cargo run --bin signup -- --testnet --recovery-file ``` -------------------------------- ### Usage syntax Source: https://github.com/pubky/pubky-homeserver/blob/main/homeservercli/README.md Shows the general usage syntax for the CLI. ```text homeservercli [OPTIONS] ``` -------------------------------- ### Install cloudflared as systemd service Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/deploy/cloudflare-tunnel.md Installs cloudflared as a systemd service and enables/starts it. The config path is passed explicitly because sudo changes the home directory to /root. ```bash sudo cloudflared --config ~/.cloudflared/config.yml service install sudo systemctl enable cloudflared sudo systemctl start cloudflared ``` -------------------------------- ### Create pubky_homeserver database (native or Docker) Source: https://github.com/pubky/pubky-homeserver/blob/main/docs/INSTALL.md Creates the missing pubky_homeserver database. Use the first command for a native PostgreSQL install, the second when PostgreSQL runs in Docker. Alternatively, update [general].database_url in ~/.pubky/config.toml to point at an existing database. ```bash createdb -h -U pubky_homeserver ``` ```bash docker exec pubky-postgres createdb -U postgres pubky_homeserver ```