Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(license): bind entitlement to the device and guard against clock rollback

enes7599334883a8
diff --git a/src/main/license.test.ts b/src/main/license.test.ts
index 4632f6768..3dca66b5e 100644
--- a/src/main/license.test.ts
+++ b/src/main/license.test.ts
@@ -1,17 +1,25 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import crypto from 'node:crypto'
-import { mkdtempSync, rmSync } from 'fs'
+import { mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import path from 'path'
import { IPC } from '../shared/ipc'
import type { LicenseStatus } from '../shared/types'
// One temp userData dir per run; hoisted so the electron mock factory can see it.
-const h = vi.hoisted(() => ({ userData: '', publicKeyPem: '' }))
+const h = vi.hoisted(() => ({
+ userData: '',
+ publicKeyPem: '',
+ handlers: {} as Record<string, (...args: unknown[]) => unknown>
+}))
vi.mock('electron', () => ({
app: { getPath: () => h.userData, isPackaged: false },
- ipcMain: { handle: vi.fn() },
+ ipcMain: {
+ handle: (channel: string, fn: (...args: unknown[]) => unknown) => {
+ h.handlers[channel] = fn
+ }
+ },
shell: { openExternal: vi.fn() }
}))
@@ -25,10 +33,10 @@ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519')
h.publicKeyPem = publicKey.export({ type: 'spki', format: 'pem' }).toString()
/** Mint a token the same way the server does: base64url(payload).base64url(sig). */
-function mint(ttlSeconds: number): string {
+function mint(ttlSeconds: number, deviceId = 'test-device'): string {
const payload = Buffer.from(
JSON.stringify({
- deviceId: 'test-device',
+ deviceId,
tier: 'pro',
licenseId: 'lic_test',
iat: Math.floor(Date.now() / 1000),
@@ -71,6 +79,9 @@ describe('license entitlement refresh', () => {
// 8s abort timers stay on the real event loop so awaits actually settle.
vi.useFakeTimers({ toFake: ['setInterval', 'Date'] })
h.userData = mkdtempSync(path.join(tmpdir(), 'nt-license-test-'))
+ h.handlers = {}
+ // Pin this "machine"'s device id so minted tokens match it (device-bound verification).
+ writeFileSync(path.join(h.userData, 'device-id'), 'test-device')
delete process.env.DO_NOT_TRACK
delete process.env.NODETERM_TELEMETRY_DISABLED
process.env.NODETERM_API_BASE = 'http://127.0.0.1:1'
@@ -136,4 +147,40 @@ describe('license entitlement refresh', () => {
await flush()
expect(sent[sent.length - 1].active).toBe(false)
})
+
+ it('rejects a token minted for a different device (copied license.json)', async () => {
+ // Simulates copying license.json + a foreign token onto this machine.
+ fetchMock.mockResolvedValue(
+ jsonResponse({ active: true, token: mint(7 * 24 * 60 * 60, 'other-device') })
+ )
+ const { initLicense } = await import('./license')
+ const { win, sent } = fakeWindow()
+ initLicense(win)
+ await flush()
+
+ expect(sent.length).toBeGreaterThan(0)
+ expect(sent[sent.length - 1].active).toBe(false)
+ })
+
+ it('does not revive an expired token when the system clock is rolled back', async () => {
+ fetchMock.mockResolvedValueOnce(
+ jsonResponse({ active: true, token: mint(7 * 24 * 60 * 60) })
+ )
+ const { initLicense } = await import('./license')
+ const { win, sent } = fakeWindow()
+ initLicense(win)
+ await flush()
+ expect(sent[sent.length - 1].active).toBe(true)
+
+ // Server unreachable from now on (offline grace path), and the token expires in-session.
+ fetchMock.mockRejectedValue(new Error('offline'))
+ await vi.advanceTimersByTimeAsync(7 * 24 * HOUR + 12 * HOUR)
+ await flush()
+
+ // Attacker rolls the clock back before the expiry: exp is "in the future" again,
+ // but the app has already observed a later time — the token must stay dead.
+ vi.setSystemTime(Date.now() - 9 * 24 * HOUR)
+ const status = (await h.handlers[IPC.licenseStatus]()) as LicenseStatus
+ expect(status.active).toBe(false)
+ })
})
diff --git a/src/main/license.ts b/src/main/license.ts
index 18b9d9ccb..98e09d5f0 100644
--- a/src/main/license.ts
+++ b/src/main/license.ts
@@ -1,7 +1,8 @@
// License/premium client. Runs in the main process: stores the key + last entitlement token,
// activates/refreshes against our API, and verifies the token OFFLINE with the embedded
// Ed25519 public key. Offline grace: a still-unexpired stored token keeps premium alive when
-// a refresh can't reach the server.
+// a refresh can't reach the server. The offline check also binds the token to this machine's
+// device id and anchors expiry to the largest observed timestamp (clock-rollback guard).
import { promises as fs, readFileSync } from 'fs'
import path from 'path'
import crypto from 'node:crypto'
@@ -34,6 +35,8 @@ function allowed(): boolean {
interface Stored {
key?: string
token?: string
+ /** Largest unix-seconds timestamp this install has observed — the clock-rollback anchor. */
+ lastSeen?: number
}
function file(): string {
@@ -58,6 +61,10 @@ interface Payload {
}
// Offline verification of our compact Ed25519 token: base64url(payload).base64url(sig).
+// Beyond the signature, the token must be minted for THIS machine (a copied license.json
+// from another install must not validate), and its expiry is checked against the largest
+// timestamp we've ever observed — not just Date.now() — so rolling the system clock back
+// can't revive an expired token (see lastSeen).
function verify(token: string | undefined): Payload | null {
if (!token || !ENTITLEMENT_PUBLIC_KEY) return null
const dot = token.indexOf('.')
@@ -68,7 +75,9 @@ function verify(token: string | undefined): Payload | null {
const key = crypto.createPublicKey(ENTITLEMENT_PUBLIC_KEY)
if (!crypto.verify(null, Buffer.from(p), key, Buffer.from(s, 'base64url'))) return null
const payload = JSON.parse(Buffer.from(p, 'base64url').toString('utf-8')) as Payload
- if (typeof payload.exp !== 'number' || payload.exp * 1000 <= Date.now()) return null
+ if (payload.deviceId !== getDeviceId()) return null
+ const now = Math.max(Date.now(), (load().lastSeen ?? 0) * 1000)
+ if (typeof payload.exp !== 'number' || payload.exp * 1000 <= now) return null
return payload
} catch {
return null
@@ -155,7 +164,7 @@ export function initLicense(win: BrowserWindow): void {
}
const r = await getJson(`/v1/license/status?deviceId=${encodeURIComponent(deviceId)}`)
if (r.active && r.token) {
- await save({ key: load().key, token: r.token })
+ await save({ ...load(), token: r.token })
broadcast(statusFrom(r.token))
polling = false
return
@@ -169,7 +178,7 @@ export function initLicense(win: BrowserWindow): void {
ipcMain.handle(IPC.licenseActivate, async (_e, key: string) => {
const r = await call('/v1/license/activate', { key: String(key).trim(), deviceId })
- if (r.token) await save({ key: String(key).trim(), token: r.token })
+ if (r.token) await save({ ...load(), key: String(key).trim(), token: r.token })
const status = statusFrom(r.token, r.error ?? null)
broadcast(status)
return status
@@ -178,12 +187,20 @@ export function initLicense(win: BrowserWindow): void {
ipcMain.handle(IPC.licenseDeactivate, async () => {
const stored = load()
if (stored.key) await call('/v1/license/deactivate', { key: stored.key, deviceId })
- await save({})
+ await save({ lastSeen: stored.lastSeen }) // keep the clock anchor across deactivations
const status = statusFrom(undefined)
broadcast(status)
return status
})
+ // Advance the clock-rollback anchor (see verify()): record the largest timestamp we've
+ // observed, so setting the system clock back can't revive an expired token.
+ const bumpLastSeen = async (): Promise<void> => {
+ const stored = load()
+ const now = Math.floor(Date.now() / 1000)
+ if (now > (stored.lastSeen ?? 0)) await save({ ...stored, lastSeen: now })
+ }
+
// Re-establish entitlement, keeping the last valid token on failure (offline grace).
const refresh = async (): Promise<void> => {
const stored = load()
@@ -191,7 +208,7 @@ export function initLicense(win: BrowserWindow): void {
// Key-paste flow: refresh against the stored key.
const r = await call('/v1/license/refresh', { key: stored.key, deviceId })
if (r.token) {
- await save({ key: stored.key, token: r.token })
+ await save({ ...stored, token: r.token })
broadcast(statusFrom(r.token))
} else {
broadcast(statusFrom(stored.token, r.error ?? null)) // offline grace
@@ -201,7 +218,7 @@ export function initLicense(win: BrowserWindow): void {
// after the in-app Upgrade poll window, and every later relaunch.
const r = await getJson(`/v1/license/status?deviceId=${encodeURIComponent(deviceId)}`)
if (r.active && r.token) {
- await save({ key: stored.key, token: r.token })
+ await save({ ...stored, token: r.token })
broadcast(statusFrom(r.token))
} else if (r.error === 'offline' || r.error === 'network' || r.error === 'disabled') {
// Couldn't reach the server → offline grace: keep the last valid token.
@@ -209,13 +226,13 @@ export function initLicense(win: BrowserWindow): void {
} else {
// Server responded: this device is no longer entitled (canceled / suspended / expired)
// → drop Pro and clear the cached token, even though it hasn't expired yet.
- if (stored.token) await save({ key: stored.key })
+ if (stored.token) await save({ ...stored, token: undefined })
broadcast(statusFrom(undefined))
}
}
}
// On launch + every 6h while the app stays open (see REFRESH_INTERVAL_MS).
- void refresh()
- setInterval(() => void refresh(), REFRESH_INTERVAL_MS).unref()
+ void bumpLastSeen().then(refresh)
+ setInterval(() => void bumpLastSeen().then(refresh), REFRESH_INTERVAL_MS).unref()
}