Sync
CloudStore syncs a store with a Civility server. Reads and writes stay local. A background loop pushes local changes and pulls remote ones.
Configure
Add a cloud option with your app id.
import { CloudStore } from '@civility/cloud'
import { IDBStorage } from '@civility/cloud/storage/idb'
const APP_ID = 'app-k3m7q2x4p6w5z7n3b2v4c6h5'
export const cloud = new CloudStore({
id: APP_ID,
storage: { db: new IDBStorage() },
documents: ['settings'],
collections: ['items'],
versions: [{ version: '1.0.0', schema }],
cloud: { appId: APP_ID },
})
// On startup: resume a saved session, or finish a sign-in redirect.
await cloud.resume()
Every declared document and collection syncs. The entity names are the store names on the server, so keep them the same across releases. To keep one entity on the device, set entities: { name: { sync: false } }.
cloud option |
Type | Default | Notes |
|---|---|---|---|
appId |
string |
required | From civ id. See Registration. |
manifest |
AppManifest |
none | Registered on the first sync. |
selectiveSync |
string[] |
all | Entity names (collections and documents) to sync. [] syncs none. |
blobPolicy |
'eager' | 'lazy' | (ref) => boolean |
'eager' |
When to download blob bytes. 'lazy' downloads on demand. |
blobTransfers |
BlobTransferPolicy |
none | Concurrency, pacing and network rules for blob transfers. |
blobRefExtractors |
((change) => string[])[] |
none | Find blob hashes in records that do not use { hash, mime, size }. |
syncInterval |
number |
30000 |
Milliseconds between sync cycles. |
debounceDelay |
number |
500 |
Milliseconds to wait after a local change before syncing. |
timeout |
number |
30000 |
Request timeout in milliseconds. |
pushBatchSize |
number |
200 |
Maximum changes per push request. |
shared |
{ backend } |
none | Storage for read-only replicas of other apps' data. |
metaBackend |
EntryStore |
storage.db |
Where the saved connection and sync cursor are kept. |
Sign in
Your app never asks for the user's Civility password. The user approves the app on their server's consent page, and the app receives a token limited to the scope it asked for. The flow is OAuth 2.0 authorization code with PKCE.
Scope
The scope is a string of items separated by spaces or commas.
| Item | Grants |
|---|---|
* |
Read, write and delete on all stores. |
read:<store> |
Read one store. <store> may be *. |
write:<store> |
Write one store. |
delete:<store> |
Delete in one store. |
sessions:manage |
List, rename and sign out the user's sessions. |
identity:sign |
Sign as the user with a delegated key. |
shared:<type> |
Read another app's data of that shared type. |
* does not include sessions:manage or identity:sign.
With the component
<civ-account> renders the server field and starts the sign-in. Signed in, it shows who is signed in and to which server, the state of sync, and anything that needs the user's attention, with Sync now and Sign out. It is the one element an app must mount.
<civ-account app-id="app-k3m7q2x4p6w5z7n3b2v4c6h5"
scope="*"></civ-account>
import '@civility/cloud/ui'
const account = document.querySelector('civ-account')!
Object.assign(account, { synced: cloud })
The package exports no element types, so set properties with Object.assign or a cast.
| Property | Type | Notes |
|---|---|---|
synced |
SyncTarget |
The CloudStore. |
appId |
string |
Attribute app-id. |
scope |
string |
Default '*'. |
servers |
PresetServer[] |
{ label, url } suggestions for the URL field. |
authorize |
AuthorizeStrategy |
Replaces the web redirect, for example with authorizeNative. |
variant |
string |
wide (default) is a card for a settings page; chip and icon are a button that opens a menu, for a header. |
@civility/cloud/ui is styled by @inro/ui's stylesheet and imports none of its elements. The civ-* elements use its CSS variables, its dialog rules, and its ui-alert, ui-badge, ui-button-group and ui-spinner tags, so load its base stylesheet (exported as a string from @inro/ui/base-css) to style them. The dialogs are native <dialog> elements and need nothing registered.
Without the component
connectButton.onclick = () =>
cloud.authorize({
serverUrl: serverInput.value,
scope: 'read:items write:items',
})
authorize() sends the current tab to the consent page. It does not open a window. When the tab comes back, cloud.resume() exchanges the code, saves the session, starts syncing, and dispatches authorized.
authorize option |
Notes |
|---|---|
serverUrl |
HTTP(S) URL with no credentials, query or fragment. |
scope |
See Scope. |
redirectUri |
Default: the page's origin and path. |
returnTo |
Same-origin URL to restore in the address bar after sign-in. Default: location.href. |
signKey |
The app's Ed25519 public key, when asking for identity:sign. |
signal |
Cancels the sign-in before the tab leaves. |
restore() puts returnTo back with history.replaceState, which does not fire hashchange. If your router needs to know, listen for authorized:
cloud.addEventListener('authorized', (e) => {
const { returnTo } = (e as CustomEvent).detail
if (returnTo) router.go(new URL(returnTo).hash)
})
A failed sign-in does not throw. It dispatches error with phase authorize and sets cloud.authorizationError. The codes are auth.access_denied when the user refused and auth.authorization_lost when the sign-in was finished in another browser.
Native apps
In a Tauri app, use authorizeNative from @civility/tauri. It opens the consent page in the system browser.
import type { AuthorizeStrategy } from '@civility/cloud/ui'
import { authorizeNative } from '@civility/tauri'
const authorize: AuthorizeStrategy = (options) =>
authorizeNative({
...options,
redirectUri: 'com.example.notes:/civility/callback',
})
Object.assign(input, { authorize })
beginAuthorization takes the same optional manifest. cloud.authorize() sends the one you gave CloudStore.
In other shells, run the two halves yourself:
import { beginAuthorization, completeAuthorization } from '@civility/cloud'
const { url, pending } = await beginAuthorization({
serverUrl,
appId: cloud.appId,
scope: 'read:items',
redirectUri: 'com.example.notes:/civility/callback',
})
const callbackUrl = await openInSystemBrowser(url) // your code
await cloud.adoptAuthorization(
await completeAuthorization(callbackUrl, pending),
)
Methods and properties
| Method | Does |
|---|---|
restore() |
Finishes a sign-in redirect or resumes a saved session. Resolves false if there is none. |
authorize(options) |
Starts the web sign-in. |
adoptAuthorization(authorization) |
Connects, saves the session and starts syncing with a completed authorization. |
connect(serverUrl) / disconnect() |
Sets or drops the server. connect does not authenticate. |
setToken(token) |
Uses a token directly. |
saveConnection(url, token) / loadConnection() / clearConnection() |
Saves, reads or erases the stored session. |
logout() |
Signs out, stops syncing and clears the saved session. |
startSync() / stopSync() |
Starts or stops the background loop. |
blockSync() / unblockSync() |
Pauses or resumes syncing without disconnecting. |
sync(options?) |
Runs one cycle now. { entities } limits it to some entities. |
forcePush() |
Replaces the server's data with local data. Needs a token with delete on all stores (* or delete:*); a narrower scope gets permission.insufficient_scope. |
forcePull() |
Wipes local synced data and pulls it again. |
usage() |
Returns the account's storage use and limits. |
storageEstimate() |
Returns the space in use on this device against what the browser allows this app, or null where the browser cannot say (a Tauri app). |
shared(type) |
Returns a read-only replica of another app's data. Needs cloud.shared. |
blob(hash) / evictBlob(hash) / compactBlobs(options?) |
See Blobs. |
dispose() |
Stops syncing and releases the store. |
| Property | Type | Notes |
|---|---|---|
connected |
boolean |
A server is set. |
authenticated |
boolean |
A token is set and has not been rejected. |
syncing |
boolean |
A cycle is running. |
syncBlocked |
boolean |
blockSync() is in effect. |
lastSync |
string | null |
ISO time of the last finished cycle. |
appId |
string |
|
connection |
{ serverUrl, token } | null |
The live credentials. Do not log or display them. |
authorizationError |
CivilityApiError | null |
Why the last web sign-in failed. |
canShare |
boolean |
share is configured and a server is set. |
share |
CloudShare |
See Share links. |
api |
SyncApi | null |
The HTTP client. |
Events
Listen with cloud.addEventListener(type, listener).
| Event | Details |
|---|---|
connected |
A server was set. |
disconnected |
The server was dropped. |
auth |
The token was set, cleared or rejected. Check cloud.authenticated. |
authorized |
A sign-in finished. detail: { serverUrl, identity?, returnTo? }. |
sync |
A cycle finished. detail: { pushed, pulled, serverSeq }. |
error |
SyncErrorEvent with error (a CivilityApiError) and context: { phase, storeName?, entryId?, blobHash? }. |
force-sync |
Before forcePush/forcePull. Has direction. Call preventDefault() to cancel. |
blob-progress |
blobHash, phase, loaded, total. |
blob-complete |
blobHash, phase, mode ('background' or 'on-demand'). |
context.phase is one of push, pull, blob_upload, blob_download, blob_compact, blob_history, register, shared, sync, authorize.
When the server rejects the token with 401, the loop stops and auth fires with cloud.authenticated false. Send the user through sign-in again.
When the server has pruned the history a device needs (sync.history_pruned), sync() calls forcePull(). Cancel the force-sync event to get the error instead.
When something goes wrong
Mount <civ-account> and the user is told about every problem Civility knows of: storage full on the server or on the device, offline, signed out by the server, an app that is out of date, a server that cannot sync with the app. Each one has a headline, what it means for the user's data, and one thing to do. You write no code for this.
<civ-account variant="chip" app-id="app-k3m7q2x4p6w5z7n3b2v4c6h5"></civ-account>
Object.assign(document.querySelector('civ-account')!, { synced: cloud })
<civ-settings-cloud> mounts one for you, in its wide form.
Four things are left to your app.
A write of yours can be refused. When the device is out of space, set(), delete() and the other writes reject with a CivilityApiError whose code is quota.local_exceeded. The write did not happen and nothing is kept in memory. <civ-account> says why; your app says what was not saved, next to the thing the user was doing.
try {
await notes.set(id, note)
} catch (error) {
if (error.code !== 'quota.local_exceeded') throw error
showNotSaved(id)
}
Deleting synced entries does not reliably free space: a delete is itself a write. If your app keeps data it can drop without one (a cache of map tiles, downloaded audio), that is what to offer.
The names of files. Civility knows a file by its hash, so it can say "3 files couldn't be uploaded" and not which. Tell <civ-account> what you call a file and it lists them, in the row for a few and in a dialog for many, with "Try again" where trying again can help.
Object.assign(document.querySelector('civ-account')!, {
// Answer nothing for a hash you do not know. A promise is fine.
fileName: (hash: string) => tracks.byBlob(hash)?.title ?? null,
})
<civ-settings-cloud> takes the same fileName and hands it on. For a list of your own, cloud.issues.scopes(issue.key) gives every hash under an issue, and cloud.retryBlobTransfers() tries them again.
Controls only your app can offer. Civility cannot free space on the device or update your app, so those two problems have a message and no button. Put your own control in a slot of <civ-account>:
<civ-account variant="chip" app-id="…">
<button slot="menu-start" id="clear-cache">Clear downloaded maps</button>
<a slot="menu-end" href="/help">Help</a>
</civ-account>
The slots are menu-start, links and menu-end while signed in, signed-out under the server field, and footer in wide.
A message somewhere of your own. The problems are cloud.issues, and issueMessage gives the same words the element shows, in the language you set with setLocale.
import { issueMessage } from '@civility/cloud/ui'
function banner() {
const issue = cloud.issues.list().find((i) => i.impact === 'critical')
if (!issue) return hideBanner()
const { message, body } = issueMessage(issue, {
server: cloud.capabilities?.name ??
new URL(cloud.serverUrl ?? location.href).host,
links: cloud.capabilities?.links ?? {},
})
showBanner(message, body)
}
cloud.issues.addEventListener('change', banner)
Errors that follow one action of the user's (a share that failed, an import) are not in cloud.issues. The element that ran the action shows them beside it. For an action of your own, toSyncError(error) from @civility/cloud/ui gives the headline.
<civ-account> dispatches two cancelable events. on-navigate (detail: { href }) comes before it opens a page on the server; a Tauri app cancels it and opens the system browser. on-action (detail: { action, issue }) comes before it signs in again, retries, copies the error log or fetches a fresh copy; cancel it to do that your own way.
Working offline
- Writes are available to local reads at once. Do not wait for
sync()before showing data. - The app must work with no server. Sync is something the user turns on.
- Show sync state from the properties and events. Do not disable features while offline.
Blobs
Set storage.blobs and store blob references as described in Store. Blob bytes then upload and download with the records that reference them.
import { IDBBlobStorage, IDBStorage } from '@civility/cloud/storage/idb'
const cloud = new CloudStore({
id: APP_ID,
storage: { db: new IDBStorage(), blobs: new IDBBlobStorage() },
collections: ['photos'],
versions: [{ version: '1.0.0', schema }],
cloud: { appId: APP_ID, blobPolicy: 'lazy' },
})
const body = await cloud.blob(hash) // local copy, or download it
await cloud.evictBlob(hash) // drop the local copy; false if the server lacks it
await cloud.compactBlobs() // delete local blobs no record references
With blobPolicy: 'lazy', records sync right away and blob bytes download when you call cloud.blob(hash).
Failed transfers retry with backoff. After four failed attempts a transfer stays queued but paused; call cloud.retryBlobTransfers() to resume. cloud.blobTransfers controls concurrency and pausing, and cloud.blobPresence.check(hashes) reports whether the server has each blob.
Blob URLs with a service worker
<img>, <audio> and <video> cannot send an Authorization header, so they cannot load blobs from the server directly. withBlobProxy from @civility/cloud/worker answers same-origin GET /blob/<key> requests in a service worker. It serves the local blob if present, and otherwise fetches it from the server with the token.
In the service worker:
import { withBlobProxy } from '@civility/cloud/worker'
withBlobProxy({ id: APP_ID })({})
withBlobProxy(options) returns a function that adds fetch and message listeners when you call it. Call it while the worker script first runs. It takes one argument, a context object, and {} is enough. If the context has a reserved set, the plugin adds its path prefix to it. This is the plugin shape that init() from @inro/workers accepts, so you can also pass withBlobProxy(...) in its plugin list. @civility/cloud/worker does not import @inro/workers.
| Option | Default | Notes |
|---|---|---|
id |
required | The store's id, not the derived database name. |
pathPrefix |
'/blob/' |
Path prefix to answer. |
cache |
true |
Save full server responses into the local blob store. |
On the page, pass the connection to the worker:
import { bindBlobProxy } from '@civility/cloud/worker'
const binding = bindBlobProxy(cloud, { id: APP_ID })
await cloud.resume()
await binding.ready // the worker has the current credentials
img.src = `/blob/${photo.hash}`
bindBlobProxy updates the worker on sign-in, token change, logout and disconnect. With no controlling service worker it does nothing. binding.dispose() stops the updates but does not clear the worker's stored credentials; log out and await binding.ready first if you need them cleared. To send credentials yourself, use configureBlobProxy({ id, serverUrl, token }).
The proxy serves images, audio, video, fonts, plain text and application/octet-stream inline. Other types, including SVG, are sent as attachments.
Sessions
An app can list the user's signed-in devices, rename them and sign them out. Ask for sessions:manage in the scope.
import { createSessionsHttp } from '@civility/cloud/api'
const conn = cloud.connection
if (conn) {
const sessions = createSessionsHttp(conn.serverUrl, conn.token)
const list = await sessions.listSessions()
await sessions.renameSession(list[0].id, 'Kitchen tablet')
await sessions.revokeSession(list[0].id)
}
A token without sessions:manage gets auth.unauthorized (401). That includes tokens issued before you added the scope, so tell those users to reconnect.
Encrypting your data
Civility syncs the JSON you store and does not encrypt it. To encrypt, store your ciphertext as an ordinary JSON value and write the schema for that value.
- Keep nonce, ciphertext and tag in one value, so a merge cannot split them.
- Encrypt blob bytes before
put. Keep{ hash, mime, size }references outside the encrypted value, or supplyblobs.referenceExtractors, so the blobs are not garbage collected. - Your app handles keys, unlock, rotation and recovery.