# PRODUCT Source: https://docs.tinycloud.xyz/PRODUCT # Product ## Register brand ## Users Application developers building browser or Node.js integrations, protocol implementers checking capability and delegation behavior, and operators deploying TinyCloud nodes or using the CLI. They arrive with a concrete job and need the shortest trustworthy route to a working result. ## Product Purpose TinyCloud documentation teaches developers and operators how to build with, understand, and run a user-owned personal data cloud. Success means readers can select the right journey immediately, complete a verified first task, and find exact source-backed behavior without confusing tutorials, concepts, and reference material. ## Brand Personality Sovereign, technical, and direct. The experience should create confidence through precise language, visible trust boundaries, and practical paths rather than hype. ## Anti-references Do not resemble an uncustomized Mintlify starter kit, a generic SaaS documentation template, or a marketing page that hides operational constraints behind abstract claims. Avoid decorative complexity that competes with navigation and code. ## Design Principles * Lead with reader intent: Build, Understand, and Operate should always be obvious entry points. * Earn trust with exactness: distinguish verified behavior, boundaries, beta versions, and known limitations. * Separate ownership from confidentiality: ordinary nodes and hosted MCP can process plaintext; distinguish transport/storage encryption, application E2EE, network key custody, verified TEE assumptions and self-hosted operator access. * Make progress visible: every tutorial should state prerequisites, actions, and a recognizable success result. * Keep theory and action connected: concepts should clarify implementation decisions, not become detours. * Make TinyCloud unmistakable: use TinyCloud identity and language instead of framework defaults. ## Accessibility & Inclusion Meet WCAG 2.1 AA for text, controls, focus, and color contrast in light and dark modes. Preserve keyboard navigation, descriptive labels, reduced-motion preferences, and readable line lengths. Do not rely on color alone to communicate navigation state or meaning. # Account discovery Source: https://docs.tinycloud.xyz/cli/account Inspect the canonical account space and application registries The account registry connects a TinyCloud identity to its known spaces and registered application manifests. Use the live commands below for read-only, canonical owner-side discovery. > [!NOTE] > > Use the profile you signed in with. `tinycloud onboard` already includes > account registry read. Current `tc account` commands derive the account > registry from the active profile. ## Account summary and billing ```bash theme={null} tc --json account status tc account billing status tc account billing portal --open ``` `account status` returns the owner DID, host, primary and account space IDs, and counts of applications, spaces, and granted and received delegations. `account billing` prints, or with `--open` opens, the billing page at `https://account.tinycloud.xyz/billing`, where plans and storage are managed. There is no CLI command for storage usage. ## List spaces ```bash theme={null} tc --quiet --json account spaces list --live tc --quiet --json account spaces info ``` The list returns each space ID, name, owner DID, type, status, permissions, and timestamps. Pass the returned full space ID to `info` or to another command's `--space` flag. > [!WARNING] > > For read-only exploration, keep `--live`. Without it, `account spaces list` > prefers the materialized SQLite index and may synchronize accessible spaces > into the account registry when the index is empty. ## List applications ```bash theme={null} tc --quiet --json account apps list --live tc --quiet --json account apps info ``` Application records contain registered manifests. Use their declared spaces, prefixes, databases, and knowledge metadata to decide what to inspect next. The registry record grants no additional data authority by itself. ## Inspect selected KV data ```bash theme={null} tc --quiet --json kv list --space --prefix tc --quiet --json kv get --space ``` The active profile must still hold `tinycloud.kv/list` or `tinycloud.kv/get` authority for the selected resource. If a read is denied, ask once with `tinycloud auth request --cap --grant --paste --expiry 30d`, send the owner the link, and pass back the code they send exactly as sent. ## Read-only boundary The workflow on this page does not use `account spaces sync`, `register`, `remove`, application registration, KV writes, or deletion. Those are separate mutating operations and require explicit user intent and authority. # Auth Artifacts Source: https://docs.tinycloud.xyz/cli/auth-artifacts Request, grant, import, and retry TinyCloud permission artifacts Use auth artifacts when one process requests permissions and another identity grants or imports them. ## Request ```bash theme={null} tc auth request --cap tinycloud.kv:default:documents/:get,list --emit request.json tc auth request --permission permissions.json tc auth request --manifest ./manifest.json ``` `--cap` accepts `tinycloud.:::` and repeats for multiple entries. ## Grant ```bash theme={null} tc auth grant request.json tc auth grant request.json --stdin tc auth grant request.json --yes ``` Use `grant` when you want to approve a request artifact and return a delegation artifact. ## Import ```bash theme={null} tc auth import delegation.json tc auth import --paste tc auth import --stdin ``` Import can accept a delegation artifact or a stored request artifact. It is the path for moving permissions between processes. ## Retry ```bash theme={null} tc auth retry request-id tc auth retry --last tc auth retry --last --exec ``` Retry checks whether a stored request is now covered by the active session and, optionally, runs the captured command. ## Inspect ```bash theme={null} tc auth caps tc auth caps --diff tinycloud.kv:default:documents/:get,list tc auth caps --history ``` > [!NOTE] > > The CLI source treats these commands as the artifact path for advanced permission workflows, while `tc auth login` remains the normal sign-in path. # Authentication Source: https://docs.tinycloud.xyz/cli/authentication Set up a profile and sign in with OpenKey or a local key Use this page when you need a TinyCloud profile, a session, or a headless auth path for automation. ## Pick a method > [card] OpenKey > > Browser or paste sign-in. Best for interactive use. > [card] OpenKey device > > The owner approves on their phone. Useful for servers. > [card] Local key > > Private-key sign-in. Best for CI against a key you control. Agents sign in once with `tinycloud onboard` (see [agents.tinycloud.xyz/onboarding](https://agents.tinycloud.xyz/onboarding)) and ask for more with `tinycloud auth request --cap --grant --paste --expiry 30d`, which adds to that profile. Signing an existing profile in again with `auth login` for a different purpose can replace the session another app relies on. ## Start with a profile `tc init` creates a profile directory, generates a keypair, and can optionally sign in immediately. ```bash theme={null} tc init --name my-app tc init --name my-app --key-only ``` Useful flags: | Flag | What it does | | - | - | | `--host ` | Set the node URL for the new profile | | `--default-space ` | Set the profile's default space name | | `--paste` | Use manual paste mode if the browser callback is unavailable | | `--no-popup` | Print the OpenKey URL instead of opening a browser | ## Sign in ```bash theme={null} tc auth login tc auth login --method openkey tc auth login --method local ``` OpenKey sign-in opens a browser flow. Local-key sign-in uses the profile's private key without a browser. ```bash theme={null} tc auth login --method openkey --paste tc auth login --method openkey --no-popup ``` ## Request only what you need `--manifest` asks OpenKey for one app manifest's permissions instead of the default abilities. The owner sees every capability on the consent page and may uncheck some; the JSON result lists `permissions` (approved) and `declined`. ```bash theme={null} tc --profile my-app auth login --method openkey --manifest ./manifest.json --expiry 7d tc --profile my-app auth login --method openkey --paste --manifest ./manifest.json ``` | Flag | What it does | | - | - | | `--manifest ` | Request one space's permissions from an app manifest; `builtin:share-publishing` covers `tc share publish` | | `--expiry ` | Session lifetime from approval: `1h`, `7d`, at least `1m`. ISO dates are refused | | `--owner ` | Refuse an approval by any other identity | | `--replace-session` | Allow replacing a live session with a narrower, different, or shorter one | A profile that already recorded an owner is held to that owner on every later login. A live session is only replaced by a scope that keeps everything it holds and lasts at least as long; anything else fails with `SESSION_IN_USE` and saves nothing. If another `tc` or MCP process holds the profile while a login commits, the CLI waits up to 45 seconds and then fails with `PROFILE_LOCK_TIMEOUT`; retry once the other process finishes. ## Device login for servers Use device login when the owner cannot open a browser on the machine running `tc`. It requires a KV-scoped manifest. ```bash theme={null} tc init --name publisher --key-only tc --profile publisher auth login --device --manifest builtin:share-publishing --expiry 7d ``` The command prints one approval line to stderr and keeps polling for about 10 minutes: ``` Approve on your phone: https://openkey.so/device?user_code=ABCD-EFGH (code ABCD-EFGH) ``` The owner opens the link, signs in to OpenKey, confirms they started the request, and approves. The code alone grants nothing. Device sessions default to 30 days, the maximum. Device login is limited to KV access and `capabilities/read` in one space. It cannot grant SQL, secrets, or encryption; use browser or paste login with a manifest for those. | Error | Meaning | | - | - | | `DEVICE_AUTH_DENIED` (exit `5`) | The owner declined | | `DEVICE_AUTH_EXPIRED` (exit `3`) | Nobody approved within the window; run it again | | `DEVICE_AUTH_RATE_LIMITED` (exit `1`) | Five device requests from this network in 10 minutes; wait | | `SCOPE_REJECTED` (exit `5`) | OpenKey does not grant that capability over device login | | `DEVICE_AUTH_UNSUPPORTED_SCOPE` (exit `2`) | The manifest asks for secrets or encryption | | `OPENKEY_UNREACHABLE` (exit `6`) | The CLI cannot reach OpenKey | ## Which OpenKey key signed in An OpenKey account can hold several keys, and each key is a separate owner with its own spaces. OpenKey preselects the account's **primary** key on CLI and agent approval pages, and other keys sit behind **Use a different key**. To change it, open a key from **Your Keys** on the OpenKey dashboard with **Manage**, then choose **Make primary**. Only OpenKey-managed keys can be primary. > [!NOTE] > > CLI 1.1.0 beta records whether the approving key was primary (`tc auth status` > shows `Primary Key`) and warns on stderr when it was not. `tc auth login --owner ` no longer needs `--manifest`. `--paste` also accepts the eight-character > code OpenKey shows instead of the full delegation. ## Check state ```bash theme={null} tc auth status tc auth whoami tc context --json tc auth logout ``` `tc auth status` shows which DID is active and whether the profile has a stored session; it does not check that the session is still valid. `tc context` reports the selected profile, owner and session DIDs, host, space, and local session state (`present`, `expired`, `missing`, or `unknown-expiry`) as JSON, without contacting the node. ## When a session expires OpenKey browser and paste sessions last 7 days unless you pass `--expiry`; device sessions default to 30 days, their maximum. When `tc context` shows the session as `expired`, sign in again with the same command you used to create it. > [!NOTE] > > In CLI 1.1.0 beta, every command run on an expired session fails with > `AUTH_REQUIRED` (exit `3`) before contacting the node, and the hint names the right sign-in for the profile: scoped > paste login for a delegate, `--method local` for a local key, and `--method > openkey` for an OpenKey owner. `tc auth login` and `tc auth logout` on a > profile that does not exist fail with `PROFILE_NOT_FOUND`. ## OpenKey host overrides OpenKey auth uses this resolution order: 1. `TC_OPENKEY_HOST` 2. `profile.json` `openkeyHost` 3. `https://openkey.so` That lets you point a profile at a self-hosted OpenKey instance without changing the CLI command itself. ## Automation `tc auth login --method local` signs in with the profile's own stored key, or generates one, without a browser. `TC_PRIVATE_KEY` and `--private-key` are read by `tc vault`, `tc vars`, and `tc secrets`, not by `auth login`. In a non-interactive run, an OpenKey `tc auth login` without `--paste`, `--no-popup`, or `--device` fails with `INTERACTIVE_LOGIN_REQUIRED` (exit `2`) instead of waiting for a browser. `tc auth rotate` replaces the profile's session key and signs in again; it accepts `--paste` and `--no-popup`. # Delegations Source: https://docs.tinycloud.xyz/cli/delegations Grant another DID scoped, revocable access to paths in your space Use delegations when another DID needs access to a path in your space. To send a file to a person, use [Share](/cli/share) instead. ## Create a delegation ```bash theme={null} tc delegation create \ --to did:pkh:eip155:1:0xRecipient... \ --path documents/ \ --actions kv/get,kv/list \ --expiry 7d ``` The CLI prefixes short actions with `tinycloud.` automatically, so `kv/get` becomes `tinycloud.kv/get`. ## Inspect and revoke ```bash theme={null} tc delegation list tc delegation list --granted tc delegation list --received tc delegation info bafy... tc delegation revoke bafy... ``` ## Share links To hand someone a file rather than a standing delegation, use [`tc share publish`](/cli/share). It publishes a bearer link or an addressed link (one email address or an email domain) that opens in the Share viewer, and keeps an encrypted sender history you can list and revoke. ## DID and expiry rules * Use a PKH DID for user-to-user delegations * `did:key` is for session-key style identities * Expiry can be relative (`1h`, `7d`) or an absolute ISO timestamp; `delegation create` defaults to `1h` > [!NOTE] > > Bearer Share links are built on the same delegations: `tc share revoke` on a > bearer link revokes its delegation. Addressed shares add a signed policy that > your node enforces. # Diagnostics Source: https://docs.tinycloud.xyz/cli/diagnostics Run health checks and inspect node reachability Use diagnostics when a command fails and you need to separate local profile problems from node problems. ## `tc doctor` ```bash theme={null} tc doctor ``` `tc doctor` checks: * Node.js version * Profile existence * Local key presence * Session presence * Node reachability * Hosted space presence It prints a human-readable checklist by default and JSON with `--json`. ## `tc node` ```bash theme={null} tc node health tc node version tc node status ``` These commands emit JSON and are useful for scripts and health probes. ## Shell completions ```bash theme={null} tc completion bash tc completion zsh tc completion fish ``` ## Exit codes and error output When stdout is not a terminal, errors go to stderr as `{ "error": { "code", "message", "hint" } }`. CLI 1.1.0 beta also does this for `--json` at a terminal. Branch on `error.code`; the exit status groups related codes. | Exit | Meaning | | - | - | | `0` | Success | | `1` | Operation error | | `2` | Invalid input (`USAGE_ERROR`) | | `3` | Authentication required (`AUTH_REQUIRED`) | | `4` | Not found (`NOT_FOUND`, including a missing secret) | | `5` | Permission denied (`PERMISSION_DENIED`) | | `6` | Network error | | `7` | Node error | | `10` | Storage full (`STORAGE_QUOTA_EXCEEDED`, `STORAGE_LIMIT_REACHED`); CLI 1.1.0 beta | `tc share` has its own codes, including `8` and `9`; see [Share files](/cli/share#errors). ## When a check fails * No profile or no key: run `tc init` * No session: run `tc auth login` * No space: run `tc space create ` * Node unreachable: confirm the node URL and network access > [!TIP] > > `tc doctor` is the fastest way to tell whether a failure is local state, auth state, or node reachability. # DuckDB Source: https://docs.tinycloud.xyz/cli/duckdb Query, export, and import DuckDB databases Beta Use `tc duckdb` when you need DuckDB-specific query behavior instead of SQLite. ## Commands ```bash theme={null} tc duckdb query "SELECT count(*) FROM events" --db analytics tc duckdb execute "CREATE TABLE events (type VARCHAR)" --db analytics tc duckdb describe --db analytics tc duckdb export --db analytics --output analytics.duckdb tc duckdb import analytics.duckdb --db analytics ``` ## Notes * `--db` chooses the DuckDB database name * `--params` binds JSON-array parameters to `?` placeholders * `query` and `describe` emit JSON with `--json` DuckDB is beta. Prefer `tc sql` for ordinary application data unless you specifically need DuckDB. # Manifests Source: https://docs.tinycloud.xyz/cli/manifest Resolve app manifests into TinyCloud spaces and databases Use `tc manifest resolve` when you want to turn a manifest into the concrete `--space` and `--db` values you should pass to other CLI commands. ```bash theme={null} tc manifest resolve ./manifest.json tc manifest resolve https://example.com/manifest.json ``` ## What it returns * App id, name, and manifest version * Effective owned-space name and resolved space URI * Permission entries with resolved paths * Derived SQL database basenames ## Typical use ```bash theme={null} tc manifest resolve ./manifest.json tc sql query --space applications --db xyz.tinycloud.listen/conversations "SELECT count(*) FROM conversation" ``` The command is read-only. It helps you line up manifest declarations with the CLI target values you need later. > [!NOTE] > > The manifest command resolves against the active profile so it can compute the correct owned-space URI without contacting the node. # TinyCloud MCP Source: https://docs.tinycloud.xyz/cli/mcp Setup and support status for ChatGPT, Claude, coding agents and chat bots The TinyCloud MCP server exposes 20 hosted tools or 17 local stdio tools to Model Context Protocol clients. If your agent can install and run the CLI, use the CLI instead: start at [agents.tinycloud.xyz/onboarding](https://agents.tinycloud.xyz/onboarding). Otherwise, clients supporting Streamable HTTP MCP and OpenKey OAuth can use the hosted endpoint below. Meetings are available through the CLI. ## Choose your client This is a connection-method guide, not a claim that TinyCloud is published in every client's app directory. Client interfaces and administrator settings change; a working transport does not guarantee that an account has the UI. | Client | Setup path and support boundary | | - | - | | ChatGPT | Use a custom remote MCP connection with OpenKey OAuth; see [ChatGPT setup](#chatgpt-setup). This does not claim app-directory publication or verification on every ChatGPT surface. | | Claude app (web, iOS, Android) | Add the [remote MCP connector](#connect-a-remote-mcp-client). The app does not need a local CLI or skill installation. Connector availability/settings are controlled by the client. | | Claude Code | Prefer [CLI onboarding](https://agents.tinycloud.xyz/onboarding) and the [agent skill](/guides/agent-skills); local stdio MCP is an alternative. | | Codex | Use [CLI onboarding](https://agents.tinycloud.xyz/onboarding) and [agent skills](/guides/agent-skills) in a shell-enabled runtime. This does not promise CLI installation in every hosted Codex environment. | | OpenCode | Use [CLI onboarding](https://agents.tinycloud.xyz/onboarding) and [agent skills](/guides/agent-skills). Local stdio MCP is also available to MCP-capable runtimes. | | Grok / GrokBot | Choose [CLI onboarding](https://agents.tinycloud.xyz/onboarding) only if the actual bot/runtime can install and run commands. Otherwise use the hosted endpoint only if it supports Streamable HTTP MCP and OAuth. No native Grok connector or universal bot-install support is verified here. | | WhatsApp / Instinct | WhatsApp is the conversation channel; the bot's runtime determines integration. In Cian's reported test, Instinct read a Claude Code-written note with a two-hour, read-only Todos delegation and made no writes. That observation is not proof of native WhatsApp MCP, general installation support or all-device approval compatibility. | If a bot cannot install the CLI or connect through MCP, sending it a setup link does not add those capabilities. Do not send it an owner private key. Use [Windows installation](/cli/overview#windows) for a Windows shell. > [!WARNING] > > Hosted MCP and the connected AI client receive plaintext tool inputs/results. > Local CLI/stdio avoids the hosted MCP hop, but does not make ordinary node > storage or AI processing E2EE. Read [Security and trust](/concepts/security-and-trust) > before granting access. ### ChatGPT setup 1. Open ChatGPT on the web and use its custom MCP server connection form. Follow [OpenAI's current custom MCP setup guide](https://help.openai.com/en/articles/12584461-connecting-custom-mcp-servers-in-chatgpt) for the current UI and account/workspace availability. If the form is absent, check that guidance or your workspace administrator; this guide does not infer a subscription restriction. 2. Enter `https://mcp.tinycloud.xyz/mcp` and complete OpenKey OAuth. Use the same OpenKey owner/key that holds your TinyCloud data. 3. Enable/select the connection in the conversation, ask it to call `tinycloud_connect`, and complete the scoped approval flow below. 4. Continue only when `tinycloud_connect` reports `connected: true`; ask to list spaces and read one known record before requesting edits. This is the custom-connection route documented by TinyCloud MCP, not a claim of reviewed/published ChatGPT app status. Actual ChatGPT UI acceptance and mobile availability must be checked in the target account. ## Connect a remote MCP client For example, in Claude (web, iOS or Android), add a custom connector with this URL. Other compatible clients, including ChatGPT, use the same endpoint: ```text theme={null} https://mcp.tinycloud.xyz/mcp ``` The client discovers OpenKey OAuth from the endpoint, registers its OAuth client, and asks you to sign in. After the connector is enabled: 1. Ask the client to call `tinycloud_connect`. 2. Open the returned `approvalUrl` and approve the account-registry delegation in OpenKey. 3. Ask the client to call `tinycloud_connect` again. It now returns `connected: true`. 4. Ask the client to list your spaces, then perform the KV or SQLite operation you want. When a tool returns `authority_required`, open its `approval.url` and retry the same tool unchanged. Hosted mode adds `tinycloud_connect` and four personal-record tools to the local surface, and omits the local-only `tinycloud_auth_import` and `tinycloud_secrets_status`. The service stores a distinct delegated session key for each OpenKey OAuth subject and accepts only delegations from an owner DID carried by that subject's resource-bound access token. It never receives an owner private key. ### Keep personal records naturally Ask “Log my weight: 80.5 kg today”, “Mark my passport todo done”, or “How much did I run last month?” Claude can keep and read the same records as coding agents using `tc-apps`, without a local CLI or skill installation. At first use, approve connect and then personal-record access in OpenKey. Records use one grant for get, list, put and delete under `xyz.tinycloud.agent-data/` in your `default` space, not a separate approval for every key. Supply an IANA timezone once; the client must not infer your local date from the hosted server's clock or require your precise location. In **Settings → Connectors → TinyCloud**, you can set `tinycloud_apps_write` to **Always allow** to avoid per-call tool confirmations. This does not bypass OpenKey permission approval. | Hosted-only tool | Purpose | | - | - | | `tinycloud_apps_context` | Read the rules, catalog, local time, timezone and fast-copy state; optionally set the timezone | | `tinycloud_apps_read` | List prefixes and read up to 100 records with their ETags | | `tinycloud_apps_write` | Run 1–10 ordered create, conditional edit, move or delete operations | | `tinycloud_apps_query` | Refresh the optional fast copy and answer a bounded question over selected kinds | For edits, read fresh and pass the returned ETag. A put without an ETag creates only; a stale ETag returns `CHANGED`, not an overwrite. A move requires the source ETag; a delete can also be guarded by one. Inspect each operation's outcome and a move's completed `steps` (`written`, `deleted`): an `ok` envelope does not mean every operation succeeded. Report partial outcomes rather than blindly replaying the batch. `TIMEZONE_REQUIRED` means the owner's timezone must be set before the write. For questions over many records, Claude can first answer from the records and offer **a fast, searchable copy of your records**. This is optional and needs its own approval. KV records remain the source of truth. Developer reference: the copy is the exact SQL database `xyz.tinycloud.agent-data.index`, with read, write and schema authority; query refreshes derived data, not KV records. `COPY_PARTIAL` is a successful result with the kinds still to rebuild; the next query resumes them. A nonretryable `NODE_ERROR` with `error.details.reason: "copy_unavailable"` needs the node team's resolution. Answer from KV instead; retrying the copy or changing its name is not a fix. Production requests 30-day grants and uses 15-minute approval links. A missing or expired session returns a fresh connect link in `error.details`; a missing or expired grant returns an `authority_required` approval link. Open the new link and retry after approval. If the owner declines, stop rather than asking again in that conversation. > [!WARNING] > > The hosted service can observe plaintext operation inputs and results while it > executes them, including delegated secrets. Local stdio removes that hosted > service from the path; it does not remove the node or AI-client trust boundary. ## Requirements * Node.js 22.20 or later * The TinyCloud CLI, signed in with `tinycloud onboard`, for local stdio * A hosted deployment with the apps tools for personal records; local stdio does not expose them * A TinyCloud node running 1.6.0 or newer * Local stdio requires structured tool results; hosted clients can also read canonical JSON in text results ## Configure local stdio Install both packages with Node.js 22.20 or later: ```bash theme={null} npm install --global @tinycloud/cli @tinycloud/mcp ``` Sign in once with `tinycloud onboard` (see [agents.tinycloud.xyz/onboarding](https://agents.tinycloud.xyz/onboarding)), then start the server with that profile. An onboarded profile signs in with OpenKey, so pass `--allow-owner-profile` with it. Then add the local stdio server to your MCP client: ```json theme={null} { "mcpServers": { "tinycloud": { "command": "tinycloud-mcp", "args": ["--profile", "default", "--allow-owner-profile"] } } } ``` The server captures the selected profile at startup. Restart it to select a different profile. Delegation imports persist, so retry can happen in the same process or a later one. ## Available tools | Tool | Purpose | | - | - | | `tinycloud_status` | Inspect safe local profile state | | `tinycloud_auth_status` | Inspect authentication state | | `tinycloud_auth_capabilities` | Inspect validated active capabilities | | `tinycloud_auth_request` | Create or recover an exact permission request | | `tinycloud_auth_import` | Validate and import a request-bound delegation (local only) | | `tinycloud_account_spaces_list` | List the canonical account space registry | | `tinycloud_account_applications_list` | List registered apps and manifests | | `tinycloud_kv_list` | List keys in one selected space or prefix | | `tinycloud_kv_get` | Read one selected KV key | | `tinycloud_kv_head` | Read metadata and the ETag for one selected KV key | | `tinycloud_kv_put` | Create, conditionally replace, or explicitly upsert one selected KV key | | `tinycloud_kv_delete` | Delete one selected KV key, optionally only when its ETag matches | | `tinycloud_sql_schema_inspect` | Inspect tables, views, indexes, and triggers in one SQLite database | | `tinycloud_sql_query` | Run one bounded read-only query against one SQLite database | | `tinycloud_sql_execute` | Run one positional-parameterized `INSERT`, `UPDATE`, or `DELETE` | | `tinycloud_secrets_get` | Read and decrypt one delegated secret | | `tinycloud_secrets_status` | Inspect delegated secret readiness without reading values (local only) | These tools use the same versioned operation contracts as the CLI projections. Results use one of four statuses: `ok`, `authority_required`, `setup_required`, or `error`. Generic data operations plan authority for the exact space and key, prefix, or database in their input. The hosted apps tools use the single records-prefix grant described above instead. When authority is missing, the tool returns `authority_required` with a `tinycloud.auth.request`; it does not widen the request or silently fall back to owner authority. Generic KV tools reject the TinyCloud `account` and `secrets` spaces. Use the dedicated account and secret tools for those protected spaces. For the account and data discovery sequence, including how to handle `authority_required`, see [Access and explore my TinyCloud](/guides/access-and-explore-my-tinycloud). Account registry discovery is capped at 1,000 records, 1 MiB per record, and 4 MiB total serialized output. It fails closed instead of returning a partial registry. Hosted text results include readable canonical JSON as well as `structuredContent`, except that successful secret values remain structured-only. Read-only results over 100,000 characters return a nonretryable size error with narrowing guidance. This cap never truncates write results or conceals completed writes. Tool-call logs contain only tool name, outcome code, duration and the number of successfully replayed grants—not keys, values, catalog text, SQL or parameters. ## KV data safety `tinycloud_kv_list` returns at most 100 keys by default, accepts a limit from 1 through 1,000, and reports whether the result was truncated. KV reads and writes are limited to 1 MiB per value. `tinycloud_kv_get` returns the byte length, metadata, and a tagged representation. Base64 is the default and preserves arbitrary files exactly; request `text` or `json` only when the bytes use that representation. A decoded GET can carry a weak representation ETag; use `tinycloud_kv_head` when a strong validator is needed for a conditional mutation. `tinycloud_kv_put` accepts one of these tagged content objects: ```json theme={null} { "encoding": "utf8", "value": "# Field notes\n" } { "encoding": "json", "value": { "status": "draft" } } { "encoding": "base64", "value": "AAECAw==" } ``` Choose the write mode deliberately: * `create` succeeds only when the key does not exist. * `replace` requires the current strong ETag from `tinycloud_kv_head` and fails if the value changed. * `upsert` writes without a precondition and can overwrite an existing value. For deletion, pass the current ETag to `tinycloud_kv_delete` when concurrent changes must be preserved. A failed create, replace, or guarded delete returns a precondition error instead of overwriting or deleting newer data. If a conditional mutation reports a retryable database serialization conflict, re-read the key state, which may still be absent. If it exists, compare its current ETag before deciding whether to retry. Deletion immediately removes the key from reads and listings, but retained content-addressed blob bytes, including historical versions, continue to count toward storage quota unless a future garbage collector safely reclaims them. ## SQLite reads `tinycloud_sql_schema_inspect` uses a fixed query to list user tables, views, indexes, and triggers. `tinycloud_sql_query` accepts exactly one SQLite `SELECT`, optional bind parameters, and no write, DDL, attachment, pragma, or multi-statement input. Both read tools request read authority for one exact database. Queries default to 100 rows and 1 MiB. Callers may request up to 1,000 rows and 4 MiB. Schema inspection is capped at 500 objects and 1 MiB. Limits are sent to the node and verified again by the MCP operation; excess results fail rather than being silently truncated. SQL BLOB parameters use `{ "type": "blob", "base64": "..." }`; BLOB results add `byteLength` to the same tagged representation. ## SQLite writes `tinycloud_sql_execute` is a destructive, non-idempotent tool. It accepts exactly one `INSERT`, `UPDATE`, or `DELETE`, requires at least one positional `?` placeholder, and requires one `params` value per placeholder. It rejects literal-only mutations, CTEs, DDL, pragmas, attachments, and multiple statements. The input must also set `acknowledgeDatabaseWideAuthority: true`. ```json theme={null} { "space": "", "database": "notes", "sql": "UPDATE notes SET body = ? WHERE id = ?", "params": ["reviewed", 42], "acknowledgeDatabaseWideAuthority": true } ``` > [!WARNING] > > Approving `tinycloud.sql/write` grants full read, write, and schema-mutation > authority over the exact database. The capability is not scoped to the table, > row, statement, or mutation types accepted by `tinycloud_sql_execute`. The MCP > tool enforces its narrower DML contract, but the delegation can authorize > broader database operations when used outside that tool. Grant it only when > database-wide authority is acceptable. Execution failures are never marked automatically retryable. Because the tool is non-idempotent, inspect database state before deciding whether another write is safe. ## Delegated secret flow 1. Call `tinycloud_secrets_get` with the secret name and scope. 2. If the result is `authority_required`, send the owner its `approval.url` and one line saying what it allows. The server never silently falls back to owner authority. 3. In local stdio, pass the code or delegation the owner sends back, exactly as sent, to `tinycloud_auth_import`. In hosted mode the owner approves and says continue. 4. Retry `tinycloud_secrets_get`. Requests are persisted so approval and retry can happen in separate client sessions. 5. If the result is `setup_required`, follow its Secret Manager action to add the missing value, then retry. Secret values appear only in the structured result, not in the text result, TinyCloud logs, errors, request files, or delegation files. Your MCP client may retain structured results in its own transcript, so use a client and retention policy appropriate for secrets. ## Owner profiles Owner-profile data access is disabled by default. A profile signed in with `tinycloud onboard` is an OpenKey owner profile, so select it explicitly and pass both flags, as in [Configure local stdio](#configure-local-stdio). Omitting either flag keeps owner data execution closed. ## Related CLI workflows * [Profiles](/cli/profiles) * [Auth artifacts](/cli/auth-artifacts) * [Secrets, vault, and variables](/cli/secrets) # CLI Overview Source: https://docs.tinycloud.xyz/cli/overview Install the TinyCloud CLI and pick the right command path `tinycloud` (also installed as `tc` when available) is the terminal entry point for TinyCloud. Start here to sign in, store data or inspect local profile state. ## Choose a path > [card] [Sign in](/cli/authentication) > > Set up a profile, choose OpenKey or a local key, and create a session. > [card] [Store data](/cli/storage) > > Write and read key-value data in the active space. > [card] [Manage spaces](/cli/spaces) > > Host your owned space, inspect it, or switch the active space. > [card] [Troubleshoot](/cli/diagnostics) > > Run `tc doctor`, inspect node health, and check local state. ## Install Use Node.js 22.20 or later. Reuse a compatible installed CLI (1.5.0 or newer) rather than downgrading it or creating a second installation. For a fresh manual npm installation: ```bash theme={null} npm install -g @tinycloud/cli@1.5.1 tinycloud --version ``` On Linux, `tc` may be the system traffic-control command (`/usr/sbin/tc`). Do not replace it. Use the TinyCloud executable selected by onboarding or `tinycloud`, and keep an explicit `TC_BIN` override if you already use one. Agents: start at [agents.tinycloud.xyz/onboarding](https://agents.tinycloud.xyz/onboarding). It installs the CLI and its skill and signs in with `tinycloud onboard`; see also [Agent skills](/guides/agent-skills). ### Windows Use Node.js 22.20 or later and npm. Run installation in PowerShell; the resulting launchers also work in Command Prompt. The installer reuses a compatible CLI or installs into a private npm prefix, then adds its Windows shim directory to your **user** PATH without replacing the machine PATH or unrelated commands. PowerShell: ```powershell theme={null} $installDir = Join-Path ([IO.Path]::GetTempPath()) ("tinycloud-install-" + [guid]::NewGuid()) New-Item -ItemType Directory -Path $installDir | Out-Null $installer = Join-Path $installDir "install.mjs" Invoke-WebRequest https://agents.tinycloud.xyz/install-cli.mjs -OutFile $installer node $installer if ($LASTEXITCODE -ne 0) { throw "TinyCloud installation failed; inspect the error above." } $env:TC_BIN = (node $installer --resolve) if ($LASTEXITCODE -ne 0) { throw "TinyCloud selection failed." } $env:Path += ";$env:USERPROFILE\.local\bin" Remove-Item -Recurse $installDir ``` For a new private installation, packages live under `%USERPROFILE%\.local\share\tinycloud\cli`; `tinycloud.cmd` and `tc.cmd` shims live under `%USERPROFILE%\.local\bin` when those names are available. Existing commands are not overwritten. Use the executable path the installer reports when a name is already occupied or an existing CLI was selected. **Restart the entire terminal application and your agent, not just a tab.** Running processes do not inherit the updated user PATH. If their launcher still has the old environment, sign out of Windows and sign in again. This does not require another OpenKey approval or a new TinyCloud profile. #### Repair Windows PATH For the current session only, use the block for your shell: ```powershell theme={null} $env:Path += ";$env:USERPROFILE\.local\bin" Get-Command tinycloud,tc -All tinycloud --version ``` ```bat theme={null} set "PATH=%PATH%;%USERPROFILE%\.local\bin" where tinycloud where tc tinycloud --version ``` For persistent repair, rerun the installer above. If you retained a downloaded `install.mjs`, `node install.mjs --repair-path` repairs only the Windows user PATH without installing packages or replacing launchers. The installer preserves existing entries and expandable variables, never copies the merged process PATH into the registry, never changes machine PATH, and never uses `setx`. `TC_PATH_UPDATED` or `TC_PATH_READY` means success. If it reports `TC_PATH_FAILED`, correct the reported registry/permission problem first; do not retry with administrator privileges. When a command name conflicts or before restarting, use the reported `TC_BIN`. For a fresh private installation, the absolute executable works without PATH: ```powershell theme={null} & "$env:USERPROFILE\.local\share\tinycloud\cli\node_modules\.bin\tc.cmd" --version ``` ```bat theme={null} "%USERPROFILE%\.local\share\tinycloud\cli\node_modules\.bin\tc.cmd" --version ``` If the installer selected a different existing executable, use that path instead. Never delete or replace an unrelated `tc` or `tinycloud` command. ## Defaults `tc` applies global flags first, then environment variables, then profile settings. | Flag or env | Purpose | | - | - | | `--profile` / `TC_PROFILE` | Select the active profile | | `--host` / `TC_HOST` | Override the TinyCloud node URL (default `https://tee.node.tinycloud.xyz`) | | `--json` | Force machine-readable output | | `--quiet` | Suppress banner output | | `TC_OPENKEY_HOST` | Override the OpenKey host used by browser auth | | `TC_PRIVATE_KEY` | Private key for `tc vault`, `tc vars`, and `tc secrets` | | `TC_HOME` | Move the profile store from `~/.tinycloud` | ## What the CLI covers * Authentication and session management * Key-value storage * SQLite and DuckDB database operations * Spaces, delegations, and Share links * Secrets, vault, and plaintext variables * Manifest resolution and local state inspection ## Source note Command names, flags, and defaults on the CLI pages were originally written against `@tinycloud/cli` 1.0.0. New installation examples pin stable 1.5.1; reuse a compatible newer CLI rather than downgrading. # Profiles Source: https://docs.tinycloud.xyz/cli/profiles Manage TinyCloud identities, sessions, and default spaces Profiles keep separate TinyCloud identities, keys, sessions, and defaults on one machine. ## Common commands ```bash theme={null} tc profile list tc profile create staging --host https://staging.tinycloud.xyz tc profile show tc profile switch staging tc profile delete staging ``` `tc profile create` also takes `--posture` (`owner-openkey`, `delegate-session`, or `local-owner-key`) and `--operator` (`human` or `agent`). The profile is chosen from `--profile`, then `TC_PROFILE`, then the configured default, then `default`. The node host is chosen from `--host`, then `TC_HOST`, then a discovered local node, then the profile's `host`, then `https://tee.node.tinycloud.xyz`. ## Inspect a profile ```bash theme={null} tc --profile publisher context --json ``` `tc context` reports the profile, owner and session DIDs, host, space, and whether the local session is `present`, `expired`, `missing`, or has an unknown expiry. It reads local state only and does not test access. ## Default space ```bash theme={null} tc profile set-default-space applications tc profile set-default-space --unset ``` The default space is the short name used when you omit `--space` on `tc kv` and `tc sql`. ## What each profile stores * `profile.json` for host, DID, owner, posture, and default space * `key.json` for the local keypair * `session.json` for the active session * `additional-delegations.json` and `auth-grants.jsonl` for imported and granted access Profiles live in `~/.tinycloud/profiles//` (or under `TC_HOME`), with files written `0600` in `0700` directories. ## Practical use * Create one profile for each environment or identity * Use `TC_PROFILE` to pick a default profile in a shell session * Use `TC_HOST` when you want a per-command node override > [!TIP] > > `tc init` creates a profile too, so you only need `tc profile create` when you want a profile without signing in immediately. # Secrets, Vault, and Variables Source: https://docs.tinycloud.xyz/cli/secrets Manage encrypted secrets, encrypted vault data, and plaintext variables Use this page when you need to pick the right storage layer for sensitive or non-sensitive configuration. ## Choose the layer | Layer | Command | Best for | | - | - | - | | Encrypted secrets | `tc secrets` | API keys, passwords, tokens | | Encrypted vault data | `tc vault` | Low-level encrypted key paths | | Plaintext variables | `tc vars` | URLs, feature flags, log levels | ## `tc secrets` ```bash theme={null} tc secrets network init tc secrets network show tc secrets doctor tc secrets put STRIPE_KEY "sk_live_..." tc secrets get STRIPE_KEY tc secrets list tc secrets delete STRIPE_KEY tc secrets manage ``` `tc secrets` stores values in the literal `secrets` space by default and supports logical scopes with `--scope`. ```bash theme={null} tc secrets put DATABASE_URL "postgres://..." --scope prod tc secrets get DATABASE_URL --scope prod tc secrets list --scope prod ``` You can also target another owned space with `--space`. ### Read and write options | Command | Flags | | - | - | | `get ` | `--raw` or `--value-only` prints only the value; `-o, --output ` writes it to an owner-only (0600) file atomically; `--delegation ` reads through a delegation file or imported profile | | `put [value]` | `--file ` or `--stdin` keeps the value out of shell history | | `doctor [name]` | `--scope`, `--network` (default `default`) | | `network grant [name]` | Grants another DID decrypt on the network | `tc secrets manage` opens Secret Manager at `https://secrets.tinycloud.xyz`. ### A secret that does not exist yet `tc secrets get` on a missing name exits `4` with `NOT_FOUND`. The hint is a Secret Manager link for that name, scope, and space, so the owner can add the value in the browser without it passing through the terminal or an agent. CLI 1.1.0 beta links straight to the add form with the name filled in. ## Give an agent read access to a secret An agent reads named secrets through its own profile, with a scoped OpenKey login that the owner approves. The manifest names exactly the secrets the agent may read: ```bash theme={null} cat > agent-secrets.json <<'JSON' { "app_id": "my.agent", "name": "My agent", "space": "secrets", "secrets": { "OPENAI_API_KEY": true } } JSON tc init --name agent-secrets --key-only tc --profile agent-secrets auth login --method openkey --paste \ --manifest agent-secrets.json \ --owner did:pkh:eip155:1:0xOWNER_ADDRESS --expiry 7d # Send the owner the approval URL printed on stderr and one line saying what it allows. # The owner sends back a code in chat; paste it here exactly as sent. tc --profile agent-secrets secrets get OPENAI_API_KEY --raw ``` * `secrets: { NAME: true }` requests `kv/get` on that one secret, `capabilities/read` on the `secrets` space, and decrypt on the owner's default secrets network. * `--owner` is the `did:pkh` of the account that will approve. The secrets network belongs to the owner, so a fresh profile needs it; without it the login fails with `OWNER_DID_UNKNOWN`. * Device login (`--device`) cannot grant secrets. Use `--paste` or the browser flow. * Run headless without a grant for the name, a secrets command fails fast with `PERMISSION_DENIED` (exit `5`). With a missing or expired session it fails with `AUTH_REQUIRED` (exit `3`) and names the scoped login to run. From the SDK, `secrets.listAll()` returns every secret name the session can see, global and scoped, as `{ name, scope? }` entries. It never returns values. ## Match an app manifest An app manifest's `secrets` field and `tc secrets` address the same encrypted vault entries when their names and scopes match: | Manifest declaration | CLI command | Backing path in the `secrets` space | | - | - | - | | `"API_KEY": ["read"]` | `tc secrets put API_KEY "..."` | `vault/secrets/API_KEY` | | `"API_KEY": { "scope": "my-app", "actions": ["read"] }` | `tc secrets put API_KEY "..." --scope my-app` | `vault/secrets/scoped/my-app/API_KEY` | A scoped secret is a separate entry from a global secret with the same name; TinyCloud does not fall back from one to the other. The manifest declares the access an app requests during sign-in, while the CLI or SDK writes the value. See the [complete app manifest and resolved path mapping](/reference/protocol/app-manifests#complete-runtime-app-manifest) for a copyable browser-app example. ## `tc vault` `tc vault` is the lower-level encrypted KV layer. It requires a private key. ```bash theme={null} tc vault unlock --private-key 0x... tc vault put my-app/api-key "sk_live_..." tc vault get my-app/api-key tc vault list tc vault head my-app/api-key tc vault delete my-app/api-key ``` ## `tc vars` `tc vars` stores plaintext configuration in the `variables/` prefix and also requires a private key. ```bash theme={null} tc vars put API_BASE_URL "https://api.example.com" tc vars get API_BASE_URL tc vars list tc vars delete API_BASE_URL ``` ## Private keys Use `TC_PRIVATE_KEY` or `--private-key` for `vault` and `vars`. `secrets` can use the active authenticated profile, but it also accepts a private key override. > [!NOTE] > > The CLI source treats `tc secrets network init` as the way to create or reuse the default secrets encryption network, and `tc secrets doctor` as the quickest access check. # Share Files Source: https://docs.tinycloud.xyz/cli/share Publish files as Share links, address them to a person or domain, and revoke them `tc share` publishes files from your space as links that open in the Share viewer at `share.tinycloud.xyz`. A link is either a **bearer link** that anyone holding the URL can read, or an **addressed link** that only a named email address or email domain can open. ## Enable publishing Publishing needs a session that can write to Share's paths in your `default` space. Sign a dedicated profile in once through OpenKey: ```bash theme={null} tc init --name publisher --key-only tc --profile publisher auth login --method openkey --paste \ --manifest builtin:share-publishing --expiry 30d ``` Open the link it prints and approve; the CLI then waits for the code. Agents send the owner the link and pass back the code the owner sends, exactly as sent. Publish with `tc --profile publisher share publish ...`. To approve on your phone instead, run `tc --profile publisher enable share`. `tc enable share` is the same as `tc auth login --device --manifest builtin:share-publishing`. It opens an OpenKey device approval for a narrow scope: `capabilities/read` on the space, `kv/get` and `kv/put` on `xyz.tinycloud.share/shares/` (bearer-link files), and `kv/get`, `kv/metadata`, `kv/put`, and `kv/list` on `shares/` (addressed shares). Add `--replace-session` only if you mean to replace the profile's current session with the narrower one. ## Publish ```bash theme={null} tc share publish ./report.md # bearer link (default --to anyone) tc share publish ./report.md --to alice@example.com # addressed: one email address tc share publish ./report.md --to domain:example.com # addressed: anyone verified at the domain tc share publish ./report.md --to did:pkh:eip155:1:0x... # addressed: one DID cat notes.md | tc share publish - --name notes.md # from stdin ``` Human output is exactly one URL. Use `--json` for versioned, redacted metadata. | Flag | Purpose | Default | | - | - | - | | `--to ` | `anyone`, an email address, `email:`, `domain:`, or a DID | `anyone` | | `--notify` | Email an invitation to an exact-email recipient | off | | `--expires ` | `1h`, `7d`, `1w`, or an ISO date | `7d`, clamped to the session | | `--action ` | Addressed permission: `read`, `list`, or `edit` | `read` | | `--prefix` | Publish several files beneath one addressed prefix (the viewer cannot open folders yet) | off | | `--name ` | Filename for stdin input | `stdin.md` | | `--media-type ` | Media type for a single input | inferred | | `--max-bytes ` | Bound the input size | 100 MiB maximum | | `--binary` | Allow non-UTF-8 bearer content | off | ### Expiry Without `--expires`, publish requests seven days. A session-only profile cannot grant longer than its own session, so the CLI clamps the request, prints a notice to stderr, and reports `"expiryClamped": true` in JSON. An explicit `--expires` past the session's end fails with `SESSION_LIFETIME_EXCEEDED`. ### Filenames A filename with characters other than `A-Z a-z 0-9 . _ -`, a leading character that is not a letter or digit, `..`, or more than 128 characters is stored under a readable URI-safe name: `Q3 plan (draft).md` becomes `Q3-plan-draft.md`, and `.env` becomes `share.env`. Bearer links show the stored name; addressed links keep the original. Names with control or invisible characters are refused with `UNSAFE_FILENAME`. ## Bearer and addressed links | | Bearer (`--to anyone`) | Addressed (`--to email:`, `domain:`, DID) | | - | - | - | | URL form | `share.tinycloud.xyz/viewer#tc1=...` | `share.tinycloud.xyz/s/inline#v=2&p=...` | | Who can read | Anyone with the complete URL | Only the recipient, after proving the email address | | Content | Signed delegation to the stored file | Encrypted; sealed envelope | | Revoke | Ends the delegation; cannot recall copies already read | Revokes the share's signed policy at your node | The part after `#` is the read authority. Browsers never send it to a server, but keep complete URLs out of logs, analytics, and issue trackers. Email recipients claim an addressed link in the Share viewer by entering an 8-digit code sent to that mailbox. A `domain:` target accepts any verified mailbox at exactly that domain; subdomains do not match. > [!WARNING] > > The CLI can publish to a DID (`--to did:...`), but the Share viewer cannot open > DID-addressed links yet. Use an email address or domain for links people open > in a browser. ### Email invitations `--notify` sends the recipient an invitation email with the link. It applies to exact-email targets. Invitations can be sent until the earlier of the share's expiry or five minutes after publication. If delivery fails within that window, publish exits `9` and you can retry without republishing: ```bash theme={null} tc share notify --to alice@example.com ``` After the window closes, send the link yourself or publish again. > [!NOTE] > > `@tinycloud/cli` 1.1.0 beta adds domain invitations > (`--to domain:example.com --notify --notify-to bob@example.com`) and reports a > repeat invitation as `already-delivered`. ## Inspect and receive ```bash theme={null} printf '%s' "$SHARE_URL" | tc share inspect --stdin --json # verify and print safe metadata printf '%s' "$SHARE_URL" | tc share receive --stdin --stdout # verified bytes of a bearer link tc share receive "$SHARE_URL" --output ./downloads ``` `receive` reads bearer links without a TinyCloud account. For an addressed link it exits `6` with `CLAIM_REQUIRED`: the recipient opens it in the Share viewer instead. `receive` writes a sanitized filename and will not overwrite an existing file unless you pass `--force`. Older `?tc2` links and pre-1.0 blob-backed links are not accepted. ## History and revoke ```bash theme={null} tc share list --json # encrypted sender history, without complete URLs tc share show # one record tc share show --reveal-link # include the complete URL tc share revoke tc share revoke --ancestor # also revoke the owner delegation ancestry ``` Sender history is an encrypted file in the profile's local cache, so `list`, `show`, `notify`, and `revoke` only know about shares published from that profile on that machine. ## Errors `tc share` uses its own exit codes. Read the structured `error.code` in JSON output rather than relying on the exit status alone. | Exit | Codes | Meaning | | - | - | - | | `2` | `INVALID_ARGUMENT`, `INVALID_LINK`, `ORIGIN_MISMATCH`, `SESSION_LIFETIME_EXCEEDED`, `UNSUPPORTED_LINK`, `UNSUPPORTED_TARGET` | Fix the command or link | | `3` | `AUTH_REQUIRED` | Sign in, or run `tc enable share` | | `4` | `UPLOAD_FAILED`, `STORAGE_QUOTA_EXCEEDED`, `UNAVAILABLE` | Publish failed; nothing was shared | | `4` | `NOT_FOUND`, `EXPIRED` | The share or history record is gone or expired | | `5` | `PERMISSION_DENIED` | The session lacks the scope, or carries restrictions a bearer link cannot honor | | `5` | `SIGNATURE_INVALID`, `CID_MISMATCH`, `DECRYPT_FAILED`, `ENVELOPE_INVALID`, `CAPABILITY_INVALID`, `CONTENT_INTEGRITY_FAILED` | A received link failed verification; do not trust it | | `6` | `CLAIM_REQUIRED`, `DEVICE_AUTH_REQUIRED`, `REGISTRY_REJECTED` | The recipient or owner must act, or the registry refused the owner's location record | | `7` | `MAX_BYTES_EXCEEDED` | Input or download exceeds `--max-bytes` | | `8` | `UNSAFE_FILENAME`, `OUTPUT_EXISTS` | Rename the file, or pass `--force` on receive | | `9` | partial failure | Stored, but the invitation email failed; retry `tc share notify` | A session whose Share authority carries signed restrictions (caveats) cannot publish a bearer link, because the link's delegation cannot carry them. The CLI refuses with `PERMISSION_DENIED` before uploading anything. Approve Share publishing on a fresh profile without restrictions. > [!NOTE] > > In `@tinycloud/cli` 1.1.0 beta, a full space exits `10` with > `STORAGE_QUOTA_EXCEEDED` or `STORAGE_LIMIT_REACHED`, matching the rest of the > CLI. See [When storage is full](/troubleshooting#storage-is-full). ## Related * [Share viewer](/guides/share-viewer) for what recipients see and how apps receive shares * [Sharing links](/guides/sharing) for SDK-generated bearer tokens * [Delegations](/cli/delegations) for persistent DID-to-DID access # Spaces Source: https://docs.tinycloud.xyz/cli/spaces Host, inspect, and switch TinyCloud spaces A space is the owned container TinyCloud uses for data and permissions. Use this page when you need to host a new owned space, inspect the current one, or switch the active space name. ## Host a space ```bash theme={null} tc space create applications tc space host applications ``` `create` and `host` are aliases. They host one of your owned spaces by name and return the resolved space URI. ## Inspect a space ```bash theme={null} tc space list tc space info tc space info applications ``` `tc space info` accepts either the active space or a specific space URI/name. Use `tc space list` first if you want to see what is already hosted. ## Switch the active space name ```bash theme={null} tc space switch applications ``` Switching changes the default space name stored in the profile. It does not create or host the space by itself. ## Delegate-only hosting If you are not the owner of a space, use `tc space host-request ` to emit a host request artifact for the owner. ## When to use spaces * Host the `applications` space before writing manifest-scoped app data * Host the `secrets` space when a session needs TinyCloud secrets access * Switch the active space name when you want the CLI to target a different owned space by default > [!TIP] > > `tc kv`, `tc sql`, and `tc secrets` all use the active profile and may target a non-primary space with `--space` when needed. # SQL Source: https://docs.tinycloud.xyz/cli/sql Query and manage SQLite databases in TinyCloud Use `tc sql` when your app stores structured data in a TinyCloud space and you want SQLite semantics from the terminal. ## Core commands ```bash theme={null} tc sql query "SELECT * FROM notes ORDER BY id" tc sql execute "INSERT INTO notes (body) VALUES (?)" --params '["ship docs"]' tc sql export --output notes.db tc sql copy --from-db source --to-db destination ``` ## Targeting `--db` picks the database name inside the current space. `--space` targets a different owned space. ```bash theme={null} tc sql query "SELECT count(*) FROM events" --db analytics tc sql query "SELECT count(*) FROM conversation" --space applications --db xyz.tinycloud.listen/conversations ``` ## Parameters Pass bind parameters as a JSON array. ```bash theme={null} tc sql query "SELECT * FROM notes WHERE id = ?" --params '[1]' tc sql execute "UPDATE notes SET body = ? WHERE id = ?" --params '["edited", 1]' ``` ## Outputs * `query` prints a table in the terminal and JSON with `--json` * `execute` returns `changes` and `lastInsertRowId` * `export` writes a `.db` file locally * `copy` moves rows between databases and can run as a dry run ## Practical order 1. Create or host the target space 2. Run `tc sql execute` to materialize the schema 3. Query with `tc sql query` 4. Export only when you need a local copy > [!TIP] > > If a SQL command fails because the target space is not hosted, host the owned space first and retry the command. # Status Source: https://docs.tinycloud.xyz/cli/status Inspect local profiles, sessions, delegations, and permissions `tc status` is the local-state command. Use it when you need a compact view of all configured profiles and what each one can currently do. ```bash theme={null} tc status tc status --json ``` ## What it shows * Active and default profile names * Profile count * How many profiles are authenticated * Active delegation count * Per-profile session state, DID, address, and space * Compact permission summaries * Issues discovered while reading local profile state ## When to use it * Before retrying a failed command * Before importing or granting a delegation artifact * When you need to prove which profile is active in a workspace > [!NOTE] > > `tc status` reads local profile files only; it does not contact the node. # Key-Value Storage Source: https://docs.tinycloud.xyz/cli/storage Store and retrieve data in TinyCloud spaces Use `tc kv` when you want the shortest path from a shell prompt to a stored value. ## Basic workflow ```bash theme={null} tc kv put greeting "Hello, TinyCloud" tc kv get greeting tc kv list tc kv delete greeting ``` ## Input and output `tc kv put` accepts one of three inputs: | Input | Example | | | - | - | - | | Argument | `tc kv put greeting "Hello"` | | | File | `tc kv put config --file ./config.json` | | | Stdin | \`cat payload.json | tc kv put payload --stdin\` | `tc kv get` can print plain text, raw bytes, or JSON: ```bash theme={null} tc kv get greeting tc kv get greeting --raw tc kv get greeting --output ./greeting.txt ``` ## Target a different space ```bash theme={null} tc kv get greeting --space applications tc kv put config/app --space applications --file ./config.json ``` `--space` accepts either a short owned-space name or a full `tinycloud:pkh:eip155:...` URI. ## What the command family does * `put`, `get`, `list`, `delete` * `head` for metadata without fetching the body * `--prefix` for listing a subset of keys * the global `--json` flag for scripting-friendly output ## Key rules Keys cannot contain spaces or control characters. `get`, `put`, `head`, `delete`, and `list --prefix` refuse them with `USAGE_ERROR` (exit `2`) before contacting the node. Use `-`, `_`, `.`, or `/` instead. ## When storage is full Reads keep working when your storage is full; writes are refused and nothing is saved. In CLI 1.0.0, `tc kv put` exits `1` with `STORAGE_QUOTA_EXCEEDED` and the used and limit sizes when the node reports them. > [!NOTE] > > CLI 1.1.0 beta gives every command one storage-full result: exit `10`, code > `STORAGE_QUOTA_EXCEEDED` (or `STORAGE_LIMIT_REACHED` when a single write is > larger than the space left), and a link to manage storage. See > [Storage is full](/troubleshooting#storage-is-full). ## Good defaults * Quote JSON-like shell values so the shell passes them as a single argument * Use `--raw` when you need the exact stored value in a pipe * Use `--output` when you want to save binary data to a file > [!NOTE] > > The CLI source routes KV operations through the active profile and uses the node's primary space unless you pass `--space`. # App manifests Source: https://docs.tinycloud.xyz/concepts/app-manifests Understand how manifests shape TinyCloud sign-in and requested capabilities. An app manifest is the input the SDK uses to build the sign-in capability request. It describes the app, the resources it needs, and any derived delegations it should request on the user's behalf. Use a manifest when you want one sign-in flow to cover: * the app's own data surface * any backend or agent permissions that should be bundled at sign-in * optional account-registry writes for the signed-in user ## What the SDK does During sign-in, the SDK resolves the manifest or pre-composed capability request, unions the requested permissions, and signs a single recap. For owned encryption networks, the SDK can also request `tinycloud.encryption/network.create` alongside `tinycloud.encryption/decrypt` so the network exists after sign-in. The manifest is not backend configuration. It is a client-side declaration that the SDK turns into a capability request before the user signs in. ## What manifests are good at * keeping app permissions in one place * giving consent UIs and agents a readable summary of intent * describing app-scoped prefixes and default spaces * carrying optional knowledge-bundle metadata for agent-readable apps ## What to avoid * do not treat a manifest as a substitute for server policy * do not duplicate exact permission syntax here if you only need the field list * do not invent a backend/delegation section that the SDK does not support ## Reference For the exact manifest fields, defaults, and composition rules, see [App manifest reference](/reference/protocol/app-manifests). For the app-authoring bundle shape, see [Agent-readable Apps](/guides/agent-readable-apps). ## Source note The manifest behavior described here follows the TinyCloud JS SDK manifest composer and sign-in tests. The reference page contains the field-level shape. # Capabilities Source: https://docs.tinycloud.xyz/concepts/capabilities Read TinyCloud ability strings, delegation scope, and registry status. TinyCloud capabilities answer one question: what may a principal do, and on which resource. Ability strings use the form `tinycloud.{service}/{action}`. The generated capability registry lists the exact action names, aliases, and reserved entries from `tinycloud-node`. > [card] [Generated registry](/reference/protocol/capabilities) > > Use the generated registry for the exact action spellings, status, aliases, > and service groupings. This concept page explains how to interpret them. ## How to read an ability An ability has two parts: * `tinycloud.{service}` names the service namespace * `{action}` names the permitted operation For example, `tinycloud.kv/get` allows KV reads, while `tinycloud.sql/schema` allows schema changes that the SQL authorizer accepts. Deprecated aliases are normalized by the node before authorization. ## Scope comes from the resource The action says what the capability can do. The resource URI and path say where it can do it. * KV and VFS use prefix containment when the capability path ends with `/` * KV and VFS use exact matching when the path does not end with `/` * SQL uses exact path matching That means `docs/` can cover `docs/readme.md`, but `docs` does not act like a prefix. This is the same containment rule the node uses when checking policy capabilities. ## Delegation and attenuation Capabilities are delegatable and can be narrowed by: * reducing the action set * narrowing the path * shortening the expiry * disabling sub-delegation Revocation cuts off the revoked capability and anything derived from it. That gives TinyCloud a chain-of-trust model instead of a static API-key model. ## Source note This page describes the authorization model. The generated registry page is the source of truth for action spelling and status; the node and SDK code describe how scope containment and delegation attenuation are enforced. # Data Vault Source: https://docs.tinycloud.xyz/concepts/data-vault Understand the client-side encrypted vault model used by TinyCloud. TinyCloud's data vault encrypts values before KV storage. Storage receives ciphertext and metadata, but **key custody depends on the vault mode**. Do not equate every encrypted vault with endpoint-only E2EE. For the wallet-derived unlock and sharing flow, see [Data Vault](/guides/data-vault). ## Vault model The vault sits on top of the user's TinyCloud space and is available through the Node and Web SDKs: | Mode | Key and plaintext boundary | | - | - | | Wallet-derived vault | The SDK derives keys from wallet signing material and encrypts/decrypts locally. Keeping the wallet/key material and decrypted results exclusively at trusted endpoints is an application responsibility. | | Network-backed vault | The SDK encrypts values locally to an encryption network and uses a node-mediated decrypt/key-release request before local value decryption. The network's key custody, authorization and any verified TEE policy are additional trust assumptions. | A storage-only node sees encrypted values, not their contents. This is not a claim that a key-release service, an authorized client or hosted MCP cannot obtain plaintext. Metadata, paths and access patterns may remain visible. See [Security and trust](/concepts/security-and-trust). In wallet-derived mode, unlock also publishes discovery metadata so other principals can share data with you. The important split is: * primary space: encrypted vault data and sharing grants * public space: discovery metadata only Do not store sensitive data in the public space. ## What the vault is for * client-side encrypted KV storage * per-entry encryption and decryption * sharing encrypted values with another principal * keeping ciphertext usable across sessions, subject to the chosen key-custody mode ## Source note The implementation uses the vault helpers in the JS SDK and WASM bindings. The guide page explains the task flow; this concept page explains the trust model and the public/primary space split. # DID Formats Source: https://docs.tinycloud.xyz/concepts/did-formats Use the right DID for identity, delegation, and debugging. TinyCloud uses two DID shapes in the SDK: * a persistent owner DID, usually `did:pkh:...` * an ephemeral session DID, usually `did:key:...#...` The SDK exposes both through `tc.did` and `tc.sessionDid`. Which value you get depends on whether the instance has an authenticated wallet-backed identity or is running in session-only mode. ## Owner DID After `signIn()` with a wallet, `tc.did` returns the owner DID. ```typescript theme={null} await tc.signIn(); console.log(tc.did); // did:pkh:eip155:1:0x... ``` Use the owner DID for: * delegations to other users or services * persistent user identity * records that should survive wallet re-authentication ## Session DID `tc.sessionDid` always returns the session key DID. ```typescript theme={null} console.log(tc.sessionDid); // did:key:z6Mk...#z6Mk... ``` Use the session DID for: * debugging * tracing the active session key * understanding temporary session-only setups ## What `tc.did` returns | State | `tc.did` | `tc.sessionDid` | | - | - | - | | Wallet signed in | owner DID | session DID | | Session-only mode | session DID | session DID | The practical rule is simple: after wallet sign-in, use `tc.did` for delegation targets and user identity. Reach for `tc.sessionDid` only when you need the ephemeral key itself. ## Source note The SDK behavior described here is implemented in `TinyCloudNode.ts` and shared through the browser wrapper. The docs use owner DID and session DID to avoid the `did:pkh` vs `did:key` mix-up that breaks delegation chains. # Security and trust Source: https://docs.tinycloud.xyz/concepts/security-and-trust What TinyCloud assumes, what it verifies, and what you should not infer. TinyCloud is built around cryptographic proofs and attenuated capabilities. The safe default is to assume only what the linked docs and source explicitly establish. ## Encryption and operator access TinyCloud capabilities control **who is authorized to act**. They do not by themselves encrypt content or make the service unable to read it. The [homepage mode comparison](/#privacy-at-a-glance) summarizes the choices. * **Transport and storage:** HTTPS encrypts traffic to its TLS endpoint. Disk, database, backup or sealed-state encryption protects stored bytes, not plaintext in the process that can decrypt them. Do not assume every deployment encrypts every disk or backup. * **Ordinary KV and SQL:** the SDK sends values, SQL and parameters to the node for processing. Unless the application encrypts content first, an ordinary node operator can read it. A space is an authorization boundary, not an encryption boundary. * **Application E2EE:** this requires encryption before storage and keys available only to the intended endpoints. The SDK's wallet-derived vault mode encrypts and decrypts locally. Network-backed vault mode also encrypts values locally, but uses a node-mediated key-release/decrypt flow: its key service is an additional trust boundary. Do not describe both modes as “only the user can decrypt.” See [Data Vault](/concepts/data-vault). * **Authorized clients:** a client, agent or recipient that receives plaintext can retain or disclose it. An AI provider's handling of tool results is a separate trust decision. Expiry and revocation stop future authorized access; they cannot recall copies already read. * **Hosted MCP:** the service processes readable inputs and results, including delegated secret values. Its runtime and operator are in the trust boundary even when the node stores encrypted envelopes. Local CLI/stdio removes that hosted MCP hop, not the node or AI-client boundary. * **Self-hosting:** choosing your own node or MCP operator changes whom you trust. It does not hide plaintext from that operator's administrators, runtime, logs or backups unless a separate verified protection does so. ### TEE and OpenKey limits A trusted execution environment (TEE) is a server-side execution boundary, not application E2EE. The protected program may handle plaintext or keys. Protection from the infrastructure operator depends on hardware trust, verification of a fresh attestation bound to the service/key, accepted code measurements, key-release policy, and what the program exports or logs. It does not protect plaintext sent onward to an authorized client. OpenKey's production key-sealing implementation uses dstack-derived keys and exposes bound quotes; its explicit local-development mode uses mock keys. OpenKey-managed keys are unsealed for signing in the service runtime. This is different from a wallet whose key stays exclusively on the user's device. Passkey sign-in alone does not encrypt application records. Neither a `tee` hostname, a deployment file, nor the existence of an attestation endpoint proves that your client verified the running deployment. These docs do not certify a live deployment or promise that every SDK/MCP request verifies hardware attestation. Check the actual verifier, accepted measurements and deployment policy before relying on operator exclusion. ## What TinyCloud verifies * A signer proves control of the wallet or key that signs the SIWE flow. * The session carries capabilities that bound what it may do. * Delegations must stay within the parent capability's scope. * The generated capability registry records the exact action names, aliases, and statuses that the node currently accepts. ## What TinyCloud does not hand you for free * A session DID is not a durable user identity. Use `tc.did` after `signIn()` when you need the owner's DID. * An ability listed in the whitepaper is not automatically a shipped action. Check the generated registry and implementation docs. * OpenKey OAuth is not the same thing as TinyCloud authentication. TinyCloud still uses SIWE for its own sign-in flow. * Revoking a bearer Share link stops new reads, but cannot recall copies already downloaded. Anyone holding the complete URL can read it until then. Use an addressed share when only one person or domain should read it. * An HTML page shared as a bearer link runs in a sandboxed frame. It cannot read the link or the viewer's session, but it can reveal the reader's IP address to the sender. ## Trust boundaries | Boundary | Safe assumption | Read more | | - | - | - | | Identity | `tc.did` becomes the owner DID after sign-in; `tc.sessionDid` remains the ephemeral session key DID. | [DID Formats](/concepts/did-formats) | | Authorization | Capabilities are delegated, scoped, and revocable. | [Capabilities](/concepts/capabilities) and [Delegations](/guides/delegations) | | Storage | Ordinary node operators can read unencrypted values; application encryption and network-backed key release have separate trust boundaries. | [Spaces](/guides/spaces) and [Data Vault](/concepts/data-vault) | | App requests | Manifests describe requested permissions and delegation targets before sign-in. | [App manifests](/concepts/app-manifests) | | Sharing | Browsers omit a URL fragment from the HTTP request, but client code can read it. Addressed shares use encryption and a signed policy at the owner's node. Keep complete links out of logs and messages to unintended recipients. | [Share files](/cli/share) | | Agents | An agent holds only what the owner approved for its profile through OpenKey, and the owner sees each capability before approving. | [Agent skills](/guides/agent-skills) | ## Security posture 1. Treat the implementation docs as the source of truth for shipped behavior. 2. Treat the generated capability registry as the source of truth for ability names, aliases, and status. 3. Treat whitepaper material as normative only when it does not conflict with code-backed behavior. 4. Do not infer extra guarantees from a page layout, a proposal, or a marketing summary. ## Source note The boundaries above follow the SDK's `KVService`, `SQLService`, `DataVaultService` and `EncryptionService`, the MCP operation/result pipeline, and OpenKey's `packages/tee` sealing and quote implementation. Source: [JS SDK](https://github.com/TinyCloudLabs/js-sdk) and [OpenKey](https://github.com/TinyCloudLabs/openkey). They describe implementation paths, not a live deployment audit. # System model Source: https://docs.tinycloud.xyz/concepts/system-model How identity, spaces, capabilities, manifests, and services fit together in TinyCloud. TinyCloud is easier to use when you keep four pieces distinct: * identity * space * capability * service ## The core pieces | Piece | What it does | Where to read next | | - | - | - | | Identity | Tells TinyCloud who is acting. After `signIn()`, `tc.did` is the owner DID and `tc.sessionDid` is the session DID. | [DID Formats](/concepts/did-formats) | | Space | Isolates a user's data into a deterministic ownership container. | [Spaces](/guides/spaces) | | Capability | States what an actor may do, using TinyCloud ability strings and delegation chains. | [Capabilities](/concepts/capabilities) and [Capability Registry](/reference/protocol/capabilities) | | Manifest | Describes which capabilities an app asks for during sign-in and which principals can receive derived delegations. | [App manifests](/concepts/app-manifests) | ## How the pieces work together 1. A user signs in with a wallet or with OpenKey as the signer. 2. TinyCloud establishes a session and resolves the identity that should act for that session. 3. The SDK composes the requested capabilities and provisions missing owned resources when the flow requires it. 4. Requests go through the node with the capability chain and resource scope that the session carries. ## Reading order by task * If you are building a browser app, start with [Browser app path](/start/browser-app). * If you are building a backend service, start with [Backend service path](/start/backend-service). * If you are checking ability spelling or manifest fields, start with [Protocol path](/start/protocol). * If you are deploying or debugging the stack, start with [Operator path](/start/operator). ## Trust note This page explains the model, not the full protocol surface. For exact action names, statuses, and aliases, use the generated capability registry. For shipped behavior around auth, spaces, and storage, defer to the linked guides and the SDK source. # Access and explore my TinyCloud Source: https://docs.tinycloud.xyz/guides/access-and-explore-my-tinycloud Let an agent discover, read, and safely update selected TinyCloud data Use this workflow when an agent needs to discover what is in a user's TinyCloud. Agents that can run the CLI sign in once with `tinycloud onboard` (start at [agents.tinycloud.xyz/onboarding](https://agents.tinycloud.xyz/onboarding)) and use the [CLI path](#cli-path). Other agents need a compatible hosted MCP connection; check [client setup and support](/cli/mcp#choose-your-client). Approval codes and delegations are credentials. Return them only to the requesting agent's trusted conversation when that flow requires it; never publish them or send an owner private key. ## MCP path In a client that supports Streamable HTTP MCP and OAuth (for example Claude app or a ChatGPT custom connection), add `https://mcp.tinycloud.xyz/mcp`. Call `tinycloud_connect`, approve its one-time OpenKey link, and call it again before continuing with account discovery below. Hosted mode creates and maintains the agent's profile for you and exposes 20 tools. For personal records, just ask “Log my weight: 80.5 kg today.” Approve connect and the separate records request once, then Claude uses `tinycloud_apps_context`, `tinycloud_apps_read`, `tinycloud_apps_write` and `tinycloud_apps_query`. These hosted-only tools share the coding-agent records under `xyz.tinycloud.agent-data/` in `default`, using one prefix grant for get, list, put and delete. Generic KV tools still request their exact input scope. Supply an IANA timezone once, not your city or precise location. Fresh reads return ETags for conditional edits; stale edits return `CHANGED`. Ordered write batches can partially succeed: inspect each outcome and move steps before retrying, and report only what was saved. For larger questions, Claude can offer an optional **fast, searchable copy of your records**, with its own approval. KV remains the truth. `COPY_PARTIAL` resumes on the next query; nonretryable `copy_unavailable` needs the node team, so answer from KV. See [TinyCloud MCP](/cli/mcp) for the complete contract and approval settings. Hosted MCP and the AI client receive plaintext results. Read the [privacy boundaries](/concepts/security-and-trust) before approving access. Production grants last 30 days and approval links last 15 minutes. An expired session returns a fresh link in `error.details`; an expired grant returns an `authority_required` approval link. Approve the new link before retrying. Hosted results include readable canonical JSON in text except successful secret values. Read-only results have a 100,000-character cap; write results are never truncated by it. For a local MCP client, install the CLI and MCP packages with Node.js 22.20 or later and sign in once with `tinycloud onboard`. The local stdio surface has 17 tools and needs a TinyCloud node running 1.6.0 or newer. ```bash theme={null} npm install --global @tinycloud/cli @tinycloud/mcp tinycloud onboard ``` Onboarding already allows account registry reads. Configure MCP with that profile as described in [TinyCloud MCP](/cli/mcp). The data surface is: | Tool | Purpose | | - | - | | `tinycloud_account_spaces_list` | List spaces in the canonical account registry | | `tinycloud_account_applications_list` | List applications and their registered manifests | | `tinycloud_kv_list` | List keys in one selected space, optionally under a prefix | | `tinycloud_kv_get` | Read one selected key | | `tinycloud_kv_head` | Read metadata and the current ETag for one selected key | | `tinycloud_kv_put` | Create, conditionally replace, or explicitly upsert one selected key | | `tinycloud_kv_delete` | Delete one selected key, optionally guarded by its ETag | | `tinycloud_sql_schema_inspect` | Inspect one selected SQLite database | | `tinycloud_sql_query` | Run one bounded `SELECT` against one selected SQLite database | | `tinycloud_sql_execute` | Run one positional-parameterized `INSERT`, `UPDATE`, or `DELETE` | The remaining seven local tools manage the selected session and protected secret flow: | Tool | Purpose | | - | - | | `tinycloud_status` | Inspect safe local profile state | | `tinycloud_auth_status` | Inspect authentication state | | `tinycloud_auth_capabilities` | Inspect validated active capabilities | | `tinycloud_auth_request` | Create or recover an exact permission request | | `tinycloud_auth_import` | Validate and import a request-bound delegation (local only) | | `tinycloud_secrets_get` | Read one specifically delegated secret | | `tinycloud_secrets_status` | Inspect secret readiness without reading values (local only) | Call `tinycloud_account_spaces_list` first. Compare its space IDs with `tinycloud_account_applications_list`, then choose a space and call `tinycloud_kv_list`. Read individual keys with `tinycloud_kv_get` only after their names and app context are known. Account registry discovery is capped at 1,000 records, 1 MiB per record, and 4 MiB total serialized output. It fails closed instead of returning a partial registry. Do not treat an application name as permission to read every key in its space. Use its manifest and any linked knowledge bundle to identify relevant prefixes and data shapes. See [Agent-readable Apps](/guides/agent-readable-apps). ## Store a file safely TinyCloud KV values can hold arbitrary bytes. After selecting the target space and key, call `tinycloud_kv_put` with tagged content. For a Markdown file the tool input can be: ```json theme={null} { "space": "", "key": "agent-notes/sqlite-safety.md", "mode": "create", "content": { "encoding": "utf8", "value": "# SQLite safety notes\n\nUse bind parameters and bounded reads.\n" }, "contentType": "text/markdown; charset=utf-8" } ``` If that returns `authority_required`, follow [Approving more access](#approving-more-access) and retry the same input. `create` cannot overwrite an existing key. To update a known value safely, call `tinycloud_kv_head`, copy its strong quoted `etag`, and use `mode: "replace"` with that ETag. Use `mode: "upsert"` only when overwriting without a concurrency check is intentional. For binary files, base64-encode the bytes and use `{ "encoding": "base64", "value": "..." }`. KV reads and writes are capped at 1 MiB. `tinycloud_kv_get` defaults to base64 and also supports explicit `text` and `json` representations. It returns the representation tag, byte length, ETag, and available content metadata. Delete only a selected key. Passing the ETag from `tinycloud_kv_head` to `tinycloud_kv_delete` prevents deleting a value that changed after inspection. If a conditional mutation reports a retryable database serialization conflict, re-read the key state, which may still be absent. If it exists, compare its current ETag before deciding whether to retry. Deletion removes the key from reads and listings immediately; retained content-addressed blob bytes, including historical versions, continue to count toward storage quota unless a future garbage collector safely reclaims them. Generic KV tools cannot access the protected `account` or `secrets` spaces. ## Inspect SQLite Call `tinycloud_sql_schema_inspect` with an exact `space` and `database` first. Then call `tinycloud_sql_query` with the same target, exactly one SQLite `SELECT`, and optional bind `params`. These MCP tools do not execute writes, DDL, pragmas, attachments, or multiple statements. Queries default to 100 rows and 1 MiB and allow explicit limits up to 1,000 rows and 4 MiB. Oversized results fail instead of being silently truncated. SQLite BLOB parameters use `{ "type": "blob", "base64": "..." }`; BLOB results use the same tag and include `byteLength`. Each SQL read tool requests read capability for the exact database, not the entire space. ### Mutate SQLite data `tinycloud_sql_execute` is destructive and non-idempotent. It accepts exactly one `INSERT`, `UPDATE`, or `DELETE` with at least one positional `?` placeholder and one `params` value per placeholder. The input must explicitly include `acknowledgeDatabaseWideAuthority: true`: ```json theme={null} { "space": "", "database": "notes", "sql": "INSERT INTO notes (body, status) VALUES (?, ?)", "params": ["Review delegation boundaries", "draft"], "acknowledgeDatabaseWideAuthority": true } ``` The tool rejects literal-only mutations, CTEs, DDL, pragmas, attachments, and multiple statements. Its result reports the statement type, changed-row count, and last inserted row ID when available. > [!WARNING] > > The requested `tinycloud.sql/write` capability is broader than this tool. > Approving it grants full read, write, and schema-mutation authority over the > exact database, including when the delegation is used outside MCP. It is not > scoped to a table, row, SQL statement, or the three mutation types enforced by > `tinycloud_sql_execute`. Approve only when database-wide authority is intended. Execution failures are never marked automatically retryable. Because the tool is non-idempotent, inspect database state before deciding whether another write is safe. ## Approving more access When a tool returns `authority_required`, send the owner its approval link and one line saying what it allows. On local stdio the owner sends back the short code and you pass it to `tinycloud_auth_import` exactly as sent; on hosted MCP the owner approves, says continue, and you retry the same tool unchanged. Imports persist in the selected profile, so approval and retry may happen in different MCP process sessions. Don't edit the request, and don't replace an exact request with a broad space-wide one. For `tinycloud.sql/write`, tell the owner it covers the whole database. ## CLI path After `tinycloud onboard`, the agent can read the account registry and the applications space directly. Use machine-readable output and canonical live account reads: ```bash theme={null} tinycloud --quiet --json account spaces list --live tinycloud --quiet --json account apps list --live tinycloud --quiet --json account spaces info tinycloud --quiet --json account apps info ``` `--live` matters for read-only discovery. The default indexed spaces path may refresh and register accessible spaces when its index is empty. After selecting a space, list keys and read only the chosen key: ```bash theme={null} tinycloud --quiet --json kv list --space --prefix tinycloud --quiet --json kv get --space ``` If a command needs more than onboarding granted, ask once: ```bash theme={null} tinycloud auth request --cap tinycloud.kv:::get,list \ --grant --paste --expiry 30d ``` Send the owner the link it prints and one line saying what it allows. The owner approves and sends back a short code; pass it to the CLI exactly as sent. ## Stop conditions Stop and return the structured result instead of widening authority when: * the owner rejects or changes the request * a space or app is absent from the canonical account registry * the app manifest does not explain a prefix or value shape * a write or delete was not explicitly requested, or its exact target is unclear * a SQL read request is not one bounded read-only `SELECT` * a SQL mutation lacks the explicit database-wide-authority acknowledgment * the owner does not accept database-wide SQL write and schema authority * the next step needs a secret value that the user did not request Secret tools have an additional transcript boundary: the MCP server keeps secret values out of text results and TinyCloud logs, but the MCP client may retain structured results. See [TinyCloud MCP](/cli/mcp) before reading secrets. # Agent-readable Apps Source: https://docs.tinycloud.xyz/guides/agent-readable-apps Ship concise app knowledge alongside TinyCloud app manifests TinyCloud app manifests declare what an app needs at install and sign-in time. Agent-readable app knowledge explains what those resources mean after the app is installed. Ship the two together: ```text theme={null} my-app/ manifest.json knowledge/ index.md resources.md sql.md kv.md secrets.md operations.md ``` Small apps should keep this flat. Add nested directories only when a category is large enough that a single file becomes hard to scan. ## Manifest Link Use the manifest to point to the knowledge bundle: ```json theme={null} { "manifest_version": 1, "app_id": "com.example.notes", "name": "Notes", "knowledge": true } ``` `knowledge: true` means the default root is `knowledge/index.md`. Use a string when the root differs: ```json theme={null} { "knowledge": "knowledge/index.md" } ``` The manifest remains the runtime declaration. The knowledge bundle is the operational map for humans and agents. ## Required File Every bundle starts with `knowledge/index.md`: ```md theme={null} --- type: TinyCloud App title: Notes description: Personal notes with optional AI summaries. --- # Notes Notes stores user-authored documents in KV and search metadata in SQLite. ## Resources - [KV](kv.md) - Note documents under `documents/*`. - [SQL](sql.md) - Search metadata in the `main` SQLite database. - [Secrets](secrets.md) - Optional model provider key for summaries. - [Operations](operations.md) - Install, migration, and recovery notes. ``` The index should be useful by itself. Do not make it a table of contents that forces agents to open several files before understanding the app. ## Category Files Use category files only when the app uses that category. | File | Purpose | | - | - | | `resources.md` | One-page summary of all TinyCloud data surfaces. | | `sql.md` | SQLite databases, tables, schema notes, and mutation rules. | | `kv.md` | KV prefixes, value shapes, and lifecycle rules. | | `secrets.md` | Secret references, consumers, rotation, and failure behavior. | | `operations.md` | Install, migration, repair, and agent operating notes. | For a single SQLite database, prefer `sql.md`. Use `sql/index.md` only when the app has multiple independent databases or a large schema. For schema setup, document the migration path and required `tinycloud.sql/schema` capability. See [SQL Schema and Migrations](/guides/sql-schema-and-migrations). ## Resource Sections Each resource section should stay concise: ```md theme={null} ## Documents Prefix: `documents/*` Purpose: User-authored notes stored as JSON documents. Access: | Capability | Why | | --- | --- | | `tinycloud.kv/get` | Read notes. | | `tinycloud.kv/put` | Save edits. | | `tinycloud.kv/list` | List note ids. | Agent notes: - Do not delete documents unless the user explicitly asks. - Preserve unknown JSON fields. ``` SQL files should also say whether tables are canonical data or rebuildable indexes. Rebuildable tables should name the source of truth. ## Secrets Document secret references, never secret values: ```md theme={null} ## Model API Key Name: `model-api-key` Purpose: Optional provider key used by the summary worker. Consumers: - `agent.summarizer` Rotation: User-managed. Agent notes: - Never write the plaintext value into the knowledge bundle. - If missing, disable summaries instead of blocking note editing. ``` ## Tooling TinyCloud app-kit owns schemas, examples, guides, and app-authoring skills: [TinyCloudLabs/tinycloud-app-kit](https://github.com/TinyCloudLabs/tinycloud-app-kit). The docs explain the contract; app-kit artifacts make it executable. # Install TinyCloud Agent Skills Source: https://docs.tinycloud.xyz/guides/agent-skills Give any agent that runs a shell the TinyCloud CLI skill, and add app skill packs Coding agents use TinyCloud through the `tinycloud` CLI. Its stable npm package ships a `tinycloud-cli` skill that teaches the commands, authentication flows and error codes for that exact release. The quickest setup is [agents.tinycloud.xyz/onboarding](https://agents.tinycloud.xyz/onboarding): it installs the CLI and skill and runs `tinycloud onboard`. The steps below do the same by hand. For ChatGPT, Claude app, Grok/GrokBot and WhatsApp/Instinct connection qualifications, see [Choose your client](/cli/mcp#choose-your-client). The shell instructions below apply to Claude Code, Codex and OpenCode runtimes that can execute local commands, not every app bearing those names. ## Install the CLI and the `tinycloud-cli` skill Use Node.js 22.20 or later. Prefer onboarding, which reuses a compatible installed CLI rather than installing a second copy. For a fresh manual installation, the stable CLI pin is 1.5.1; do not downgrade a compatible newer installation. ### macOS and Linux ```bash theme={null} npm install --global @tinycloud/cli@1.5.1 TC="$(npm prefix --global)/bin/tc" # avoids /usr/sbin/tc on Linux VERSION="$("$TC" --version)" npx --yes skills@1.7.0 add \ "https://registry.npmjs.org/@tinycloud/cli/-/cli-${VERSION}.tgz" \ --skill tinycloud-cli --global --copy --agent opencode codex claude-code --yes ``` This copies the skill for that CLI release into each client's skill directory, for example `~/.claude/skills` for Claude Code, or `~/.agents/skills` for OpenCode and Codex. Pass the agents you use; other agents use their own skills folder. Start a new agent session and ask it to use `tinycloud-cli`. > [!WARNING] > > On Linux, `tc` on the `PATH` often resolves to `/usr/sbin/tc`, the iproute2 > traffic-control tool. Point agents at the CLI by absolute path, as above. ### Windows Follow [Windows installation and PATH repair](/cli/overview#windows). For a manual npm installation, resolve the Windows npm shim and install the skill for that CLI's actual version in PowerShell: ```powershell theme={null} $TC = Join-Path (npm prefix --global) 'tinycloud.cmd' $Version = (& $TC --version).Trim() npx --yes skills@1.7.0 add "https://registry.npmjs.org/@tinycloud/cli/-/cli-$Version.tgz" --skill tinycloud-cli --global --copy --agent opencode codex claude-code --yes ``` If onboarding selected an existing CLI or the private installer, use that reported executable as `$TC` instead. Do not install another copy just to match this example. ## Check, update, and remove ```bash theme={null} "$TC" --version npx --yes skills@1.7.0 list --global ``` Keep the skill and CLI release aligned. To update, explicitly upgrade the selected installation and rerun `skills add` with that version's tarball URL; a pinned URL never updates itself. Preserve locally modified skills. ```bash theme={null} npx --yes skills@1.7.0 remove tinycloud-cli --global --agent opencode codex claude-code --yes npm uninstall --global @tinycloud/cli ``` Removing the skill or the CLI does not delete TinyCloud profiles or revoke any access an agent was granted. Revoke those with `tc delegation revoke` or from the account app. ## Give the agent access The agent runs `tinycloud onboard` once and reuses its grants. If a task needs more access, request only the missing permissions with `tinycloud auth request ... --grant --no-popup --expiry 30d`. Send the complete short URL on its own line and keep the command running; it retrieves approval automatically. After interruption, rerun the same command and profile. Explicit `--paste` selects the older long-link, manual-code fallback. | Task | How the agent gets access | | - | - | | Explore and edit app data | Included in `tinycloud onboard`; see [Access and explore my TinyCloud](/guides/access-and-explore-my-tinycloud) | | Publish Share links | A dedicated `publisher` profile: `tinycloud --profile publisher auth login --method openkey --no-popup --manifest builtin:share-publishing --expiry 30d`; see [Share files](/cli/share) | | Read named API keys | A `secrets` manifest on its own profile; see [Secrets](/cli/secrets#give-an-agent-read-access-to-a-secret) | ## App skill packs App skill packs build on `tinycloud-cli` for one job and publish their own CLI requirements. The packs below are in [TinyCloudLabs/prompts](https://github.com/TinyCloudLabs/prompts), currently in preview: * **`tc-publish`** publishes a document or HTML page and returns an owner-only or public Share link. * **`tc-secrets`** reads API keys the owner keeps in Secret Manager, without the values passing through chat. Install a pack by copying its directory into the agent's skill path, and follow its `QUICKSTART.md` for the operator settings it expects. Packs never install software themselves; if the CLI is too old they stop and say so. ## Related * [Agent-readable apps](/guides/agent-readable-apps) to describe your own app's data to agents * [CLI overview](/cli/overview) # Authentication Source: https://docs.tinycloud.xyz/guides/authentication Choose the TinyCloud sign-in path for browsers, backends, and delegation consumers TinyCloud sign-in is SIWE-based. This page helps you pick the right path without mixing browser, backend, and delegation-only flows. ## Choose Your Path | Intent | Go here | | - | - | | Browser app with wallet sign-in | [Web sign-in](/guides/authentication/web) | | Automated, agent-run, or CI browser test | [Automated OpenKey + TinyCloud E2E testing](/guides/browser-e2e-testing) | | Node backend that owns a space | [Node sign-in](/guides/authentication/node) | | Node process that only receives delegations | [Node sign-in](/guides/authentication/node) | | SDK defaults and exact method names | [Web SDK reference](/reference/sdk/web) and [Node SDK reference](/reference/sdk/node) | ## What This Page Covers * TinyCloud uses SIWE for the sign-in boundary. * `TinyCloudWeb` is the browser entry point. * `TinyCloudNode` is the backend entry point. * OpenKey can be the signer for TinyCloud sign-in, but OpenKey OAuth is a separate flow. > [!NOTE] > > Keep OpenKey references scoped to TinyCloud sign-in support on this page. Use the OpenKey docs for the widget and OAuth flow itself. ## When To Split the Journey Use the Web page when you need a wallet popup and browser session restore. Use the Node page when you need a private-key-backed backend or a session-only consumer of received delegations. > [!NOTE] > > Verified against `@tinycloud/web-sdk` and `@tinycloud/node-sdk` 3.0.0. # Node sign-in Source: https://docs.tinycloud.xyz/guides/authentication/node Sign in from Node.js, persist an explicit session, handle expiry, and end access Use this page after the [Node SDK quickstart](/quickstart/node-sdk) when you need to manage a backend session beyond one process run. ## Choose a mode | Mode | Use when | Can sign in? | Can create delegations? | | - | - | - | - | | Wallet-backed | The process owns a space | Yes | Yes | | Session-only | The process receives an existing session or delegation | No | No | ## Create a wallet-backed session ```typescript theme={null} import { TinyCloudNode } from '@tinycloud/node-sdk'; const privateKey = process.env.WALLET_PRIVATE_KEY; if (!privateKey) throw new Error('WALLET_PRIVATE_KEY is required'); const tc = new TinyCloudNode({ privateKey, host: 'https://node.tinycloud.xyz', prefix: 'my-app', autoCreateSpace: true, sessionExpirationMs: 24 * 60 * 60 * 1000, }); await tc.signIn(); ``` Keep the private key in a secret manager or local `.env` file excluded from Git. `sessionExpirationMs` applies to the newly issued session; changing it does not extend an existing session. ## Persist and restore explicitly After sign-in, `restorableSession` contains the delegation header and private session-key material needed to resume access: ```typescript theme={null} const session = tc.restorableSession; if (!session) throw new Error('Sign-in did not produce a restorable session'); await saveEncryptedSession(session); // Your secret store, not plaintext source control. ``` On the next process start, create a session-only client and restore that encrypted payload: ```typescript theme={null} import { TinyCloudNode } from '@tinycloud/node-sdk'; const savedSession = await loadEncryptedSession(); const tc = new TinyCloudNode({ host: 'https://node.tinycloud.xyz', }); await tc.restoreSession(savedSession); console.log(tc.restorableSession?.spaceId); ``` `saveEncryptedSession()` and `loadEncryptedSession()` stand for your infrastructure's secret-storage calls. The session payload grants access until expiry, so protect it like a credential. Do not put it in a normal database column or log it. ## Handle an invalid or expired session Reject an unusable stored session, delete it, and establish a fresh wallet-backed session: ```typescript theme={null} try { await tc.restoreSession(savedSession); } catch (error) { await deleteEncryptedSession(); throw new Error('Stored TinyCloud session is invalid; create a new session', { cause: error, }); } ``` An already-restored session can also expire during a long-running process. Service calls return `AUTH_EXPIRED`; create and sign in a wallet-backed client before retrying work that is safe to repeat. ## End backend access `TinyCloudNode` does not currently expose the Web SDK's `signOut()` convenience method. To end local access, stop using the client instance and delete the stored restorable-session payload. This removes the backend's credential but does not revoke copies that were exported elsewhere. Use the delegation lifecycle controls for separately issued delegations. ## Session-only delegation use ```typescript theme={null} const tc = new TinyCloudNode({ host: 'https://node.tinycloud.xyz' }); const access = await tc.useDelegation(portableDelegation); const value = await access.kv.get('shared/report.json'); ``` The received delegation must target this instance's session DID. ## Next steps * [Spaces provisioning](/guides/spaces/provisioning) * [Delegations](/guides/delegations) * [Node client overview](/reference/sdk/node) > [!NOTE] > > Verified against `@tinycloud/node-sdk` 3.0.0. # Web sign-in Source: https://docs.tinycloud.xyz/guides/authentication/web Sign in with a browser wallet, restore sessions, handle expiry, and sign out Use this page after the [Web SDK quickstart](/quickstart/web-sdk) when you need to control the browser session lifecycle. ## Create the client ```typescript theme={null} import { TinyCloudWeb } from '@tinycloud/web-sdk'; const provider = (window as Window & { ethereum?: unknown }).ethereum; if (!provider) throw new Error('A browser wallet is required'); const tc = new TinyCloudWeb({ provider, tinycloudHosts: ['https://node.tinycloud.xyz'], spacePrefix: 'my-app', persistSession: true, sessionStorageKeyPrefix: 'my-app:production:', sessionExpirationMs: 24 * 60 * 60 * 1000, }); ``` The injected provider is the signer used for SIWE. Without `provider`, `providers.web3.driver`, or another supported signing strategy, this client can restore compatible session data but cannot start a new wallet sign-in. `persistSession` defaults to `true` and uses browser `localStorage`. Use a stable, environment-specific `sessionStorageKeyPrefix` so development and production sessions do not collide. Set `persistSession: false` when the browser must not retain session data. ## Sign in or reuse a session The shortest path is: ```typescript theme={null} const session = await tc.signIn(); ``` `signIn()` first attempts to restore a valid persisted session. It opens the wallet only when no usable session exists or the configured manifest needs permissions the restored session does not cover. To render separate restoring and wallet-prompt states, call `restoreSession()` explicitly: ```typescript theme={null} const restored = await tc.restoreSession(); if (restored.status === 'restored') { console.log('Restored', restored.session?.address); } else { const session = await tc.signIn(); console.log('Signed in', session.address); } ``` Ordinary restore outcomes are reported as statuses rather than thrown errors: | Status | Meaning | Next action | | - | - | - | | `restored` | A valid session is active | Continue | | `missing` | No session exists for the connected address | Call `signIn()` from a user action | | `expired` or `stale` | The saved session cannot be reused | Call `signIn()` | | `corrupt` or `restore-failed` | Saved data was rejected and cleared | Log the failure and call `signIn()` | | `disabled` or `storage-unavailable` | Persistence is off or inaccessible | Call `signIn()`; expect a future prompt | ## Handle expiry during an operation Service calls return `Result` objects. If a long-lived page sees an expired session, ask the user to sign in again and then retry only the operation that is safe to repeat: ```typescript theme={null} const result = await tc.kv.get('profile'); if (!result.ok && result.error.code === 'AUTH_EXPIRED') { await tc.signIn(); // Retry the read after sign-in. Be deliberate before retrying writes. } ``` `sessionExpirationMs` sets the requested lifetime for newly created sessions. It does not extend an already-issued session. ## Sign out ```typescript theme={null} await tc.signOut(); ``` `signOut()` clears the persisted TinyCloud session and in-memory session-scoped state. It does not disconnect or lock the user's wallet extension. Call `signIn()` again before the next TinyCloud operation. ## Next steps * [Spaces provisioning](/guides/spaces/provisioning) * [KV basic operations](/guides/kv/basic-operations) * [Web client overview](/reference/sdk/web) > [!NOTE] > > Verified against `@tinycloud/web-sdk` 3.0.0. # Automated OpenKey + TinyCloud E2E testing Source: https://docs.tinycloud.xyz/guides/browser-e2e-testing Run unattended, agent-driven, or CI browser tests against the real OpenKey and TinyCloud flow. Use this pattern when a browser app signs in through OpenKey and TinyCloud, but an end-to-end test must run unattended—whether from an agent, CI, or a local automation loop. It replaces the human passkey ceremony with a test-only EIP-1193 wallet. The application still uses its production OpenKey external-wallet path, requests a real SIWE signature, and initializes TinyCloud normally. This is a browser-test technique, not an application authentication mode. Do not add a test private key, a bypass flag, or a mock signer to production app code. ## What the bootstrap covers The test account bootstrap has two boundaries: 1. Before navigation, Playwright installs a test-only wallet provider that can answer account, chain, and `personal_sign` requests. 2. After the test selects that wallet in OpenKey, the application performs its usual TinyCloud initialization. With `autoCreateSpace: true`, that creates the app space when needed. If the app uses encrypted data, its initializer must also create or reuse the owner's encryption network. The browser never creates an OpenKey passkey and the test never approves a passkey prompt. It still verifies the integration points that matter: OpenKey widget selection, wallet-backed signing, TinyCloud session setup, and an authorized read or write. ## Bootstrap a test account Install the wallet before `page.goto()`. The example uses a deterministic Anvil development key so the account is reproducible; it must be used only for test data and must never hold funds, production data, or reusable credentials. ```typescript theme={null} import { expect, test, type Page } from "@playwright/test"; import { Wallet, utils } from "ethers"; const TEST_PRIVATE_KEY = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"; const TEST_ADDRESS = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"; const TEST_WALLET_NAME = "TinyCloud E2E Wallet"; function exposeTestShadowRoots() { return () => { const attachShadow = Element.prototype.attachShadow; Element.prototype.attachShadow = function (init: ShadowRootInit) { return attachShadow.call(this, { ...init, mode: "open" }); }; }; } function installTestWallet() { return ({ address, walletName, }: { address: string; walletName: string; }) => { const provider = { selectedAddress: address, chainId: "0x1", async request({ method, params = [], }: { method: string; params?: unknown[]; }) { switch (method) { case "eth_requestAccounts": case "eth_accounts": return [address]; case "eth_chainId": return "0x1"; case "personal_sign": { const message = params[0]; if (typeof message !== "string") throw new Error("personal_sign missing message"); return (window as any).__openkeyE2ESignMessage(message); } case "wallet_getPermissions": case "wallet_requestPermissions": return [{ parentCapability: "eth_accounts" }]; default: return null; } }, on: () => provider, removeListener: () => provider, isConnected: () => true, }; const announce = () => window.dispatchEvent( new CustomEvent("eip6963:announceProvider", { detail: { info: { uuid: "8fd9b04a-e8a0-4c43-9d87-5af504aa1f0d", name: walletName, icon: 'data:image/svg+xml,%3Csvg xmlns="http://www.w3.org/2000/svg"/%3E', rdns: "xyz.tinycloud.e2e-wallet", }, provider, }, }), ); Object.defineProperty(window, "ethereum", { value: provider, configurable: true, }); window.addEventListener("eip6963:requestProvider", announce); announce(); }; } async function bootstrapTestAccount(page: Page) { const wallet = new Wallet(TEST_PRIVATE_KEY); await page.exposeFunction("__openkeyE2ESignMessage", (message: string) => { return wallet.signMessage( message.startsWith("0x") ? utils.arrayify(message) : message, ); }); await page.addInitScript(exposeTestShadowRoots()); await page.addInitScript(installTestWallet(), { address: TEST_ADDRESS, walletName: TEST_WALLET_NAME, }); } ``` `exposeFunction()` installs the signer before navigation and avoids depending on the order of multiple browser init scripts. `addInitScript()` then installs the provider before the application's scripts, so OpenKey's widget can discover it through EIP-6963. Opening shadow roots makes the widget's wallet picker visible to Playwright; keep that behavior in the test only. ## Drive the real application flow Use your application's existing OpenKey entry point and select the injected external wallet. The selectors below are from TinyCloud Secret Manager; replace the button selector with your app's stable test id. ```typescript theme={null} test("creates and reads a record through OpenKey", async ({ page }) => { await bootstrapTestAccount(page); await page.goto("/app"); await page.getByTestId("connect-openkey").click(); await page .frameLocator('iframe[src*="/widget/embed/connect"]') .getByText(/or use an external wallet/i) .click(); await page.getByText(TEST_WALLET_NAME).click(); // Assert your app's completion state only after its normal TinyCloud // initializer has signed in and provisioned the required account resources. await expect(page.getByTestId("network-decrypt-ready")).toBeVisible(); // Exercise one useful app operation, then read it back and remove it. }); ``` For Secret Manager, its normal initializer calls `signIn()`, creates its `secrets` space when absent, then creates or reuses the owner-scoped default encryption network before marking the UI as decrypt-ready. Other applications should keep the same shape: bootstrap the signer in the test, but provision spaces, schemas, networks, and other account resources in the app's normal initialization path. ## Keep runs isolated * Use a dedicated test account and test-only resources. A deterministic key is public test infrastructure, not a secret. * Use a distinct app or space prefix for E2E data; do not point a test account at user-owned production records. * Delete every record the test creates, including after a retry when practical. * Run tests serially when they share a deterministic account, or derive a unique resource name from the Playwright worker and test run. * Do not live-test provider credentials in this flow. Use a syntactically valid dummy value and disable provider calls, unless the provider integration is explicitly the subject of the test. ## When to use a mock instead Use this account bootstrap when the behavior under test includes OpenKey widget integration, SIWE signing, TinyCloud provisioning, or authorization. Use a module mock for fast component tests and for error states that the real service cannot reliably produce. Keep at least one smoke test on this real path. ## Related pages * [Web sign-in](/guides/authentication/web) * [App manifests](/concepts/app-manifests) * [Spaces provisioning](/guides/spaces/provisioning) * [OpenKey TinyCloud integration](/openkey/tinycloud-integration) * [Run OpenKey locally](/openkey/local-development) # Data Vault Source: https://docs.tinycloud.xyz/guides/data-vault Unlock the vault, store encrypted values, and share them. Use the data vault when you want to encrypt KV values before storage instead of sending plain TinyCloud KV. This page describes the wallet-derived flow; network-backed vaults use a separate node-mediated key-release path. Check which mode your app configures before assuming only its endpoints hold keys. For both trust boundaries and the public/primary space split, see [Data Vault](/concepts/data-vault). ## Unlock the vault ```typescript theme={null} import { PrivateKeySigner, TinyCloudNode } from "@tinycloud/node-sdk"; const tc = new TinyCloudNode({ privateKey: process.env.WALLET_PRIVATE_KEY, host: "https://node.tinycloud.xyz", prefix: "my-app", }); await tc.signIn(); const signer = new PrivateKeySigner(process.env.WALLET_PRIVATE_KEY); await tc.vault.unlock(signer); ``` In wallet-derived mode, unlocking derives encryption keys locally. The same wallet signing material produces the same vault keys again later, so the encrypted data remains readable across sessions. This statement does not describe network-backed key custody. ## Store and read values ```typescript theme={null} await tc.vault.put("medical/records", { bloodType: "O+", allergies: ["penicillin"], }); const result = await tc.vault.get("medical/records"); ``` Use `list()`, `head()`, and `delete()` the same way you would on a normal KV store. The storage layer receives ciphertext and metadata; authorized decrypting clients can still see and retain plaintext. ## Share encrypted data To share a vault entry, grant the recipient access to the entry key and add a delegation for the same path scope. ```typescript theme={null} // Assuming alice and bob are signed-in TinyCloudNode instances. await alice.vault.reencrypt("medical/records", bob.did); const delegation = await alice.createDelegation({ delegateDID: bob.did, path: "", actions: ["tinycloud.kv/get", "tinycloud.kv/metadata"], expiryMs: 24 * 60 * 60 * 1000, }); const access = await bob.useDelegation(delegation); await bob.vault.unlock(new PrivateKeySigner("0x...")); const shared = await bob.vault.getShared(alice.did, "medical/records", { kv: access.kv, }); ``` ## CLI All `tc vault` commands require `--private-key ` or `TC_PRIVATE_KEY`, because the CLI resolves a private key before running vault operations. ```bash theme={null} tc vault unlock tc vault put api-key "sk_live_abc123" tc vault get api-key tc vault list --prefix credentials/ tc vault head api-key tc vault delete api-key ``` ## When to use this page Use this flow for wallet-derived encrypted KV and review key custody before using it for sensitive data. If you only need plain TinyCloud KV, use the [KV guide](/guides/kv-storage) instead. ## Source note The vault API names and the unlock/share flow come from the JS SDK and its WASM bindings. This guide stays on the usage path and leaves the trust model to the concept page. # Delegations & Sharing Source: https://docs.tinycloud.xyz/guides/delegations Grant scoped TinyCloud access to another principal. Use this guide to grant another signed-in TinyCloud principal access to a path in your space. In the examples, `alice` and `bob` are SDK instances that have already completed `signIn()`. ## Create and use a delegation Use the recipient's owner DID. After wallet sign-in, `bob.did` is that owner DID; `bob.sessionDid` identifies the ephemeral session key instead. ```typescript theme={null} const delegation = await alice.createDelegation({ delegateDID: bob.did, path: "shared/", actions: ["tinycloud.kv/get", "tinycloud.kv/put"], expiryMs: 7 * 24 * 60 * 60 * 1000, }); // Deliver `delegation` to Bob through your authenticated application channel. const access = await bob.useDelegation(delegation); const value = await access.kv.get("document.json"); if (!value.ok) throw new Error(value.error.message); console.log(value.data.data); ``` `useDelegation()` returns a `DelegatedAccess` handle for the delegator's space. Its KV service is already rooted at `shared/`, so its keys are relative to that delegated path. It does not copy the data into the recipient's space. ## Serialize for transport `createDelegation()` returns a `PortableDelegation` object. To send it as text, use the SDK helpers instead of manually converting its `Date` fields: ```typescript theme={null} import { serializeDelegation, deserializeDelegation, } from "@tinycloud/node-sdk"; const payload = serializeDelegation(delegation); // Send `payload` through an authenticated channel. const received = deserializeDelegation(payload); const receivedAccess = await bob.useDelegation(received); ``` The same helpers are exported by `@tinycloud/web-sdk` for browser applications. The serialized delegation is a bearer credential; do not log it or send it through an untrusted channel. ## Narrow access further If the parent permits sub-delegation, Bob can grant Carol a narrower subset: ```typescript theme={null} const child = await bob.createSubDelegation(delegation, { delegateDID: carol.did, path: "shared/public/", actions: ["tinycloud.kv/get"], expiryMs: 24 * 60 * 60 * 1000, }); ``` The child must stay within the parent's resources and action set, cannot outlive the parent, and cannot bypass a parent's sub-delegation restriction. Without `expiryMs`, `createSubDelegation` defaults to the longest lifetime the parent allows. Sessions activated from a received delegation default the same way. ## Block further delegation `createSubDelegation()` signs with the wallet, so it cannot set `disableSubDelegation`; passing `true` throws. To issue a grant the recipient cannot pass on, use `createDelegation()` with `disableSubDelegation: true` and address it to the recipient's session-key `did:key`, not its `did:pkh` owner DID. Here `carolSession` is a client without a wallet signer. Its `credentialHolderDid` is the bare `did:key` session-key DID; use it rather than `carolSession.did`, which carries a `#fragment` that `createDelegation` rejects as an invalid audience DID: ```typescript theme={null} const terminal = await alice.createDelegation({ delegateDID: carolSession.credentialHolderDid, path: "shared/public/", actions: ["tinycloud.kv/get"], disableSubDelegation: true, }); const access = await carolSession.useDelegation(terminal); ``` The delegation carries the node's terminal marker, so the node refuses any delegation that cites it as a parent. A recipient in wallet mode chains a new session from the grant, which the node refuses for a terminal parent, so `createDelegation()` throws if `disableSubDelegation` is combined with a `did:pkh` recipient. Drop the flag for a wallet recipient. ## Revoke access Both the Node and Web SDKs expose `revokeDelegation()`: ```typescript theme={null} const revoked = await alice.revokeDelegation(delegation.cid); if (!revoked.ok) throw new Error(revoked.error.message); ``` Revocation is node-confirmed and invalidates use of that delegation. Revoking an ancestor also prevents its descendants from being used. The Node SDK can query the node-confirmed lifecycle state: ```typescript theme={null} const status = await alice.getDelegationStatus(delegation.cid); if (status.ok) console.log(status.data.status); // "revoked" ``` Delegations also stop working at their signed expiry. Expiry limits exposure, but it is not a substitute for `revokeDelegation()` when access must end now. ## Inspect received grants The Node SDK records delegations installed by `useDelegation()`: ```typescript theme={null} const receivedDelegations = bob.delegations.list(); const oneDelegation = bob.delegations.get(delegation.cid); ``` For the SDK transport fields and the node's validation model, see [Delegations](/reference/protocol/delegations). # KV Storage Source: https://docs.tinycloud.xyz/guides/kv-storage Store and retrieve data inside a TinyCloud space TinyCloud KV is the direct read/write API for data inside a space. Use it when you want JSON, strings, arrays, or binary values stored under a key. ## Start here * For a focused walk-through of `put`, `get`, `list`, `head`, and `delete`, go to [KV basic operations](/guides/kv/basic-operations). * For exact method signatures and return types, use the TypeScript declarations shipped with your installed SDK. The [Web client overview](/reference/sdk/web) and [Node client overview](/reference/sdk/node) cover the primary client surfaces. ## What KV is good for * User profiles * App state * Cached objects * Shared records in a delegated space ## What to keep in mind * KV values live inside the user's TinyCloud space. * The same `tc.kv` surface exists in both SDKs. * Space naming and key naming are separate concerns. * When the account's storage is full, reads keep working and `put` returns a failed result with `error.code` `STORAGE_QUOTA_EXCEEDED`, or `STORAGE_LIMIT_REACHED` when one value is larger than the space left. Keep the app usable read-only; see [Storage is full](/troubleshooting#storage-is-full). > [!NOTE] > > Verified against the KV service shipped with TinyCloud SDK 3.0.0. # KV basic operations Source: https://docs.tinycloud.xyz/guides/kv/basic-operations Use put, get, list, head, and delete with TinyCloud KV Use this page when you want the shortest path from a space to a working read/write example. ## The core operations | Method | Use it for | | - | - | | `put` | Store a value under a key | | `get` | Read a value back | | `list` | Enumerate keys, optionally by prefix | | `head` | Read metadata without fetching the value | | `delete` | Remove a key | ## Write a record ```typescript theme={null} const putResult = await tc.kv.put('profile', { name: 'Alice', joinedAt: new Date().toISOString(), }); ``` `put()` accepts JSON-like values and strings. The SDK returns a `Result`, so check `ok` before using the data. ## Read it back ```typescript theme={null} const getResult = await tc.kv.get('profile'); if (getResult.ok) { console.log(getResult.data.data); } ``` ## List a prefix ```typescript theme={null} const listResult = await tc.kv.list({ prefix: 'user/' }); if (listResult.ok) { console.log(listResult.data.keys); } ``` ## Inspect metadata or remove the key ```typescript theme={null} const headResult = await tc.kv.head('profile'); const deleteResult = await tc.kv.delete('profile'); ``` Use `head()` when you only need metadata, and `delete()` when the record should be removed entirely. ## Next step * [Spaces](/guides/spaces) * [Web SDK reference](/reference/sdk/web) * [Node SDK reference](/reference/sdk/node) > [!NOTE] > > Verified against the KV service shipped with TinyCloud SDK 3.0.0. # Local Replicas (Beta) Source: https://docs.tinycloud.xyz/guides/local-replicas Keep a read-only KV prefix on a device for offline reads. > [!NOTE] > > **Beta feature in the stable packages.** Local replica behavior and the on-disk > format may change in a minor release. A local replica is a durable, read-only copy of the latest values under one KV prefix. Sync it while online, then read that prefix from the device while offline. It is not offline writes, and it is not a replica of SQL data. ## Requirements * The TinyCloud node must advertise `kv-sync-v1` in its `/info` response. The production node at `tee.node.tinycloud.xyz` advertises this feature. * Install the stable CLI (version 1.1.0 or later): ```sh theme={null} npm i -g @tinycloud/cli ``` * CLI replicas need Node.js 22.20 or later, or Bun. SQLite rejects older Node versions; Bun supplies its own SQLite runtime. * For browser apps, install and pin an exact replica package version. For example, use `@tinycloud/replica@0.3.0`. * A device needs a grant that covers its configured KV prefix and includes `get` and `sync`. `list` and `metadata` are optional. ## CLI: grant, sync, and read offline ### 1. Grant the device access to one prefix Create or select a device profile and make it request access to the narrowest prefix it needs. For example, the `device` profile requests `get` and `sync` access to `notes/`: ```sh theme={null} tc profile create device --posture delegate-session tc --profile device auth request \ --cap "tinycloud.kv::notes/:get,sync" \ --expiry 30d --emit request.json ``` The space owner reviews and grants that request, then the device imports the grant. Run the owner command in the owner's profile; import the resulting artifact in the device profile: ```sh theme={null} tc --profile owner auth grant request.json --yes > grant.json tc --profile device auth import grant.json ``` `sync` is an explicit capability: a grant for ordinary KV reads alone is not enough. The replica stores only its configured prefix, which must be covered by the grant; the grant may cover a broader prefix. ### 2. Sync the prefix Run the first sync with the desired prefix. The CLI creates a local replica named after that prefix unless you supply `--replica`: ```sh theme={null} tc --profile device replica sync --prefix notes/ ``` Later, run `tc --profile device replica sync` again to poll for updates and deletes. The configured source host, space, and prefix are fixed for that replica. Use a different `--replica` name if you need a different scope. ### 3. Read while offline First log in with the device profile and its grant: ```sh theme={null} tc --profile device auth login ``` The grant must authorize the configured prefix. For a secrets-space or `vault/` prefix, login also requires `--replication-allow-secrets`; otherwise it fails with `SECRETS_OPT_IN_REQUIRED` (exit 2). Runtime grants can also provide authority when the node-sdk is used. `get` and `list` read only from local replica storage; they never fall back to a host KV request. Stop the network or disconnect, then run: ```sh theme={null} tc --profile device replica get notes/today.txt tc --profile device replica list notes/ ``` Use `--raw` to write the value bytes to standard output, or `-o file` to save them to a file. Sync must have completed the initial prefix coverage before you can rely on reads of keys that have not yet been observed. ### 4. Inspect or reset local data ```sh theme={null} tc --profile device --replication replica report tc --profile device replica reset ``` `tc --profile device --replication replica report` reports live replica status, including scope, sync state, authority, counts, and failures. `reset` clears entries, content, and the cursor but keeps the replica configuration and grant, so sync can populate it again. Add `--purge` to remove that replica entirely: ```sh theme={null} tc --profile device replica reset --purge ``` ### Command options | Command | Options | Behavior | | - | - | - | | `replica sync` | `--replica ` | Select a replica; without it, the CLI uses the profile's only replica or names a new one from the first-sync prefix. | | `replica sync` | `--space `, `--prefix ` | Set the space and prefix on first sync. The prefix is required; later syncs keep the original scope. | | `replica sync` | `--limit ` | Set feed page size from 1 to 1000. | | `replica sync` | `--allow-secrets` | Explicitly allow a secrets-space or `vault/` replica; see the security warning below. | | `replica sync` | `--retention-grant ` | Use an owner-issued `tinycloud.kv/retain` grant; see [Retaining reads after grant expiry](#retaining-reads-after-grant-expiry). | | `replica get ` | `--replica ` | Select the replica. | | `replica get ` | `--raw` or `-o, --output ` | Write raw bytes to stdout or atomically to a private output file. | | `replica get ` | `--no-verify` | Skip the stored-content hash check; leave verification enabled unless you have a specific reason not to. | | `replica list [prefix]` | `--replica `, `--after `, `--limit ` | Select the replica and paginate local keys after a key, optionally limiting the result count. | | `replica status` | `--replica ` | Show one replica; omit it to show all replicas in the profile. | | `replica reset` | `--replica `, `--purge` | Select a replica; `--purge` removes it instead of clearing its entries and cursor. | Pass the global `--host ` when creating a replica if the profile has no default host; the chosen source is pinned to that replica. For example, after confirming that storing encrypted secret material locally is acceptable: ```sh theme={null} tc --profile device replica sync --prefix vault/ --allow-secrets ``` This flag only opts in to copying ciphertext. It does not grant decrypt access. ### Retaining reads after grant expiry By default, local reads are allowed only while the device's sync grant is valid. An owner may separately issue a `tinycloud.kv/retain` grant to authorize a bounded retention window for already-synced local reads after that sync grant expires. Supply the retention grant's CID during a sync: ```sh theme={null} tc --profile device replica sync --retention-grant ``` The node attests the permitted retention window. This does not extend the sync grant or allow new syncs after it expires. A learned revocation still blocks reads. Omit the option to use the default policy. ### Error codes and next steps The CLI prints a machine-readable error code alongside the message. Common replica errors: | Code | Meaning | What to do | | - | - | - | | `NOT_COVERED` | The key is outside this replica's prefix. | Read from an authorized source or sync the intended prefix with a separately scoped replica. | | `KEY_DELETED` | The replica holds a tombstone for a key deleted at the source. | Recreate the key at the source, then sync to fetch its value again. | | `KEY_ABSENT` | The key is not in a replica with complete prefix coverage. | Check the key or source data; syncing will not help if it was never present. | | `COVERAGE_INCOMPLETE` | The first sync has not finished covering the prefix. | Run `tc replica sync` until coverage completes. | | `CONTENT_MISSING` | The key is known, but its content is not stored locally. | Run `tc replica sync` to fetch it. | | `GRANT_MISSING` | No usable device grant is installed. | Request and import a grant with the required prefix and capabilities. This also occurs when stored grants are malformed, for another audience, insufficient for this prefix, not yet valid, or expired; unusable grants are filtered out. | | `GRANT_EXPIRED` | The device grant's authority window ended. | Renew the grant and sync again. To retain local reads after expiry, configure retention and sync while the sync grant is still valid; an expired grant cannot obtain a new retention attestation. | | `GRANT_REVOKED` | The node reported that the grant was revoked. | Ask the owner for a new grant; revoked authority cannot be restored by retrying the old grant. | | `SECRETS_OPT_IN_REQUIRED` | The requested scope includes the secrets space or a vault namespace. | Reconsider whether encrypted secret material should be stored on this device; only then use `--allow-secrets`. | | `NETWORK_ERROR` | Sync could not reach the pinned host. | Reconnect to the host and retry sync; local reads remain separate from sync. | | `STORAGE_FULL` | Local storage could not accept the data. | Free device storage and retry. | Other errors identify configuration, grant, storage, or node failures: | Code | Meaning | What to do | | - | - | - | | `REPLICA_CONFIG_MISMATCH` | An existing replica name is already pinned to a different space, prefix, or host. | Use another `--replica` name, or reset it with `--purge` before recreating it. | | `GRANT_INVALID`, `GRANT_FORMAT_UNSUPPORTED` | The installed grant is malformed, has an invalid signature, or is not a UCAN. | Import a valid UCAN delegation issued for the device. | | `GRANT_AUDIENCE_MISMATCH` | The grant is addressed to another device. | Ask the owner to issue a grant for this profile's device. | | `GRANT_NOT_COVERING` | The grant lacks the required `get` or `sync` ability on the prefix. | Request unrestricted `tinycloud.kv/get` coverage of the folder prefix (or broader) and explicit `tinycloud.kv/sync` on that prefix (or broader); wildcard grants do not include `sync`. Exact-key grants never cover a folder prefix. | | `GRANT_NOT_YET_VALID` | The grant's validity window has not started. | Wait until it becomes valid, then sync again. | | `GRANT_UNAUTHORIZED` | The node refused the grant for a reason other than revocation. | Check the grant scope and node authorization; ask the owner to issue the intended access. | | `RETENTION_GRANT_REFUSED` | The node refused the retention grant. | Check that its CID names a valid `tinycloud.kv/retain` grant for this replica. | | `REPLICA_BUSY` | Another process is syncing or modifying this replica. | Wait for it to finish, then retry. | | `RUNTIME_UNSUPPORTED` | The runtime cannot provide the replica's durable local storage. | Use a supported runtime. | | `STORAGE_ERROR` | Local storage failed, for example because of I/O or corruption. | Resolve the device storage problem before retrying. | | `NODE_ERROR`, `PROTOCOL_ERROR` | The node returned an error or an unexpected sync response. | Check node health and version support, then retry; report persistent failures. | | `RESET_REQUIRED` | The node requires the replica to bootstrap again. | Sync automatically retries once from a fresh bootstrap. If the error still reaches you, investigate the node, or reset the replica and sync again. | | `SOURCE_CHANGED` | The replica's pinned source node differs from the responding node. | Sync against the original host or create a separate replica for the new source. | | `SCOPE_VIOLATION` | The feed included a key outside the configured prefix. | Stop using this replica and report the node/protocol failure. | | `CONTENT_MISMATCH`, `INTEGRITY_ERROR` | Downloaded or stored content failed its integrity check. | Do not use the value; retry sync and report a persistent mismatch. | | `REPLICA_NOT_FOUND` | The selected replica name does not exist. | Sync with its `--prefix` to create it, or choose an existing replica. | Exit codes: `0` success; `1` busy/runtime/storage error; `2` usage, invalid replication prefix, outside-scope or caveated prefix, or `SECRETS_OPT_IN_REQUIRED`; `3` missing or invalid grant; `4` absent, deleted, missing-content, or incomplete-coverage key; `5` expired, revoked, or not-yet-valid grant; `6` network; `7` node, protocol, or integrity error; `10` local storage full. ## Read-through flag (beta): CLI and node-sdk This Phase 1 read-through beta is separate from the explicit `tc replica` commands above. It routes eligible `node.kv.get()` and `node.kv.list()` calls through a local replica, falling back to the unchanged network request when the replica cannot safely answer. It is opt-in and applies only to primary-space KV. Browser `web-sdk` read-through is available only in the pre-release line; see [Browser read-through](#browser-read-through-pre-release) below. ### Enable read-through The CLI flag enables read-through for one invocation; it does not select prefixes. Save one or more prefixes during login so later invocations can use them: ```sh theme={null} tc auth login --replication-prefix notes/ tc --replication kv get notes/today.txt ``` `--replication` or `TC_REPLICATION=1` enables read-through; the environment variable sets the default to on. `--no-replication` disables it even when `TC_REPLICATION=1` is set. The feature is off by default. `tc auth login --replication-prefix ` is repeatable; an explicit list replaces the saved prefixes, while omitted options reuse saved prefixes on later logins and key rotation. Without a saved prefix, the CLI has nothing to replicate. For a node-sdk client, enable the option and provide storage explicitly: ```ts theme={null} import { TinyCloudNode, sqliteReplicaStorage } from "@tinycloud/node-sdk"; const node = new TinyCloudNode({ replication: { enabled: true, prefixes: ["notes/"], storage: sqliteReplicaStorage({ dir: "./.tinycloud-replicas" }), }, }); ``` `enabled` requires a non-empty `prefixes` array and `storage`; overlapping prefixes are rejected. The Node SQLite adapter requires Node.js 22.13 or newer (or Bun). `sqliteReplicaStorage({ dir, guard })` accepts an optional `guard` for serialized storage mutations. `node.replication` exposes `status()`, `sync()`, `purge()` and `clearPending()`. There are **no default prefixes**. A replication prefix is a folder: non-empty, slash-terminated, with no leading slash or empty path segments (for example `notes/` or `notes/private/`), or `/` for the whole space. `""`, bare paths such as `notes`, `/notes/`, and paths containing `//` are invalid. CLI login rejects these with `INVALID_REPLICATION_PREFIX` and exit 2; the node-sdk rejects invalid configuration with a `TypeError`, and replica APIs report `REPLICA_INVALID_ARGUMENT`. Bare prefixes persisted by 3.1.0 replicas are no longer accepted. Purge an explicit CLI replica with `tc replica reset --replica --purge`, then recreate it with `--prefix notes/`. Replace a saved CLI read-through prefix at login with `tc auth login --replication-prefix notes/`. Replication requires unrestricted `tinycloud.kv/get` authority covering the entire folder prefix (or broader) and explicit `tinycloud.kv/sync` on that prefix (or broader); wildcards never grant `sync`. An exact-key grant never qualifies. Owner logins using a local key or OpenKey that already have unrestricted whole-space `get` add `sync` once to the whole-space KV entry, regardless of the number of configured prefixes. Delegated and device sessions need `sync` authority on the prefix (or broader) in their grant. CLI login refuses a prefix without unrestricted covering `get` with `REPLICATION_PREFIX_OUTSIDE_SCOPE` or `REPLICATION_PREFIX_CAVEATED` (exit 2). The node-sdk instead skips sync augmentation for that prefix; it needs sufficient authority before the replica can serve local reads. For CLI read-through, `vault/` and `/` require `--replication-allow-secrets` at login, otherwise login fails with `SECRETS_OPT_IN_REQUIRED` (exit 2). For node-sdk, set `replication.allowSecrets: true` for either prefix; otherwise construction throws a `TypeError`. `/` selects the whole space and includes `vault/`, so it also requires `--replication-allow-secrets`. Whole-space sync requires a node advertising `kv-sync-root` in `/info` (tinycloud-node 1.20.1 or later). On older nodes, root replication fails with `REPLICATION_ROOT_UNSUPPORTED`, and replica status reports that same code as unavailable. LIST coverage follows the actual list path. A `notes/` replica serves `node.kv.list({ prefix: "notes/" })` and nested lists locally. In contrast, `node.kv.withPrefix("notes").list()` uses path `notes`, which is not covered by a `notes/` replica and falls back to the network. A `/` replica serves any list locally. A pending write in the unread portion of a list range forces network fallback; with a local continuation cursor, it instead returns `INVALID_INPUT` with `meta.replication: "cursor_restart"`. Restart the list without that cursor. ### Where reads go An eligible local answer requires the replica selection and current unrestricted authority to cover the whole key or list range, complete coverage, no pending-write pin for the key or list range, and no failed stale-sync attempt that requires a network fallback. A list path `P` covers the key `P` and descendants under `P/`; a pending write in the unread portion of that range forces network fallback or, with a local continuation cursor, returns `INVALID_INPUT` with `meta.replication: "cursor_restart"`. A stale local value can still be used when the bounded sync fails offline. The table gives common outcomes; network fallback returns the network result, not the replica result. | Condition | Read source | Reason or result | | - | - | - | | Covered, complete, authorized replica has the key | Local | `hit` | | Covered and complete replica knows the key is absent or deleted | Local | `absent` or `deleted` | | No configured prefix covers the key or complete list range | Network | `not_covered` | | Initial sync has not completed, or local content is missing | Network | `coverage_incomplete` or `content_missing` | | No usable, unrestricted runtime grant for this prefix at read time | Network | `grant_missing` | | A pending write pins the key or list range | Network | `pending_write` | | The replica has not synced through a committed write's epoch | Network | `REPLICA_BEHIND_OWN_WRITES` | | A required stale sync is busy or fails with a non-network error | Network | `stale` | | Replica runtime cannot provide supported storage | Network | `runtime_unsupported` | | Other replica-open failure, including invalid or mismatched storage | Network | `replica_unavailable` | | Stale sync fails with `NETWORK_ERROR` or reaches its timeout, the drained sync has settled, status refresh succeeds, and local coverage, authority and pending-write checks still pass | Local | `hit`, `absent` or `deleted`, with `syncError` | Other network fallback reasons include `replica_error` (local read or storage failure), `unsupported_option` (for example, an oversized `get` under `maxResponseBytes` or raw `list`), and `network_cursor` (a node-issued list cursor). Events are available through the SDK's `onEvent` callback; the CLI can print per-read and sync diagnostics with `--replication-debug`. A local `tcr1.` continuation that cannot be served safely returns `INVALID_INPUT` with `meta.replication: "cursor_restart"` instead of making a network request; see [List ordering and cursors](#list-ordering-and-cursors). ### Freshness and offline reads On a stale read, the SDK tries a sync before using the local answer. The node-sdk defaults are a 120-second maximum staleness and a 5-second stale-sync timeout. CLI foreground mode has no background timer; defaults are 60 seconds and 10 seconds. Override the CLI values per process: ```sh theme={null} TC_REPLICATION_MAX_STALENESS_MS=30000 \ TC_REPLICATION_SYNC_TIMEOUT_MS=3000 \ tc --replication kv get notes/today.txt ``` When offline, an eligible stale value (or authoritative absent/deleted result) can be served locally after the sync reports a network error or times out; its read event includes `syncError: "NETWORK_ERROR"` or `"TIMEOUT"`. An unresolved pending write, incomplete coverage, or unusable authority still prevents a local answer. Without a local answer the SDK uses the network path and that request can fail. **Known limitation (TC-897):** offline CLI network errors currently exit 1, not 6. ### Read-your-writes and pinned keys Read-your-writes protection applies only to writes made while read-through is enabled. A write made while the flag is off creates no pending record; it is treated like a write from another device and may appear after a later sync. With the flag on, a committed write stays protected until a sync that started after its commit catches up. A write with an unknown outcome (`ambiguous`), or an unfinished `in_flight` write, pins its key to the network. Matching content, absence, or a later write does not resolve an ambiguous outcome; it remains pinned until explicitly cleared or purged. A pin means the read does not get a stale local result, even when offline. `tc --replication replica report` shows pinned keys, state, operation, `since`, error code and whether an in-flight record is likely orphaned. ### Inspect, clear, and purge ```sh theme={null} tc --replication --replication-debug kv get notes/today.txt tc --replication replica report tc --replication replica report --json tc --replication replica report --clear-pending tc --replication replica report --purge ``` The report summarizes reads by source and reason, hit ratio, latency and staleness percentiles, syncs, writes, divergences, live replica status, pinned keys, and other local identity partitions. `--since ` selects the event window (default `24h`); `--json` emits structured output, including the `since` window value. `--clear-pending` clears unresolved ambiguous and likely-orphaned in-flight records for the current identity. It prints a warning first: clearing stops pinning keys whose write outcome was unknown; if that write committed or commits later, an older local value can be served until a sync after the commit. Young in-flight and committed records are not cleared by this option. `--purge` removes the configured replicas and their pending-write records for the **current identity**; they can be rebuilt on a later covered read. It prints the same pending-write warning. It does not purge other identities or revoke node-side grants. `--host ` selects the host and therefore the identity partition for a CLI invocation; use the relevant `--host` to inspect or purge data for another host partition. Purge covers the configured prefixes, not every saved prefix or every identity in the profile. Physical cleanup can retain a contentless SQLite generation/tombstone marker so previously opened handles fail closed. The local identity partition is the canonical host, full space and principal (the signing identity). Different hosts, spaces or principals have separate replicas and pending-write state. In particular, changing `--host` does not reuse another host's local cache or read-your-writes state. ### List ordering and cursors Local list keys are ordered by UTF-8 bytes. A node may order them differently: SQLite uses byte order, while production Postgres uses its database collation. Do not assume identical order across local and network list results. Local pagination uses a `tcr1.` cursor bound to its space and list path. Node-issued cursors are served by the network. A pending write in the unread portion of a list range forces network fallback; with a local continuation cursor, it instead returns `INVALID_INPUT` with `meta.replication: "cursor_restart"`. Restart the list without that cursor. Other unsafe local continuations (for example, incomplete coverage or a space/path mismatch) also return this typed input error without making a network request. Do not mix pages from the local and network sources. ### Network-only reads Use the KV read option `source: "network"` for checks whose answer must reflect the node, such as an existence check. It bypasses replica open, sync and local reads: ```ts theme={null} const result = await node.kv.get("notes/today.txt", { source: "network" }); ``` `list()` accepts the same option. The CLI's secret and vault existence checks already use network-authoritative reads. This option is for reads; writes remain network writes. ### Revocation and security Revocation is discovered at the next sync, not while the device is offline. Once a sync reports revocation, the local replica is blocked and purged; `tc replica report` shows the replica as `revoked`. Do not retry with the revoked device grant; obtain a new device. Local delegation checks verify the signature, CID, audience and expiry, but **not the proof chain**. The node verifies the chain on every sync. Local checks are not a substitute for node verification. `tc auth logout` removes legacy replicas and the flag-owned `replication/` directory for every identity partition by default, including its device keys, identity and pending-write files, and event log. Pass `--keep-replicas` to retain both local roots. Logout clears the local session; it does **not** revoke delegations or grants at the node, which remain valid until expiry unless separately revoked. Cleanup refuses unsafe symlinks or active sync leases; a cleanup failure can leave local files behind. **Code-derived defaults and scope:** the CLI overrides the SDK defaults above (60 seconds / 10 seconds); the code defaults for node-sdk are 120 seconds / 5 seconds. CLI `--purge` addresses only the currently bound identity and configured prefixes, while logout removes all profile partitions. These specifics follow the Phase 1 implementation rather than the broader planning notes. ## Browser read-through (pre-release) > [!WARNING] > > **Pre-release.** Browser read-through is available from the `beta` dist-tag of `@tinycloud/web-sdk`, not in the stable 3.2.x line. Install `@tinycloud/web-sdk`, `@tinycloud/replica`, `@tinycloud/node-sdk` and `@tinycloud/sdk-core` from their `beta` dist-tags together and pin the exact versions they resolve to. Each package has its own version number (for example `@tinycloud/replica` is 0.3.x while `@tinycloud/web-sdk` is 3.3.x). Browser read-through is exercised in Chromium. With the `replication` option on, `kv.get()` and `kv.list()` under the configured prefixes read from an encrypted IndexedDB replica when it covers the key, and from the network otherwise. It is off by default. Register the plugin once, before you construct the client: ```ts theme={null} import { TinyCloudWeb, registerBrowserReplica } from "@tinycloud/web-sdk"; import { browserReplicaPlugin } from "@tinycloud/web-sdk/replica"; registerBrowserReplica(browserReplicaPlugin); const tcw = new TinyCloudWeb({ // ...your usual config replication: { enabled: true, prefixes: ["notes/"], // folders ending in "/" onEvent: (event) => console.debug(event), }, }); ``` Constructing the client with `replication.enabled` and no registered plugin throws. The replica code lives in its own entry (`@tinycloud/web-sdk/replica`) and its storage and worker load lazily, so apps that do not import it do not pay for it. * **Prefixes.** Each entry is a folder ending in `/`. Browser read-through requires `allowSecrets` to stay `false` and excludes the whole space (`/`), `vault/` and the secrets space; a configuration that includes them is rejected. * **Reads.** A covered key is served from the replica. A stale replica syncs first (`maxStalenessMs`, default 120 seconds; the sync is bounded by `staleSyncTimeoutMs`, default 5 seconds) and falls back per the read rules above. Pass `{ source: "network" }` to `kv.get()` or `kv.list()` to bypass the replica for one read. * **Grant and consent.** The replica uses a device grant that lasts 24 hours by default (`grantTtlMs`, at most 7 days) and renews silently, without a wallet prompt, while your sign-in is still inside its 7-day consent window. After that, sign in again. A session that was restored from before replication was enabled may need a fresh sign-in so the sync permission can be consented. * **Size.** `maxBytes` caps replica data for the whole origin. When the budget is reached, syncing stops with `STORAGE_BUDGET` and nothing is evicted, so new data stops mirroring until you raise the cap or erase. The browser also keeps a free-space floor (`minFreeBytes`, default 64 MiB). * **Status and events.** `tcw.replication.status()` reports each prefix; `onEvent` receives `replication.sync`, `replication.grant` and `replication.lifecycle` events. * **Encrypted at rest.** Replica rows are sealed with non-extractable AES-GCM keys held in the browser, and no content, paths, prefixes or account identifiers are stored in readable form in replica storage. ### Sign-out and account switch Signing out, or switching to another account, removes the replica's keys first and then erases the content; the erase can finish the next time the page loads. When the local copy could not be confirmed removed, `tcw.signOut()` rejects with an `Error` whose message begins `Replica gate was not denied`; the session is already cleared, so show the message to the user. If another TinyCloud tab is open when you sign out, the local copy stays off until the page reloads, and reads continue from the network. ### Scope Replicas are read-only mirrors of KV prefixes: there are no offline writes and SQL data is not replicated. ## Browser: open, grant, sync, and read locally The browser API is exported by `@tinycloud/replica/browser`; `@tinycloud/web-sdk` does not wrap or re-export replica operations. It does expose owner delegation methods used here: `requestPermissions()` obtains the explicit KV authority and `delegateTo()` issues it to the replica's device DID. The `owner` below is an authenticated `TinyCloudWeb` instance configured with the app manifest needed for permission requests. ```ts theme={null} import { openReplica } from "@tinycloud/replica/browser"; const replica = await openReplica({ host: "https://tee.node.tinycloud.xyz", space: spaceId, prefix: "notes/", principal: signedInUserDid, }); // The authenticated owner explicitly authorizes this prefix for the device. const permission = [{ service: "tinycloud.kv", space: spaceId, path: "notes/", actions: ["get", "sync"], }] satisfies Parameters[1]; const approval = await owner.requestPermissions(permission); if (!approval.approved) throw new Error("The owner did not approve the replica grant."); const issued = await owner.delegateTo(replica.deviceDid, permission, { expiry: "30d" }); // "30d" is a requested lifetime; the issued grant may expire sooner if the // owner's session expires sooner. await replica.installGrant(issued.delegation.delegationHeader.Authorization); await replica.sync(); // Local read APIs never use the network; they still enforce grant expiry. const read = await replica.get("notes/today.txt"); if (read.status === "present") { const text = new TextDecoder().decode(read.value); console.log(text); } const keys = await replica.list({ prefix: "notes/" }); console.log(keys.entries.map(({ key }) => key)); await replica.close(); ``` `principal` is the signed-in user's identity DID and partitions data for users sharing a browser origin; it is not an authorization check. The grant and the node authorize sync. Browser data is stored in IndexedDB through a dedicated worker. Browser `get` and `list` are explicitly local; call `sync()` to poll for updates. Browser sync requires Web Locks (`navigator.locks`); without it, `sync()` rejects with `RUNTIME_UNSUPPORTED`, but an existing replica can still be read. If a browser does not support IndexedDB, opening the replica fails instead of silently switching to non-durable in-memory storage. ## Security model * A replica stores only its configured KV prefix, and the grant must cover that prefix; the grant may be broader. Out-of-scope names and bytes are not fetched into replica storage. * By default, local reads stop when the node-attested grant window expires. A retention window attested by the node can allow reads after expiry. An offline device cannot discover an online revocation until it reconnects; once the replica learns that its serving grant was revoked, reads are blocked and content purge begins. If physical cleanup is pending, the next open retries it. * CLI replica files use mode `0600` under directories with mode `0700`. Protect the device account and backups as well; file permissions do not protect against the same operating-system user. * Sync grants do not grant decryption. Replicating the secrets space, a `vault/` folder, or `/` (the whole space) requires explicit opt-in: `tc replica sync --allow-secrets` on the CLI, or `openReplica({ allowSecrets: true })` in the browser. It copies encrypted secret material to the device. If you separately grant decrypt, note that decrypt authority is network-wide today, not limited to one secret name. Do not use it unless that scope is acceptable. * **Since CLI 1.1.0:** `tc auth logout` deletes local replicas for that CLI profile by default; pass `--keep-replicas` to keep them. Logout does not revoke the profile's grants on the node. To revoke node-side authority, use `tc delegation revoke `. Logout refuses to remove replicas if a sync is running or the replicas directory is a symlink. ## Known limitations * **Known node limitations being tracked (TC-737):** a quiet prefix in a busy space can make each poll scan newer changes outside that prefix, increasing sync work and potentially latency even when the prefix has no updates. * **Known node limitations being tracked (TC-735):** on Postgres, blob uploads run inside the per-space write lock, so uploads can slow other writes in that space. * Remote refresh is polling through `sync()`; there is no remote push or watch API. In the browser, `onCommitted` reports only local commits from other tabs. * Replicas are read-only. Offline writes are not supported. # Share Viewer and Receiving Source: https://docs.tinycloud.xyz/guides/share-viewer What recipients see at share.tinycloud.xyz, and how a browser app receives addressed shares Share links published with [`tc share publish`](/cli/share) open in the Share viewer at `share.tinycloud.xyz`. This page covers what the viewer shows, how recipients claim addressed links, and how your own browser app can receive and keep a share with the Web SDK. ## What the viewer previews | Content | Shown as | | - | - | | Markdown (`.md`, `text/markdown`) | Rendered document, including Mermaid diagrams | | Text (`text/*`, `.txt`, `.csv`, `.log`, `.json`, `.yaml`) | Source view | | Images other than SVG | Inline image | | Single-file HTML | Sandboxed page, on bearer links only | | SVG, JavaScript, anything else | Download only | Files larger than 1 MB, and text that is not valid UTF-8, are download only. **HTML pages** run in an isolated frame with a notice that the page comes from the sender. The frame cannot read the link or the viewer's session, or make signed-in requests to the viewer. It can still reveal the reader's IP address to the sender. Addressed links never run HTML, because the viewer holds the recipient's credential there; they offer a download instead. **Mermaid** fenced blocks render as diagrams, up to 12 per document, 20,000 characters of source each, and 5 seconds of render time each. A diagram over those limits stays visible as source. ## Claiming an addressed link An addressed link names who may open it: one email address or everyone at an email domain. * **Email address:** the recipient enters the 8-digit code Share emails to that mailbox. No TinyCloud account is needed. * **Email domain:** the recipient chooses which of their mailboxes to verify. Any verified mailbox at exactly that domain works; subdomains do not. The viewer cannot open DID-addressed links or multi-file (`--prefix`) shares yet. After a successful claim the viewer decrypts the file in the browser. Any recipient can choose **Save a private copy**, sign in with OpenKey, and keep the file in their own space under **Files for you**. ## Receive shares in your app `TinyCloudWeb` exposes `share.receive()` for email and email-domain links. Configure the Share and registry origins your app trusts: ```typescript theme={null} import { TinyCloudWeb } from "@tinycloud/web-sdk"; const tcw = new TinyCloudWeb({ shareReceiver: { expectedShareOrigin: "https://share.tinycloud.xyz", registryOrigin: "https://registry.tinycloud.xyz", }, }); const received = await tcw.share.receive(shareUrl, { identity: "auto", // "account", "receiver", or "auto" interaction: { kind: "inline", mountTarget: "#claim" }, onProgress: (event) => console.log(event.state, event.status), }); console.log(received.recipient); // { kind: "exactEmail", email } or { kind: "emailDomain", domain } const file = await received.get(); console.log(file.filename, file.mediaType, file.bytes.byteLength); ``` `identity: "receiver"` proves the credential with a browser session key and does not need a TinyCloud account. `"account"` uses the signed-in user's session. `"auto"` picks the account when one is signed in. ### Keep a copy `importInto()` needs a signed-in account session; with `identity: "receiver"` or no one signed in, sign in before importing. ```typescript theme={null} const imported = await received.importInto(tcw, { namespace: "files-for-you" }); // imported.status is "imported" or "existing" ``` ### Hand access to another key A received share can be re-delegated, including decryption, to another key such as an account's session key. The delegate opens the same URL with the delegation instead of proving the credential again: ```typescript theme={null} const delegation = await received.delegate({ to: accountSessionDid }); const again = await tcw.share.receive(shareUrl, { identity: "account", interaction: { kind: "inline", mountTarget: "#claim" }, delegation, }); ``` `delegate()` and sessions opened from a received share default to the longest lifetime the share allows, so a kept share stays readable until the share itself expires. ### Errors | Code | Meaning | | - | - | | `PROOF_REJECTED` | The email issuer rejected a code; the inline view asks again | | `VERIFICATION_FAILED` | Too many wrong codes (`proof_attempts_exhausted`) | | `ISSUER_UNREADY` | The email issuer is rate limiting (`rate_limited`); retry later | ## Publish from code `@tinycloud/share-sdk` is the library behind `tc share`. It exports `publishTargetShare`, `prepareAddressedShare`, `notifyShare`, `canonicalShareFilename`, and `addressedCredentialRequirement`. Most apps should publish through the CLI or the Share app and only receive in code. ## Related * [Share files](/cli/share) to publish, notify, and revoke from the terminal * [Sharing links](/guides/sharing) for SDK `tc1:` bearer tokens * [Security and trust](/concepts/security-and-trust) for what a bearer URL grants # Sharing Links Source: https://docs.tinycloud.xyz/guides/sharing Create bearer links for read-only access to one TinyCloud key. Sharing links provide read-only access to one KV key without requiring the recipient to have a TinyCloud account. The SDK packages a scoped delegation and an ephemeral private key into a `tc1:` bearer token. > [!TIP] > > To send a file that opens in the Share viewer, or to address it to an email > address or domain, use [`tc share publish`](/cli/share) and the > [Share viewer](/guides/share-viewer) instead. This page covers the lower-level > SDK token. ## Store data and generate a link The generating SDK instance must be signed in and have delegation capability. ```typescript theme={null} const stored = await tc.kv.put("my-document", { title: "Project notes", body: "Next review is Friday.", }); if (!stored.ok) throw new Error(stored.error.message); const shared = await tc.sharing.generate({ path: "my-document", expiry: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), }); if (!shared.ok) throw new Error(shared.error.message); const shareUrl = shared.data.url; console.log(shareUrl); ``` `sharing.generate()` is available from both the Node and Web SDKs. By default, the generated delegation grants `tinycloud.kv/get` and `tinycloud.kv/metadata` for the selected key. `data.url` is `${baseUrl}/share/tc1:...` when you pass `baseUrl`, and the bare `tc1:` token otherwise. Your app decides where that URL opens. ### Check before you generate A session can only issue a sharing delegation from authority it holds without restrictions. `preflightGenerate()` answers that without side effects: ```typescript theme={null} const check = tc.sharing.preflightGenerate({ path: "my-document" }); // "ok", "caveated" (only restricted authority covers it), or "not-covered" ``` Generate only on `"ok"`. A caveated session cannot pass its restrictions on to the link's delegation. ## Receive the same key Browser recipients can retrieve the shared value with the static helper. They do not create an SDK instance or call `signIn()`. ```typescript theme={null} import { TinyCloudWeb } from "@tinycloud/web-sdk"; const received = await TinyCloudWeb.receiveShare<{ title: string; body: string; }>(shareUrl); if (!received.ok) throw new Error(received.error.message); console.log(received.data.path); // "my-document" (with any app prefix) console.log(received.data.data.title); // "Project notes" ``` The helper reads the path embedded in the link unless the caller explicitly passes a different key. For a single-key sharing flow, do not substitute an unrelated key at receive time. ## What the link contains * schema version `1` * the full shared KV path * the TinyCloud host and owner space ID * a signed read delegation * a private JWK for the generated share principal Anyone who has the URL can exercise the embedded authority until it expires or the delegation is revoked. Do not log sharing links or put them in analytics, referrer URLs, or public issue trackers. ## End access early Keep the generated delegation CID if the owner may need to revoke the link: ```typescript theme={null} const revoked = await tc.revokeDelegation(shared.data.delegation.cid); if (!revoked.ok) throw new Error(revoked.error.message); ``` Use short expiries as a second limit. A new link creates a new share principal and delegation; it does not extend the old link. ## When to use a delegation instead Use a sharing link for a one-click, read-only handoff of a single value. Use a normal [delegation](/guides/delegations) when the recipient has a persistent identity, needs several paths or actions, or may sub-delegate. # Spaces Source: https://docs.tinycloud.xyz/guides/spaces Understand the TinyCloud container that owns a user's data A TinyCloud space is the owned container for data. It is the thing you land in after sign-in, and it is the boundary that keeps one user's application data separate from another user's data. ## What To Use This Page For * Decide which space name your app should use. * See how the Web and Node SDKs name a space. * Move on to provisioning when you need the space to exist on the node. | SDK | Input | Result | | - | - | - | | Web | `spacePrefix` | The primary space name used by `TinyCloudWeb` | | Node | `prefix` | The primary space name used by `TinyCloudNode` | The resulting space URI has the form `tinycloud:pkh:eip155::
:`. After sign-in, `tc.spaceId` or `node.spaceId` gives you the active primary space URI. ## Read Next * [Spaces provisioning](/guides/spaces/provisioning) * [Authentication](/guides/authentication) * [Node SDK reference](/reference/sdk/node) > [!NOTE] > > Verified against `@tinycloud/web-sdk` and `@tinycloud/node-sdk` 3.0.0. # Spaces provisioning Source: https://docs.tinycloud.xyz/guides/spaces/provisioning Create and host the user's TinyCloud space during sign-in Use this page when you need the user's space to exist before the first write. ## Provision during sign-in ```typescript theme={null} import { TinyCloudWeb } from '@tinycloud/web-sdk'; const provider = (window as Window & { ethereum?: unknown }).ethereum; if (!provider) throw new Error('A browser wallet is required'); const web = new TinyCloudWeb({ provider, tinycloudHosts: ['https://node.tinycloud.xyz'], spacePrefix: 'my-app', }); await web.signIn(); console.log(web.spaceId); ``` ```typescript theme={null} import { TinyCloudNode } from '@tinycloud/node-sdk'; const node = new TinyCloudNode({ privateKey: process.env.WALLET_PRIVATE_KEY, host: 'https://node.tinycloud.xyz', prefix: 'my-app', autoCreateSpace: true, }); await node.signIn(); console.log(node.spaceId); ``` In the Web SDK, `autoCreateSpace` defaults to `true`. In the Node SDK, it defaults to `false`, so backends that own their own space should opt in explicitly. ## Check the active space After sign-in, `spaceId` gives you the current primary space URI. Use that value when you need to confirm which container the next `tc.kv` or `node.kv` call will target. ## Additional owned spaces TinyCloudNode can host additional owned spaces by name after sign-in: ```typescript theme={null} import { TinyCloudNode } from '@tinycloud/node-sdk'; const node = new TinyCloudNode({ privateKey: process.env.WALLET_PRIVATE_KEY, host: 'https://node.tinycloud.xyz', }); await node.signIn(); await node.ensureOwnedSpaceHosted('secrets'); ``` Use this when a backend needs a separate owned space such as `secrets` and the node has not hosted it yet. ## Next step * [KV basic operations](/guides/kv/basic-operations) * [Web sign-in](/guides/authentication/web) * [Node sign-in](/guides/authentication/node) > [!NOTE] > > Verified against `@tinycloud/web-sdk` and `@tinycloud/node-sdk` 3.0.0. # SQL Schema and Migrations Source: https://docs.tinycloud.xyz/guides/sql-schema-and-migrations Apply TinyCloud SQL schema changes through migrations. Use this guide when you need to create or change a TinyCloud SQL schema. The SDK's migration helper applies versioned SQL during install or startup instead of running ad hoc DDL in a hot path. ## Apply migrations ```ts theme={null} await tc.sql.db("main").migrations.apply({ namespace: "com.example.notes", migrations: [ { id: "001_initial_note_index", sql: [ "CREATE TABLE IF NOT EXISTS note_index (id TEXT PRIMARY KEY, title TEXT NOT NULL, updated_at TEXT NOT NULL)", "CREATE INDEX IF NOT EXISTS idx_note_index_updated_at ON note_index(updated_at)", ], }, ], }); ``` Use stable migration ids and run them before serving user traffic. ## Request the schema capability Schema changes need the `tinycloud.sql/schema` action for the same database path used at runtime. If you use the `tc.sql` shortcut, the database name is `default`. ```ts theme={null} await tc.signIn(); const sql = "CREATE TABLE IF NOT EXISTS notes (id TEXT PRIMARY KEY, body TEXT NOT NULL)"; const direct = await tc.sql.execute(sql); if (!direct.ok) throw new Error(direct.error.message); const scoped = await tc.sql.db("default").execute(sql); if (!scoped.ok) throw new Error(scoped.error.message); ``` Those two forms target the same database. ## What to avoid * do not run cold `CREATE TABLE` or `ALTER TABLE` in a request path * do not copy app-specific schema bootstrap helpers between apps * do not treat mirrored indexes as canonical data without saying so ## Source note The migration helper and schema permission behavior are implemented in the JS SDK and SQL service tests. This guide stays on the operational path and leaves exact SQL semantics to the code. # TinyCloud VFS Source: https://docs.tinycloud.xyz/guides/tinycloud-vfs Mount TinyCloud KV as a Node.js virtual file system `@tinycloud/vfs` mounts TinyCloud data as a Node.js virtual file system. In this first cut it is KV-only: files and directories are backed by TinyCloud KV in the underlying space or delegated subtree. It is meant for Node runtimes, not the browser. ## Access Modes TinyCloud VFS supports two entry points: * **Owner access** uses an authenticated `TinyCloudNode` instance and mounts your own space * **Delegated access** uses a portable delegation and mounts the delegator's scoped subtree The delegated factory is async because it resolves the delegation before building the mounted VFS: `await createTinyCloudDelegatedVfs(...)`. ## Installation ```bash npm theme={null} npm install @tinycloud/node-sdk @tinycloud/vfs ``` ```bash bun theme={null} bun add @tinycloud/node-sdk @tinycloud/vfs ``` ## Owner Usage Use `createTinyCloudVfsFromNode(node)` when the process owns the TinyCloud session. ```typescript theme={null} import fs from "node:fs"; import { TinyCloudNode } from "@tinycloud/node-sdk"; import { createTinyCloudVfsFromNode } from "@tinycloud/vfs"; const owner = new TinyCloudNode({ privateKey: process.env.TINYCLOUD_PRIVATE_KEY!, host: "https://node.tinycloud.xyz", autoCreateSpace: true, }); await owner.signIn(); const { provider, vfs } = createTinyCloudVfsFromNode(owner); vfs.mount("/tmp/tinycloud-owner"); try { fs.writeFileSync("/tmp/tinycloud-owner/hello.txt", "hello from owner"); console.log(fs.readFileSync("/tmp/tinycloud-owner/hello.txt", "utf8")); } finally { vfs.unmount(); provider.close(); } ``` ## Delegated Usage Use `await createTinyCloudDelegatedVfs({ node, delegation })` when you want to mount a path that was granted through delegation. ```typescript theme={null} import fs from "node:fs"; import { TinyCloudNode } from "@tinycloud/node-sdk"; import { createTinyCloudDelegatedVfs } from "@tinycloud/vfs"; const alice = new TinyCloudNode({ privateKey: process.env.ALICE_PRIVATE_KEY!, host: "https://node.tinycloud.xyz", autoCreateSpace: true, }); const bob = new TinyCloudNode({ privateKey: process.env.BOB_PRIVATE_KEY!, host: "https://node.tinycloud.xyz", autoCreateSpace: true, }); await alice.signIn(); await bob.signIn(); const delegation = await alice.createDelegation({ delegateDID: bob.did, path: "shared/", actions: [ "tinycloud.kv/get", "tinycloud.kv/put", "tinycloud.kv/list", "tinycloud.kv/del", "tinycloud.kv/metadata", ], }); const { provider, vfs } = await createTinyCloudDelegatedVfs({ node: bob, delegation }); vfs.mount("/tmp/tinycloud-delegated"); try { fs.writeFileSync("/tmp/tinycloud-delegated/bob-note.txt", "written through delegation"); console.log(fs.readFileSync("/tmp/tinycloud-delegated/bob-note.txt", "utf8")); } finally { vfs.unmount(); provider.close(); } ``` ## Live-Tested Behavior These examples were validated against the live Node coverage added in js-sdk PR #194. * Owner mounts support read, write, stat, list, rename, unlink, and `rmdir` * Delegated mounts can read and write within the delegated subtree * Read-only delegations reject writes with `EACCES` ## Cleanup The current examples explicitly call `vfs.unmount()` and then `provider.close()`. Keep that order in your own code: unmount first, then close the provider. > [!TIP] > > If you are writing a long-lived service, treat the provider as a resource that should be closed on shutdown even after the VFS has been unmounted. # Write Hooks Source: https://docs.tinycloud.xyz/guides/write-hooks Subscribe to TinyCloud writes with SSE or durable webhooks. Use write hooks when you need to react to TinyCloud writes without polling. The SDK exposes the same hook scope model for live SSE subscriptions and durable webhooks. ## Choose a delivery mode * use SSE when the consumer stays connected inside your app or worker * use webhooks when you need HTTP POST delivery, retries, or decoupled work Both modes scope to: * `space` * `service` * optional `pathPrefix` * optional `abilities` ## Subscribe to live writes ```typescript theme={null} await tc.signIn(); const stream = tc.hooks.subscribe([ { space: tc.spaceId!, service: "sql", pathPrefix: "main.db", abilities: ["tinycloud.sql/write"], }, ]); for await (const event of stream) { console.log(event.type, event.service, event.path); } ``` `subscribe()` is live-only. It does not replay missed events after reconnect. ## Register a webhook ```typescript theme={null} await tc.signIn(); const created = await tc.hooks.register({ space: tc.spaceId!, service: "kv", pathPrefix: "documents", abilities: ["tinycloud.kv/put", "tinycloud.kv/del"], callbackUrl: "https://example.com/tinycloud/hooks", secret: process.env.TINYCLOUD_WEBHOOK_SECRET!, }); ``` The webhook secret is stored encrypted on the server. TinyCloud signs each delivery with `X-TinyCloud-Signature`. ## Verify deliveries before parsing them The signature is `sha256=` over the exact request-body bytes. Capture the raw body and compare the HMAC in constant time before accepting the event. For example, with Express: ```typescript theme={null} import { createHmac, timingSafeEqual } from 'node:crypto'; import express from 'express'; const app = express(); app.post('/tinycloud/hooks', express.raw({ type: 'application/json' }), (req, res) => { const secret = process.env.TINYCLOUD_WEBHOOK_SECRET; const signature = req.header('X-TinyCloud-Signature'); const match = signature?.match(/^sha256=([0-9a-f]{64})$/i); if (!secret || !match) return res.sendStatus(401); const expected = createHmac('sha256', secret).update(req.body).digest(); const received = Buffer.from(match[1], 'hex'); if (received.length !== expected.length || !timingSafeEqual(received, expected)) { return res.sendStatus(401); } const event = JSON.parse(req.body.toString('utf8')); console.log(event.id, event.service, event.path); return res.sendStatus(204); }); ``` Do not run JSON middleware before this route: re-serializing parsed JSON changes the signed bytes. Keep the webhook secret in a secret manager and rotate it by re-registering the hook. Each POST body is one write event: | Field | Type | Meaning | | - | - | - | | `type` | `"write"` | Event kind | | `id` | `string` | Stable event identifier | | `space` | `string` | Affected TinyCloud space | | `service` | `string` | `kv`, `sql`, or `duckdb` | | `ability` | `string` | Capability for the write, such as `tinycloud.kv/put` | | `path` | `string` (optional) | Affected key or database path | | `actor` | `string` | DID that performed the write | | `epoch` | `string` | Node epoch identifier | | `eventIndex` | `number` | Event position within the epoch | | `timestamp` | `string` | Event time | Use `X-TinyCloud-Delivery-Id` as an idempotency key for delivery attempts and `X-TinyCloud-Event-Id` for the underlying event. ## Inspect and remove hooks ```typescript theme={null} await tc.signIn(); const list = await tc.hooks.list({ space: tc.spaceId, service: "kv", pathPrefix: "documents", }); await tc.hooks.unregister("hook-id", { target: { space: tc.spaceId!, service: "kv", pathPrefix: "documents", }, }); ``` ## Delivery semantics * SSE is best-effort live delivery only * webhooks are durable and at-least-once * duplicates are possible for webhooks, so receivers must be idempotent The node normalizes `pathPrefix` by trimming surrounding slashes and matches the exact path or descendants beneath it. ## Verification note Verified against the TinyCloud SDK hook types and the node webhook dispatcher. # Configuration Source: https://docs.tinycloud.xyz/hosting/configuration Configure a TinyCloud node with TOML and environment variables TinyCloud node config comes from built-in defaults, `tinycloud.toml`, and `TINYCLOUD_` environment variables. Canonical nested env vars use double underscores. ## Canonical examples ```bash theme={null} TINYCLOUD_STORAGE__DATABASE="sqlite:./data/caps.db" TINYCLOUD_STORAGE__BLOCKS__TYPE="Local" TINYCLOUD_STORAGE__BLOCKS__PATH="./data/blocks" TINYCLOUD_KEYS__SECRET="base64url-secret" TINYCLOUD_PROMETHEUS__PORT=8001 TINYCLOUD_TELEMETRY__ENABLED=true ``` ## Core keys | TOML key | Purpose | Default | | - | - | - | | `port` | HTTP API port | `8000` | | `address` | Bind address | `127.0.0.1` | | `cors` | Enable CORS headers | `false` | | `storage.datadir` | Root directory for local data | `./data` | | `storage.database` | SQL database connection string | `sqlite:./data/caps.db` | | `storage.blocks.type` | Block backend | `Local` | | `storage.staging.type` | Staging backend | `Memory` | | `prometheus.port` | Metrics port | `8001` | | `telemetry.enabled` | Start the metrics server | `false` | | `log.format` | Log format | `Text` | | `log.tracing.enabled` | Enable OTLP tracing | `false` | ## Storage layout If you leave local paths unset, the node resolves them under `storage.datadir`: * `caps.db` for the SQL database * `blocks/` for local block storage * `sql/` and `duckdb/` for database artifacts ## Keys The node requires a static secret for key derivation unless you are using a specialized deployment mode. ```bash theme={null} openssl rand -base64 32 | tr '+/' '-_' | tr -d '=' ``` Set the URL-safe, unpadded result in `TINYCLOUD_KEYS__SECRET`. ## Logging and tracing Use `[log]` for log format and tracing settings: ```toml theme={null} [log] format = "Json" [log.tracing] enabled = true ``` When tracing is enabled, the node builds an OTLP gRPC exporter using the exporter's default endpoint. The current TinyCloud config exposes the enable flag and trace-header name, but not a collector-endpoint setting. > [!WARNING] > > The server still accepts legacy single-underscore env vars, but canonical double-underscore env vars take precedence when both are present. # Database Setup Source: https://docs.tinycloud.xyz/hosting/databases Configure SQLite, PostgreSQL, or MySQL TinyCloud stores metadata and related state in a relational database. The node accepts SQLite, PostgreSQL, and MySQL connection strings. ## Supported backends | Backend | Example | | - | - | | SQLite | `sqlite:./data/caps.db` | | PostgreSQL | `postgres://user:pass@host:5432/dbname` | | MySQL | `mysql://user:pass@host:3306/dbname` | ## SQLite SQLite is the default. It is the simplest option for development and single-node deployments. ```toml theme={null} [storage] database = "sqlite:./data/caps.db" ``` ```bash theme={null} TINYCLOUD_STORAGE__DATABASE="sqlite:./data/caps.db" ``` ## PostgreSQL Use PostgreSQL for production deployments that need concurrency and operational tooling. ```toml theme={null} [storage] database = "postgres://tinycloud:password@localhost:5432/tinycloud" ``` ```bash theme={null} TINYCLOUD_STORAGE__DATABASE="postgres://tinycloud:password@localhost:5432/tinycloud" ``` ## MySQL MySQL is also supported if your infrastructure already uses it. ## Migrations The node applies database migrations automatically on startup. There is no separate migration command. ## Practical guidance * Use SQLite for a quick local node * Use PostgreSQL for most production deployments * Make sure the database is reachable before starting the node > [!WARNING] > > If startup fails after a database change, check the node logs and confirm the connection string in `tinycloud.toml` or `TINYCLOUD_STORAGE__DATABASE`. # Docker Deployment Source: https://docs.tinycloud.xyz/hosting/docker Run TinyCloud with Docker For an ordinary VPS, follow the [personal-node guide](https://github.com/TinyCloudLabs/tinycloud-node/blob/main/deploy/personal-node/README.md). Its Compose profile pins the published 1.20.6 ordinary-node image by digest, mounts a keyless configuration, persists SQLite and local blocks, terminates HTTPS at Caddy, and uses an installation-specific persistent key. The guide's CI rehearsal uses the same operator script to check signed KV/SQL, restart, fresh-volume restore, upgrade from 1.20.5 to 1.20.6, and restore-based rollback. Do not use an unversioned image or the dstack Compose profile as an ordinary-server recipe. TinyCloud currently runs 1.20.6 in production; 1.20.7 was rolled back. The guide names what its published-image job has verified and which key-default change needs the next approved release. Running an ordinary VPS does not provide TEE attestation or dstack key isolation. For configuration details, see [Configuration](/hosting/configuration). Keep the node's plain HTTP API and unauthenticated metrics private; expose only the HTTPS reverse proxy. Retain the node root and an offline data backup independently. # Host the MCP server Source: https://docs.tinycloud.xyz/hosting/mcp Deploy TinyCloud Streamable HTTP MCP with OpenKey OAuth Run the hosted MCP server when remote clients need a public Streamable HTTP endpoint. It is an OAuth resource server, not an owner authority: every tenant gets a separate generated session key and can use only capabilities approved through OpenKey. > [!WARNING] > > Hosted MCP is not an endpoint-only E2EE path: its runtime processes plaintext > tool inputs and results, including secrets it is authorized to decrypt. An > ordinary MCP operator can access that plaintext. A TEE deployment requires > separately verified attestation and code/key policy before claiming protection > from infrastructure operators. See [Security and trust](/concepts/security-and-trust). ## Container ```bash theme={null} docker run --rm -p 3000:3000 \ -e TC_MCP_PUBLIC_URL=https://mcp.example.com/mcp \ -e TC_MCP_STATE_SECRET="$(openssl rand -hex 32)" \ -v tinycloud-mcp-state:/var/lib/tinycloud-mcp \ ghcr.io/tinycloudlabs/tinycloud-mcp:latest ``` Terminate TLS at a reverse proxy and preserve the public `Host` header. The service refuses unexpected hosts and requires HTTPS for non-local public URLs. ## Configuration | Variable | Required | Purpose | | - | -: | - | | `TC_MCP_PUBLIC_URL` | Yes | Exact public MCP resource URL, including `/mcp` | | `TC_MCP_STATE_DIR` | Yes | Absolute path to the persistent tenant-state volume; the image defaults to `/var/lib/tinycloud-mcp` | | `TC_MCP_STATE_SECRET` | Yes | At least 32 bytes used to derive tenant IDs and sign one-time approval state | | `TC_MCP_OAUTH_METADATA_URL` | No | OpenKey authorization-server metadata URL | | `TC_OPENKEY_HOST` | No | OpenKey browser approval origin; defaults to `https://openkey.so` | | `TC_HOST` | No | TinyCloud node; defaults to `https://tee.node.tinycloud.xyz` | | `TC_MCP_ALLOWED_ORIGINS` | No | Comma-separated origins for direct browser requests | | `TC_MCP_APPROVAL_TTL_SECONDS` | No | One-time approval link lifetime; standalone default is 300 seconds; production compose sets 900 | | `TC_MCP_DELEGATION_EXPIRY` | No | Delegation duration sent to OpenKey; standalone default is `1h`; production compose sets `30d` | | `PORT` | No | HTTP listen port; defaults to 3000 | Keep the state secret stable. Rotating it intentionally disconnects existing OAuth subjects from their stored delegates. Back up the state volume and encrypt it at rest; it contains delegate private keys and signed capabilities, but no owner keys or OAuth access tokens. The production `docker-compose.phala.yml` explicitly sets `TC_MCP_DELEGATION_EXPIRY=30d` and `TC_MCP_APPROVAL_TTL_SECONDS=900`; the standalone container command above does not inherit those compose overrides. Expired or missing sessions return a fresh connect approval link in `error.details`; expired or missing grants return an `authority_required` approval link. The owner must approve again. Hosted mode exposes 20 tools, including `tinycloud_connect` and four `tinycloud_apps_*` tools. Local stdio has 17 tools; `tinycloud_auth_import` and `tinycloud_secrets_status` are local-only. Personal-record operations use one get/list/put/delete prefix grant for `xyz.tinycloud.agent-data/` in `default`. This is an apps-specific exception, not broader authority for generic KV tools. The optional fast copy has a separate exact-database approval. KV remains the source of truth; `COPY_PARTIAL` resumes on the next query, while nonretryable `NODE_ERROR` with `error.details.reason: "copy_unavailable"` requires the node team, not a retry loop. See [TinyCloud MCP](/cli/mcp) for the owner workflow, ETag edits and partial write outcomes. ## Scaling boundary The filesystem store supports one service replica. It uses async-scoped tenant roots and per-profile locks inside that replica, but does not provide a distributed key-creation or approval transaction. Do not point multiple replicas at the same volume. A multi-replica deployment needs a shared transactional state provider. ## OAuth requirements The OpenKey issuer must allow: * Dynamic client registration for remote MCP clients * The `tinycloud:mcp` scope * The exact `TC_MCP_PUBLIC_URL` as an OAuth resource audience * The `https://tinycloud.xyz/owner_dids` access-token claim The MCP resource validates signature, issuer, audience, expiry, and scope on every request. The browser approval callback is short-lived, HMAC-bound, single-use, and cryptographically validated by the TinyCloud SDK before the delegation is persisted. The approval page names the account that asked, and the callback refuses a delegation signed by any other account with `403 approval_owner_mismatch` (`@tinycloud/mcp` 0.3.3 and later). ## Results and privacy Hosted text blocks include the canonical JSON result so clients that ignore `structuredContent` can still read records and approval links. Successful secret values remain structured-only. Read-only results over 100,000 characters return a nonretryable size error with narrowing guidance; write results are never truncated by this cap. Writes do not use an operation deadline that could abandon reporting while a mutation continues. Each tool call emits one stderr line containing only the tool name, outcome code, duration and successful replayed-grant count. Never log keys (which can contain personal slugs), values, catalog text, SQL or parameters. > [!WARNING] > > The service processes plaintext inputs and results, including delegated secrets. > Treat its runtime and observability pipeline as part of the data trust boundary. > Do not log request bodies, text result blocks or structured tool results. # Monitoring Source: https://docs.tinycloud.xyz/hosting/monitoring Health checks, metrics, logs, and tracing Use this page after the node starts cleanly. It covers the endpoints and telemetry knobs you can wire into probes and observability. ## Health ```bash theme={null} curl http://localhost:8000/healthz ``` Use `/healthz` for load balancers, container probes, and uptime checks. ## Metrics Enable the Prometheus server with telemetry and use the metrics port for scraping. ```toml theme={null} [telemetry] enabled = true [prometheus] port = 8001 ``` ## Logging ```toml theme={null} [log] format = "Text" ``` Switch to `Json` when you want structured logs for a collector or log shipper. ## Tracing Enable tracing under `[log.tracing]`. The current node builds its OTLP gRPC exporter with the library's default collector endpoint; TinyCloud config does not currently expose an endpoint override. ```toml theme={null} [log.tracing] enabled = true ``` The node exports OTLP spans; your collector can forward them to whatever backend you use when it is reachable at that endpoint. ## What to avoid * Do not expose the metrics port publicly * Do not rely on tracing being on by default * Do not assume the Prometheus server starts unless telemetry is enabled > [!NOTE] > > The node's tracing code uses OpenTelemetry OTLP export. The docs here stay at that level instead of naming a specific collector backend. # Self-Hosting Overview Source: https://docs.tinycloud.xyz/hosting/overview Run your own TinyCloud node Run this node when you want to host TinyCloud yourself instead of using a managed node. ## What the node does * Serves the HTTP API * Verifies authentication and delegations * Stores KV, SQL, and block data * Exposes health and metrics endpoints * Supports local filesystem, SQLite, PostgreSQL, MySQL, and S3-compatible storage backends ## Default ports | Port | Purpose | | - | - | | `8000` | Main HTTP API | | `8001` | Prometheus metrics when telemetry is enabled | > [!NOTE] > > `relay.port` currently defaults to `8081` in configuration, but the node server > does not start a relay listener from that setting. Do not publish `8081` for the > minimal node unless a deployment-specific relay process requires it. ## Start here 1. Choose [Docker](/hosting/docker) or your own process supervisor and launch the node 2. Verify `http://localhost:8000/healthz` returns a successful response 3. Read [Configuration](/hosting/configuration), then choose production database and block-storage backends 4. Enable monitoring after the node starts cleanly with persistent storage > [card] [Configuration](/hosting/configuration) > > Canonical config keys, env vars, and defaults. > [card] [Docker](/hosting/docker) > > Minimal container setup and volume layout. > [card] [Databases](/hosting/databases) > > SQLite, PostgreSQL, and MySQL connection strings. > [card] [Monitoring](/hosting/monitoring) > > Health checks, metrics, and tracing. # Run TinyCloud sovereignly Source: https://docs.tinycloud.xyz/hosting/sovereignty Run your own TinyCloud node, hold your own Ethereum key, and keep control of where your data lives. ## Why > [!NOTE] > > **This section is Sam's text, lightly cleaned up from dictation.** TinyCloud should be usable sovereignly. This means if TinyCloud Labs as an organization goes away, you should still be able to use the technology. You should be able to use it without interference from anyone. And you should be fully in control of where your data lives and who has access to it. We use the same tools as crypto, which already lets people use money in a sovereign way. This is how we apply them to data. This is a little more involved and more technical, but sovereignty requires you to be more involved. We think TinyCloud should be available and accessible to everyone, which is why we built it as a service. This guide is for those who are called to sovereignty. ## This path is more involved than the hosted service The hosted service needs an account and nothing else. Running your own node means you provision a server, own a domain, keep two secrets safe, take your own backups and run your own upgrades. Nobody does those for you. TinyCloud's hosted service and free tier stay available. If you want your data and your node under your control, keep reading. ## The three parts Sovereignty in TinyCloud is three abilities: 1. **Run your own node** on your own server. 2. **Replicate your data** to that node. 3. **Use your own Ethereum key** as your identity. This guide gives working steps for parts 1 and 3. Part 2 is covered by the offline backup and restore below; node-to-node replication is under [What's next](#whats-next). ## Run a node The node is the same Rust binary and image that TinyCloud's hosted service runs. Its source and container image are public, and the source is licensed under EGPL-1.5. Everything in this section is the personal-node guide in the `tinycloud-node` repository, [`deploy/personal-node`](https://github.com/TinyCloudLabs/tinycloud-node/blob/main/deploy/personal-node/README.md). A GitHub Actions job runs the same `node.sh` operations on a clean runner on every change to that guide. That job is the evidence for every step here. ### What you need * An ordinary Linux VPS with Docker Engine and Compose v2, `bash`, `curl`, `jq`, `openssl`, `tar`, `sudo`, Node.js 22 and npm. * A domain you own, with its A/AAAA record pointing at the VPS. Ports 80 and 443 are free and reachable, so Caddy can get a certificate and serve HTTPS. * A persistent local disk with room for your live data and a full backup. * A clone of the `tinycloud-node` repository at the revision that carries the guide. Run every command below from its root. Keep the node's plain HTTP port (8000), its unauthenticated metrics port (8001) and the Docker socket off the internet. Only Caddy's 80 and 443 are public. ### What this node is, and is not * It runs one node with local SQLite and local blocks. Caddy terminates HTTPS. * It uses a digest-pinned published image (1.20.6) and a digest-pinned Caddy (2.10.2). Do not use `latest` or any other tag. * There is no hosted billing or quota service in this setup. CI checks that the node reports no quota URL. * It is **not** a TEE. You, the server operator, can read its filesystem and its key. The guide makes no attestation claim, and neither does this page. TLS proves your domain to clients; it does not prove the machine. * The node still depends on DNS and a certificate authority to be reachable over public HTTPS. ### Provision and launch ```bash theme={null} npm ci --prefix test/probe export NODE_HOME="$HOME/personal-tinycloud" bash deploy/personal-node/node.sh init node.example.com bash deploy/personal-node/node.sh check-missing-key bash deploy/personal-node/node.sh start bash deploy/personal-node/node.sh check-version 1.20.6 ``` Replace `node.example.com` with your domain. * `init` writes a unique random node key to a private `node.env` (mode `0600`) in `NODE_HOME`. It never prints it. * `check-missing-key` must run before `start`. It proves the node refuses to start with no key, rather than falling back to a shared default. * `check-version` confirms the node is running the pinned version, with no hosted quota URL and not inside a TEE. CI runs this same sequence with a local test certificate instead of a public one. Issuing a certificate for your own domain is the one part of launch CI does not run. The guide's [Caddy notes](https://github.com/TinyCloudLabs/tinycloud-node/blob/main/deploy/personal-node/README.md) tell you how to check issuance and renewal on a staging domain first. ### Stop and restart ```bash theme={null} bash deploy/personal-node/node.sh restart bash deploy/personal-node/node.sh stop ``` CI restarts the node and checks that signed data is still there. `stop` ends the node's containers and keeps its data. ## Your Ethereum key In TinyCloud your identity is an Ethereum address. This guide proves the plainest form of it: an externally owned account (EOA), a wallet key you hold, signing directly to your node. Put your wallet's 32-byte hexadecimal private key (no `0x`) in its own file, mode `0600`, outside `NODE_HOME`. Then: ```bash theme={null} bash deploy/personal-node/node.sh seed /secure/path/owner.key bash deploy/personal-node/node.sh restart bash deploy/personal-node/node.sh verify /secure/path/owner.key ``` `seed` signs in to your node with that key, creates a space the key owns, writes a key-value object and a SQL row. `verify` runs after the restart. It checks the exact KV and SQL values and checks that the node's public identity (its DID) is unchanged. Only the key file's path is passed on the command line, never the key. Two keys matter, and they are different: | Key | What it is | Where it lives | In the node backup? | | - | - | - | - | | **Your Ethereum key** | Your identity and the owner of your space. | Your wallet, or a private file you keep. | No. Keep it separately. | | **The node key** | The node's identity, used to sign for the node and seal its state. | `node.env` in `NODE_HOME`. | Yes, as a separately encrypted file. | What CI proves is signing with a private key read from a file. Signing through a browser wallet, a hardware wallet or a contract wallet is not in this guide's steps. ## Back up, and what happens if you lose your node key Take an offline backup. `backup` stops the node, archives its whole data directory, encrypts `node.env` as a separate file, and restarts the node. ```bash theme={null} # Generate a strong private passphrase file outside the node and backup tree. export BACKUP_PASSPHRASE_FILE=/secure/path/node-backup-passphrase umask 077 openssl rand -base64 48 > "$BACKUP_PASSPHRASE_FILE" bash deploy/personal-node/node.sh backup /secure/path/node-backup-2026-10-16 "$BACKUP_PASSPHRASE_FILE" ``` The data archive itself is **not** encrypted. Protect it as sensitive data. The passphrase is in neither artifact. Keep the backup and the passphrase in separate, secure places. To restore on a fresh host or directory, copy the backup, the passphrase and your owner wallet key over separate secure channels, then: ```bash theme={null} export NODE_HOME="$HOME/personal-tinycloud-restored" bash deploy/personal-node/node.sh restore /secure/path/node-backup-2026-10-16 "$BACKUP_PASSPHRASE_FILE" bash deploy/personal-node/node.sh start bash deploy/personal-node/node.sh check-version 1.20.6 bash deploy/personal-node/node.sh verify /secure/path/owner.key ``` Stop the old node before you repoint DNS, and never run two live nodes with the same identity and domain. CI restores into a fresh directory and checks that the node's DID and signed KV and SQL data match. **If you lose the node key.** The node key is what makes your node that node. Restore with the original key and the node comes back with the same identity and data. Start from a different key and `verify` fails rather than quietly giving you a new identity. A changed key can leave encrypted or sealed state unreadable: if the node key is lost, treat the node and its data as gone. So back up `node.env` independently of the data, every time you change anything. If you lose your Ethereum key, nothing in the node backup recovers it. It is not in the backup. ## Deleting your data Today, on a node you run, your data is in the `data` directory under your `NODE_HOME`, on your own disk. You delete it the way you delete any files on your own machine. The plan for deletion across hosts is that you revoke a host, the host deletes the data it holds for you, and the revocation spreads to your other hosts and through the SDK. This is not built yet; see [What's next](#whats-next). Even then, a protocol cannot reach into someone else's hardware: the owner of a machine decides whether the bytes are really gone. ## Replicate to an always-on host (planned) None of this section runs today. The offline backup above is the only copy mechanism in this guide, and it is a snapshot, not continuous replication. Your laptop goes on and off, so you will want another host that is always online and doesn't depend on TinyCloud or on one machine. The design: * Hosts will be symmetric, with no host as "home". Your laptop, your own VPS, a friend's node and TinyCloud's node will replicate host to host, then host to edge, so a nearby friend's copy can be faster to reach than a distant one. * A small host will keep the most recent data. The biggest host will keep everything and ask you to compact when it runs out of space. * Two writes at once will resolve as CRDTs. If both come from your key, the latest write wins, and history lets you revert. * Hosting a friend will need both sides to agree: the operator allows you and sets limits, and you delegate hosting to the node's key. Either side can end it, and the friend can always evict you, because they hold the hardware. ## What's next These are planned. None has steps in this guide yet. * `tc node install`, `start`, `stop`, `status` and `register`, with the Rust node bundled into the JS CLI. * A tray app in the shape of Tailscale's or Dropbox's menu-bar app, with update prompts you can defer. * Encryption at rest on by default, and a data directory kept out of Spotlight and indexing. * Publishing your node to the registry with your Ethereum key, an on-chain entry that wins, and the SDK choosing your closest host without ever turning you into a new hosted user. * Plain Ethereum wallets signing every request end to end, including browser, hardware and contract wallets. * Host-to-host replication, small hosts holding recent data, and a biggest host that asks you to compact. * Hosting others, with an operator allowlist, per-person and machine limits, and eviction. * Moving your hosted spaces to your node, switching off TinyCloud hosting and having it delete your data. * Deletion by revoking a host, with the revocation spreading to your other hosts and through the SDK. * Warnings before a node key is lost, and MPC key shares split across your hosts. * Networking for a node whose address moves, compatible with Tailscale. # Block Storage Source: https://docs.tinycloud.xyz/hosting/storage Configure local filesystem or S3-compatible block storage Block storage holds the content behind TinyCloud values. Choose the backend that matches your deployment size and operational model. ## Backends | Backend | Best for | | - | - | | Local filesystem | Development and small single-node deployments | | S3-compatible | Production and multi-node storage | ## Local filesystem ```toml theme={null} [storage.blocks] type = "Local" path = "./data/blocks" ``` ```bash theme={null} TINYCLOUD_STORAGE__BLOCKS__TYPE=Local TINYCLOUD_STORAGE__BLOCKS__PATH=./data/blocks ``` ## S3-compatible storage ```toml theme={null} [storage.blocks] type = "S3" bucket = "tinycloud-blocks" endpoint = "https://s3.amazonaws.com" ``` ```bash theme={null} TINYCLOUD_STORAGE__BLOCKS__TYPE=S3 TINYCLOUD_STORAGE__BLOCKS__BUCKET=tinycloud-blocks TINYCLOUD_STORAGE__BLOCKS__ENDPOINT=https://s3.amazonaws.com AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... AWS_DEFAULT_REGION=us-east-1 ``` ## Staging storage Staging buffers uploads before they are written to block storage. ```toml theme={null} [storage.staging] type = "Memory" ``` Use `FileSystem` when you need a disk-backed staging area. ## Data directory If you leave paths unset, the node resolves them under `storage.datadir` and creates the local directories it needs. > [!TIP] > > Use the local backend for quick setup, then move to S3-compatible storage when you need a durable shared backend. # TinyCloud Documentation Source: https://docs.tinycloud.xyz/index Find the shortest path for your TinyCloud task. # TinyCloud Documentation TinyCloud lets browser and backend applications store user-owned KV and SQL data in isolated spaces, then share access through scoped capabilities. These docs are for application developers, protocol integrators, and node operators. TinyCloud is designed for data the user should own and control. It is not a replacement for every application database, especially when the application operator must own all data and access policy. ## Privacy at a glance User-owned access is not the same as end-to-end encryption (E2EE). Choose the trust boundary for the actual data path: | Mode | Who can see plaintext? | | - | - | | HTTPS / encrypted disks or backups | HTTPS protects traffic in transit; storage encryption protects stored bytes. Neither hides data from the service processing it. Storage protection depends on the deployment. | | Ordinary KV / SQL | The node processes readable values and queries unless the app encrypts values first. An ordinary node operator can access that plaintext. | | Application E2EE | Only endpoints holding the decryption keys, **if** the app keeps those keys out of the storage service. This is not the default for all TinyCloud data; metadata may remain visible. | | Hosted MCP | MCP processes tool inputs and results, including secrets it is authorized to decrypt. Its runtime/operator and the connected AI client are in the trust boundary. | | Attested TEE processing | Plaintext or keys may exist inside the trusted runtime. Protection from infrastructure operators depends on verified attestation, approved code and key-release policy; a `tee` hostname is not proof or app E2EE. | | Self-hosted | You choose the operator; ordinary node/MCP administrators can still access plaintext processed there. Self-hosting does not add E2EE. | See [Security and trust](/concepts/security-and-trust) for encryption modes, authorized clients, OpenKey and attestation limits. > [!NOTE] > > Install examples pin the current stable `@tinycloud/web-sdk` and > `@tinycloud/node-sdk` 3.3.0 and `@tinycloud/cli` 1.5.1. Page content was last > verified against 3.0.0 / CLI 1.0.0 unless a page says otherwise; behavior > labeled beta may already be in stable. > [card] [Build in the browser](/start/browser-app) > > Follow the Web SDK path from sign-in to your first KV write. > [card] [Build on Node](/start/backend-service) > > Choose private-key or session-only mode before you write backend code. > [card] [Understand the protocol](/start/protocol) > > Check capabilities, manifests, and delegation terms before you implement. > [card] [Operate TinyCloud](/start/operator) > > Install, host, troubleshoot, and wire OpenKey without detouring into theory. > [card] [Connect an agent](/cli/mcp#choose-your-client) > > Find setup and support status for ChatGPT, Claude, coding agents and chat bots. ## Source and trust Claims on this site are grounded in the linked guides, the SDK source, and the generated capability registry. When you need the exact action name or status, use [Capability Registry](/reference/protocol/capabilities). When you need the mental model, use [System model](/concepts/system-model) and [Security and trust](/concepts/security-and-trust). # OpenKey Source: https://docs.tinycloud.xyz/openkey/index Passkey-based signing for TinyCloud and other web apps OpenKey is TinyCloud Labs' passkey-based key management service. Use it when you want a browser-friendly signer that keeps the user out of seed phrases and browser-extension wallets. OpenKey-managed keys use server-side sealing and signing, not a promise that the key stays solely on the user's device. Production sealing uses dstack; local development uses explicitly enabled mock keys. Passkeys authenticate the user but do not themselves encrypt TinyCloud records. Review [Security and trust](/concepts/security-and-trust#tee-and-openkey-limits) for runtime and attestation assumptions. ## Choose a path > [card] [Quickstart](/openkey/quickstart) > > Create an account, connect a key, and sign a message. > [card] [Widget](/openkey/widget) > > Embed OpenKey connect and sign flows in your app. > [card] [OAuth](/openkey/oauth) > > Use OpenKey as an OAuth 2.1 provider. > [card] [TinyCloud integration](/openkey/tinycloud-integration) > > Use OpenKey as the signer for TinyCloud sign-in. > [card] [Local development](/openkey/local-development) > > Run OpenKey and Secret Manager locally and verify the browser flow. ## Relationship to TinyCloud TinyCloud signs users in with SIWE. OpenKey supplies the signer for that flow, so users can authenticate to TinyCloud with passkeys instead of a browser wallet extension. OpenKey OAuth is separate from TinyCloud sign-in: * Use TinyCloud integration when you need OpenKey to sign TinyCloud's SIWE flow * Use OAuth when you need tokens for your own application ## Keys and the primary key An OpenKey account can hold several keys. Each key is a separate TinyCloud owner with its own spaces and data. One key is **primary**: OpenKey preselects it on `/delegate` approvals (the CLI, agents, and MCP connect), and apps that request `tinycloud:manage-key` use it. Widget sign-in still asks the user to pick when the account has several keys. To change it, open a key from **Your Keys** on the dashboard with **Manage** and choose **Make primary**; only OpenKey-managed keys can be primary. Switching the primary key does not move any data between owners. ## Approving CLI and agent requests The TinyCloud CLI and agents ask the owner for scoped access through two OpenKey pages: | Page | Started by | What the owner does | | - | - | - | | `openkey.so/delegate` | `tc auth login` (browser or `--paste`), MCP connect | Reviews each requested capability, may uncheck some, and approves | | `openkey.so/device` | `tc auth login --device`, `tc enable share` | Enters or confirms the code shown by the CLI, confirms they started the request, and approves | Device approvals are limited to KV access in one space and expire after 30 days at most. Ordinary `/delegate` links only return to the local machine or a registered TinyCloud callback such as the hosted MCP service. See [CLI authentication](/cli/authentication) for the commands. ## Source note OpenKey page details come from the OpenKey SDK source and TinyCloud's OpenKey integration example. # Local development Source: https://docs.tinycloud.xyz/openkey/local-development Run OpenKey and TinyCloud Secret Manager locally and verify the complete browser flow Use this setup when you are changing OpenKey or a browser app that consumes OpenKey and need a repeatable local integration check. The verified smoke flow runs the OpenKey API, OpenKey widget, and TinyCloud Secret Manager on your machine, then connects a test-only wallet and exercises a real encrypted secret write, reload, read, and delete. > [!NOTE] > > This setup runs OpenKey and Secret Manager locally. By default, encrypted KV > and SQL requests still use the TinyCloud development node at > `https://node.tinycloud.xyz`. ## Prerequisites * Bun 1.2 or later * A Chromium-compatible Playwright browser * Local `openkey` and `secret-manager` checkouts in sibling directories ```text theme={null} development/ ├── openkey/ └── secret-manager/ ``` ## Create the local environment files From the `secret-manager` checkout: ```bash theme={null} cp .env.example .env cp e2e/openkey.env.example ../openkey/.env ``` The OpenKey template uses PGlite, development TEE sealing, local-only test credentials, and CORS origins for both local web apps. The Secret Manager template points its OpenKey SDK at `http://127.0.0.1:5173`. Both generated `.env` files are ignored by Git. Do not replace their test-only values with production credentials. ## Prepare both repositories Still from `secret-manager`: ```bash theme={null} bun --cwd ../openkey install --frozen-lockfile bun --cwd ../openkey run db:push bun --cwd ../openkey run build bun install --frozen-lockfile bunx playwright install chromium bun run build ``` OpenKey's build step is required on a clean checkout because the API imports workspace packages such as `@openkey/db` from their built output. `db:push` initializes the local PGlite schema and generates the Prisma client. ## Run the end-to-end smoke test ```bash theme={null} bun run test:smoke ``` Playwright starts and stops these local services: | Service | URL | Purpose | | - | - | - | | OpenKey API | `http://127.0.0.1:3001` | Auth, authorization, and signing API | | OpenKey web | `http://127.0.0.1:5173` | Connect and signing widgets | | Secret Manager | `http://127.0.0.1:4187` | Application under test | The test uses a public Anvil development key through OpenKey's normal external wallet path. A passing run proves that the local widget discovered the wallet, the wallet signed the TinyCloud SIWE request, and Secret Manager could write, reload, decrypt, and delete its placeholder secret. To watch the browser interaction: ```bash theme={null} bun run test:smoke --headed ``` ## Interactive development loop For hot reload, prepare the repositories once as above, then run each process in a separate terminal. From `openkey`: ```bash theme={null} bun run --env-file=.env apps/api/src/index.ts ``` From `openkey` in a second terminal: ```bash theme={null} bun run --cwd apps/web --env-file=../../.env dev --host 127.0.0.1 ``` From `secret-manager`: ```bash theme={null} bun run dev --host 127.0.0.1 --port 4187 ``` Open `http://127.0.0.1:4187/app`. If the first OpenKey widget request falls back to a popup while Vite performs its cold compile, wait for the OpenKey web server to finish and retry the connection. ## Troubleshooting > [accordion] The OpenKey API cannot resolve @openkey/db > > Run `bun --cwd ../openkey run build` from Secret Manager, or `bun run build` > from OpenKey, before starting the API. > [accordion] Playwright says a web server exited early > > Confirm ports `3001`, `5173`, and `4187` are free and that both `.env` files > were created from the checked-in templates. > [accordion] The widget does not offer the test wallet > > Run the checked-in `test:smoke` flow. Its Playwright bootstrap installs the > wallet before application scripts execute and asserts that OpenKey received > `hasEoa=true`. > [accordion] Secret Manager stays on Preparing TinyCloud session > > Verify that `VITE_TINYCLOUD_HOST` is reachable. The default smoke flow needs > network access to `https://node.tinycloud.xyz`. ## Related pages * [Automated OpenKey + TinyCloud E2E testing](/guides/browser-e2e-testing) * [OpenKey widget](/openkey/widget) * [TinyCloud integration](/openkey/tinycloud-integration) # OAuth Provider Source: https://docs.tinycloud.xyz/openkey/oauth Use OpenKey as an OAuth 2.1 provider Use OpenKey OAuth when your application needs OpenKey-issued identity tokens. This is separate from using an OpenKey key to sign in to TinyCloud. ## Before you start: register a client OAuth requires a client ID and an exact redirect URI. Client registration is currently an operator-managed boundary; there is no public self-service registration flow documented for the hosted service. * For hosted OpenKey, request a client through [TinyCloud support](https://t.me/+-_2ufE0JgIcyMjYx). * For a self-hosted OpenKey deployment, an administrator can run this command from the OpenKey repository with `OPENKEY_API_URL` and `ADMIN_API_KEY` configured: ```bash theme={null} bun run oauth:register \ --name "My App" \ --type spa \ --redirect-uri "http://localhost:5173/callback" ``` The current registration API creates public `spa` or `native` clients. These clients use PKCE and do not have a client secret. ## Install the SDK ```bash theme={null} npm install @openkey/sdk@0.10.2 ``` ## Popup flow The SDK generates and stores the PKCE verifier, generates a `state` value, opens the authorization page, and validates the returned state before resolving `connect()`. ```typescript theme={null} import { OpenKey } from "@openkey/sdk"; const clientId = "ok_your_client_id"; const redirectUri = "http://localhost:5173/callback"; const openkey = new OpenKey({ host: "https://openkey.so", oauthHost: "https://api.openkey.so", appName: "My App", mode: "popup", }); const { code } = await openkey.oauth.connect({ clientId, redirectUri }); const tokens = await openkey.oauth.exchangeCode(code, { clientId, redirectUri, }); console.log(tokens.access_token, tokens.expires_in); ``` The redirect URI must be registered even for popup mode: the popup navigates to that URI before the SDK reads the authorization response. ## Redirect flow and callback Redirect mode navigates the current page, so `connect()` does not resolve in the page that starts the flow. ```typescript theme={null} const openkey = new OpenKey({ mode: "redirect" }); await openkey.oauth.connect({ clientId, redirectUri }); ``` On the registered callback page, parse the response, verify `state`, and then exchange the code. Keep these operations in this order so an untrusted callback cannot consume the stored PKCE verifier. ```typescript theme={null} import { OpenKey } from "@openkey/sdk"; const openkey = new OpenKey({ mode: "redirect" }); const callback = openkey.oauth.parseCallback(); if ("error" in callback) { throw new Error(callback.errorDescription ?? callback.error); } if (!openkey.oauth.verifyState(callback.state)) { throw new Error("OAuth state mismatch"); } const tokens = await openkey.oauth.exchangeCode(callback.code, { clientId: "ok_your_client_id", redirectUri: "http://localhost:5173/callback", }); ``` ## Token lifecycle * Use `expires_in` from the token response instead of assuming a fixed access token lifetime. * Keep access tokens in memory when possible. Store refresh tokens only in protected server-side or platform credential storage. * `refresh_token` is optional. The current browser SDK requests the `openid` scope, so applications must not assume that a refresh token will be issued. * `exchangeCode()` removes its stored PKCE verifier after the exchange. Start a new authorization flow if the exchange must be retried with a new code. The lower-level `@openkey/core` package exposes `refreshAccessToken()` for a client that has been issued a refresh token. If a refresh response includes a new refresh token, replace the old one. > [!TIP] > > If your goal is TinyCloud sign-in, use the > [TinyCloud integration](/openkey/tinycloud-integration) instead of OAuth. # OpenKey Quickstart Source: https://docs.tinycloud.xyz/openkey/quickstart Connect a key and sign a message with OpenKey Use this tutorial to add a working OpenKey connect-and-sign flow to a small browser app. ## Prerequisites * Node.js 18 or later * A browser with WebAuthn support * A passkey-capable device or hardware security key ## Create the app ```bash theme={null} npm create vite@latest openkey-demo -- --template vanilla-ts cd openkey-demo npm install npm install @openkey/sdk@0.10.2 ``` Replace `src/main.ts` with: ```typescript theme={null} import { OpenKey, type AuthResult } from "@openkey/sdk"; document.querySelector("#app")!.innerHTML = `
Not connected
`; const openkey = new OpenKey({ host: "https://openkey.so", appName: "OpenKey demo", }); const connectButton = document.querySelector("#connect")!; const signButton = document.querySelector("#sign")!; const result = document.querySelector("#result")!; let auth: AuthResult | undefined; connectButton.addEventListener("click", async () => { auth = await openkey.connect(); result.textContent = `Connected: ${auth.address}`; signButton.disabled = false; }); signButton.addEventListener("click", async () => { if (!auth) return; const signed = await openkey.signMessage({ message: "Hello from OpenKey", keyId: auth.keyId, }); result.textContent = `Address: ${signed.address}\nSignature: ${signed.signature}`; }); ``` Start the development server: ```bash theme={null} npm run dev ``` Open the local URL, select **Connect OpenKey**, and complete the OpenKey flow. The page should show an Ethereum address. Select **Sign message** and it should replace that result with the address and a hex-encoded signature. ## What happened `connect()` returns the selected key's `address`, `keyId`, and `keyType`. `signMessage()` uses that `keyId` and returns the signature plus the signing address. The default `iframe` mode falls back to a popup if the app's content security policy blocks the frame. ## Sign out ```typescript theme={null} const { revoked } = await openkey.signOut(); if (!revoked) console.warn("Signed out here, but OpenKey could not confirm the session was revoked."); ``` `signOut()` clears local state, cancels any open OpenKey flows, and asks OpenKey to end the session. It resolves to `{ requestId, revoked }`: `revoked: true` means OpenKey confirmed the old session no longer works. > [!NOTE] > > Since 0.10.2 the embedding page never receives an OpenKey session token: > `getSessionToken()` always returns `null`. Server-side signing needs an OAuth > access token; see [OAuth](/openkey/oauth). ## Next step To use the connected key as TinyCloud's wallet provider, continue to [TinyCloud Integration](/openkey/tinycloud-integration). # TinyCloud Integration Source: https://docs.tinycloud.xyz/openkey/tinycloud-integration Use OpenKey as the signer for TinyCloud sign-in Use OpenKey here when you want TinyCloud to keep its SIWE flow but replace a browser wallet with passkey-based signing. ## What stays the same * TinyCloud still uses SIWE * TinyCloud still derives identity from an Ethereum address * TinyCloud still issues the session after a valid signature ## What OpenKey provides * A browser-friendly signer * Passkey authentication * A path that does not require MetaMask or another wallet extension ## Working example ```typescript theme={null} import { OpenKey, OpenKeyProvider } from "@openkey/sdk"; import { TinyCloudWeb } from "@tinycloud/web-sdk"; const openkey = new OpenKey({ host: "https://openkey.so", appName: "My TinyCloud App" }); const authResult = await openkey.connect(); const tcw = new TinyCloudWeb({ provider: new OpenKeyProvider(openkey, authResult), }); await tcw.signIn(); await tcw.kv.put("hello", "world"); ``` ## Why this shape `@tinycloud/web-sdk` 3.0 signs through a raw EIP-1193 provider: it calls `provider.request()` directly. `OpenKeyProvider` is an EIP-1193 provider that answers `eth_accounts`, `eth_requestAccounts`, `eth_chainId`, `personal_sign`, and `eth_signTypedData_v4` with the connected OpenKey key, so pass it as is. > [!WARNING] > > Do not wrap it in an ethers `Web3Provider` or `BrowserProvider`. Web SDK 2.x > accepted an ethers provider; 3.0 needs the raw EIP-1193 object. ## TinyCloud-specific advice * Keep the OpenKey host separate from the TinyCloud host * Pass the provider as `provider`; `providers.web3.driver` still works and takes the same raw EIP-1193 object * Treat this as a sign-in flow, not an OAuth flow > [!NOTE] > > Verified against `@openkey/sdk` 0.10.2 and `@tinycloud/web-sdk` 3.0.0. # Widget Integration Source: https://docs.tinycloud.xyz/openkey/widget Embed OpenKey connect and sign flows in your web app Use the SDK-managed widget when a browser app needs to connect a key and ask the user to sign without building its own OpenKey UI. ## Install ```bash theme={null} npm install @openkey/sdk@0.10.2 ethers@6.17.0 ``` ## Connect an EIP-1193 provider ```typescript theme={null} import { OpenKey, OpenKeyProvider } from "@openkey/sdk"; import { BrowserProvider } from "ethers"; const openkey = new OpenKey({ host: "https://openkey.so", appName: "My App", }); const auth = await openkey.connect(); const eip1193Provider = new OpenKeyProvider(openkey, auth); const provider = new BrowserProvider(eip1193Provider); const signer = await provider.getSigner(); const signature = await signer.signMessage("Hello from My App"); console.log(auth.address, signature); ``` `OpenKeyProvider` implements the EIP-1193 methods needed for account discovery, chain identification, personal message signing, and EIP-712 typed-data signing. Unsupported provider methods reject with an error. ## Available SDK flows * `connect()` selects or creates a key * `signMessage()` signs a personal message * `signTypedData()` signs EIP-712 typed data * `linkWallet()` links an external wallet Managed-key signing is handled by OpenKey. External-key signing is routed to the wallet provider configured or discovered by the SDK. ## Choose the UI mode ```typescript theme={null} const openkey = new OpenKey({ host: "https://openkey.so", appName: "My App", mode: "popup", }); ``` Modes are `iframe`, `popup`, and `redirect`. The default iframe mode falls back to a popup if it does not receive the widget-ready message, which commonly happens when the app's content security policy blocks the frame. ## Direct widget messaging The widget routes and `postMessage` message shapes are SDK implementation details, not a supported public integration contract. Use `@openkey/sdk` so origin checks, timeouts, popup handling, and message changes remain inside the SDK. If the SDK cannot support your host environment, describe that constraint to [TinyCloud support](https://t.me/+-_2ufE0JgIcyMjYx) before depending on the internal protocol. # Node SDK quickstart Source: https://docs.tinycloud.xyz/quickstart/node-sdk Run a backend script that signs in and verifies its first TinyCloud write Start here when your code runs in Node.js. You will create a small TypeScript project, generate a disposable development key, and write and read back one record. ## Prerequisites * Node.js 20 or newer * Network access to `https://node.tinycloud.xyz` > [!WARNING] > > The generated key is for this tutorial only. Never put a production wallet key in source control, logs, frontend code, or a shared `.env` file. ## Create the project ```bash theme={null} mkdir tinycloud-node-quickstart cd tinycloud-node-quickstart npm init -y npm install @tinycloud/node-sdk@3.3.0 dotenv npm install --save-dev tsx typescript @types/node npm pkg set scripts.start="tsx index.ts" ``` Generate a new key for the empty tutorial space and exclude it from Git: ```bash theme={null} node -e "const c=require('node:crypto'),f=require('node:fs');f.writeFileSync('.env','WALLET_PRIVATE_KEY='+c.randomBytes(32).toString('hex')+'\n')" node -e "require('node:fs').writeFileSync('.gitignore','.env\nnode_modules/\n')" ``` Create `index.ts`: ```typescript theme={null} import 'dotenv/config'; import { TinyCloudNode } from '@tinycloud/node-sdk'; const privateKey = process.env.WALLET_PRIVATE_KEY; if (!privateKey) throw new Error('WALLET_PRIVATE_KEY is missing from .env'); async function main() { const tc = new TinyCloudNode({ privateKey, host: 'https://node.tinycloud.xyz', prefix: 'tinycloud-quickstart', autoCreateSpace: true, }); await tc.signIn(); const saved = await tc.kv.put('first-record', { message: 'Hello from TinyCloud', writtenAt: new Date().toISOString(), }); if (!saved.ok) throw new Error(`${saved.error.code}: ${saved.error.message}`); const loaded = await tc.kv.get<{ message: string }>('first-record'); if (!loaded.ok) throw new Error(`${loaded.error.code}: ${loaded.error.message}`); console.log(JSON.stringify({ ownerDid: tc.did, space: tc.spaceId, record: loaded.data.data, }, null, 2)); } main().catch((error) => { console.error(error); process.exitCode = 1; }); ``` ## Run and verify ```bash theme={null} npm start ``` Success prints the owner DID, a space ending in `:tinycloud-quickstart`, and the record read back from that space: ```json theme={null} { "ownerDid": "did:pkh:eip155:1:0x…", "space": "tinycloud:pkh:eip155:1:0x…:tinycloud-quickstart", "record": { "message": "Hello from TinyCloud" } } ``` The exact chain, address, and timestamp will differ. A failed sign-in throws before the write. A failed KV call prints its SDK error code and exits without reporting success. ## Use an existing secret safely For a real service, replace the disposable `.env` key with your secret manager's runtime injection. Keep `.env` for local development only, retain it in `.gitignore`, and use a wallet dedicated to the service rather than a personal wallet that holds assets. ## Next steps * [Node authentication and session lifecycle](/guides/authentication/node) * [KV basic operations](/guides/kv/basic-operations) * [Receive a delegation](/guides/delegations) * [Node client overview](/reference/sdk/node) > [!NOTE] > > Written against `@tinycloud/node-sdk` 3.0.0; the install commands above use the current stable 3.3.0. # Web SDK quickstart Source: https://docs.tinycloud.xyz/quickstart/web-sdk Create a browser app that signs in and verifies its first TinyCloud write Start here when your app runs in the browser. You will create a small Vite app, sign in with a browser wallet, and write and read back one record. ## Prerequisites * Node.js 18 or newer * A modern browser with an injected Ethereum wallet * A test wallet account; the tutorial does not require funds ## Create the project ```bash theme={null} npm create vite@latest tinycloud-web -- --template vanilla-ts cd tinycloud-web npm install npm install @tinycloud/web-sdk@3.3.0 ``` Replace `src/main.ts` with this complete example: ```typescript theme={null} import { TinyCloudWeb } from '@tinycloud/web-sdk'; document.querySelector('#app')!.innerHTML = `

TinyCloud first write

Ready
`; const button = document.querySelector('#start')!; const status = document.querySelector('#status')!; button.addEventListener('click', async () => { const provider = (window as Window & { ethereum?: unknown }).ethereum; if (!provider) { status.textContent = 'Install or unlock a browser wallet, then try again.'; return; } button.disabled = true; status.textContent = 'Waiting for wallet approval…'; try { const tc = new TinyCloudWeb({ provider, tinycloudHosts: ['https://node.tinycloud.xyz'], spacePrefix: 'tinycloud-quickstart', }); await tc.signIn(); const saved = await tc.kv.put('first-record', { message: 'Hello from TinyCloud', writtenAt: new Date().toISOString(), }); if (!saved.ok) throw new Error(`${saved.error.code}: ${saved.error.message}`); const loaded = await tc.kv.get<{ message: string }>('first-record'); if (!loaded.ok) throw new Error(`${loaded.error.code}: ${loaded.error.message}`); status.textContent = JSON.stringify({ space: tc.spaceId, record: loaded.data.data, }, null, 2); } catch (error) { status.textContent = error instanceof Error ? error.message : String(error); button.disabled = false; } }); ``` ## Run and verify ```bash theme={null} npm run dev ``` Open the local URL printed by Vite, select **Sign in and write**, and approve the wallet prompts. Success looks like this: ```json theme={null} { "space": "tinycloud:pkh:eip155:1:0x…:tinycloud-quickstart", "record": { "message": "Hello from TinyCloud" } } ``` The exact chain, address, and timestamp will differ. If the wallet never opens, confirm that the extension is unlocked and allowed on the local Vite origin. If a KV operation fails, the page prints the SDK error code and message instead of reporting a false success. ## What happened `TinyCloudWeb` used the injected provider to request a SIWE signature. `signIn()` created or restored the app session and ensured the `tinycloud-quickstart` space was hosted. The KV result was only displayed after the same key was read back successfully. ## Next steps * [Web authentication and session lifecycle](/guides/authentication/web) * [KV basic operations](/guides/kv/basic-operations) * [Sharing data](/guides/sharing) * [Web client overview](/reference/sdk/web) > [!NOTE] > > Written against `@tinycloud/web-sdk` 3.0.0; the install commands above use the current stable 3.3.0. # Glossary Source: https://docs.tinycloud.xyz/reference/glossary TinyCloud terms and where to verify them. Use this page when you need the TinyCloud vocabulary before you read a guide or verify a capability name. | Term | Meaning | Where to read next | | - | - | - | | Addressed share | A Share link only a named email address or email domain can open; the content is encrypted and the recipient proves who they are. | [Share files](/cli/share) | | Bearer link | A Share link that anyone holding the complete URL can read until it expires. | [Share files](/cli/share) | | Capability | A scoped permission expressed as a TinyCloud ability string such as `tinycloud.kv/get`. | [Capabilities](/concepts/capabilities) | | Capability registry | The generated reference for exact action names, aliases, and statuses from the canonical node registry. | [Capability Registry](/reference/protocol/capabilities) | | Device login | OpenKey approval on another device, such as a phone, for a CLI session limited to KV access in one space. | [CLI authentication](/cli/authentication#device-login-for-servers) | | Delegation | A signed attenuation of a capability that can be passed to another principal. | [Delegations](/guides/delegations) | | Encryption network | The network-scoped resource used by TinyCloud's encryption flows. | [App manifests](/concepts/app-manifests) and [Data Vault](/guides/data-vault) | | Manifest | The app-level request that describes identity, data, and requested capabilities. | [App manifests](/concepts/app-manifests) | | Primary key | The OpenKey key an account uses by default; each key is a separate owner. | [OpenKey](/openkey/index#keys-and-the-primary-key) | | Owner DID | The persistent DID returned by `tc.did` after sign-in. | [DID Formats](/concepts/did-formats) | | Session DID | The ephemeral `did:key` returned by `tc.sessionDid`. | [DID Formats](/concepts/did-formats) | | Space | A user-owned data container with a deterministic ID. | [Spaces](/guides/spaces) | | Storage full | The state where an account's storage is used up: reads keep working and writes fail with `STORAGE_QUOTA_EXCEEDED`. | [Troubleshooting](/troubleshooting#storage-is-full) | | OpenKey | The external signer that can back TinyCloud sign-in without a browser wallet extension. | [TinyCloud Integration](/openkey/tinycloud-integration) | ## Related entry points * [System model](/concepts/system-model) * [Security and trust](/concepts/security-and-trust) * [Start here](/) # App manifest reference Source: https://docs.tinycloud.xyz/reference/protocol/app-manifests Exact manifest fields and SDK composition rules for TinyCloud app manifests. This page records the manifest fields the TinyCloud JS SDK accepts and the rules it applies when turning a manifest into a sign-in capability request. ## Manifest v1 `manifest_version` is optional for v1. If it is omitted, the SDK treats the manifest as version 1. ```json theme={null} { "manifest_version": 1, "app_id": "com.tinycloud.notes", "name": "Notes", "description": "Personal notes synced into TinyCloud.", "knowledge": true, "defaults": true, "permissions": [] } ``` ## Complete runtime app manifest This example is deliberately explicit about app data and secret authority. It disables the default tier, names the default space and prefix, and declares the runtime capabilities the app uses. The composer still adds space-level capability introspection and, by default, account-registry permissions. ```json theme={null} { "manifest_version": 1, "app_id": "com.example.research-notes", "name": "Research Notes", "description": "Private notes with a searchable index and optional provider sync.", "icon": "https://example.com/research-notes-icon.png", "appVersion": "1.0.0", "space": "applications", "prefix": "com.example.research-notes", "knowledge": true, "defaults": false, "expiry": "30d", "includePublicSpace": false, "permissions": [ { "service": "tinycloud.kv", "path": "documents/", "actions": ["get", "put", "del", "list", "metadata"], "description": "Read and write note documents." }, { "service": "tinycloud.sql", "path": "search-index", "actions": ["read", "write", "schema"], "description": "Create and query the note search index." } ], "secrets": { "MODEL_API_KEY": { "actions": ["read"], "description": "Read an optional model provider key." }, "PROVIDER_REFRESH_TOKEN": { "scope": "research-notes", "actions": ["read", "write", "delete"], "expiry": "7d", "description": "Manage the provider sync token for this app." } } } ``` The SDK resolves the important entries as follows: | Manifest entry | Space | Resolved path | Runtime call | | - | - | - | - | | KV `documents/` | `applications` | `com.example.research-notes/documents/` | `tc.kv.withPrefix("com.example.research-notes/documents/")` | | SQL `search-index` | `applications` | `com.example.research-notes/search-index` | `tc.sql.db("com.example.research-notes/search-index")` | | Global `MODEL_API_KEY` | `secrets` | `vault/secrets/MODEL_API_KEY` | `tc.secrets.get("MODEL_API_KEY")` | | Scoped `PROVIDER_REFRESH_TOKEN` | `secrets` | `vault/secrets/scoped/research-notes/PROVIDER_REFRESH_TOKEN` | `tc.secrets.get("PROVIDER_REFRESH_TOKEN", { scope: "research-notes" })` | `secrets` declarations request access; they do not contain or create secret values. Store values with `tc.secrets.put(...)`, `tc secrets put`, or TinyCloud Secrets using the same name and scope. A scoped lookup does not fall back to a global secret: the name and scope together identify one vault entry. The example omits `did` because an ordinary app manifest grants its signed-in session access. Add `did` only to a manifest that targets a known backend or agent delegate. If that DID is learned at runtime, compose a separate delegate manifest in application code rather than hard-coding it here. ## Fields | Field | Required | Meaning | | - | - | - | | `manifest_version` | No | Schema version. Missing means `1`. | | `app_id` | Yes | Stable app namespace and default path prefix. | | `name` | Yes | Human-readable app name. | | `description` | No | Human-readable summary of what the app does. | | `did` | No | Optional delegate DID target for manifest-driven delegation. | | `icon` | No | URL for the app icon shown in permission UI. | | `appVersion` | No | Application version metadata. | | `space` | No | Default TinyCloud space. Missing means `applications`. | | `prefix` | No | Path prefix override. Missing means `app_id`; `""` disables prefixing. | | `knowledge` | No | `true` for `knowledge/index.md`, or a root path string. | | `defaults` | No | Permission tier selector. Missing means `true`. | | `expiry` | No | Default permission expiry, using duration syntax such as `30d` or `2h`. | | `permissions` | No | Explicit permission entries beyond the defaults. | | `secrets` | No | Secret-name shorthand resolved to encrypted vault KV resources in the `secrets` space. | | `includePublicSpace` | No | Whether to include the public-space companion behavior. Missing means `true`. | The TinyCloud App Kit schema also accepts a descriptive top-level `resources` object for app packaging. The JS SDK manifest composer does not currently read that object when it builds sign-in capabilities; declare runtime authority in `permissions`, `defaults`, and `secrets` instead. ## Secret declarations Use the object form when a secret needs a scope, non-default actions, an expiry, or a user-facing description. The manifest object key is the secret name unless the object sets `name` explicitly. ```json theme={null} { "secrets": { "READ_ONLY_KEY": true, "GLOBAL_TOKEN": ["read", "write"], "APP_TOKEN": { "name": "PROVIDER_TOKEN", "scope": "my-app", "actions": ["read", "write", "delete"], "expiry": "7d", "description": "Token used by the provider sync job." } } } ``` `true` means read access. Secret actions accept `read`, `write`, `delete`, `list`, and `metadata`; the SDK expands them to the backing encrypted vault KV actions. Secret names use upper snake case. Scopes are normalized to lowercase kebab case, and `default` and `global` are reserved—omit `scope` for a global secret. ## Permission entries Each permission entry names a service, optional space, path, and action list. The SDK expands short actions such as `get`, `put`, and `read` into full TinyCloud ability URNs when it builds the recap. ```json theme={null} { "service": "tinycloud.sql", "path": "conversations", "actions": ["read", "write"], "description": "Read and write normalized conversation records." } ``` Rules to keep in mind: * `space` inherits from the manifest when omitted * `space` defaults to `applications` * `path` is app-relative unless you set `skipPrefix: true` * `skipPrefix: true` tells the SDK not to prepend the manifest `app_id` * `expiry` can override the manifest expiry for one permission * `description` is user-facing context and does not change authority * encryption permissions use raw network URNs as the path value ## Default tiers When `defaults` is enabled, the SDK starts from a standard permission set for the app prefix. Higher tiers add more capabilities: * standard: KV read/write/delete/list/metadata and SQL read/write * admin: standard plus SQL schema * all: admin plus DuckDB read/write The SDK also adds `tinycloud.capabilities/read` separately for each requested space so capability introspection stays space-scoped. ## Composition rules * `capabilityRequest` takes precedence over `manifest` * `includeAccountRegistryPermissions` defaults to `true` * manifest composition can add account-registry writes * owned encryption networks can request `tinycloud.encryption/network.create` when the manifest asks for `tinycloud.encryption/decrypt` ## Source note The manifest composer, default tiers, and encryption-network behavior are implemented in the JS SDK and covered by sign-in tests. Keep this page aligned with those sources instead of the whitepaper drafts. # Capability Registry Source: https://docs.tinycloud.xyz/reference/protocol/capabilities Capability action URNs and status from the canonical TinyCloud node registry This page is the source-attributed implementation reference for capability action names and status in the canonical `tinycloud-node` registry. For the authorization model behind these names, see [Capabilities](/concepts/capabilities). > [!NOTE] > > Synced from canonical registry version 1 at [`bb44eda`](https://github.com/TinyCloudLabs/tinycloud-node/blob/bb44eda795aa1767ee6d4ac00d28d1af4636d8e6/capabilities.json) (source SHA-256 `daecd38d908d05d622684b580501dc38c5945b0499ce7eb3a18d77663b93c73a`). The registry contains 30 active actions, 3 deprecated aliases, and 5 reserved actions. ## Ability syntax An ability combines a service namespace and an action: ```text theme={null} tinycloud.{service}/{action} ``` The ability states **what** a delegate may do. The resource URI and capability caveats state **where** and under which constraints it may do it. ## Statuses | Status | Meaning | | - | - | | Active | Accepted as an active protocol action. SDK availability and runtime effects vary by service. | | Deprecated alias | Accepted for compatibility and normalized to the listed canonical action. Use the canonical action in new integrations. | | Reserved | Recognized at the policy boundary but not dispatched to a service. Do not request reserved actions. | > [!WARNING] > > Registry inclusion describes the node's authorization boundary. It does not by itself guarantee a high-level SDK method, a dedicated side effect, or availability on every deployment. Treat this registry—not proposal-only whitepaper names—as the source of truth for action spelling, relationships, and status. ## `tinycloud.capabilities` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.capabilities/read` | active | — | — | ## `tinycloud.delegation` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.delegation/list` | active | — | — | | `tinycloud.delegation/status` | active | — | — | ## `tinycloud.duckdb` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.duckdb/*` | active | Implies `tinycloud.duckdb/read`, `tinycloud.duckdb/write`, `tinycloud.duckdb/admin`, `tinycloud.duckdb/import`, `tinycloud.duckdb/export` | Per-service wildcard. Matched node-side as admin-equivalent (routes/mod.rs:2140, duckdb/parser.rs:29) and as write+admin in validate\_sql; recognized by preferred\_database\_ability (routes/mod.rs:2118). Live in the SDK root delegation grant (TinyCloudNode.ts \~2279). Implies every concrete active duckdb action. | | `tinycloud.duckdb/admin` | active | — | — | | `tinycloud.duckdb/export` | active | — | — | | `tinycloud.duckdb/import` | active | — | — | | `tinycloud.duckdb/read` | active | — | — | | `tinycloud.duckdb/select` | deprecated-alias | Alias of `tinycloud.duckdb/read` | — | | `tinycloud.duckdb/write` | active | — | — | ## `tinycloud.encryption` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.encryption/decrypt` | active | — | — | | `tinycloud.encryption/network.create` | active | — | — | | `tinycloud.encryption/network.revoke` | active | — | — | ## `tinycloud.hooks` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.hooks/list` | active | — | — | | `tinycloud.hooks/register` | active | — | — | | `tinycloud.hooks/subscribe` | active | — | — | | `tinycloud.hooks/unregister` | active | — | — | ## `tinycloud.kv` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.kv/del` | active | — | — | | `tinycloud.kv/delete` | deprecated-alias | Alias of `tinycloud.kv/del` | — | | `tinycloud.kv/get` | active | — | — | | `tinycloud.kv/list` | active | — | — | | `tinycloud.kv/metadata` | active | — | — | | `tinycloud.kv/put` | active | — | — | ## `tinycloud.space` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.space/create` | active | — | Invoked by the SDK against /invoke (SpaceService.ts create(); TinyCloud.ts lazy public-space create). The node authorizes it via the delegation chain in the invocation-verification path (not via accepted\_actions), but there is NO dedicated side-effect handler — db.rs invocation match falls through (\_ => \{}). Real space creation happens through space/host. 409/404 the SDK sees come from the space-existence check (TxError::SpaceNotFound), not a create handler. | | `tinycloud.space/host` | active | — | Creates the space: a space/host delegation inserts the space row in transact() (tinycloud-core/src/db.rs \~818, matched on Delegation events). | | `tinycloud.space/info` | active | — | Invoked by the SDK (SpaceService.ts getSpaceInfo; TinyCloud.ts probe-before-create). Authorized via the delegation chain; no dedicated node side-effect handler. A nonexistent space yields TxError::SpaceNotFound -> 404, which is exactly the SDK's existence probe. | | `tinycloud.space/list` | active | — | Invoked by the SDK (SpaceService.ts listOwnedSpaces). Authorized via the delegation chain; no dedicated node side-effect handler (db.rs invocation match falls through). Owned-space discovery is served via the capabilities/read + host layers, not a space/list handler. | ## `tinycloud.sql` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.sql/*` | active | Implies `tinycloud.sql/read`, `tinycloud.sql/write`, `tinycloud.sql/schema`, `tinycloud.sql/admin` | Per-service wildcard. Matched node-side as admin-equivalent in admin checks (routes/mod.rs:2139, sql/database.rs:177, sql/parser.rs:25) and as write+admin in validate\_sql. Live in the SDK root delegation grant (TinyCloudNode.ts \~2272). Modeled as implying every concrete active sql action so a wildcard grant authorizes any sql request via implication expansion. | | `tinycloud.sql/admin` | active | Implies `tinycloud.sql/schema` | — | | `tinycloud.sql/read` | active | — | — | | `tinycloud.sql/schema` | active | — | — | | `tinycloud.sql/select` | deprecated-alias | Alias of `tinycloud.sql/read` | — | | `tinycloud.sql/write` | active | — | — | ## `tinycloud.vfs` | Ability | Status | Relationship | Registry note | | - | - | - | - | | `tinycloud.vfs/delete` | reserved | — | — | | `tinycloud.vfs/get` | reserved | — | — | | `tinycloud.vfs/list` | reserved | — | — | | `tinycloud.vfs/metadata` | reserved | — | — | | `tinycloud.vfs/put` | reserved | — | — | ## Related documentation * [Capabilities](/concepts/capabilities) explains delegation, attenuation, and validation. * [Delegations & Sharing](/guides/delegations) shows how to grant and use capabilities. * [App manifests](/concepts/app-manifests) describes how applications request capabilities during sign-in. # Delegations Source: https://docs.tinycloud.xyz/reference/protocol/delegations TinyCloud's delegation model and current SDK transport contract. This page separates the protocol model from the JS SDK's transport object. It is not a byte-level UCAN serialization specification; use the SDK serialization helpers when moving delegations between applications. ## Protocol model A delegation is a signed capability grant from a delegator to a delegate DID. Its effective authority is determined by: * the target space, service, and resource path * the allowed action URNs * its expiry and optional not-before time * its parent chain, if the delegator is exercising received authority * whether the parent terminates further sub-delegation * node-confirmed revocation state for the delegation and its ancestors For a child grant, the node requires the same space and service, a resource path contained by the parent, supported actions, and time bounds contained by the parent. Path containment is segment-aware: `shared/` contains `shared/public/file`, while `shared` does not contain `shared-other`. ## `PortableDelegation` The Node and Web SDKs use `PortableDelegation` for application transport. Its current public fields are: | Field | Type | Meaning | | - | - | - | | `cid` | `string` | Content identifier of the signed delegation | | `delegationHeader` | `{ Authorization: string }` | Bearer authorization value | | `delegateDID` | `string` | Recipient principal | | `spaceId` | `string` | Space containing the delegated resource | | `path` | `string` | Single resource path, or the first resource's path | | `actions` | `string[]` | Single resource actions, or the first resource's actions | | `expiry` | `Date` | Delegation expiry | | `ownerAddress` | `string` | Address used to derive the owner space | | `chainId` | `number` | Owner chain identifier | | `host` | `string?` | Node where the delegation was created | | `disableSubDelegation` | `boolean?` | Terminal grant: the node refuses descendants. Only a session-key (`did:key`) recipient can use it | | `publicDelegation` | `PortableDelegation?` | Optional companion public-space grant | | `resources` | `DelegatedResource[]?` | Full set for a multi-resource UCAN | The inherited delegation metadata can also include `delegatorDID`, `createdAt`, `parentCid`, `allowSubDelegation`, and `authHeader`. Callers should use the fields needed for their task and preserve unknown optional fields during transport. Each `resources` entry has `service`, `space`, `path`, and `actions`. When `resources` is present, it is authoritative for multi-resource grants; the flat `path` and `actions` fields describe only the first entry. `delegationHeader.Authorization` is a live bearer credential. Treat the whole object and its serialized form as secrets. ## Serialize and restore ```typescript theme={null} import { serializeDelegation, deserializeDelegation, } from "@tinycloud/node-sdk"; const encoded = serializeDelegation(delegation); const restored = deserializeDelegation(encoded); ``` The serializer converts `expiry` to an ISO string. The deserializer restores it to a `Date`. These helpers are also exported from `@tinycloud/web-sdk`. ## Create, consume, and revoke ```typescript theme={null} const delegation = await alice.createDelegation({ delegateDID: bob.did, path: "shared/", actions: ["tinycloud.kv/get"], expiryMs: 60 * 60 * 1000, }); const access = await bob.useDelegation(delegation); const read = await access.kv.get("report.json"); const revoked = await alice.revokeDelegation(delegation.cid); if (!revoked.ok) throw new Error(revoked.error.message); ``` `createDelegation()` and `useDelegation()` use `PortableDelegation`. The newer `delegate()` and `delegationManager.create()` APIs return `Result` and model delegation management rather than portable activation; do not mix the two return shapes without an explicit conversion path. ## Lifecycle The node reports one of `active`, `revoked`, `expired`, `unavailable`, or `not_found` through the Node SDK's `getDelegationStatus(cid)`. Revocation is addressed by CID and takes effect for that delegation and descendants that depend on it. Expiry is signed into the grant and cannot be extended in place; issue a new delegation instead. See [Delegations & Sharing](/guides/delegations) for the task-oriented flow and [Capabilities](/reference/protocol/capabilities) for registered actions. # SDK client overviews Source: https://docs.tinycloud.xyz/reference/sdk/index Compare TinyCloud Web and Node client configuration and primary methods Use these pages to compare the Web and Node clients, review common constructor options, and find their primary methods. ## Client pages * [Web client overview](/reference/sdk/web) * [Node client overview](/reference/sdk/node) ## Use this section for * Confirming defaults before you write code * Checking whether a primary method is available in Web, Node, or both * Finding the relevant typed API surface after the quickstart > [!NOTE] > > These are curated overviews, not exhaustive generated API reference. For every service method, overload, option, and return type, use the TypeScript declarations shipped with your installed SDK version. # Node client overview Source: https://docs.tinycloud.xyz/reference/sdk/node Common TinyCloudNode constructor options, methods, and lifecycle behavior TinyCloudNode is the backend SDK. It can sign in with a private key, or operate in session-only mode when it only consumes delegations. > [!NOTE] > > This is a curated client overview. Use the TypeScript declarations shipped with `@tinycloud/node-sdk` for exhaustive parameter, service, return, and error types. ## Constructor | Option | Type | Default | Notes | | - | - | - | - | | `privateKey` | `string` | unset | Enables wallet-backed sign-in | | `signer` | `ISigner` | unset | Takes precedence over `privateKey` | | `host` | `string` | `https://node.tinycloud.xyz` | TinyCloud node endpoint | | `prefix` | `string` | `''` | Space-name input for the user's primary space | | `autoCreateSpace` | `boolean` | `false` | Create the space during sign-in | | `tinycloudRegistryUrl` | `string \| null` | `https://registry.tinycloud.xyz` | Registry used when resolving hosts | | `tinycloudFallbackHosts` | `string[] \| null` | hosted TinyCloud node | Used when host resolution needs a fallback | | `sessionExpirationMs` | `number` | 30 days | Session lifetime | | `sessionStorage` | `ISessionStorage` | Memory storage | Session persistence backend | | `enablePublicSpace` | `boolean` | `true` | Includes the public space in the session | | `spaceCreationHandler` | `ISpaceCreationHandler` | auto-approve when enabled | Custom space-creation flow | | `notificationHandler` | `INotificationHandler` | Silent notification handler | Sign-in and sign-out notifications | | `wasmBindings` | `IWasmBindings` | node-sdk-wasm default | Allows custom WASM bindings | | `ensResolver` | `IENSResolver` | unset | Resolves `.eth` names in delegation flows | | `manifest` | `Manifest \| Manifest[]` | unset | Drives manifest-based sign-in | | `capabilityRequest` | `ComposedManifestRequest` | unset | Takes precedence over `manifest` | | `includeAccountRegistryPermissions` | `boolean` | `true` | Manifest composition option | | `signStrategy` | `SignStrategy` | auto-sign for local keys | Root-signature strategy | | `nonce` | `string` | unset | SIWE nonce override | | `siweConfig` | `SiweConfig` | unset | Low-level SIWE overrides | | `telemetry` | `TelemetryConfig` | unset | Optional service telemetry | ## Primary methods | Method | Return | Notes | | - | - | - | | `signIn(options?)` | `Promise` | Requires wallet-backed mode | | `createDelegation(params)` | `Promise` | Legacy wallet-signed path | | `delegateTo(did, permissions, options?)` | `Promise` | Capability-chain delegation path | | `useDelegation(delegation)` | `Promise` | Works in wallet-backed and session-only mode | | `restoreSession(sessionData)` | `Promise` | Restores a serialized session | | `connectWallet(privateKey, options?)` | `void` | Attaches a wallet after construction | | `hostOwnedSpace(name)` | `Promise` | Hosts an additional owned space | | `ensureOwnedSpaceHosted(name)` | `Promise` | Idempotent owned-space hosting | | `createEncryptionNetwork(name?)` | `Promise` | Advanced encryption-network support | ## Useful getters * `did` * `sessionDid` * `address` * `isSessionOnly` * `spaceId` * `accountSpaceId` * `spaces` * `sharing` * `delegations` * `account` ## Notes * `signIn()` throws in session-only mode. * `createDelegation()` also throws in session-only mode. * `did` returns the wallet-backed owner DID after sign-in, or the session key DID when no wallet is connected. * `spaceId` is available after sign-in. > [!NOTE] > > Verified against `@tinycloud/node-sdk` 3.0.0. # Web client overview Source: https://docs.tinycloud.xyz/reference/sdk/web Common TinyCloudWeb constructor options, methods, and lifecycle behavior TinyCloudWeb wraps the Node SDK with browser-specific wallet, notification, and session handling. > [!NOTE] > > This is a curated client overview. Use the TypeScript declarations shipped with `@tinycloud/web-sdk` for exhaustive parameter, service, return, and error types. ## Constructor | Option | Type | Default | Notes | | - | - | - | - | | `tinycloudHosts` | `string[]` | First host is used if provided | Browser endpoint list | | `spacePrefix` | `string` | `''` | Space-name input for the user's primary space | | `kvPrefix` | `string` | `''` | Browser-side key prefix helper | | `autoCreateSpace` | `boolean` | `true` | Forwarded to the node layer | | `tinycloudRegistryUrl` | `string \| null` | `https://registry.tinycloud.xyz` | Registry used when resolving hosts | | `tinycloudFallbackHosts` | `string[] \| null` | hosted TinyCloud node | Used when host resolution needs a fallback | | `persistSession` | `boolean` | `true` | Enables session restore before prompting | | `sessionStorage` | `ISessionStorage` | Browser session storage | Custom session persistence backend | | `sessionStorageKeyPrefix` | `string` | unset | Isolates persisted sessions | | `sessionExpirationMs` | `number` | Node default applies when omitted | Passed through to `TinyCloudNode` | | `domain` | `string` | Browser hostname or `app.tinycloud.xyz` | SIWE domain | | `provider` | `any` | unset | Raw EIP-1193 provider used for SIWE (3.0 no longer accepts ethers providers) | | `notifications` | `NotificationConfig` | unset | Browser notifications and toasts | | `manifest` | `Manifest \| Manifest[]` | unset | Drives manifest-based sign-in | | `capabilityRequest` | `ComposedManifestRequest` | unset | Takes precedence over `manifest` | | `signStrategy` | `SignStrategy` | unset | Browser signing strategy | | `includeAccountRegistryPermissions` | `boolean` | `true` | Manifest composition option | | `shareReceiver` | `ShareReceiverServiceOptions` | unset | Required for `share.receive()`; see [Share viewer](/guides/share-viewer) | ## Primary methods | Method | Return | Notes | | - | - | - | | `signIn(options?)` | `Promise` | Restores a valid session first when possible | | `restoreSession(address?)` | `Promise` | Reports restore status instead of throwing for ordinary misses | | `signOut()` | `Promise` | Clears persisted session state | | `createDelegation(params)` | `Promise` | Delegation helper forwarded to the node layer | | `delegateTo(did, permissions, options?)` | `Promise` | Capability-chain delegation path | | `useDelegation(delegation)` | `Promise` | Works with received delegations | | `ensureOwnedSpaceHosted(name)` | `Promise` | Hosts an owned space after sign-in | | `space(nameOrUri)` | `ISpace` | Returns a scoped space handle | ## Useful getters * `did` * `sessionDid` * `spaceId` * `accountSpaceId` * `isSessionOnly` * `isWalletConnected` * `sessionRestoreStatus` * `kvPrefix` * `spaces` * `sharing` * `share` (addressed share receiving) * `delegations` ## Notes * `signIn()` uses the browser signer and then creates the underlying `TinyCloudNode`. * `persistSession` is browser-side behavior only. * `sessionExpirationMs` is forwarded to the node layer; the node default is 30 days when it is omitted. > [!NOTE] > > Verified against `@tinycloud/web-sdk` 3.0.0. # Build on Node Source: https://docs.tinycloud.xyz/start/backend-service Decide between private-key sign-in and session-only mode before your first backend write. Choose this path when you are building a backend service, job, or CLI with the Node SDK. ## Choose the authentication mode * Use private-key mode when the process owns a space and must sign in or create delegations. * Use session-only mode when the process only consumes access delegated by another principal. ## Get to a first write Go directly to the [Node SDK quickstart](/quickstart/node-sdk). It shows the wallet-backed path from installing the SDK to signing in and writing a KV record, then introduces session-only mode as the alternative. ## After the first write * Use [Node sign-in](/guides/authentication/node) when you need to compare the two authentication modes in detail. * Read [DID formats](/concepts/did-formats) before choosing a persistent owner DID or ephemeral session DID as a delegation target. * Read [Spaces](/guides/spaces) when the service must provision additional data containers. * Continue with [Delegations](/guides/delegations) when the service acts on behalf of another principal. * Use the [Node SDK reference](/reference/sdk/node) for the current constructor options and primary methods. ## Source note Use `tc.did` after `signIn()` when you need the owner DID for delegations. In session-only mode, the delegation must target the instance's session DID. # Build in the browser Source: https://docs.tinycloud.xyz/start/browser-app Shortest path from wallet sign-in to a first KV write in the Web SDK. Choose this path when your application runs in a browser and the user will sign in with a wallet-backed signer. ## Get to a first write Go directly to the [Web SDK quickstart](/quickstart/web-sdk). It is the end-to-end path from installing the SDK to signing in and writing a KV record. ## After the first write * Use [Web sign-in](/guides/authentication/web) when you need to change the browser authentication setup. * Use [Automated OpenKey + TinyCloud E2E testing](/guides/browser-e2e-testing) for unattended, agent-run, or CI coverage of the real OpenKey external-wallet and TinyCloud sign-in flow without automating a passkey ceremony. * Read [Spaces](/guides/spaces) before changing space naming or provisioning. * Continue with [KV basic operations](/guides/kv/basic-operations) for focused read, list, metadata, and delete examples. * Add [Delegations](/guides/delegations) or [Sharing](/guides/sharing) only when another principal needs access. * Use the [Web SDK reference](/reference/sdk/web) for the current constructor options and primary methods. ## Source note This path follows the Web SDK and guide pages that describe the shipped browser flow. Use the generated capability registry when you need exact action names or status. # Operate TinyCloud Source: https://docs.tinycloud.xyz/start/operator Install, host, troubleshoot, and wire OpenKey without mixing in protocol theory. Use this page to choose between deploying a TinyCloud node, operating a managed node from the CLI, and adding OpenKey-backed sign-in. These are separate paths; you do not need to complete all three. ## Deploy a node Go directly to [Docker deployment](/hosting/docker) for the documented end-to-end path. Run the container and verify `/healthz` before changing the database, block storage, or telemetry setup. After the node starts: * Review [Configuration](/hosting/configuration) for canonical settings. * Choose a [Database](/hosting/databases) and [Block storage](/hosting/storage) backend for the deployment. * Add [Monitoring](/hosting/monitoring) after the service starts cleanly. ## Operate from the CLI If you are using an existing node, start with the [CLI overview](/cli/overview), then sign in and follow the KV command path. The CLI is a client and operations tool; installing it does not install or run a TinyCloud node. To send files to people, use [Share files](/cli/share). To set up an agent, follow [agents.tinycloud.xyz/onboarding](https://agents.tinycloud.xyz/onboarding). ## Add OpenKey-backed sign-in Use [TinyCloud integration](/openkey/tinycloud-integration) when OpenKey should supply the signer for TinyCloud's SIWE flow. OpenKey OAuth and widget flows are separate integration choices. Use [Troubleshooting](/troubleshooting) when any path produces a specific failure symptom. ## Source note The deployment path follows the documented container configuration and node health endpoint. Use the linked operational pages for the commands, environment variables, and deployment behavior covered by each task. # Understand the protocol Source: https://docs.tinycloud.xyz/start/protocol Check the model before you implement manifests, delegations, or capability checks. Use this path when you need to verify TinyCloud terminology, capability names, or delegation behavior before you code against it. ## Read in this order 1. Start with [System model](/concepts/system-model) for the big picture. 2. Read [Capabilities](/concepts/capabilities) to understand TinyCloud's UCAN and ReCap authorization model. 3. Read [App manifests](/concepts/app-manifests) to see how apps request capabilities during sign-in. 4. Read [DID Formats](/concepts/did-formats) to keep owner DIDs and session DIDs distinct. 5. Check [Capability Registry](/reference/protocol/capabilities) for the exact action names, aliases, and statuses that the node currently exposes. ## After that * Read [Delegations](/guides/delegations) if you are enforcing attenuation rules or sharing access. * Read [Sharing](/guides/sharing) if you need portable access bundles. * Read [Data Vault](/guides/data-vault) if your flow depends on client-side encryption and re-encryption. ## Source note Implementation facts live in the linked guides, the generated capability registry, and the TinyCloud node source. Treat whitepaper language as normative only when it does not conflict with those sources. # Troubleshooting Source: https://docs.tinycloud.xyz/troubleshooting Fix common TinyCloud CLI, hosting, and OpenKey problems Use this page to map a symptom to the next command or config check. ## No profile, key, or session **Symptom:** `tc doctor` reports a missing profile, missing key, or missing session. **Fix:** Start with profile setup and sign in. ```bash theme={null} tc init tc auth login ``` If you need a non-browser path, use local-key auth: ```bash theme={null} tc auth login --method local ``` ## Session expired or sign-in required **Symptom:** `tc context --json` shows `"state": "expired"`, or a command fails with `AUTH_REQUIRED` (exit `3`; every command in CLI 1.1.0 beta, headless `tc secrets` commands in 1.0.0). **Fix:** sign in again the same way the profile was created: `tinycloud onboard` for an agent, `tc auth login` for an OpenKey owner, `tc auth login --method local` for a local key, or the scoped `--paste --manifest` login for a secrets profile. Device logins can be renewed with the same `--device --manifest` command. If a login fails with `SESSION_IN_USE`, the new request would narrow or shorten a session the profile already holds. Use a new profile for the new purpose, or pass `--replace-session` if you mean to replace it. ## Browser auth did not open **Symptom:** `tc auth login` cannot open a browser callback. **Fix:** Use paste mode or suppress the popup. ```bash theme={null} tc auth login --paste tc auth login --no-popup ``` An agent runs `tinycloud onboard` and sends the owner its link. On a server with no browser, use device login and approve on your phone: `tc auth login --device --manifest `. See [CLI authentication](/cli/authentication#device-login-for-servers). If you are pointing at a self-hosted OpenKey instance, verify `TC_OPENKEY_HOST` or the profile's `openkeyHost`. ## Node health check fails **Symptom:** `tc node health` says the node is unreachable. **Fix:** Confirm the host and check the health endpoint. ```bash theme={null} tc node health curl http://localhost:8000/healthz ``` If you changed the node URL, check `TC_HOST` and the profile's `host` value. ## `tc doctor` and `tc node health` disagree **Symptom:** `tc doctor` reports the node as unreachable, but `tc node health` or a direct `/healthz` request succeeds. **Cause:** The current CLI commands probe different paths: `tc doctor` checks the legacy `/health` path, while `tc node health` checks the node's implemented `/healthz` endpoint. **Fix:** Use `tc node health` or `/healthz` as the node-health check and treat the `tc doctor` node result as CLI drift. Continue using `tc doctor` for its local profile, key, session, and space checks. ## Space is not hosted **Symptom:** `tc kv` or `tc sql` reports that the target space is not hosted. **Fix:** Host the owned space before retrying the data command. ```bash theme={null} tc space create applications tc space create secrets ``` Use `tc space info` or `tc space list` to confirm the resolved space URI. ## Secrets network is missing **Symptom:** `tc secrets doctor` reports that the encryption network does not exist. **Fix:** Create or reuse the default network. ```bash theme={null} tc secrets network init tc secrets network show ``` ## Storage is full **Symptom:** a write fails with `STORAGE_QUOTA_EXCEEDED`, or with `STORAGE_LIMIT_REACHED` when one write is larger than the space left. **What still works:** reads. Nothing from the refused write was saved, so the space is unchanged. **Fix:** do not retry the write. Free up space or upgrade the plan at [account.tinycloud.xyz/billing](https://account.tinycloud.xyz/billing) (`tc account billing portal --open`). | Surface | What you see | | - | - | | CLI 1.0.0 | `tc kv put` exits `1`; `tc share publish` exits `4` | | CLI 1.1.0 beta | Every command exits `10`: `TinyCloud storage is full; nothing was written.` | | SDK | A failed `Result` with `error.code` `STORAGE_QUOTA_EXCEEDED` or `STORAGE_LIMIT_REACHED`; `meta.usedBytes` and `meta.limitBytes` when the node reports them | | MCP 0.4.0 beta | `STORAGE_QUOTA_EXCEEDED` with `retryable: false` | In apps, treat this as a read-only state rather than an outage: keep showing the user's data and disable writes. SDK 3.1.0 beta adds `isStorageFullError(error)` to test for both codes, and reports them from SQL and DuckDB writes too. ## A permission request is waiting **Symptom:** You created a request artifact, but the action still fails. **Fix:** Inspect local state and retry once the requested capabilities are covered. ```bash theme={null} tc status tc auth caps tc auth retry --last ``` If a request still is not covered, grant or import the matching delegation artifact first. ## Where to look next * `tc doctor` for a quick local diagnostic pass * `tc status` for local profile and permission state * `tc auth caps` for coverage details * `tc secrets doctor` for secrets-specific checks > [!NOTE] > > These fixes are based on the CLI's actual error hints and command behavior, not on hypothetical error codes.