Beta feature in the stable packages. Local replica behavior and the on-disk
format may change in a minor release.
Requirements
-
The TinyCloud node must advertise
kv-sync-v1in its/inforesponse. The production node attee.node.tinycloud.xyzadvertises this feature. -
Install the stable CLI (version 1.1.0 or later):
- 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/[email protected]. -
A device needs a grant that covers its configured KV prefix and includes
getandsync.listandmetadataare 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, thedevice profile requests get and sync
access to notes/:
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:
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: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:
--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
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:
Command options
Pass the global
--host <url> 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:
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 atinycloud.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:
Error codes and next steps
The CLI prints a machine-readable error code alongside the message. Common replica errors:
Other errors identify configuration, grant, storage, or node failures:
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 explicittc 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 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:--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 <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:
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().
Declare get on each replicated prefix in the manifest; sign-in then adds sync for that prefix.
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 <name> --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 pathP 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.
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.
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: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
--since <duration> 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 <url> 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 atcr1. 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 optionsource: "network" for checks whose answer must reflect the node, such as an existence check. It bypasses replica open, sync and local reads:
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)
With thereplication 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:
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 requiresallowSecretsto stayfalseand 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 bystaleSyncTimeoutMs, default 5 seconds) and falls back per the read rules above. Pass{ source: "network" }tokv.get()orkv.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.
maxBytescaps replica data for the whole origin. When the budget is reached, syncing stops withSTORAGE_BUDGETand 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;onEventreceivesreplication.sync,replication.grantandreplication.lifecycleevents. - 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.
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
0600under directories with mode0700. 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-secretson the CLI, oropenReplica({ 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 logoutdeletes local replicas for that CLI profile by default; pass--keep-replicasto keep them. Logout does not revoke the profile’s grants on the node. To revoke node-side authority, usetc delegation revoke <cid>. 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,onCommittedreports only local commits from other tabs. - Replicas are read-only. Offline writes are not supported.
