Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
KEYMINT_CLIENT_API_KEY=km_client_your_key_here
KEYMINT_PRODUCT_ID=prod_your_product_id_here
# Optional: point at a different API, e.g. for local testing
# KEYMINT_BASE_URL=https://api.keymint.dev
11 changes: 8 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,17 @@ Copy `.env.example` to `.env` and set:
|---|---|
| `KEYMINT_CLIENT_API_KEY` | Client API key from [Keymint Dashboard](https://app.keymint.dev) |
| `KEYMINT_PRODUCT_ID` | Your product ID |
| `KEYMINT_BASE_URL` | Optional. API base URL, defaults to `https://api.keymint.dev` |

`.env` is loaded with `dotenv` when the app starts. If the variables are missing, the activation dialog says so instead of the app crashing.

## What's Included

- **Activation dialog** — prompts the user for a license key on first launch
- **Machine binding** — locks the license to the device via `node-machine-id`
- **Machine binding** — locks the license to a stable installation ID from `KeyMint.getOrCreateInstallationId()`
- **Encrypted storage** — stores license state in `electron-store` with encryption
- **Preload bridge** — secure IPC via `contextBridge` (no `nodeIntegration`)
- **Health checks** — re-validates the license on subsequent launches
- **Health checks** — re-validates the license on launch and every 24 hours. A rejected license (revoked, expired, over its device limit) returns the user to activation; if the server can't be reached, the app keeps working with the cached state

## Project Structure

Expand All @@ -34,7 +37,9 @@ src/
├── main/
│ ├── index.ts # App lifecycle, window management
│ ├── ipc.ts # IPC handlers (activate, deactivate, getStatus)
│ └── license.ts # Keymint API calls + machine ID
│ ├── license.ts # Keymint API calls, health check, machine ID
│ ├── store.ts # Encrypted license state (electron-store)
│ └── events.ts # Activation event from IPC to the window manager
├── preload/
│ └── index.ts # contextBridge exposing licenseAPI
└── renderer/
Expand Down
23 changes: 18 additions & 5 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"smoke": "node scripts/smoke.mjs"
},
"dependencies": {
"dotenv": "^16.4.5",
"electron-store": "^8.2.0",
"keymint": "^1.5.0"
},
Expand Down
4 changes: 4 additions & 0 deletions src/main/events.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { EventEmitter } from 'events';

// Lets ipc.ts tell index.ts about license changes without a circular import.
export const licenseEvents = new EventEmitter();
55 changes: 47 additions & 8 deletions src/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
// Load .env before anything reads process.env (license.ts reads it on import).
import 'dotenv/config';
import { app, BrowserWindow } from 'electron';
import * as path from 'path';
import './ipc';
import { checkLicenseHealth } from './license';
import { store, clearLicense } from './store';
import { licenseEvents } from './events';

const HEALTH_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;

let mainWindow: BrowserWindow | null = null;
let activationWindow: BrowserWindow | null = null;
Expand All @@ -16,6 +23,9 @@ function createMainWindow() {
},
});
mainWindow.loadFile(path.join(__dirname, '../renderer/app.html'));
mainWindow.on('closed', () => {
mainWindow = null;
});
}

function createActivationWindow() {
Expand All @@ -36,24 +46,53 @@ function createActivationWindow() {
});
}

app.whenReady().then(() => {
// Always show activation dialog — the renderer checks stored state
createActivationWindow();
// Open the app before the activation dialog closes itself, so closing the
// dialog never leaves zero windows (which quits the app on Windows/Linux).
licenseEvents.on('activated', () => {
if (!mainWindow) createMainWindow();
});

app.on('window-all-closed', () => {
// The activation window opens first; when main closes, quit
if (mainWindow) {
mainWindow = null;
// A rejected license (revoked, expired, over its device limit) sends the user
// back to activation. Network failures keep the cached state.
async function revalidate(): Promise<boolean> {
const licenseKey = store.get('licenseKey');
if (!licenseKey || store.get('activated') !== true) return false;

if ((await checkLicenseHealth(licenseKey)) === 'rejected') {
clearLicense();
return false;
}
return true;
}

app.whenReady().then(async () => {
if (await revalidate()) {
createMainWindow();
} else {
createActivationWindow();
}

setInterval(async () => {
if (!(await revalidate()) && mainWindow) {
mainWindow.close();
createActivationWindow();
}
}, HEALTH_CHECK_INTERVAL_MS);
});

app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});

app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createActivationWindow();
if (store.get('activated') === true) {
createMainWindow();
} else {
createActivationWindow();
}
}
});

Expand Down
19 changes: 4 additions & 15 deletions src/main/ipc.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,17 @@
import { ipcMain } from 'electron';
import Store from 'electron-store';
import {
activateLicense,
deactivateLicense,
} from './license';

interface LicenseStore {
licenseKey?: string;
activated?: boolean;
}

const store = new Store<LicenseStore>({
name: 'license',
encryptionKey: 'electron-license-starter',
});
import { store, clearLicense } from './store';
import { licenseEvents } from './events';

ipcMain.handle('license:activate', async (_event, licenseKey: string) => {
const result = await activateLicense(licenseKey);
if (result.success) {
store.set('licenseKey', licenseKey);
store.set('activated', true);
licenseEvents.emit('activated');
}
return result;
});
Expand All @@ -38,10 +30,7 @@ ipcMain.handle('license:deactivate', async () => {
if (!key) return { success: false, message: 'No license found' };

const success = await deactivateLicense(key);
if (success) {
store.delete('licenseKey');
store.delete('activated');
}
if (success) clearLicense();
return { success, message: success ? 'Deactivated' : 'Failed' };
});

Expand Down
78 changes: 59 additions & 19 deletions src/main/license.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,101 @@ import { KeyMint } from 'keymint';

const CLIENT_API_KEY = process.env.KEYMINT_CLIENT_API_KEY || '';
const PRODUCT_ID = process.env.KEYMINT_PRODUCT_ID || '';
// Optional; defaults to https://api.keymint.dev.
const BASE_URL = process.env.KEYMINT_BASE_URL || undefined;

const client = new KeyMint(CLIENT_API_KEY);
const CONFIG_ERROR =
'Keymint is not configured: set KEYMINT_CLIENT_API_KEY and KEYMINT_PRODUCT_ID in .env';

// Created on first use so a missing key shows a message instead of
// crashing the app at startup (the SDK constructor throws on an empty key).
let client: KeyMint | null = null;
function getClient(): KeyMint | null {
if (!CLIENT_API_KEY || !PRODUCT_ID) return null;
client ??= new KeyMint(CLIENT_API_KEY, BASE_URL);
return client;
}

export function getHostId(): string {
return KeyMint.getOrCreateInstallationId();
}

/**
* The SDK throws on any non-2xx response. 401 (invalid, expired, blocked or
* not allowed on this device), 402 (vendor subscription lapsed), 403
* (activation limit reached) and 404 (product deleted or deactivated, or the
* license removed) mean the license was rejected. Anything else — no
* response, 429, 5xx — is transient and must not log the user out.
*/
function isRejected(error: unknown): boolean {
const status = (error as { status?: number } | null)?.status;
return status === 401 || status === 402 || status === 403 || status === 404;
}

function errorMessage(error: unknown, fallback: string): string {
const message = (error as { message?: string } | null)?.message;
return message || fallback;
}

export async function activateLicense(licenseKey: string): Promise<{
success: boolean;
message: string;
}> {
const sdk = getClient();
if (!sdk) return { success: false, message: CONFIG_ERROR };

try {
const result = await client.activateKey({
const result = await sdk.activateKey({
productId: PRODUCT_ID,
licenseKey,
hostId: getHostId(),
});

if (result.code === 0) {
return { success: true, message: result.message || 'License valid' };
}
return { success: true, message: result.message || 'License valid' };
} catch (error) {
return {
success: false,
message: result.message || 'Activation failed',
};
} catch (error: any) {
return {
success: false,
message: error.message || 'Network error during activation',
message: isRejected(error)
? errorMessage(error, 'License rejected')
: 'Could not reach the licensing server. Check your connection and try again.',
};
}
}

export async function deactivateLicense(licenseKey: string): Promise<boolean> {
const sdk = getClient();
if (!sdk) return false;

try {
const result = await client.deactivateKey({
await sdk.deactivateKey({
productId: PRODUCT_ID,
licenseKey,
hostId: getHostId(),
});
return result.code === 0;
return true;
} catch {
return false;
}
}

export async function checkLicenseHealth(licenseKey: string): Promise<boolean> {
export type LicenseHealth = 'valid' | 'rejected' | 'unknown';

/**
* Re-validates a stored license. Re-activating on the same device does not
* use another seat. Returns 'unknown' when the server can't be reached, so
* callers keep the cached state instead of locking the user out offline.
*/
export async function checkLicenseHealth(licenseKey: string): Promise<LicenseHealth> {
const sdk = getClient();
if (!sdk) return 'unknown';

try {
const result = await client.activateKey({
await sdk.activateKey({
productId: PRODUCT_ID,
licenseKey,
hostId: getHostId(),
});
return result.code === 0;
} catch {
return false;
return 'valid';
} catch (error) {
return isRejected(error) ? 'rejected' : 'unknown';
}
}
16 changes: 16 additions & 0 deletions src/main/store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Store from 'electron-store';

export interface LicenseStore {
licenseKey?: string;
activated?: boolean;
}

export const store = new Store<LicenseStore>({
name: 'license',
encryptionKey: 'electron-license-starter',
});

export function clearLicense(): void {
store.delete('licenseKey');
store.delete('activated');
}
Loading