Where each piece lives
An Obsidian plugin has three places to keep state, and they behave differently across devices.
| Item | Store it in | Why |
|---|---|---|
| License key | app.secretStorage |
The SecretStorage guide says it keeps secrets out of data.json, and that the value sits in local storage keyed to the vault. Obsidian 1.11.4 or later. |
| Instance id and token | app.saveLocalStorage |
Vault-specific localStorage on this device. Each device activates for itself. |
| Settings with nothing secret | saveData |
Written to data.json in the plugin folder, inside the vault. |
The data.json row is the trap. It is a file in the vault, so whatever syncs the vault copies it to every other device. A plugin that saves the instance id there gets one seat for every device the vault reaches, and the second device never activates at all. If you want that, say so in your terms. If you want a seat per device, keep the id in local storage.
SecretStorage is a shared store: the guide says any plugin can reference a secret by its name. Do not treat it as private from other plugins, and note that Obsidian plugins are code the user chose to install. On older Obsidian, the code below falls back to local storage for the key.
The check
isLicensed and verifyToken come from the offline verification guide. The requestUrl call does three things differently from fetch. It rejects on a status of 400 or more unless you pass throw: false, so a 404 body would be lost. It has no timeout, so the code races it against a timer. And res.json parses the body when you read it, so guard it in case a proxy answers with an HTML error page.
import { Platform, requestUrl, requireApiVersion, type App } from 'obsidian';
import { isLicensed, verifyToken } from './token';
const BASE = 'https://clavem.io';
const KEY_ID = 'inkwell-license-key'; // SecretStorage ids: lowercase letters, digits and dashes
const STATE_ID = 'inkwell-license-state';
export type LicenseState = 'licensed' | 'invalid' | 'needs-network' | 'unlicensed';
interface Saved { instanceId: string; token: string }
/** requestUrl has no timeout option, so stop waiting after 8 seconds. */
async function call(action: string, body: Record<string, string>) {
let timer = 0;
const timeout = new Promise<never>((_, reject) => {
timer = window.setTimeout(() => reject(new Error('timeout')), 8000);
});
try {
const res = await Promise.race([
requestUrl({
url: `${BASE}/v1/licenses/${action}`,
method: 'POST',
contentType: 'application/json',
body: JSON.stringify(body),
throw: false, // without this, any 4xx rejects and the JSON body is lost
}),
timeout,
]);
let json: any = {};
try { json = res.json; } catch { /* the body was not JSON */ }
return { status: res.status, json };
} finally {
window.clearTimeout(timer);
}
}
function put(app: App, key: string) {
if (requireApiVersion('1.11.4')) app.secretStorage.setSecret(KEY_ID, key);
else app.saveLocalStorage(KEY_ID, key); // older Obsidian has no SecretStorage
}
function get(app: App): string | null {
return requireApiVersion('1.11.4') ? app.secretStorage.getSecret(KEY_ID) : (app.loadLocalStorage(KEY_ID) as string | null);
}
/** Once per device, when the user pastes their key. Returns a message to show, or null on success. */
export async function activateLicense(app: App, licenseKey: string): Promise<string | null> {
const os = Platform.isIosApp ? 'iOS' : Platform.isAndroidApp ? 'Android' : Platform.isMacOS ? 'macOS' : Platform.isWin ? 'Windows' : 'Linux';
try {
const { json } = await call('activate', {
license_key: licenseKey.trim(),
instance_name: `${app.vault.getName()} (Obsidian, ${os})`, // what the buyer sees on the device page
});
if (!json.activated) return json.error ?? 'Activation failed.';
put(app, licenseKey.trim());
app.saveLocalStorage(STATE_ID, { instanceId: json.instance.id, token: json.token });
return null;
} catch {
return 'Could not reach the license server. Check your connection and try again.';
}
}
/** At every launch. Call it from workspace.onLayoutReady, not from onload. */
export async function checkLicense(app: App): Promise<LicenseState> {
const key = get(app);
const saved = app.loadLocalStorage(STATE_ID) as Saved | null;
if (!key || !saved) return 'unlicensed';
try {
const { status, json } = await call('validate', { license_key: key, instance_id: saved.instanceId });
if (status === 200) {
// Keep the new token even when the license is not valid: offline, it then says so.
app.saveLocalStorage(STATE_ID, { ...saved, token: json.token });
return json.valid ? 'licensed' : 'invalid';
}
if (status === 404) {
app.saveLocalStorage(STATE_ID, null); // unknown key, or this device was removed
return 'invalid';
}
} catch {
// No network, or no answer in 8 seconds.
}
// Offline, rate limited (429) or the service is down (503): trust the stored token while it is fresh.
return isLicensed(await verifyToken(saved.token)) ? 'licensed' : 'needs-network';
}
Call it once the workspace is ready, and remember the answer for the session:
this.app.workspace.onLayoutReady(async () => {
this.licensed = (await checkLicense(this.app)) === 'licensed';
});
Outcomes
| Answer | State | What the plugin does |
|---|---|---|
200, valid: true |
licensed | token replaced |
200, valid: false |
invalid | token replaced, key kept: a renewal can revive it |
| 404 | invalid | local state cleared, the user enters the key again |
| 429 or 503 | stored token decides | no retry loop, the next launch asks again |
| timeout or no network | stored token decides | the same |
There is no Retry-After handling because the plugin asks once per launch. A plugin that checks on a timer must wait at least the 60 seconds a 429 asks for.
Obsidian traps
- Mobile has no Node. The mobile guide says Node and Electron APIs are not available there, so anything that imports
osorcryptofrom Node crashes. The code above uses only Obsidian and browser APIs. Take the device name fromPlatformand the vault name, not fromos.hostname(). - No fingerprint. Obsidian gives a plugin no stable machine id. Without a
fingerprint, clearing local storage or reinstalling the plugin activates again and uses another seat until the old one is removed on the device page at clavem.io/licenses/manage. - Community directory rules. The developer policies require your README to say if payment is needed for full access and which remote services the plugin calls. They also forbid plugins that install or update themselves.
- Repeated onload. Disabling and enabling a plugin runs
onloadagain. Keep the licensed flag on the plugin instance and check once per load.
Doing this with Clavem
The License API answers Access-Control-Allow-Origin with a wildcard, and the key is the credential, so no secret ships in the plugin. The API reference lists every status code the code above branches on.
Questions
Why requestUrl and not fetch?
The License API sends Access-Control-Allow-Origin with a wildcard, so fetch works from a plugin too. requestUrl is Obsidian's own API and its typings describe it as free of CORS restrictions, so it does not depend on the server's CORS answer or on the differences between the desktop and mobile apps.
Will the license follow the vault to my phone?
Not if you keep the instance id in device-local storage as below. Each device activates for itself and counts against the device limit. If you store it in data.json, a synced vault carries the id along and the second device never activates.