Login and secrets
Valence takes no position on how you log a user in. Your web app does that against your API, by whatever means you already use — email and password, a magic link, an OAuth redirect, a one-time code. What it could not do before 0.4 is the part that needs the host: keep the credential somewhere safer than the database, and make the host’s own requests authenticated.
That is what this page is about. It is one method and one promise:
import { call } from '#lib/valence/bridge.g';
const { token } = await (await fetch('https://api.example.com/login', { … })).json();await call('auth.setToken', { token }); // the host stores it and uses it from now onFrom that moment, every pull and push of a writable bucket carries Authorization: Bearer <token>,
including the ones the host runs by itself — on resume, when connectivity returns, and in the background
every fifteen minutes. That is the whole reason the token goes to the host rather than staying in the
page: those requests are made while your JavaScript is not running.
Why not just keep the token in the web app?
Section titled “Why not just keep the token in the web app?”Two reasons, and both of them bite in production.
- A token in
prefsis in a plain-text SQLite table, inside a database that is meant to be backed up.localStorageinside the WebView is no better. - A token the page holds cannot reach the sync driver. Background sync is the feature; a token that only exists while a page is on screen cannot authenticate it.
The token
Section titled “The token”| Method | Params | Returns | What it does |
|---|---|---|---|
auth.setToken |
token: string?, account: string?, discardPending: bool? |
void |
Stores the token. null or '' clears it. The last two are the account switch. |
auth.hasToken |
none | bool |
Whether a token is stored. |
auth.account |
none | string? |
The account id last passed to auth.setToken, or null. |
There is deliberately no auth.getToken. The token is kept under the host’s reserved valence.
namespace, which secure.get refuses, so the page can set it, replace it and clear it — and never read
it back. A cold start asks auth.hasToken() to decide between a login screen and the app, which is all a
login screen actually needs.
if (await call('auth.hasToken')) goto('/today');else goto('/login');Logging out is await call('auth.setToken', { token: null }). On its own that clears the credential
and nothing else: the rows already synced to this device stay in SQLite, because only your app knows
which buckets are the user’s and whether the device is shared.
That is the right default for one-user apps, and the wrong one for a shared phone. Pass an account id
with the token and the host takes over both halves — it refuses to sign a new user in over the previous
one’s unsent writes, and clears the writable buckets when the user really does change. See
Signing users in and out. Without it, forgetting a user is yours to do with
data.put(bucket, key, null) — and know that the tombstones then push to your server.
When the token expires
Section titled “When the token expires”A 401 on a request that carried the token is not a network problem, and the host says so in two ways:
- the
auth.expiredevent fires, once per sync run; sync.now()returnsreason: 'unauthorized'.
on('auth.expired', async () => { const fresh = await refresh(); // your refresh flow, with your API if (fresh) await call('auth.setToken', { token: fresh }); else goto('/login');});The host keeps the rejected token, because a refresh flow usually has to present the expired one. It also keeps every queued write: a push that was refused stays in the outbox and goes out when a new token arrives, so nothing the user typed is lost by a session timing out.
Public buckets stay unauthenticated
Section titled “Public buckets stay unauthenticated”The token goes on writable buckets only — the user’s own data. A public read-only bucket (a catalogue, a calendar, a price list) is fetched with no header at all, so a CDN can serve it and a cache can keep it.
If a read-only bucket needs to know who is asking, it is the wrong shape for this: make it writable, or put the identity in the path your publisher writes.
Secure storage, for anything else
Section titled “Secure storage, for anything else”The same Keystore drawer is open to your app for other short secrets:
| Method | Params | Returns |
|---|---|---|
secure.get |
key |
string? |
secure.set |
key, value |
void |
secure.delete |
key |
void |
await call('secure.set', { key: 'refresh', value: refreshToken });const refresh = await call('secure.get', { key: 'refresh' });await call('secure.delete', { key: 'refresh' });secure.settakes a non-null value, andsecure.deleteis the only delete.prefs.set(key, null)anddata.put(bucket, key, null)both delete; this is deliberately the odd one out, so that clearing a credential always says so at the call site.- Keys starting with
valence.are refused withE_DENIED, exactly as they are forprefs. - It is not a cache. A record the platform can no longer decrypt — after a restored backup, or a
Keystore the OS has invalidated — is dropped rather than returned. Every read may come back
null, and anything your app cannot simply ask for again does not belong here. - It is for short strings, not blobs. A hundred bytes of token, not a file.
Where it is stored
Section titled “Where it is stored”| Platform | Where | Notes |
|---|---|---|
| Android | The Keystore, through flutter_secure_storage: an AES-GCM record whose key is wrapped by a hardware-backed key. |
Needs minSdk 23. This is what that package does now instead of the deprecated EncryptedSharedPreferences. |
| iOS | The Keychain, at first_unlock_this_device, so the item never travels to another device in a backup and a background sync after a reboot still works once the user has unlocked. |
Experimental and untested, like every iOS path in Valence. |
On the web
Section titled “On the web”window.Valence does not exist in a browser, so these calls go to your shim. Be honest about what a
browser can do: there is no Keychain there, and a token in sessionStorage is a token any script on the
page can read.
installShim({ 'auth.setToken': async ({ token }) => { if (token) sessionStorage.setItem('token', token); else sessionStorage.removeItem('token'); }, 'auth.hasToken': async () => !!sessionStorage.getItem('token'), // No shim for secure.* at all: a call throws E_UNSUPPORTED, which is the truth.});The website half of your app is a normal web app, so it keeps the session the way a web app does — a cookie your server sets, usually. The shim exists so the same build runs; it does not have to pretend the guarantees are the same.
Adding it to an app that already shipped
Section titled “Adding it to an app that already shipped”secure.*, auth.* and auth.expired arrived at schema version 2, so an app whose store build
shipped version 1 adds them like any other new method: paste the lines, bump version to 2, and run
valence codegen.
"secure.get": { "since": 2, "params": { "key": "string" }, "returns": "string?" },"secure.set": { "since": 2, "params": { "key": "string", "value": "string" }, "returns": "void" },"secure.delete": { "since": 2, "params": { "key": "string" }, "returns": "void" },"auth.setToken": { "since": 2, "params": { "token": "string?" }, "returns": "void" },"auth.hasToken": { "since": 2, "params": {}, "returns": "bool" }(The two account params and auth.account arrived later, at the template’s version 13; they are
their own page.)
"auth.expired": { "since": 2, "payload": {} }Two consequences, both of them the ordinary rules rather than anything new to auth:
- The host that answers them is a store build.
since: 2methods need a native release;has('auth.setToken')isfalseon the hosts already in the field, and an OTA bundle that calls one without checking fails there. See the bridge guide. requires.bridgemoves with the schema version, so the next OTA release declares2and older hosts stop taking it. If you want one more release to reach them, pin it withvalence bundle --requires-bridge 1.
Doing it in Dart instead
Section titled “Doing it in Dart instead”An app with its own refresh loop on the native side can keep owning the token:
ValenceConfig.authToken is a callback the host asks on every request, and when you set it, it wins over
anything stored through auth.setToken. That is the escape hatch for a token that is derived rather than
handed over — a Firebase ID token, say. Most apps should not need it.
What Valence still does not do
Section titled “What Valence still does not do”- No identity provider, no session management, no refresh-token rotation. Those are your API’s job. Valence carries a string you give it.
- No per-request scoping. One token, every writable bucket.
- No two signed-in users at once. One database, one account; switching clears the last one’s rows (Signing users in and out).
- No biometric gate on the token.
flutter_secure_storagesupports one; Valence does not expose it yet. Open an issue if you need it.
Call your API natively
Section titled “Call your API natively”http.request uses this same token on every request to an exact origin compiled from http.origins. A token-bearing 401 emits auth.expired once per HTTP request, independently of sync’s once-per-run event. Redirects are never followed. Every allowed API is trusted with the token: do not allow third-party origins or an endpoint that reflects credentials.
Recorded account changes also clear every REST cache overlay, including values in read-only buckets. Refresh and first account adoption retain them. Discard in-flight API responses on an account change. Cache lifetimes.