Clavem

How to validate a license key in a VS Code extension

Call the License API with fetch from the extension host, keep the key in context.secrets, send a salted hash of vscode.env.machineId as the fingerprint, and publish the result with setContext so menus and keybindings can use it. Do not await the check inside activate.

An extension runs in the extension host, a Node process on desktop and a worker in the browser versions of VS Code. Both have fetch, and the License API answers cross-origin calls, so the same code works in either. This page covers the online part: activation, validation and where the key lives. The token check for offline use is in offline verification in a VS Code extension.

The calls

vscode.env.machineId is documented as a unique identifier for the computer. Hash it with a constant of your own, so the value you send cannot be matched to anything outside your extension:

// src/licensing.js
import * as vscode from 'vscode';
import { check } from './token.js'; // the offline check, see the offline page

const BASE = 'https://clavem.io';
const PRODUCT_ID = 75; // from your product page
const PUBLIC_KEY = 'kq1…your key…9fA'; // from your product page
const SALT = 'com.example.inkwell';

export async function fingerprint() {
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${SALT}:${vscode.env.machineId}`));
  return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
}

async function post(action, body, base) {
  try {
    const res = await fetch(`${base}/v1/licenses/${action}`, {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      body: JSON.stringify(body),
      signal: AbortSignal.timeout(8000),
    });
    return { status: res.status, body: await res.json().catch(() => ({})), retryAfter: Number(res.headers.get('retry-after')) || null };
  } catch {
    return null; // offline, DNS failure, timeout
  }
}

export class Licensing {
  constructor(context, base = BASE) { this.context = context; this.base = base; }

  async #load() { const raw = await this.context.secrets.get('license'); return raw ? JSON.parse(raw) : null; }
  #save(license) { return this.context.secrets.store('license', JSON.stringify(license)); }

  async activate(key) {
    const name = `VS Code (${vscode.env.remoteName ?? 'local'})`; // what the customer sees on the device page
    const r = await post('activate', { license_key: key, instance_name: name, fingerprint: await fingerprint() }, this.base);
    if (!r) return { state: 'unavailable' };
    if (r.status === 200 && r.body.instance?.id && r.body.token) {
      await this.#save({ key, instanceId: r.body.instance.id, token: r.body.token });
      await this.#publish('licensed');
      return { state: 'activated' };
    }
    const lic = r.body.license_key;
    if ((r.status === 400 || r.status === 404) && lic?.activation_usage >= lic?.activation_limit && /activation limit/.test(r.body.error ?? ''))
      return { state: 'limit-reached', used: lic.activation_usage, limit: lic.activation_limit };
    return r.status === 400 || r.status === 404 ? { state: 'refused', reason: r.body.error } : { state: 'unavailable', retryAfter: r.retryAfter };
  }

  /** 'licensed' | 'invalid' | 'needs-network' | 'unlicensed'. */
  async check(now = Date.now() / 1000) {
    const saved = await this.#load();
    let state = 'unlicensed';
    if (saved) {
      const r = await post('validate', { license_key: saved.key, instance_id: saved.instanceId }, this.base);
      if (r?.status === 200 && typeof r.body.valid === 'boolean') {
        await this.#save({ ...saved, token: r.body.token ?? saved.token }); // also when not valid: offline, the token then says so
        state = r.body.valid ? 'licensed' : 'invalid';
      } else if (r?.status === 404) {
        await this.context.secrets.delete('license'); // unknown key, or this machine's activation was removed
        state = 'invalid';
      } else {
        // No answer, 429 (Retry-After: 60) or 503 (Retry-After: 5): trust the stored token while it is fresh.
        const result = await check(saved.token, { publicKey: PUBLIC_KEY, productId: PRODUCT_ID, fingerprint: await fingerprint(), now });
        state = result === 'ok' ? 'licensed' : 'needs-network';
      }
    }
    await vscode.commands.executeCommand('setContext', 'inkwell.licensed', state === 'licensed');
    return state;
  }

  #publish(state) { return vscode.commands.executeCommand('setContext', 'inkwell.licensed', state === 'licensed'); }
}

A known key always answers 200, valid or not, so read valid. A 404 is an unknown key, or instance_id not found. A 429 or 503 is not a verdict on the license, and the code falls back to the stored token and tries again on the next start.

Wire it up without blocking activation

// src/extension.js
export function activate(context) {
  const licensing = new Licensing(context);
  context.subscriptions.push(
    vscode.commands.registerCommand('inkwell.enterLicense', async () => {
      const key = await vscode.window.showInputBox({ prompt: 'License key', password: true, ignoreFocusOut: true });
      if (!key) return;
      const result = await licensing.activate(key.trim());
      if (result.state === 'limit-reached')
        vscode.window.showWarningMessage(`This key is active on ${result.used} of ${result.limit} computers.`);
    }),
  );
  void licensing.check(); // do not await: extension activation must not wait for the network
}

Awaiting the check inside activate delays every feature of your extension by the length of the network round trip. Fire it and forget it, and let setContext flip the state when it finishes. In package.json, a menu entry with "when": "inkwell.licensed" then appears once the license is valid. That hides the entry only. Check licensing.check() or the stored state inside the command too, because a command can be run from the palette.

What the code returned

fingerprint length: 64
before: unlicensed
activate: { state: 'activated' }
token fp matches this machine: true
online: licensed
server down: licensed
setContext calls: false, true, true, true

Where the key lives

context.secrets is VS Code’s secret store. The API reference describes it as state that is stored independently of the open workspace, and it is the supported place for credentials. The key, the instance id and the token go in one JSON value. globalState is plain data in VS Code’s own storage, so keep flags there and never a key. Do not put the key in settings.json: it is readable and gets committed to repositories by accident.

Pitfalls specific to VS Code

  • Check fetch at your minimum VS Code version. The extension host’s Node version depends on VS Code’s. Read engines.vscode in your package.json, and test that typeof fetch === 'function' there. Otherwise use the https module.
  • Remote windows. In WSL, SSH and container windows the extension host can run on the remote machine. vscode.env.remoteName says which. Put it in instance_name so the customer can tell the seats apart, and test the fingerprint in each remote type you support.
  • Web extension hosts have no Node modules. crypto.subtle and fetch work there. node:crypto does not.
  • Do not log the key. Output channels are visible to the user and end up in bug reports.

Doing this with Clavem

The License API needs no secret, so nothing sensitive ships in the extension. Plan limits never block validation. See the API reference for every field.

Questions

Where should a VS Code extension store a license key?

In context.secrets, which is SecretStorage. It is documented as storing secrets independently of the open workspace, which is what a license key needs. globalState and settings are plain data, which suits flags and not keys.

What should a VS Code extension send as the fingerprint?

A salted SHA-256 hash of vscode.env.machineId, which VS Code documents as a unique identifier for the computer. Send the hash, never the raw id, and test what it reports in each remote window type you support.

Does a when clause protect a paid command?

Only the menu or keybinding. A command can still be run from the command palette or by another extension. Check the license inside the command handler too, and treat setContext as a user interface hint.

Sources

  1. VS Code API reference, env and ExtensionContext (checked November 2026)