From f6b968aba0668b7e720a8024141d5f2c0605bbe1 Mon Sep 17 00:00:00 2001 From: catsika Date: Mon, 12 Oct 2026 23:49:00 +0000 Subject: [PATCH 1/2] fix: load .env, open the app after activation, and re-check licenses - Load .env with dotenv. Previously the documented `cp .env.example .env` flow left the key empty and `new KeyMint('')` threw at startup. - Create the SDK client lazily and show a configuration message instead of crashing when the variables are missing. - Open the main window when activation succeeds. Before, the activation dialog closed itself and nothing opened the app (it quit on Windows/Linux). - Re-validate on launch and every 24 hours. The SDK throws on non-2xx, so treat 401/402/403 as a rejected license and anything else (offline, 429, 5xx) as unknown, keeping the cached state. - Optional KEYMINT_BASE_URL; README matches the code. --- .env.example | 2 ++ README.md | 11 +++++-- package-lock.json | 23 +++++++++++--- package.json | 1 + src/main/events.ts | 4 +++ src/main/index.ts | 55 +++++++++++++++++++++++++++----- src/main/ipc.ts | 19 +++-------- src/main/license.ts | 77 ++++++++++++++++++++++++++++++++++----------- src/main/store.ts | 16 ++++++++++ 9 files changed, 158 insertions(+), 50 deletions(-) create mode 100644 src/main/events.ts create mode 100644 src/main/store.ts diff --git a/.env.example b/.env.example index 92c1abd..265808e 100644 --- a/.env.example +++ b/.env.example @@ -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 diff --git a/README.md b/README.md index f3aaa17..015ebe4 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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/ diff --git a/package-lock.json b/package-lock.json index ca880dc..4f3a7a6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "keymint-electron-starter", "version": "1.0.0", "dependencies": { + "dotenv": "^16.4.5", "electron-store": "^8.2.0", "keymint": "^1.5.0" }, @@ -1890,13 +1891,15 @@ } }, "node_modules/dotenv": { - "version": "9.0.2", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-9.0.2.tgz", - "integrity": "sha512-I9OvvrHp4pIARv4+x9iuewrWycX6CcZtoAu1XrzPxc5UygMJXJZYmBsynku8IkrJwgypE5DGNjDPmPRhDCptUg==", - "dev": true, + "version": "16.6.1", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.6.1.tgz", + "integrity": "sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==", "license": "BSD-2-Clause", "engines": { - "node": ">=10" + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" } }, "node_modules/dotenv-expand": { @@ -3670,6 +3673,16 @@ "node": ">=12.0.0" } }, + "node_modules/read-config-file/node_modules/dotenv": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-9.0.2.tgz", + "integrity": "sha512-I9OvvrHp4pIARv4+x9iuewrWycX6CcZtoAu1XrzPxc5UygMJXJZYmBsynku8IkrJwgypE5DGNjDPmPRhDCptUg==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=10" + } + }, "node_modules/readable-stream": { "version": "3.6.2", "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", diff --git a/package.json b/package.json index c762460..1b7b85c 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,7 @@ "smoke": "node scripts/smoke.mjs" }, "dependencies": { + "dotenv": "^16.4.5", "electron-store": "^8.2.0", "keymint": "^1.5.0" }, diff --git a/src/main/events.ts b/src/main/events.ts new file mode 100644 index 0000000..c4ec7c9 --- /dev/null +++ b/src/main/events.ts @@ -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(); diff --git a/src/main/index.ts b/src/main/index.ts index 8b45823..eb1a634 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -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; @@ -16,6 +23,9 @@ function createMainWindow() { }, }); mainWindow.loadFile(path.join(__dirname, '../renderer/app.html')); + mainWindow.on('closed', () => { + mainWindow = null; + }); } function createActivationWindow() { @@ -36,16 +46,41 @@ 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 { + 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(); } @@ -53,7 +88,11 @@ app.on('window-all-closed', () => { app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) { - createActivationWindow(); + if (store.get('activated') === true) { + createMainWindow(); + } else { + createActivationWindow(); + } } }); diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 4d795ac..f6cd814 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -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({ - 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; }); @@ -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' }; }); diff --git a/src/main/license.ts b/src/main/license.ts index e2aa100..33c28eb 100644 --- a/src/main/license.ts +++ b/src/main/license.ts @@ -2,61 +2,100 @@ 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) and 403 + * (activation limit reached) 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; +} + +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 { + 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 { +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 { + 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'; } } diff --git a/src/main/store.ts b/src/main/store.ts new file mode 100644 index 0000000..520f233 --- /dev/null +++ b/src/main/store.ts @@ -0,0 +1,16 @@ +import Store from 'electron-store'; + +export interface LicenseStore { + licenseKey?: string; + activated?: boolean; +} + +export const store = new Store({ + name: 'license', + encryptionKey: 'electron-license-starter', +}); + +export function clearLicense(): void { + store.delete('licenseKey'); + store.delete('activated'); +} From 9a819f24c3481563e3eab0dda45d9dbe33bd57e8 Mon Sep 17 00:00:00 2001 From: catsika Date: Sat, 17 Oct 2026 23:35:09 +0000 Subject: [PATCH 2/2] fix: treat 404 from activation as a rejected license Keymint returns 404 when the product is deleted or deactivated, or the license was removed. Treating it as transient kept the cached license valid indefinitely; it now logs the user out like 401/402/403. --- src/main/license.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/main/license.ts b/src/main/license.ts index 33c28eb..4af9ac7 100644 --- a/src/main/license.ts +++ b/src/main/license.ts @@ -23,13 +23,14 @@ export function getHostId(): string { /** * The SDK throws on any non-2xx response. 401 (invalid, expired, blocked or - * not allowed on this device), 402 (vendor subscription lapsed) and 403 - * (activation limit reached) mean the license was rejected. Anything else — - * no response, 429, 5xx — is transient and must not log the user out. + * 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; + return status === 401 || status === 402 || status === 403 || status === 404; } function errorMessage(error: unknown, fallback: string): string {