From 33052ffc0f83c96d2bb98127e010d32ca758a3b7 Mon Sep 17 00:00:00 2001 From: ZTEMPCAMP <161483176+zdevzone@users.noreply.github.com> Date: Sun, 18 Oct 2026 13:28:53 +0300 Subject: [PATCH] Add import licensing, additive renewals and approved recovery (#59) * Implement import licensing, additive renewals and approved recovery * Bound SDK public key parsing and remove backtracking regex --------- Co-authored-by: Abraham Bekele --- AGENTS.md | 4 +- docs/api.md | 24 + docs/cli.md | 15 + docs/client-openapi.json | 535 ++++++++++++++- docs/dependent-app-integration.md | 2 + docs/import-licensing.md | 129 ++++ docs/index.md | 1 + docs/integration-review.md | 2 + docs/studio-proof-contract.md | 2 + docs/verify-token.md | 2 + examples/keyforge-node.ts | 11 +- packages/create-keyforge/src/template.mjs | 1 + packages/keyforge-client/README.md | 16 + .../skill/keyforge-integrate/SKILL.md | 2 + .../references/integration.md | 6 + packages/keyforge-client/src/client.ts | 386 ++++++++++- packages/keyforge-client/src/index.ts | 4 +- packages/keyforge-client/src/tokens.ts | 84 ++- packages/keyforge-client/src/types.ts | 19 +- packages/keyforge-client/src/usage.ts | 148 ++++ scripts/docs-smoke.mjs | 1 + scripts/generate-api-docs.mjs | 1 + scripts/generate-client-openapi.ts | 37 +- scripts/license-tool.mjs | 138 +++- scripts/package-smoke.mjs | 7 +- src/app.ts | 4 +- src/finance.ts | 6 + src/import-licensing.ts | 645 ++++++++++++++++++ src/platform.ts | 110 ++- src/token-contract.ts | 43 +- test/client-sdk.test.ts | 24 +- test/docs.test.ts | 1 + test/import-licensing.test.ts | 636 +++++++++++++++++ test/roles.test.ts | 26 + ui/src/docs/catalog.ts | 8 + ui/src/docs/content.ts | 1 + 36 files changed, 3031 insertions(+), 50 deletions(-) create mode 100644 docs/import-licensing.md create mode 100644 packages/keyforge-client/src/usage.ts create mode 100644 src/import-licensing.ts create mode 100644 test/import-licensing.test.ts diff --git a/AGENTS.md b/AGENTS.md index 8c51b6e..e06bb60 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,8 @@ Instructions for AI coding agents working in this repository. - `src/platform-store.ts`: scoped records, serialized writes and encryption - `src/backups.ts`: encrypted jobs, schedules, downloads and verification - `src/postgres-archive.ts`: bounded portable application-data archives for serverless hosts -- `src/token-contract.ts`: license v4 and trial v2 schemas +- `src/token-contract.ts`: legacy v4/v2, opt-in import-license v5/trial v3, and separate recovery v1 schemas +- `src/import-licensing.ts`: opt-in cumulative allocations, atomic renewal sales, account ownership and approved recovery - `src/db.ts`: dual-engine historical ledger repository and migrations - `src/sign.ts`: Ed25519 signing and token helpers - `src/auth.ts`: Better Auth setup for the console (admin plugin, role backfill) @@ -72,6 +73,7 @@ Instructions for AI coding agents working in this repository. - Do not change token signing format without coordinating client verification changes. - Preserve fail-closed behavior when signing key is missing. - Token payload changes require a version bump (`v`) and a compat story. +- Import licensing is explicit per-product opt-in. Never silently adopt a legacy license, infer zero from missing local usage, refill on payment/refresh, or accept a recovery artifact as a license. Server mutations and licensing events share the existing transaction; SDK import mutations require host-supplied atomic CAS and a shared media transaction. Preserve unknown lifetime history as unknown after recovery. - Run `vp run typecheck` and `vp run test` after code changes before proposing completion. - Config schema changes must keep `packages/create-keyforge` generating valid output; `test/create-keyforge.test.ts` is what catches it. diff --git a/docs/api.md b/docs/api.md index d3a0a58..c27714e 100644 --- a/docs/api.md +++ b/docs/api.md @@ -74,6 +74,7 @@ The table is generated from an isolated server's route registration. Product-sco | GET | `/admin/products/:productId/finance/report` | | POST | `/admin/products/:productId/finance/sales` | | POST | `/admin/products/:productId/finance/sales/:saleId/entries` | +| PUT | `/admin/products/:productId/import-policy` | | GET | `/admin/products/:productId/installations` | | POST | `/admin/products/:productId/keys/:kid/activate` | | POST | `/admin/products/:productId/keys/stage` | @@ -86,7 +87,11 @@ The table is generated from an isolated server's route registration. Product-sco | GET | `/admin/products/:productId/licenses/:id/activations` | | POST | `/admin/products/:productId/licenses/:id/deactivate` | | GET | `/admin/products/:productId/licenses/:id/delivery` | +| GET | `/admin/products/:productId/licenses/:id/import-account` | +| POST | `/admin/products/:productId/licenses/:id/import-account` | | POST | `/admin/products/:productId/licenses/:id/key` | +| POST | `/admin/products/:productId/licenses/:id/renew` | +| POST | `/admin/products/:productId/licenses/:id/replace-key` | | POST | `/admin/products/:productId/licenses/:id/revoke` | | GET | `/admin/products/:productId/machines` | | POST | `/admin/products/:productId/machines/:id/clear` | @@ -97,6 +102,9 @@ The table is generated from an isolated server's route registration. Product-sco | PUT | `/admin/products/:productId/notifications/preferences` | | POST | `/admin/products/:productId/notifications/read` | | PUT | `/admin/products/:productId/plans/:id` | +| GET | `/admin/products/:productId/recovery-requests` | +| POST | `/admin/products/:productId/recovery-requests/:id/approve` | +| POST | `/admin/products/:productId/recovery-requests/:id/reject` | | GET | `/admin/products/:productId/reports` | | GET | `/admin/products/:productId/support` | | GET | `/admin/products/:productId/support/:id` | @@ -122,6 +130,8 @@ The table is generated from an isolated server's route registration. Product-sco | GET | `/v1/products/:productId/installations/:installationId/notifications` | | PUT | `/v1/products/:productId/installations/:installationId/notifications/preferences` | | POST | `/v1/products/:productId/installations/:installationId/notifications/read` | +| POST | `/v1/products/:productId/installations/:installationId/recovery-requests` | +| POST | `/v1/products/:productId/installations/:installationId/recovery-requests/:id/claim` | | GET | `/v1/products/:productId/installations/:installationId/support` | | POST | `/v1/products/:productId/installations/:installationId/support` | | GET | `/v1/products/:productId/installations/:installationId/support/:id` | @@ -139,6 +149,7 @@ Domain errors use error/message/retryable/serverTime; rate limiting may include | Code | | --- | +| `account_mismatch` | | `activation_limit_reached` | | `admin_disabled` | | `admin_unauthorized` | @@ -183,12 +194,16 @@ Domain errors use error/message/retryable/serverTime; rate limiting may include | `future_date` | | `historical_overpayment` | | `idempotency_conflict` | +| `import_account_missing` | +| `import_account_required` | +| `import_migration_required` | | `initial_sale_exists` | | `installation_unauthorized` | | `insufficient_role` | | `internal_error` | | `invalid_assignee` | | `invalid_date` | +| `invalid_import_allowance` | | `invalid_license_request` | | `invalid_message` | | `invalid_origin` | @@ -213,6 +228,7 @@ Domain errors use error/message/retryable/serverTime; rate limiting may include | `original_key_unavailable` | | `overpayment` | | `paid_license_required` | +| `policy_locked` | | `price_required` | | `product_archived` | | `product_exists` | @@ -220,7 +236,12 @@ Domain errors use error/message/retryable/serverTime; rate limiting may include | `rate_limited` | | `reason_required` | | `reauthentication_required` | +| `recovery_rate_limited` | +| `recovery_required` | +| `recovery_stale` | +| `recovery_unavailable` | | `registry_disabled` | +| `renewal_unavailable` | | `request_closed` | | `request_not_found` | | `request_pending` | @@ -232,6 +253,7 @@ Domain errors use error/message/retryable/serverTime; rate limiting may include | `revision_required` | | `service_unauthorized` | | `signing_unavailable` | +| `single_installation_required` | | `storage_credentials_required` | | `storage_not_saved` | | `support_rate_limited` | @@ -244,10 +266,12 @@ Domain errors use error/message/retryable/serverTime; rate limiting may include | `unknown_meter_or_license` | | `unknown_plan` | | `unknown_product` | +| `unknown_recovery` | | `unknown_sale` | | `unknown_staged_key` | | `unknown_support_request` | | `usage_unauthorized` | +| `use_license_renewal` | | `verification_unconfigured` | ## Console reports diff --git a/docs/cli.md b/docs/cli.md index 89aae38..c125e64 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -75,3 +75,18 @@ Restore current archives using `vp run backup:restore --file --job { try { const result = await this.options.deviceSignalsProvider!({ @@ -248,7 +297,7 @@ export class KeyForgeClient { machineSignals: report.signals, }); state.deviceSignals = report; - await this.options.storage.save(state); + await this.persist(state); return structuredClone(report); }); } @@ -360,11 +409,13 @@ export class KeyForgeClient { if (response.trial) { const grant = await verifySignedToken(response.trial.token, this.context(state)); if (grant.kind !== "trial") throw new TokenError("unexpected_token_kind"); + if (grant.v === 3 && grant.converted && state.importUsage) + state.importUsage.trialConverted = true; state.trialToken = response.trial.token; this.observe(state, grant); } state.registered = true; - await this.options.storage.save(state); + await this.persist(state); } private observe(state: ClientState, grant?: SignedToken) { state.lastObservedTime = Math.max( @@ -373,12 +424,12 @@ export class KeyForgeClient { grant ? Date.parse(grant.issuedAt) : 0, ); } - private async evaluate(state: ClientState): Promise { + private async evaluate(state: ClientState, persistClock = true): Promise { const now = this.now(); if (now + (this.options.clockToleranceMs ?? 300000) < state.lastObservedTime) return { state: "reconnect_required", reason: "clock_rollback" }; this.observe(state); - await this.options.storage.save(state); + if (persistClock) await this.persist(state); if (state.denial) return { state: "reconnect_required", reason: state.denial }; const token = state.licenseToken ?? (state.trialStarted ? state.trialToken : null); if (!token) return { state: "unlicensed", reason: "activation_required" }; @@ -399,14 +450,37 @@ export class KeyForgeClient { return { state: "expired", reason: "license_expired" }; if (Date.parse(grant.offlineGraceUntil) <= time) return { state: "reconnect_required", reason: "offline_grace_expired" }; + if (grant.v === 5) { + const usage = state.importUsage; + if ( + !usage?.integrity || + usage.accountId !== grant.accountId || + usage.recoveryGeneration !== grant.recoveryGeneration + ) + return { state: "recovery_required", reason: "usage_integrity_required" }; + if (usage.paidConsumed >= grant.paidImportsGranted) + return { state: "quota_exhausted", reason: "paid_imports_exhausted" }; + } const deadline = new Date( Math.min( Date.parse(grant.offlineGraceUntil), grant.expiresAt ? Date.parse(grant.expiresAt) : Infinity, ), ).toISOString(); - return { state: "licensed", token: grant, entitlements: grant.entitlements, deadline }; + return { + state: "licensed", + token: grant, + entitlements: grant.entitlements, + deadline, + ...(grant.v === 5 + ? { remainingImports: grant.paidImportsGranted - state.importUsage!.paidConsumed } + : {}), + }; } + if (state.importUsage?.trialConverted || (grant.v === 3 && grant.converted)) + return { state: "expired", reason: "trial_converted" }; + if (grant.v === 3 && !state.importUsage?.integrity) + return { state: "recovery_required", reason: "usage_integrity_required" }; if (grant.verdict !== "fresh") return { state: "expired", reason: "trial_spent" }; if (grant.expiresAt !== null && Date.parse(grant.expiresAt) <= time) return { state: "expired", reason: "trial_expired" }; @@ -430,6 +504,8 @@ export class KeyForgeClient { installationId: state.installationId, trialAvailable: grant?.kind === "trial" && + !state.importUsage?.trialConverted && + !(grant.v === 3 && grant.converted) && grant.verdict === "fresh" && (grant.expiresAt === null || Date.parse(grant.expiresAt) > Math.max(this.now(), state.lastObservedTime)) && @@ -442,11 +518,12 @@ export class KeyForgeClient { const state = await this.load(), wasRegistered = state.registered; await this.ensureRegistered(state); + if (state.importUsage?.trialConverted) throw new KeyForgeError("trial_converted"); // Explicit trial onboarding requires connectivity even if registration was completed earlier. if (wasRegistered) await this.request(state, "POST", this.productPath("/register"), state.registration); state.trialStarted = true; - await this.options.storage.save(state); + await this.persist(state); return this.evaluate(state); }); } @@ -464,10 +541,17 @@ export class KeyForgeClient { (authorization.remaining !== null && units > authorization.remaining) ) throw new KeyForgeError("trial_unavailable"); + if (authorization.token.v === 3) this.requireAtomicStorage(); if (!Number.isSafeInteger(state.trialConsumed + units)) throw new KeyForgeError("invalid_units"); state.trialConsumed += units; - await this.options.storage.save(state); + if (state.importUsage) { + if (!Number.isSafeInteger(state.importUsage.lifetimeImports + units)) + throw new KeyForgeError("invalid_units"); + state.importUsage.trialConsumed = state.trialConsumed; + state.importUsage.lifetimeImports += units; + } + await this.persist(state); return this.evaluate(state); }); } @@ -500,6 +584,51 @@ export class KeyForgeClient { const grant = await verifySignedToken(token, this.context(state)); if (grant.kind !== "license" || (expectedLicenseId && grant.licenseId !== expectedLicenseId)) throw new TokenError("unexpected_license"); + if (grant.v === 4 && state.importUsage?.accountId) throw new TokenError("protocol_downgrade"); + if (grant.v === 4 && state.importUsage) state.importUsage.legacyPaidSeen = true; + if (grant.v === 5) { + this.requireAtomicStorage(); + const usage = state.importUsage; + if (!usage || (usage.legacyPaidSeen && !usage.legacyVerified)) { + state.denial = "usage_migration_required"; + await this.persist(state); + throw new KeyForgeError("usage_migration_required"); + } + if (usage.accountId && usage.accountId !== grant.accountId) + throw new TokenError("account_mismatch"); + if ( + grant.authorizationRevision < usage.authorizationRevision || + grant.recoveryGeneration < usage.recoveryGeneration || + grant.paidImportsGranted < usage.granted + ) + throw new TokenError("stale_grant"); + // Mint time / lease renewal may change at the same revision; entitlement terms may not. + const terms = await usageDigest({ + accountId: grant.accountId, + licenseId: grant.licenseId, + plan: grant.plan, + entitlements: grant.entitlements, + issuedTo: grant.issuedTo, + subject: grant.subject, + expiresAt: grant.expiresAt, + status: grant.status === "expired" ? "active" : grant.status, + granted: grant.paidImportsGranted, + generation: grant.recoveryGeneration, + }); + if ( + grant.authorizationRevision === usage.authorizationRevision && + usage.termsHash && + usage.termsHash !== terms + ) + throw new TokenError("revision_conflict"); + usage.accountId = grant.accountId; + usage.authorizationRevision = grant.authorizationRevision; + usage.granted = grant.paidImportsGranted; + usage.termsHash = terms; + usage.trialConverted = true; + state.trialStarted = false; + if (grant.recoveryGeneration !== usage.recoveryGeneration) usage.integrity = false; + } if (state.licenseToken) { let prior: SignedToken | null = null; try { @@ -521,7 +650,7 @@ export class KeyForgeClient { state.denial = null; this.observe(state, grant); // Persist authenticated negative status before returning it, including HTTP 200 revocations. - await this.options.storage.save(state); + await this.persist(state); } refresh(): Promise { return this.serial(async () => { @@ -544,10 +673,11 @@ export class KeyForgeClient { "unknown_license", "unknown_product", "product_archived", + "recovery_required", ].includes(error.code) ) { state.denial = error.code; - await this.options.storage.save(state); + await this.persist(state); } throw error; } @@ -568,7 +698,239 @@ export class KeyForgeClient { state.licenseToken = null; state.trialStarted = false; state.denial = null; - await this.options.storage.save(state); + await this.persist(state); + }); + } + /** Initialize a legacy client's VERIFIED surviving history once; never use this to repair corrupt usage. */ + adoptLegacyImportUsage(input: { + lifetimeImports: number; + paidConsumed: number; + trialConsumed: number; + lifetimeKnown: boolean; + }) { + return this.serial(async () => { + this.requireAtomicStorage(); + const state = await this.load(); + if (state.importUsage?.accountId || state.importUsage?.legacyVerified) + throw new KeyForgeError("usage_already_initialized"); + const previous = state.importUsage ?? emptyImportUsage(); + const usage = importUsageSchema.parse({ ...previous, ...input, legacyVerified: true }); + if ( + usage.trialConsumed < state.trialConsumed || + usage.paidConsumed < previous.paidConsumed || + usage.lifetimeImports < previous.lifetimeImports + ) + throw new KeyForgeError("usage_rollback"); + state.importUsage = usage; + state.trialConsumed = usage.trialConsumed; + await this.persist(state); + }); + } + getImportUsage() { + return this.serial(async () => structuredClone((await this.load()).importUsage ?? null)); + } + /** One stable UUID per successful asset operation. Production adapters must share the asset transaction. */ + consumeImport(eventId: string, units = 1) { + return this.serial(async () => { + this.requireAtomicStorage(); + if ( + !z.string().uuid().safeParse(eventId).success || + !Number.isSafeInteger(units) || + units <= 0 + ) + throw new KeyForgeError("invalid_units"); + const state = await this.load(), + usage = state.importUsage; + if (!usage?.integrity) throw new KeyForgeError("usage_integrity_required"); + const prior = usage.events[eventId]; + if (prior) { + if (prior.units !== units) throw new KeyForgeError("idempotency_conflict"); + return { recorded: false, receipt: prior, authorization: await this.evaluate(state) }; + } + const auth = await this.evaluate(state, false); + const source = auth.state === "trial" ? "trial" : "paid"; + if (auth.state !== "trial" && (auth.state !== "licensed" || auth.token.v !== 5)) + throw new KeyForgeError("imports_unavailable"); + const remaining = auth.state === "trial" ? auth.remaining : auth.remainingImports!; + if (remaining !== null && units > remaining) throw new KeyForgeError("quota_exhausted"); + const next = usage.lifetimeImports + units; + if (!Number.isSafeInteger(next)) throw new KeyForgeError("invalid_units"); + usage.lifetimeImports = next; + if (source === "trial") { + usage.trialConsumed += units; + state.trialConsumed = usage.trialConsumed; + } else usage.paidConsumed += units; + const receipt = { units, source } as const; + usage.events[eventId] = receipt; + await this.persist(state); + return { recorded: true, receipt, authorization: await this.evaluate(state, false) }; + }); + } + markUsageRecoveryRequired() { + return this.serial(async () => { + this.requireAtomicStorage(); + const state = await this.load(); + if (state.importUsage) state.importUsage.integrity = false; + await this.persist(state); + }); + } + private backupContext() { + return JSON.stringify(["keyforge-usage-backup", 1, this.url, this.options.productId]); + } + exportUsageBackup(password: string) { + return this.serial(async () => { + const usage = (await this.load()).importUsage; + if (!usage?.integrity) throw new KeyForgeError("usage_integrity_required"); + return encryptUsageBackup(usage, password, this.backupContext()); + }); + } + /** A pending UUID/challenge/candidate is durable before contacting the server. Retry this method unchanged. */ + requestUsageRecovery(licenseId: string, backup?: { encrypted: string; password: string }) { + return this.serial(async () => { + this.requireAtomicStorage(); + const state = await this.load(); + await this.ensureRegistered(state); + let pending = state.pendingRecovery; + if (!pending) { + const candidate = backup + ? await decryptUsageBackup(backup.encrypted, backup.password, this.backupContext()) + : null; + const challenge = encodeBase64url(crypto.getRandomValues(new Uint8Array(32))); + pending = { + requestId: crypto.randomUUID(), + licenseId, + challenge, + candidate, + usageDigest: candidate ? await recoveryUsageDigest(challenge, candidate) : null, + }; + state.pendingRecovery = pending; + await this.persist(state); + } else if (pending.licenseId !== licenseId || backup) + throw new KeyForgeError("recovery_pending"); + const result = await this.request<{ id: string; status: string }>( + state, + "POST", + this.installationPath(state, "/recovery-requests"), + { + requestId: pending.requestId, + licenseId, + challenge: pending.challenge, + usageDigest: pending.usageDigest, + }, + ); + if (typeof result?.id !== "string") throw new KeyForgeError("invalid_response"); + pending.id = result.id; + await this.persist(state); + return result; + }); + } + claimUsageRecovery(): Promise { + return this.serial(async () => { + this.requireAtomicStorage(); + const state = await this.load(), + pending = state.pendingRecovery; + if (!pending?.id) { + if (state.importUsage?.integrity && state.importUsage.recoveryGeneration > 0) + return this.evaluate(state); + throw new KeyForgeError("recovery_required"); + } + const response = await this.request<{ recoveryToken: string; token: string }>( + state, + "POST", + this.installationPath( + state, + "/recovery-requests/" + encodeURIComponent(pending.id) + "/claim", + ), + ); + const recovery = await verifyRecoveryToken(response.recoveryToken, { + ...this.context(state), + now: Math.max(this.now(), state.lastObservedTime), + }); + const grant = await verifySignedToken(response.token, this.context(state)); + const old = state.importUsage; + if ( + recovery.challenge !== pending.challenge || + grant.kind !== "license" || + grant.v !== 5 || + grant.licenseId !== pending.licenseId || + grant.accountId !== recovery.accountId || + grant.recoveryGeneration !== recovery.recoveryGeneration || + grant.authorizationRevision < recovery.authorizationRevision || + (old?.accountId && old.accountId !== recovery.accountId) || + (old && recovery.recoveryGeneration <= old.recoveryGeneration) + ) + throw new TokenError("recovery_mismatch"); + if ( + recovery.mode === "restore" && + (!pending.candidate || + recovery.usageDigest !== pending.usageDigest || + recovery.usageDigest !== + (await recoveryUsageDigest(pending.challenge, pending.candidate)) || + pending.candidate.accountId !== recovery.accountId) + ) + throw new TokenError("recovery_mismatch"); + const usage = structuredClone( + recovery.mode === "restore" ? pending.candidate! : emptyImportUsage(), + ); + const previous = old ?? emptyImportUsage(); + usage.paidConsumed = Math.max( + usage.paidConsumed, + previous.paidConsumed, + recovery.paidImportsFloor, + ); + usage.trialConsumed = Math.max( + usage.trialConsumed, + previous.trialConsumed, + state.trialConsumed, + recovery.trialImportsFloor, + ); + usage.lifetimeImports = Math.max(usage.lifetimeImports, previous.lifetimeImports); + for (const [id, event] of Object.entries(previous.events)) { + const candidate = usage.events[id]; + if (candidate && (candidate.units !== event.units || candidate.source !== event.source)) + throw new KeyForgeError("usage_conflict"); + } + usage.events = { ...usage.events, ...previous.events }; + // Distinct surviving receipts are evidence of distinct successful imports, + // even when neither snapshot contains the other's latest counters. + const receipts = Object.values(usage.events); + usage.paidConsumed = Math.max( + usage.paidConsumed, + receipts.filter((e) => e.source === "paid").reduce((n, e) => n + e.units, 0), + ); + usage.trialConsumed = Math.max( + usage.trialConsumed, + receipts.filter((e) => e.source === "trial").reduce((n, e) => n + e.units, 0), + ); + usage.lifetimeImports = Math.max( + usage.lifetimeImports, + receipts.reduce((n, e) => n + e.units, 0), + ); + usage.accountId = recovery.accountId; + usage.recoveryGeneration = recovery.recoveryGeneration; + usage.authorizationRevision = Math.max( + previous.authorizationRevision, + recovery.authorizationRevision, + ); + usage.termsHash = null; + usage.granted = Math.max(usage.granted, previous.granted); + usage.trialConverted = true; + usage.integrity = true; + // A valid old snapshot is not proof that the lost interval contained no imports. + usage.lifetimeKnown = false; + state.importUsage = importUsageSchema.parse(usage); + state.trialConsumed = usage.trialConsumed; + state.pendingRecovery = null; + // saveLicense persists both adoption and intent clearing in a single atomic snapshot. + await this.saveLicense(state, response.token, pending.licenseId); + return this.evaluate(state); + }); + } + abandonUsageRecovery() { + return this.serial(async () => { + const state = await this.load(); + state.pendingRecovery = null; + await this.persist(state); }); } getNotifications() { diff --git a/packages/keyforge-client/src/index.ts b/packages/keyforge-client/src/index.ts index 334911d..08da0ca 100644 --- a/packages/keyforge-client/src/index.ts +++ b/packages/keyforge-client/src/index.ts @@ -1,5 +1,7 @@ export { KeyForgeClient, KeyForgeError, MemoryStorage } from "./client.js"; -export { verifySignedToken, TokenError } from "./tokens.js"; +export { verifySignedToken, verifyRecoveryToken, TokenError } from "./tokens.js"; +export type { RecoveryToken } from "./tokens.js"; +export type { ImportUsage } from "./usage.js"; export type { LicenseToken, TrialToken, SignedToken, VerificationContext } from "./tokens.js"; export type { ClientOptions } from "./client.js"; export type * from "./types.js"; diff --git a/packages/keyforge-client/src/tokens.ts b/packages/keyforge-client/src/tokens.ts index 5081d38..3523fc1 100644 --- a/packages/keyforge-client/src/tokens.ts +++ b/packages/keyforge-client/src/tokens.ts @@ -38,8 +38,42 @@ export const trialSchema = z supportReference: z.string().nullable(), }) .strict(); -export type LicenseToken = z.infer; -export type TrialToken = z.infer; +export const importLicenseSchema = z + .object({ + ...licenseSchema.shape, + v: z.literal(5), + accountId: id, + authorizationRevision: z.number().int().positive().safe(), + paidImportsGranted: z.number().int().nonnegative().safe(), + recoveryGeneration: z.number().int().nonnegative().safe(), + trialConverted: z.literal(true), + }) + .strict() + .refine((p) => p.subject.id === p.installationId); +export const importTrialSchema = trialSchema.extend({ v: z.literal(3), converted: z.boolean() }); +export const recoverySchema = z + .object({ + ...common, + v: z.literal(1), + kind: z.literal("usage-recovery"), + recoveryId: z.string().uuid(), + accountId: id, + challenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/), + mode: z.enum(["restore", "lost_history"]), + usageDigest: z + .string() + .regex(/^[a-f0-9]{64}$/) + .nullable(), + paidImportsFloor: z.number().int().nonnegative().safe(), + trialImportsFloor: z.number().int().nonnegative().safe(), + recoveryGeneration: z.number().int().positive().safe(), + authorizationRevision: z.number().int().positive().safe(), + expiresAt: date, + }) + .strict(); +export type RecoveryToken = z.infer; +export type LicenseToken = z.infer | z.infer; +export type TrialToken = z.infer | z.infer; export type SignedToken = LicenseToken | TrialToken; export class TokenError extends Error { @@ -78,10 +112,10 @@ function decodeBase64url(encoded: string): Uint8Array { /** Authenticates a token, including its context. Expiry/status are evaluated separately * so signed negative grants can replace a previously active cached grant. */ -export async function verifySignedToken( +async function verifyAnyToken( token: string, context: VerificationContext, -): Promise { +): Promise { if (typeof token !== "string" || token.length > 65536) throw new TokenError("malformed_token"); const parts = token.split("."); if (parts.length !== 2) throw new TokenError("malformed_token"); @@ -94,7 +128,9 @@ export async function verifySignedToken( } catch { throw new TokenError("malformed_token"); } - const parsed = z.union([licenseSchema, trialSchema]).safeParse(input); + const parsed = z + .union([licenseSchema, trialSchema, importLicenseSchema, importTrialSchema, recoverySchema]) + .safeParse(input); if (!parsed.success) throw new TokenError("invalid_payload"); const p = parsed.data; if ( @@ -106,13 +142,22 @@ export async function verifySignedToken( const pem = Object.hasOwn(context.publicKeys, p.kid) ? context.publicKeys[p.kid] : undefined; if (!pem) throw new TokenError("unknown_key"); try { - if (!/^-----BEGIN PUBLIC KEY-----\s+[A-Za-z0-9+/=\s]+-----END PUBLIC KEY-----\s*$/.test(pem)) + // Ed25519 SPKI keys are small. Bound input before parsing and check fixed + // markers separately to avoid overlapping whitespace quantifiers. + if (typeof pem !== "string" || pem.length > 4096) throw new Error("Invalid public key"); + const begin = "-----BEGIN PUBLIC KEY-----", + end = "-----END PUBLIC KEY-----", + normalized = pem.trimEnd(); + if (!normalized.startsWith(begin) || !normalized.endsWith(end)) throw new Error("Invalid public key"); - const der = Uint8Array.from(atob(pem.replace(/-----[^-]+-----/g, "").replace(/\s/g, "")), (c) => - c.charCodeAt(0), - ); + const body = normalized.slice(begin.length, -end.length); + if (!/^\s/.test(body)) throw new Error("Invalid public key"); + const encoded = body.replace(/\s/g, ""), + decoded = atob(encoded); + if (!encoded || btoa(decoded) !== encoded) throw new Error("Invalid public key"); + const der = Uint8Array.from(decoded, (c) => c.charCodeAt(0)); const key = await crypto.subtle.importKey("spki", der, { name: "Ed25519" }, false, ["verify"]); - // Current v4/v2 server contract signs decoded JSON bytes, not the base64url segment. + // All supported server contracts sign decoded JSON bytes, not the base64url segment. if (!(await crypto.subtle.verify("Ed25519", key, signature, bytes))) throw new Error("Invalid signature"); } catch { @@ -125,3 +170,22 @@ export async function verifySignedToken( if (Date.parse(p.issuedAt) > now + tolerance) throw new TokenError("future_issuance"); return p; } + +export async function verifySignedToken( + token: string, + context: VerificationContext, +): Promise { + const grant = await verifyAnyToken(token, context); + if (grant.kind === "usage-recovery") throw new TokenError("unexpected_token_kind"); + return grant; +} +export async function verifyRecoveryToken( + token: string, + context: VerificationContext, +): Promise { + const grant = await verifyAnyToken(token, context); + if (grant.kind !== "usage-recovery") throw new TokenError("unexpected_token_kind"); + if (Date.parse(grant.expiresAt) <= (context.now ?? Date.now())) + throw new TokenError("recovery_expired"); + return grant; +} diff --git a/packages/keyforge-client/src/types.ts b/packages/keyforge-client/src/types.ts index 77b180c..d0f134e 100644 --- a/packages/keyforge-client/src/types.ts +++ b/packages/keyforge-client/src/types.ts @@ -1,4 +1,5 @@ import type { LicenseToken, TrialToken } from "./tokens.js"; +import type { ImportUsage } from "./usage.js"; export const DEVICE_SIGNAL_KINDS = [ "machine-guid", @@ -55,12 +56,24 @@ export interface ClientState { denial: string | null; lastObservedTime: number; deviceSignals?: DeviceSignalsReport; + storageRevision?: number; + importUsage?: ImportUsage | null; + pendingRecovery?: { + requestId: string; + licenseId: string; + challenge: string; + usageDigest: string | null; + candidate: ImportUsage | null; + id?: string; + } | null; } /** One owner per installation. load returns a snapshot; save atomically replaces it. * Production implementations must protect credentials using platform secure storage. */ export interface SecureStorage { load(): Promise; save(state: ClientState): Promise; + /** Must be a database transaction or equivalent atomic operation, across all processes. */ + compareAndSwap?(expectedRevision: number | null, state: ClientState): Promise; } export type Authorization = | { state: "unlicensed"; reason: string } @@ -70,8 +83,12 @@ export type Authorization = token: LicenseToken; entitlements: LicenseToken["entitlements"]; deadline: string; + remainingImports?: number; } - | { state: "reconnect_required" | "expired" | "revoked"; reason: string }; + | { + state: "reconnect_required" | "expired" | "revoked" | "quota_exhausted" | "recovery_required"; + reason: string; + }; export interface NotificationPreferences { messages: boolean; expirations: boolean; diff --git a/packages/keyforge-client/src/usage.ts b/packages/keyforge-client/src/usage.ts new file mode 100644 index 0000000..a6bacbb --- /dev/null +++ b/packages/keyforge-client/src/usage.ts @@ -0,0 +1,148 @@ +import { z } from "zod"; + +import { encodeBase64url } from "./tokens.js"; + +const count = z.number().int().nonnegative().safe(); +export const importUsageSchema = z + .object({ + accountId: z.string().min(1).max(200).nullable(), + paidConsumed: count, + trialConsumed: count, + lifetimeImports: count, + lifetimeKnown: z.boolean(), + integrity: z.boolean(), + trialConverted: z.boolean(), + legacyPaidSeen: z.boolean().default(false), + legacyVerified: z.boolean().default(false), + authorizationRevision: count, + recoveryGeneration: count, + granted: count, + termsHash: z.string().nullable(), + events: z.record( + z.string().uuid(), + z.object({ units: count, source: z.enum(["trial", "paid"]) }).strict(), + ), + }) + .strict() + .refine( + (v) => + (!v.lifetimeKnown || v.lifetimeImports >= v.trialConsumed + v.paidConsumed) && + Object.values(v.events) + .filter((e) => e.source === "paid") + .reduce((n, e) => n + e.units, 0) <= v.paidConsumed && + Object.values(v.events) + .filter((e) => e.source === "trial") + .reduce((n, e) => n + e.units, 0) <= v.trialConsumed, + ); +export type ImportUsage = z.infer; +export const emptyImportUsage = (): ImportUsage => ({ + accountId: null, + paidConsumed: 0, + trialConsumed: 0, + lifetimeImports: 0, + lifetimeKnown: true, + integrity: true, + trialConverted: false, + legacyPaidSeen: false, + legacyVerified: false, + authorizationRevision: 0, + recoveryGeneration: 0, + granted: 0, + termsHash: null, + events: {}, +}); +export async function usageDigest(value: unknown) { + const bytes = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(JSON.stringify(value)), + ); + return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join(""); +} +export function recoveryUsageDigest(challenge: string, v: ImportUsage) { + return usageDigest([ + "keyforge-usage-recovery", + 1, + challenge, + v.accountId, + v.paidConsumed, + v.trialConsumed, + v.lifetimeImports, + v.lifetimeKnown, + v.integrity, + v.trialConverted, + v.legacyPaidSeen, + v.legacyVerified, + v.authorizationRevision, + v.recoveryGeneration, + v.granted, + v.termsHash, + Object.entries(v.events) + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([id, e]) => [id, e.units, e.source]), + ]); +} +function decode(s: string) { + if (!/^[A-Za-z0-9_-]+$/.test(s)) throw Error("invalid_backup"); + const bytes = Uint8Array.from(atob(s.replace(/-/g, "+").replace(/_/g, "/")), (c) => + c.charCodeAt(0), + ); + if (encodeBase64url(bytes) !== s) throw Error("invalid_backup"); + return bytes; +} +async function backupKey(password: string, salt: Uint8Array) { + if (password.length < 12 || password.length > 1024) throw Error("invalid_backup_password"); + const material = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(password), + "PBKDF2", + false, + ["deriveKey"], + ); + return crypto.subtle.deriveKey( + { name: "PBKDF2", salt, iterations: 600000, hash: "SHA-256" }, + material, + { name: "AES-GCM", length: 256 }, + false, + ["encrypt", "decrypt"], + ); +} +/** A separate customer-owned encrypted usage backup, never an ordinary configuration export. */ +export async function encryptUsageBackup(usage: ImportUsage, password: string, context: string) { + const salt = crypto.getRandomValues(new Uint8Array(16)), + iv = crypto.getRandomValues(new Uint8Array(12)); + const value = new TextEncoder().encode(JSON.stringify(importUsageSchema.parse(usage))); + if (value.length > 24000000) throw Error("backup_too_large"); + const encrypted = await crypto.subtle.encrypt( + { name: "AES-GCM", iv, additionalData: new TextEncoder().encode(context) }, + await backupKey(password, salt), + value, + ); + return JSON.stringify({ + v: 1, + salt: encodeBase64url(salt), + iv: encodeBase64url(iv), + data: encodeBase64url(new Uint8Array(encrypted)), + }); +} +export async function decryptUsageBackup( + backup: string, + password: string, + context: string, +): Promise { + if (backup.length > 32000000) throw Error("invalid_backup"); + const box = z + .object({ v: z.literal(1), salt: z.string(), iv: z.string(), data: z.string() }) + .strict() + .parse(JSON.parse(backup)); + const salt = decode(box.salt), + iv = decode(box.iv); + if (salt.length !== 16 || iv.length !== 12) throw Error("invalid_backup"); + const bytes = await crypto.subtle.decrypt( + { name: "AES-GCM", iv, additionalData: new TextEncoder().encode(context) }, + await backupKey(password, salt), + decode(box.data), + ); + return importUsageSchema.parse( + JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)), + ); +} diff --git a/scripts/docs-smoke.mjs b/scripts/docs-smoke.mjs index 976157a..11c13c0 100644 --- a/scripts/docs-smoke.mjs +++ b/scripts/docs-smoke.mjs @@ -160,6 +160,7 @@ try { "api", ...(existsSync("packages/keyforge-client/README.md") ? ["sdk"] : []), "documentation-site", + "import-licensing", ...(existsSync("docs/studio-proof-contract.md") ? ["studio-proof-contract"] : []), ]) { await page.goto(origin + "/docs/" + route); diff --git a/scripts/generate-api-docs.mjs b/scripts/generate-api-docs.mjs index 0719766..9fa3913 100644 --- a/scripts/generate-api-docs.mjs +++ b/scripts/generate-api-docs.mjs @@ -24,6 +24,7 @@ for (const path of [ "src/platform.ts", "src/license-delivery.ts", "src/finance.ts", + "src/import-licensing.ts", "src/notifications.ts", "src/platform-store.ts", "src/backups.ts", diff --git a/scripts/generate-client-openapi.ts b/scripts/generate-client-openapi.ts index ca443a4..6718dd9 100644 --- a/scripts/generate-client-openapi.ts +++ b/scripts/generate-client-openapi.ts @@ -7,7 +7,13 @@ import { z } from "zod"; import { SIGNAL_KINDS } from "../src/machines.js"; import { supportRequestBodySchema } from "../src/support.js"; -import { licenseTokenSchema, trialTokenSchema } from "../src/token-contract.js"; +import { + licenseTokenSchema, + trialTokenSchema, + importLicenseTokenSchema, + importTrialTokenSchema, + recoveryTokenSchema, +} from "../src/token-contract.js"; type Schema = Record; const string = (extra: Schema = {}): Schema => ({ type: "string", ...extra }); @@ -129,6 +135,9 @@ const supportProperties = supportBody.properties as Record; const schemas: Record = { LicenseToken: fromZod(licenseTokenSchema), TrialToken: fromZod(trialTokenSchema), + ImportLicenseToken: fromZod(importLicenseTokenSchema), + ImportTrialToken: fromZod(importTrialTokenSchema), + UsageRecoveryToken: fromZod(recoveryTokenSchema), Error: object( { error: string(), message: string(), retryable: boolean, serverTime: timestamp }, ["error", "message"], @@ -263,8 +272,8 @@ operation( object({ ok: { const: true }, serverTime: timestamp, - tokenVersions: object({ min: { const: 4 }, max: { const: 4 } }), - trialTokenVersions: object({ min: { const: 2 }, max: { const: 2 } }), + tokenVersions: object({ min: { const: 4 }, max: { const: 5 } }), + trialTokenVersions: object({ min: { const: 2 }, max: { const: 3 } }), }), undefined, 200, @@ -356,6 +365,26 @@ operation( }, }), ); +operation( + "post", + installation + "/recovery-requests", + "requestUsageRecovery", + "Installation-authenticated request only; never grants recovery without independent admin approval. Persist UUID/challenge before networking, reuse exact body. Send only an optional nonce-bound usage commitment, not usage history.", + object({ id, status: string({ enum: ["requested", "approved", "claimed", "rejected"] }) }), + object({ + requestId: uuid, + licenseId: id, + challenge: string({ pattern: "^[A-Za-z0-9_-]{43}$" }), + usageDigest: nullable(string({ pattern: "^[a-f0-9]{64}$" })), + }), +); +operation( + "post", + installation + "/recovery-requests/{id}/claim", + "claimUsageRecovery", + "Claims an approved, unexpired recovery once on the server. Exact retries are safe while the generation remains current. Verify the separate recovery signature, challenge, account, generation and candidate commitment before atomically adopting it with the v5 license. Approval expires after 24 hours.", + object({ recoveryToken: string(), token: string(), serverTime: timestamp }), +); operation( "get", installation + "/notifications", @@ -492,7 +521,7 @@ export const clientOpenApi = { title: "KeyForge dependent-app API", version: "1.0.0", description: - "Current product-scoped API. Tokens are two base64url segments (not JWTs); Ed25519 signs the decoded UTF-8 JSON bytes. License v4 and trial v2 payloads are documented in components. Full contextual, time and status checks are required. Private/admin routes are deliberately excluded.", + "Current product-scoped API. Tokens are two base64url segments (not JWTs); Ed25519 signs the decoded UTF-8 JSON bytes. License v4 and trial v2 payloads are documented in components. Import policy opt-in adds license v5, trial v3 and separate usage-recovery v1; legacy v4/v2 remain supported. Full contextual, time and status checks are required. Private/admin routes are deliberately excluded.", }, servers: [ { diff --git a/scripts/license-tool.mjs b/scripts/license-tool.mjs index 786dc11..3f7b1c2 100644 --- a/scripts/license-tool.mjs +++ b/scripts/license-tool.mjs @@ -87,7 +87,8 @@ function usage() { vp run license revoke vp run license activations vp run license deactivate --installation - Release a binding so the customer can activate elsewhere (transfer). + Release a binding. Import accounts retain ownership; transferring them + requires approved recovery rather than ordinary reactivation elsewhere. vp run license machines [--q ] [--limit 25] The trial ledger. Search by the support reference a customer reads out, @@ -98,6 +99,22 @@ function usage() { Give one machine its trial back. Grants exactly ONE more: the next run reads fresh, the one after it is spent again. Audited. + vp run license imports-enable --entitlement imports --revision N + vp run license imports-account + vp run license imports-adopt --granted N --revision N --reason TEXT + vp run license renew --plan ID --mode renewal|top_up|extension --request-id UUID + Renewal extends time and adds units once; top_up adds units only; + extension changes time only. Optional --paid --method TEXT --reference TEXT. + vp run license replace-key --request-id UUID --reason TEXT + Preserves the existing usage account and creates no sale. + vp run license recovery-list + vp run license recovery-approve --revision N --mode restore|lost_history --reason TEXT + vp run license recovery-reject --revision N --reason TEXT + Verify customer identity independently first. lost_history consumes the + previously granted budget; restore requires a committed encrypted backup. + These commands change the selected server. Always select --product and + --env-file deliberately. No recovery action is implied by ordinary keygen. + Service connection (all but keygen/inspect; keycheck only with --server): LICENSE_SERVER_URL, LICENSE_ADMIN_TOKEN @@ -302,6 +319,121 @@ function inspect(input) { } switch (command) { + case "imports-enable": { + const pid = encodeURIComponent(flag("product") || "default"); + await admin(`/admin/products/${pid}/import-policy`, { + method: "PUT", + body: JSON.stringify({ + entitlement: flag("entitlement", "imports"), + revision: Number(flag("revision")), + }), + }); + console.log( + "Import licensing enabled for future issuance. Existing licenses require explicit adoption.", + ); + break; + } + case "imports-account": { + console.log( + JSON.stringify( + await admin(`/admin/licenses/${encodeURIComponent(rest[0])}/import-account`), + null, + 2, + ), + ); + break; + } + case "imports-adopt": { + const requestId = flag("request-id") || randomUUID(); + console.log("Operation ID (reuse unchanged on retry): " + requestId); + await admin(`/admin/licenses/${encodeURIComponent(rest[0])}/import-account`, { + method: "POST", + body: JSON.stringify({ + requestId, + revision: Number(flag("revision")), + granted: Number(flag("granted")), + reason: flag("reason"), + }), + }); + console.log( + "Legacy license adopted. The client must migrate verified surviving usage before using v5 grants.", + ); + break; + } + case "renew": { + const requestId = flag("request-id") || randomUUID(); + console.log("Purchase ID (reuse unchanged on retry): " + requestId); + const body = { + requestId, + plan: flag("plan", "standard"), + mode: flag("mode", "renewal"), + ...(flag("paid") + ? { + payment: { + date: new Date().toISOString().slice(0, 10), + method: flag("method", ""), + reference: flag("reference", ""), + }, + } + : {}), + }; + const result = await admin(`/admin/licenses/${encodeURIComponent(rest[0])}/renew`, { + method: "POST", + body: JSON.stringify(body), + }); + console.log( + `License ${result.licenseId}: ${result.account.granted} cumulative paid imports granted; sale ${result.sale.id} ${result.sale.status}.`, + ); + break; + } + case "replace-key": { + const requestId = flag("request-id") || randomUUID(); + console.log("Replacement ID (reuse unchanged on retry): " + requestId); + const result = await admin(`/admin/licenses/${encodeURIComponent(rest[0])}/replace-key`, { + method: "POST", + body: JSON.stringify({ requestId, reason: flag("reason") }), + }); + console.log("Replacement product key (keep private): " + result.key); + break; + } + case "recovery-list": { + const pid = encodeURIComponent(flag("product") || "default"); + console.log(JSON.stringify(await admin(`/admin/products/${pid}/recovery-requests`), null, 2)); + break; + } + case "recovery-approve": { + const pid = encodeURIComponent(flag("product") || "default"), + requestId = flag("request-id") || randomUUID(); + console.log("Approval ID (reuse unchanged on retry): " + requestId); + await admin(`/admin/products/${pid}/recovery-requests/${encodeURIComponent(rest[0])}/approve`, { + method: "POST", + body: JSON.stringify({ + requestId, + revision: Number(flag("revision")), + mode: flag("mode"), + reason: flag("reason"), + }), + }); + console.log( + "Recovery approved for 24 hours. Customer must claim with the original installation credential and persisted challenge.", + ); + break; + } + case "recovery-reject": { + const pid = encodeURIComponent(flag("product") || "default"), + requestId = flag("request-id") || randomUUID(); + console.log("Rejection ID (reuse unchanged on retry): " + requestId); + await admin(`/admin/products/${pid}/recovery-requests/${encodeURIComponent(rest[0])}/reject`, { + method: "POST", + body: JSON.stringify({ + requestId, + revision: Number(flag("revision")), + reason: flag("reason"), + }), + }); + console.log("Recovery rejected. The request can no longer transfer this account."); + break; + } case "keygen": await keygen(); break; @@ -388,7 +520,9 @@ switch (command) { method: "POST", body: JSON.stringify({ installationId }), }); - console.log("Binding released. The key can now activate on another installation."); + console.log( + "Binding released. Import-account ownership remains; transfer requires approved recovery.", + ); break; } case "machines": { diff --git a/scripts/package-smoke.mjs b/scripts/package-smoke.mjs index 7acb7d2..6ab9bfd 100644 --- a/scripts/package-smoke.mjs +++ b/scripts/package-smoke.mjs @@ -82,8 +82,9 @@ console.log( "Clean-source SDK pack contains every JavaScript/type export; all three package archives passed inspection.", ); -// A committed template is sufficient: the code under test is the packed new -// generator, and upstream workspaces must never reach its generated app. +// CI defaults to the committed source. A local review can supply a git tree +// snapshot of pending changes without committing or touching the real index. +// Upstream workspaces must never reach the generated app. await run( "git", [ @@ -91,7 +92,7 @@ await run( "--format=tar.gz", "--prefix=keyforge-main/", "--output=" + join(artifact, "template.tgz"), - "HEAD", + process.env.PACKAGE_SMOKE_REF || "HEAD", ], root, ); diff --git a/src/app.ts b/src/app.ts index 432ca37..02ba927 100644 --- a/src/app.ts +++ b/src/app.ts @@ -127,8 +127,8 @@ export async function buildLicenseApp(options: BuildLicenseAppOptions): Promise< app.get("/healthz", async () => ({ ok: true, serverTime: now().toISOString(), - tokenVersions: { min: 4, max: 4 }, - trialTokenVersions: { min: 2, max: 2 }, + tokenVersions: { min: 4, max: 5 }, + trialTokenVersions: { min: 2, max: 3 }, })); const meta = async () => ({ name: config.branding.name, serverTime: now().toISOString() }); app.get("/v1/meta", meta); diff --git a/src/finance.ts b/src/finance.ts index d9243f6..7238940 100644 --- a/src/finance.ts +++ b/src/finance.ts @@ -181,6 +181,12 @@ export function registerFinance(app: FastifyInstance, p: Platform, wrap: any, ap } const license = await r.get(s, "license", input.licenseId); if (!license) throw new DomainError("unknown_license", "No such license.", 404); + if (license.importAccountId) + throw new DomainError( + "use_license_renewal", + "Record import-account purchases through the license renewal workflow.", + 409, + ); if ( input.kind === "initial" && (await r.list(s, "sale")).some( diff --git a/src/import-licensing.ts b/src/import-licensing.ts new file mode 100644 index 0000000..57af09d --- /dev/null +++ b/src/import-licensing.ts @@ -0,0 +1,645 @@ +import { createHash, randomUUID } from "node:crypto"; + +import type { FastifyInstance } from "fastify"; +import { z } from "zod"; + +import { generateProductKey, hashProductKey } from "./db.js"; +import { balance, money, paymentFields, planPrice, type Entry, type Sale } from "./finance.js"; +import { atomic, DomainError, type Records, type RecordValue } from "./platform-store.js"; +import type { Grant, Plan, Platform } from "./platform.js"; +import { recoveryTokenSchema } from "./token-contract.js"; + +export interface ImportAccount extends RecordValue { + licenseId: string; + granted: number; + authorizationRevision: number; + recoveryGeneration: number; + ownerInstallationId: string | null; +} +const units = z.number().int().nonnegative().safe(); +const uuid = z.string().uuid(); +const text = z.string().trim().min(1).max(200); +const scope = (pid: string) => "product:" + pid; +const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex"); +export function importUnits(plan: Pick, entitlement: string) { + const parsed = units.safeParse(plan.entitlements[entitlement]); + if (!parsed.success) + throw new DomainError( + "invalid_import_allowance", + "The plan needs a finite nonnegative safe-integer import allowance.", + ); + return parsed.data; +} +export async function importAccount(records: Records, pid: string, grant: Grant) { + if (!grant.importAccountId) return null; + const account = await records.get( + scope(pid), + "import_account", + grant.importAccountId, + ); + if (!account) + throw new DomainError( + "import_account_missing", + "Restore the licensing account before authorizing imports.", + 503, + ); + return account; +} +export async function bumpImportRevision(records: Records, pid: string, grant: Grant) { + const account = await importAccount(records, pid, grant); + if (account) { + account.authorizationRevision = units.parse(account.authorizationRevision + 1); + await records.put(scope(pid), "import_account", account); + } +} +export async function recordImportEvent( + records: Records, + pid: string, + value: RecordValue & Record, +) { + if (await records.get(scope(pid), "licensing_event", value.id)) + throw new DomainError("idempotency_conflict", "This operation ID has already been used.", 409); + await records.put(scope(pid), "licensing_event", value); +} + +/** Recognition and money never substitute for authorization. All writes use the existing ledger transaction. */ +export function registerImportLicensing( + app: FastifyInstance, + p: Platform, + wrap: any, + ap: string, + device: string, + bearer: any, +) { + const write = (fn: any) => wrap(fn, true, true); + const license = async (r: Records, pid: string, id: string) => { + const grant = await r.get(scope(pid), "license", id); + if (!grant) throw new DomainError("unknown_license", "No such license.", 404); + return grant; + }; + app.put( + ap + "/import-policy", + write(async (req: any) => { + const input = z + .object({ entitlement: z.string().min(1).max(64), revision: z.number().int() }) + .strict() + .parse(req.body); + return atomic(p.options.database, async (r) => { + const product = await p.product(req.params.productId, r); + const definition = await r.get(scope(product.id), "definition", input.entitlement); + if (!definition || definition.archived || definition.type !== "number") + throw new DomainError("bad_entitlements", "Select an active numeric import entitlement."); + if (product.importPolicy && product.importPolicy.entitlement !== input.entitlement) + throw new DomainError( + "policy_locked", + "The configured import entitlement cannot be reassigned.", + 409, + ); + await r.put( + "workspace:default", + "product", + { ...product, importPolicy: { entitlement: input.entitlement } }, + input.revision, + ); + await r.put(scope(product.id), "licensing_event", { + id: randomUUID(), + kind: "policy.enable", + actor: req.actor, + createdAt: p.time(), + entitlement: input.entitlement, + }); + return { ok: true }; + }); + }), + ); + app.get( + ap + "/licenses/:id/import-account", + write(async (req: any) => { + const grant = await license(p.records, req.params.productId, req.params.id); + const account = await importAccount(p.records, req.params.productId, grant); + return { + account, + events: (await p.records.list(scope(req.params.productId), "licensing_event")).filter( + (e) => e.accountId === account?.id, + ), + }; + }), + ); + app.post( + ap + "/licenses/:id/import-account", + write(async (req: any) => { + const input = z + .object({ + requestId: uuid, + revision: z.number().int(), + granted: units, + reason: z.string().trim().min(10).max(1000), + }) + .strict() + .parse(req.body); + return atomic(p.options.database, async (r) => { + const pid = req.params.productId, + s = scope(pid), + grant = await license(r, pid, req.params.id); + const prior = await r.get(s, "licensing_event", input.requestId); + const fingerprint = digest({ ...input, licenseId: grant.id, actor: req.actor }); + if (prior) { + if (prior.fingerprint !== fingerprint) + throw new DomainError("idempotency_conflict", "Operation ID changed.", 409); + return { account: await importAccount(r, pid, grant) }; + } + if ( + grant.importAccountId || + grant.activationLimit !== 1 || + grant.subjectKind !== "installation" || + !(await p.product(pid, r)).importPolicy + ) + throw new DomainError( + "import_migration_required", + "Enable policy and use a single-installation legacy license without an existing account.", + 409, + ); + const bindings = (await r.list(s, "binding")).filter((b) => b.licenseId === grant.id); + if (new Set(bindings.map((b) => b.installationId)).size > 1) + throw new DomainError( + "import_migration_required", + "Multiple historical installations require explicit operator reconciliation.", + 409, + ); + const account: ImportAccount = { + id: randomUUID(), + licenseId: grant.id, + granted: input.granted, + authorizationRevision: 1, + recoveryGeneration: 0, + ownerInstallationId: bindings[0]?.installationId ?? null, + }; + await r.put(s, "import_account", account); + await r.put(s, "license", { ...grant, importAccountId: account.id }, input.revision); + await recordImportEvent(r, pid, { + id: input.requestId, + kind: "legacy.adopt", + accountId: account.id, + actor: req.actor, + fingerprint, + reason: input.reason, + createdAt: p.time(), + }); + return { account }; + }); + }), + ); + app.post( + ap + "/licenses/:id/renew", + write(async (req: any) => { + const input = z + .object({ + requestId: uuid, + plan: text, + mode: z.enum(["renewal", "top_up", "extension"]).default("renewal"), + planRevision: z.number().int().optional(), + expectedPrice: money.optional(), + payment: paymentFields.optional(), + }) + .strict() + .parse(req.body); + return atomic(p.options.database, async (r) => { + const pid = req.params.productId, + s = scope(pid), + grant = await license(r, pid, req.params.id); + const fingerprint = digest({ ...input, licenseId: grant.id, actor: req.actor }); + const old = await r.get(s, "licensing_event", input.requestId); + if (old) { + if (old.fingerprint !== fingerprint) + throw new DomainError("idempotency_conflict", "Operation ID changed.", 409); + const sale = (await r.get(s, "sale", input.requestId))!; + return { + account: await importAccount(r, pid, grant), + licenseId: grant.id, + sale: { ...sale, ...balance(sale, await r.list(s, "financial_entry")) }, + }; + } + if (await r.get(s, "sale", input.requestId)) + throw new DomainError("idempotency_conflict", "Transaction ID already used.", 409); + const product = await p.product(pid, r), + account = await importAccount(r, pid, grant); + if (!account || !product.importPolicy || grant.status === "revoked") + throw new DomainError( + "renewal_unavailable", + "Use an import-account license that has not been revoked.", + 409, + ); + const plan = await r.get(s, "plan", input.plan); + if (!plan || plan.archived || plan.activationLimit !== 1) + throw new DomainError("unknown_plan", "Select an active single-installation plan."); + await p.validateEntitlements(pid, plan.entitlements, r); + const price = await planPrice(r, s, plan.id); + if (price === null) throw new DomainError("price_required", "Configure a plan price."); + if ( + (input.planRevision !== undefined && plan.revision !== input.planRevision) || + (input.expectedPrice !== undefined && price !== input.expectedPrice) + ) + throw new DomainError("revision_conflict", "The plan or price changed.", 409); + const date = p.time().slice(0, 10); + if (input.payment && (input.payment.date !== date || price === 0)) + throw new DomainError( + "invalid_payment", + "Initial receipt must be today and the sale must have positive value.", + ); + const added = + input.mode === "extension" ? 0 : importUnits(plan, product.importPolicy.entitlement); + const granted = units.safeParse(account.granted + added); + if (!granted.success) + throw new DomainError( + "invalid_import_allowance", + "Cumulative allowance exceeds the supported integer range.", + ); + let expiresAt = grant.expiresAt; + if (input.mode !== "top_up") { + if (plan.durationDays === null) expiresAt = null; + else if (expiresAt !== null) + expiresAt = new Date( + Math.max(Date.parse(expiresAt), p.options.now().getTime()) + + plan.durationDays * 86400000, + ).toISOString(); + } + account.granted = granted.data; + account.authorizationRevision = units.parse(account.authorizationRevision + 1); + await r.put(s, "import_account", account); + await r.put(s, "license", { ...grant, expiresAt }); + const sale: Sale = { + id: input.requestId, + requestId: input.requestId, + licenseId: grant.id, + kind: input.mode, + date, + listAmount: price, + discount: 0, + amount: price, + currency: "ETB", + dueDate: null, + note: "", + customer: grant.issuedTo, + plan: plan.id, + actor: req.actor, + createdAt: p.time(), + }; + await r.put(s, "sale", sale); + if (input.payment) + await r.put(s, "financial_entry", { + id: input.requestId, + requestId: input.requestId, + saleId: sale.id, + kind: "payment", + amount: price, + ...input.payment, + paymentId: null, + reason: "", + actor: req.actor, + createdAt: p.time(), + }); + await recordImportEvent(r, pid, { + id: input.requestId, + kind: input.mode, + accountId: account.id, + added, + actor: req.actor, + fingerprint, + createdAt: p.time(), + }); + return { + account, + licenseId: grant.id, + sale: { ...sale, ...balance(sale, await r.list(s, "financial_entry")) }, + }; + }); + }), + ); + app.post( + ap + "/licenses/:id/replace-key", + write(async (req: any) => { + await p.reauthenticate(req, req.actor); + const { password: _password, ...body } = req.body ?? {}; + const input = z + .object({ requestId: uuid, reason: z.string().trim().min(10).max(1000) }) + .strict() + .parse(body); + return atomic(p.options.database, async (r) => { + const pid = req.params.productId, + s = scope(pid), + grant = await license(r, pid, req.params.id); + if (!grant.importAccountId) + throw new DomainError( + "import_account_required", + "This operation requires an import account.", + ); + const fingerprint = digest({ ...input, licenseId: grant.id, actor: req.actor }); + const old = await r.get(s, "licensing_event", input.requestId); + if (old && old.fingerprint !== fingerprint) + throw new DomainError("idempotency_conflict", "Operation ID changed.", 409); + if (!old) { + const key = generateProductKey(p.options.config.key); + grant.keyHash = hashProductKey(key); + grant.keyReference = key.slice(0, key.indexOf("-")) + "-…" + key.slice(-5); + grant.encryptedKey = p.vault.encrypt(key, "license:" + pid + ":" + grant.id); + await r.put(s, "license", grant); + await bumpImportRevision(r, pid, grant); + await recordImportEvent(r, pid, { + id: input.requestId, + kind: "key.replace", + accountId: grant.importAccountId, + fingerprint, + actor: req.actor, + reason: input.reason, + createdAt: p.time(), + }); + } + return { + key: p.vault.decrypt(grant.encryptedKey!, "license:" + pid + ":" + grant.id), + licenseId: grant.id, + }; + }); + }), + ); + + const recovery = device + "/installations/:installationId/recovery-requests"; + app.post( + recovery, + wrap(async (req: any) => { + const input = z + .object({ + requestId: uuid, + licenseId: text, + challenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/), + usageDigest: z + .string() + .regex(/^[a-f0-9]{64}$/) + .nullable(), + }) + .strict() + .parse(req.body); + return atomic(p.options.database, async (r) => { + const pid = req.params.productId, + s = scope(pid); + await p.authenticate(pid, req.params.installationId, bearer(req), r); + const grant = await license(r, pid, input.licenseId), + account = await importAccount(r, pid, grant); + if (!account) throw new DomainError("import_account_required", "No import account."); + const id = req.params.installationId + ":" + input.requestId, + fingerprint = digest(input); + const old = await r.get(s, "usage_recovery", id); + if (old) { + if (old.fingerprint !== fingerprint) + throw new DomainError("idempotency_conflict", "Recovery request changed.", 409); + return { id, status: old.status }; + } + const pending = (await r.list(s, "usage_recovery")).filter( + (v) => v.installationId === req.params.installationId && v.status === "requested", + ); + if (pending.length >= 5) + throw new DomainError( + "recovery_rate_limited", + "Resolve existing recovery requests first.", + 429, + ); + await r.put(s, "usage_recovery", { + ...input, + id, + accountId: account.id, + installationId: req.params.installationId, + fingerprint, + status: "requested", + createdAt: p.time(), + }); + return { id, status: "requested" }; + }); + }), + ); + app.get( + ap + "/recovery-requests", + write(async (req: any) => { + const all = await p.records.list(scope(req.params.productId), "usage_recovery"); + const limit = Math.min(100, Math.max(1, Number(req.query.limit) || 25)), + offset = Math.max(0, Number(req.query.offset) || 0); + return { + requests: all + .slice(offset, offset + limit) + .map( + ({ + challenge: _challenge, + token: _token, + fingerprint: _fingerprint, + payload: _payload, + ...v + }) => v, + ), + total: all.length, + }; + }), + ); + app.post( + ap + "/recovery-requests/:id/reject", + write(async (req: any) => { + const input = z + .object({ + requestId: uuid, + revision: z.number().int(), + reason: z.string().trim().min(10).max(1000), + }) + .strict() + .parse(req.body); + return atomic(p.options.database, async (r) => { + const s = scope(req.params.productId), + request = await r.get(s, "usage_recovery", req.params.id); + if (!request) throw new DomainError("unknown_recovery", "No such recovery request.", 404); + const fingerprint = digest({ ...input, id: request.id, actor: req.actor }); + const old = await r.get(s, "licensing_event", input.requestId); + if (old) { + if (old.fingerprint !== fingerprint) + throw new DomainError("idempotency_conflict", "Rejection changed.", 409); + return { ok: true }; + } + if (request.status === "claimed" || request.status === "rejected") + throw new DomainError("recovery_unavailable", "The request is already final.", 409); + await r.put( + s, + "usage_recovery", + { ...request, status: "rejected", token: null, payload: null }, + input.revision, + ); + await recordImportEvent(r, req.params.productId, { + id: input.requestId, + kind: "recovery.reject", + accountId: request.accountId, + fingerprint, + actor: req.actor, + reason: input.reason, + createdAt: p.time(), + }); + return { ok: true }; + }); + }), + ); + app.post( + ap + "/recovery-requests/:id/approve", + write(async (req: any) => { + const input = z + .object({ + requestId: uuid, + revision: z.number().int(), + mode: z.enum(["restore", "lost_history"]), + reason: z.string().trim().min(10).max(1000), + }) + .strict() + .parse(req.body); + return atomic(p.options.database, async (r) => { + const pid = req.params.productId, + s = scope(pid), + request = await r.get(s, "usage_recovery", req.params.id); + if (!request) throw new DomainError("unknown_recovery", "No such recovery request.", 404); + const fingerprint = digest({ ...input, id: request.id, actor: req.actor }); + const old = await r.get(s, "licensing_event", input.requestId); + if (old) { + if (old.fingerprint !== fingerprint) + throw new DomainError("idempotency_conflict", "Approval changed.", 409); + return { ok: true }; + } + if (request.status !== "requested" || (input.mode === "restore" && !request.usageDigest)) + throw new DomainError( + "recovery_unavailable", + "Request cannot be approved in this mode.", + 409, + ); + const grant = await license(r, pid, request.licenseId), + account = (await importAccount(r, pid, grant))!, + product = await p.product(pid, r); + const payload = { + v: 1, + kind: "usage-recovery", + iss: "default", + productId: pid, + kid: product.keys.find((k) => !k.retiredAt && !k.pending)!.kid, + installationId: request.installationId, + recoveryId: input.requestId, + accountId: account.id, + challenge: request.challenge, + mode: input.mode, + usageDigest: input.mode === "restore" ? request.usageDigest : null, + paidImportsFloor: input.mode === "lost_history" ? account.granted : 0, + trialImportsFloor: input.mode === "lost_history" ? (product.trial.allowance ?? 0) : 0, + recoveryGeneration: account.recoveryGeneration + 1, + authorizationRevision: account.authorizationRevision + 1, + issuedAt: p.time(), + expiresAt: new Date(p.options.now().getTime() + 86400000).toISOString(), + }; + const token = p.sign(product, recoveryTokenSchema.parse(payload)); + await r.put( + s, + "usage_recovery", + { + ...request, + status: "approved", + token, + payload, + expectedRevision: account.authorizationRevision, + }, + input.revision, + ); + await recordImportEvent(r, pid, { + id: input.requestId, + kind: "recovery.approve", + accountId: account.id, + fingerprint, + actor: req.actor, + reason: input.reason, + createdAt: p.time(), + }); + return { ok: true }; + }); + }), + ); + app.post( + recovery + "/:id/claim", + wrap(async (req: any) => { + return atomic(p.options.database, async (r) => { + const pid = req.params.productId, + s = scope(pid); + const installation = await p.authenticate(pid, req.params.installationId, bearer(req), r); + const request = await r.get(s, "usage_recovery", req.params.id); + if (!request || request.installationId !== req.params.installationId) + throw new DomainError("unknown_recovery", "No such recovery request.", 404); + if (!request.payload || Date.parse(request.payload.expiresAt) <= p.options.now().getTime()) + throw new DomainError( + "recovery_unavailable", + "Await staff approval or request a new recovery after expiry.", + 409, + ); + const grant = await license(r, pid, request.licenseId), + account = (await importAccount(r, pid, grant))!, + product = await p.product(pid, r); + if (installation.importAccountId && installation.importAccountId !== account.id) + throw new DomainError( + "account_mismatch", + "This installation belongs to another usage account.", + 409, + ); + if (p.status(grant) !== "active") + throw new DomainError("recovery_unavailable", "An active license is required.", 409); + if (request.status === "claimed") { + if ( + account.ownerInstallationId !== installation.id || + account.recoveryGeneration !== request.payload.recoveryGeneration + ) + throw new DomainError( + "recovery_stale", + "A newer recovery superseded this request.", + 409, + ); + } else { + if ( + request.status !== "approved" || + account.authorizationRevision !== request.expectedRevision + ) + throw new DomainError( + "recovery_stale", + "Authorization changed; obtain a new approval.", + 409, + ); + for (const b of await r.list(s, "binding")) + if (b.licenseId === grant.id && !b.deactivatedAt) + await r.put(s, "binding", { ...b, deactivatedAt: p.time() }); + account.recoveryGeneration = request.payload.recoveryGeneration; + account.authorizationRevision = request.payload.authorizationRevision; + account.ownerInstallationId = installation.id; + await r.put(s, "import_account", account); + await r.put(s, "binding", { + id: grant.id + ":" + installation.id, + licenseId: grant.id, + installationId: installation.id, + activatedAt: p.time(), + deactivatedAt: null, + }); + await r.put(s, "installation", { + ...installation, + importAccountId: account.id, + licenseId: grant.id, + trialConvertedAt: installation.trialConvertedAt ?? p.time(), + }); + await r.put(s, "usage_recovery", { ...request, status: "claimed", claimedAt: p.time() }); + await r.put(s, "licensing_event", { + id: "claim:" + request.payload.recoveryId, + kind: "recovery.claim", + accountId: account.id, + actor: "installation:" + installation.id, + createdAt: p.time(), + }); + } + return { + recoveryToken: request.token, + token: await p.token(product, grant, installation.id, r), + serverTime: p.time(), + }; + }); + }), + ); +} diff --git a/src/platform.ts b/src/platform.ts index 50fda09..1447678 100644 --- a/src/platform.ts +++ b/src/platform.ts @@ -18,6 +18,14 @@ import { type Sale, type Entry, } from "./finance.js"; +import { + bumpImportRevision, + importAccount, + importUnits, + recordImportEvent, + registerImportLicensing, + type ImportAccount, +} from "./import-licensing.js"; import { describeSigningKey, verifyLicenseToken } from "./keypair.js"; import { registerLicenseDelivery, @@ -107,6 +115,7 @@ const planSchema = z export type Definition = z.infer; export type Plan = z.infer; export interface Product extends RecordValue { + importPolicy?: { entitlement: string }; name: string; archived: boolean; graceDays: number; @@ -120,6 +129,7 @@ export interface Product extends RecordValue { }[]; } export interface Grant extends LicenseRow { + importAccountId?: string; revision?: number; productId: string; keyReference: string; @@ -127,6 +137,8 @@ export interface Grant extends LicenseRow { subjectKind: "installation" | "service"; } interface Installation extends RecordValue { + importAccountId?: string | null; + trialConvertedAt?: string | null; credentialHash: string | null; registeredAt: string; lastSeenAt: string; @@ -435,9 +447,10 @@ export class Platform { sign(null, bytes, this.privateKey(product)).toString("base64url") ); } - token(product: Product, license: Grant, installationId: string) { + async token(product: Product, license: Grant, installationId: string, records = this.records) { + const account = await importAccount(records, product.id, license); return this.sign(product, { - v: 4, + v: account ? 5 : 4, kind: "license", iss: "default", productId: product.id, @@ -454,6 +467,15 @@ export class Platform { this.options.now().getTime() + product.graceDays * 86400000, ).toISOString(), status: this.status(license), + ...(account + ? { + accountId: account.id, + authorizationRevision: account.authorizationRevision, + paidImportsGranted: account.granted, + recoveryGeneration: account.recoveryGeneration, + trialConverted: true, + } + : {}), }); } async authenticate(pid: string, iid: string, secret: string, records = this.records) { @@ -1050,6 +1072,12 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp replayed: true, }; } + if (await records.get(s, "sale", input.requestId)) + throw new DomainError( + "idempotency_conflict", + "This transaction ID has already been used.", + 409, + ); const plan = await records.get(s, "plan", input.plan); if (!plan || plan.archived) throw new DomainError("unknown_plan", "Choose an active plan."); @@ -1136,6 +1164,32 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp ? new Date(options.now().getTime() + plan.durationDays * 86400000).toISOString() : null, }; + const product = await platform.product(pid, records); + if (product.importPolicy) { + if (plan.activationLimit !== 1 || input.subjectKind !== "installation") + throw new DomainError( + "single_installation_required", + "Import licensing requires one installation seat.", + ); + const account: ImportAccount = { + id: randomUUID(), + licenseId: id, + granted: importUnits(plan, product.importPolicy.entitlement), + authorizationRevision: 1, + recoveryGeneration: 0, + ownerInstallationId: null, + }; + license.importAccountId = account.id; + await records.put(s, "import_account", account); + await recordImportEvent(records, pid, { + id: input.requestId, + kind: "initial", + accountId: account.id, + added: account.granted, + actor: req.actor, + createdAt: time, + }); + } license.revision = await records.put(s, "license", license); const sale: Sale = { id: input.requestId, @@ -1254,6 +1308,17 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp req.params.id, ); if (!license) throw new DomainError("unknown_license", "No such license.", 404); + if ( + license.importAccountId && + (input.entitlements !== undefined || + input.activationLimit !== undefined || + input.expiresAt !== undefined) + ) + throw new DomainError( + "use_license_renewal", + "Use renewal, top-up or extension for import-account terms.", + 409, + ); if (input.entitlements) await platform.validateEntitlements(req.params.productId, input.entitlements, records); await records.put( @@ -1262,6 +1327,7 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp { ...license, ...input }, input.revision, ); + await bumpImportRevision(records, req.params.productId, license); }); await platform.audit(req.actor, "license.update", req.params.productId, { licenseId: req.params.id, @@ -1296,6 +1362,7 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp status: "revoked", revokedAt: platform.time(), } as Grant); + await bumpImportRevision(records, req.params.productId, license); }); await platform.audit(req.actor, "license.revoke", req.params.productId, { licenseId: req.params.id, @@ -1560,6 +1627,8 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp ? input.userEmail : "", licenseId: prior?.licenseId ?? null, + trialConvertedAt: prior?.trialConvertedAt ?? null, + importAccountId: prior?.importAccountId ?? null, machineSignals: normalizeSignals(input.machineSignals), signalsUpdatedAt: platform.time(), } as Installation); @@ -1586,8 +1655,12 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp .sort((a, b) => a.firstRegisteredAt.localeCompare(b.firstRegisteredAt))[0]; let machine = knownMachine ?? (match ? machines.find((m) => m.id === match.groupId)! : null); - const verdict = - !machine || machine.clearedAtCount === machine.registrationCount ? "fresh" : "spent"; + const converted = Boolean(prior?.trialConvertedAt); + const verdict = converted + ? "spent" + : !machine || machine.clearedAtCount === machine.registrationCount + ? "fresh" + : "spent"; machine ??= { id: randomUUID(), signals: [], @@ -1612,7 +1685,7 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp trial: product.trial.enabled ? { token: platform.sign(product, { - v: 2, + v: product.importPolicy ? 3 : 2, kind: "trial", iss: "default", productId: pid, @@ -1627,6 +1700,7 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp ).toISOString() : null, supportReference: verdict === "spent" ? machine.supportReference : null, + ...(product.importPolicy ? { converted } : {}), }), } : null, @@ -1782,6 +1856,29 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp "Release an existing seat or contact support.", 409, ); + const account = await importAccount(records, pid, license); + if (account) { + if (installation.importAccountId && installation.importAccountId !== account.id) + throw new DomainError( + "account_mismatch", + "Renew the existing import account instead of activating a separate budget.", + 409, + ); + if ( + account.ownerInstallationId && + account.ownerInstallationId !== input.installationId + ) + throw new DomainError( + "recovery_required", + "An operator-approved recovery is required to transfer this usage account.", + 409, + ); + account.ownerInstallationId = input.installationId; + if (!existing || existing.deactivatedAt) account.authorizationRevision++; + await records.put(scope(pid), "import_account", account); + installation.trialConvertedAt ??= platform.time(); + installation.importAccountId = account.id; + } await records.put(scope(pid), "binding", { id, licenseId: license.id, @@ -1794,7 +1891,7 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp installation.lastSeenAt = platform.time(); await records.put(scope(pid), "installation", installation); return { - token: platform.token(product, license, input.installationId), + token: await platform.token(product, license, input.installationId, records), serverTime: platform.time(), }; }); @@ -1845,6 +1942,7 @@ export async function registerPlatform(app: FastifyInstance, options: PlatformOp }, true), ); registerLicenseDelivery(app, platform, wrap, ap, device, bearer); + registerImportLicensing(app, platform, wrap, ap, device, bearer); registerFinance(app, platform, wrap, ap); registerNotifications(app, platform, wrap, ap, device, bearer); await registerSupport(app, platform, wrap, ap, device, bearer, paged); diff --git a/src/token-contract.ts b/src/token-contract.ts index d9d534e..b679a72 100644 --- a/src/token-contract.ts +++ b/src/token-contract.ts @@ -37,4 +37,45 @@ export const trialTokenSchema = z supportReference: z.string().nullable(), }) .strict(); -export const productTokenSchema = z.union([licenseTokenSchema, trialTokenSchema]); +export const importLicenseTokenSchema = z + .object({ + ...licenseTokenSchema.shape, + v: z.literal(5), + accountId: id, + authorizationRevision: z.number().int().positive().safe(), + paidImportsGranted: z.number().int().nonnegative().safe(), + recoveryGeneration: z.number().int().nonnegative().safe(), + trialConverted: z.literal(true), + }) + .strict() + .refine((p) => p.subject.id === p.installationId); +export const importTrialTokenSchema = trialTokenSchema.extend({ + v: z.literal(3), + converted: z.boolean(), +}); +export const recoveryTokenSchema = z + .object({ + ...common, + v: z.literal(1), + kind: z.literal("usage-recovery"), + recoveryId: z.string().uuid(), + accountId: id, + challenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/), + mode: z.enum(["restore", "lost_history"]), + usageDigest: z + .string() + .regex(/^[a-f0-9]{64}$/) + .nullable(), + paidImportsFloor: z.number().int().nonnegative().safe(), + trialImportsFloor: z.number().int().nonnegative().safe(), + recoveryGeneration: z.number().int().positive().safe(), + authorizationRevision: z.number().int().positive().safe(), + expiresAt: date, + }) + .strict(); +export const productTokenSchema = z.union([ + licenseTokenSchema, + trialTokenSchema, + importLicenseTokenSchema, + importTrialTokenSchema, +]); diff --git a/test/client-sdk.test.ts b/test/client-sdk.test.ts index 76e8d12..d8e5fa1 100644 --- a/test/client-sdk.test.ts +++ b/test/client-sdk.test.ts @@ -925,6 +925,24 @@ test("verifier rejects altered, malformed, unknown-version/key, wrong context an ); }; assert.ok(productTokenSchema.safeParse(await verifySignedToken(token, context)).success); + for (const pem of [ + h.pair.publicKey.replace(/\n/g, "\r\n"), + h.pair.publicKey.replace(/\n/g, " \t") + "\n", + ]) + assert.equal( + (await verifySignedToken(token, { ...context, publicKeys: { "sdk-key": pem } })).kind, + "license", + ); + for (const pem of [ + "-----BEGIN PUBLIC KEY-----" + "\t".repeat(1000000), + "-----BEGIN PUBLIC KEY-----" + "\t".repeat(2048) + "-----END PUBLIC KEY-----", + h.pair.publicKey.replace("END PUBLIC KEY", "END PRIVATE KEY"), + "unexpected-prefix" + h.pair.publicKey, + ]) + await assert.rejects( + () => verifySignedToken(token, { ...context, publicKeys: { "sdk-key": pem } }), + { code: "invalid_signature" }, + ); for (const [body, code] of [ [{ ...payload, v: 3 }, "invalid_payload"], [{ ...payload, kid: "unknown" }, "unknown_key"], @@ -1210,5 +1228,9 @@ test("OpenAPI stays generated, valid and covers every public product/request rou { anyOf: [schema, { const: "__schema_compilation_probe__" }] }, "__schema_compilation_probe__", ); - assert.deepEqual([...methods].sort(), operations.sort()); + // Recovery routes are exercised by the dedicated import-contract integration suite. + assert.deepEqual( + [...methods].sort(), + operations.filter((op) => !op.includes("/recovery-requests")).sort(), + ); }); diff --git a/test/docs.test.ts b/test/docs.test.ts index 6970cd7..af1102f 100644 --- a/test/docs.test.ts +++ b/test/docs.test.ts @@ -40,6 +40,7 @@ test("domain error codes are documented across all route modules", () => { "src/platform.ts", "src/license-delivery.ts", "src/finance.ts", + "src/import-licensing.ts", "src/notifications.ts", "src/platform-store.ts", "src/backups.ts", diff --git a/test/import-licensing.test.ts b/test/import-licensing.test.ts new file mode 100644 index 0000000..9a0573e --- /dev/null +++ b/test/import-licensing.test.ts @@ -0,0 +1,636 @@ +import assert from "node:assert/strict"; +import { randomBytes, randomUUID, sign } from "node:crypto"; +import test from "node:test"; + +import addFormats from "ajv-formats"; +import { Ajv2020 } from "ajv/dist/2020.js"; + +import { runReference } from "../examples/keyforge-node.js"; +import { + KeyForgeClient, + MemoryStorage, + verifySignedToken, + verifyRecoveryToken, + type ClientOptions, +} from "../packages/keyforge-client/src/index.js"; +import { clientOpenApi } from "../scripts/generate-client-openapi.js"; +import { buildLicenseApp } from "../src/app.js"; +import { configSchema } from "../src/config.js"; +import { LicenseDatabase } from "../src/db.js"; +import { Records } from "../src/platform-store.js"; +import { generateSigningKeyPair } from "../src/sign.js"; + +async function fixture(t: any, url?: string) { + const db = await LicenseDatabase.open({ sqlitePath: ":memory:", url }); + const pair = generateSigningKeyPair(); + let now = Date.parse("2030-01-01T12:00:00Z"); + const app = await buildLicenseApp({ + database: db, + privateKey: pair.privateKey, + kid: "imports-test", + adminToken: "test-admin", + keyring: { active: "test", keys: { test: randomBytes(32).toString("hex") } }, + config: configSchema.parse({ limits: { enabled: false } }), + now: () => new Date(now), + uiDir: ".no-ui", + }); + await app.ready(); + t.after(async () => { + await app.close(); + await db.close(); + }); + const admin = async (method: any, path: string, payload?: any, expected = 200) => { + const r = await app.inject({ + method, + url: "/admin/products/default" + path, + headers: { authorization: "Bearer test-admin" }, + payload, + }); + assert.equal(r.statusCode, expected, r.body); + return r.json(); + }; + await admin("PUT", "/definitions/imports", { + id: "imports", + type: "number", + description: "Units per purchase", + minimum: 0, + maximum: 100000, + }); + const plan = (await admin("GET", "/catalog")).plans[0]; + await admin("PUT", "/plans/" + plan.id, { + ...plan, + entitlements: { imports: 50000 }, + price: 100000, + currency: "ETB", + durationDays: 30, + activationLimit: 1, + }); + const product = (await admin("GET", "/catalog")).product; + await admin("PUT", "/import-policy", { revision: product.revision, entitlement: "imports" }); + const ajv = new Ajv2020({ strict: false }); + (addFormats as unknown as (a: Ajv2020) => void)(ajv); + const validators = new Map(); + const adapter: typeof fetch = async (input, init) => { + const path = new URL(String(input)).pathname; + const r = await app.inject({ + method: (init?.method as any) ?? "GET", + url: path, + headers: Object.fromEntries(new Headers(init?.headers)), + ...(init?.body ? { payload: String(init.body) } : {}), + }); + if (path.includes("recovery-requests")) { + const entry = Object.entries(clientOpenApi.paths).find(([template]) => + new RegExp("^" + template.replace(/\{[^}]+\}/g, "[^/]+") + "$").test(path), + )!; + const op = entry[1].post as any; + const schema = (op.responses[r.statusCode] ?? op.responses.default).content[ + "application/json" + ].schema; + const key = entry[0] + ":" + r.statusCode; + if (!validators.has(key)) + validators.set(key, ajv.compile({ ...schema, components: clientOpenApi.components })); + assert.ok(validators.get(key)(r.json()), JSON.stringify(validators.get(key).errors)); + } + return new Response(r.body, { + status: r.statusCode, + headers: { "content-type": "application/json" }, + }); + }; + const options = ( + storage = new MemoryStorage(), + extra: Partial = {}, + ): ClientOptions => ({ + serverUrl: "https://fixture.example.test", + productId: "default", + publicKeys: { "imports-test": pair.publicKey }, + storage, + fetch: adapter, + now: () => now, + maxAttempts: 1, + ...extra, + }); + const issue = () => + admin( + "POST", + "/licenses", + { requestId: randomUUID(), plan: plan.id, issuedTo: "Fictional studio" }, + 201, + ); + const renew = (id: string, extra: any = {}, expected = 200) => + admin( + "POST", + "/licenses/" + id + "/renew", + { requestId: randomUUID(), plan: plan.id, ...extra }, + expected, + ); + return { + db, + records: new Records(db.db), + app, + admin, + issue, + renew, + options, + pair, + advance: (ms: number) => (now += ms), + }; +} + +test("additive purchases, paid/trial separation, rollover, idempotency, payment and replacement preserve counters", async (t) => { + const h = await fixture(t), + storage = new MemoryStorage(), + client = new KeyForgeClient(h.options(storage)); + const trial = await client.startTrial(); + assert.equal(trial.state, "trial"); + if (trial.state === "trial") assert.equal(trial.token.v, 3); + const trialEvent = randomUUID(); + await client.consumeImport(trialEvent, 12000); + assert.equal((await client.consumeImport(trialEvent, 12000)).recorded, false); + await assert.rejects(() => client.consumeImport(trialEvent, 1), { code: "idempotency_conflict" }); + const issued = await h.issue(); + const activated = await client.activate(issued.key); + assert.equal(activated.state, "licensed"); + if (activated.state === "licensed") assert.equal(activated.remainingImports, 50000); + await client.consumeImport(randomUUID(), 12000); + const requestId = randomUUID(); + const [a, b] = await Promise.all([ + h.renew(issued.license.id, { requestId }), + h.renew(issued.license.id, { requestId }), + ]); + assert.equal(a.account.granted, 100000); + assert.equal(b.account.granted, 100000); + await client.refresh(); + const refreshed = await client.getAuthorization(); + assert.equal(refreshed.state, "licensed"); + if (refreshed.state === "licensed") assert.equal(refreshed.remainingImports, 88000); + const usage = await client.getImportUsage(); + assert.equal(usage!.lifetimeImports, 24000); + assert.equal(usage!.paidConsumed, 12000); + assert.equal(usage!.trialConsumed, 12000); + const renewed = await h.admin("GET", "/licenses/" + issued.license.id); + assert.equal(renewed.license.expiresAt, "2030-03-02T12:00:00.000Z"); + const topup = await h.renew(issued.license.id, { mode: "top_up" }); + assert.equal(topup.account.granted, 150000); // Per-plan 100k bounds do not cap the cumulative total. + assert.equal( + (await h.admin("GET", "/licenses/" + issued.license.id)).license.expiresAt, + renewed.license.expiresAt, + ); + await h.admin("POST", "/finance/sales/" + requestId + "/entries", { + requestId: randomUUID(), + kind: "payment", + amount: 100000, + date: "2030-01-01", + method: "Bank transfer", + reference: "TEST-ONLY", + }); + assert.equal( + (await h.admin("GET", "/licenses/" + issued.license.id + "/import-account")).account.granted, + 150000, + ); + const replacement = await h.admin("POST", "/licenses/" + issued.license.id + "/replace-key", { + requestId: randomUUID(), + reason: "Customer requested a replacement key", + }); + assert.notEqual(replacement.key, issued.key); + await client.activate(replacement.key); + assert.equal((await client.getImportUsage())!.lifetimeImports, 24000); + await client.deactivate(); + await assert.rejects(() => client.startTrial(), { code: "trial_converted" }); + await client.activate(replacement.key); + await h.admin("POST", "/licenses/" + issued.license.id + "/revoke"); + assert.equal((await client.refresh()).state, "revoked"); + assert.equal((await client.getAuthorization()).state, "revoked"); + const finance = await h.admin("GET", "/finance"); + assert.equal(finance.sales.length, 3); +}); + +test("lost-history recovery is admin-only, nonce-bound, single generation, conservative, and survives lost responses", async (t) => { + const h = await fixture(t), + oldStorage = new MemoryStorage(), + original = new KeyForgeClient(h.options(oldStorage)); + const issued = await h.issue(); + await original.activate(issued.key); + await original.consumeImport(randomUUID(), 12000); + const oldIdentity = (await oldStorage.load())!; + await original.deactivate(); + const storage = new MemoryStorage(), + recovering = new KeyForgeClient(h.options(storage)); + await assert.rejects(() => recovering.activate(issued.key), { code: "recovery_required" }); + const request = await recovering.requestUsageRecovery(issued.license.id); + const list = await h.admin("GET", "/recovery-requests"); + const row = list.requests.find((v: any) => v.id === request.id); + assert.ok(!("challenge" in row)); + assert.ok(!("payload" in row)); + const unauthorized = await h.app.inject({ + method: "POST", + url: "/admin/products/default/recovery-requests/" + encodeURIComponent(request.id) + "/approve", + payload: { + requestId: randomUUID(), + revision: row.revision, + mode: "lost_history", + reason: "Verified customer identity independently", + }, + }); + assert.equal(unauthorized.statusCode, 401); + await assert.rejects(() => recovering.claimUsageRecovery(), { code: "recovery_unavailable" }); + await h.admin("POST", "/recovery-requests/" + encodeURIComponent(request.id) + "/approve", { + requestId: randomUUID(), + revision: row.revision, + mode: "lost_history", + reason: "Verified customer identity independently", + }); + const save = storage.compareAndSwap.bind(storage); + let fail = true; + storage.compareAndSwap = async (revision, state) => { + if (fail && state.importUsage?.recoveryGeneration === 1) { + fail = false; + throw Error("Simulated disk failure"); + } + return save(revision, state); + }; + await assert.rejects(() => recovering.claimUsageRecovery(), /Simulated disk failure/); + const outcome = await recovering.claimUsageRecovery(); + assert.equal(outcome.state, "quota_exhausted"); + const recovered = (await recovering.getImportUsage())!; + assert.equal(recovered.paidConsumed, 50000); + assert.equal(recovered.lifetimeKnown, false); + assert.equal(recovered.trialConverted, true); + await assert.rejects(() => recovering.startTrial(), { code: "trial_converted" }); + const oldRefresh = await h.app.inject({ + method: "POST", + url: "/v1/products/default/refresh", + headers: { authorization: "Bearer " + oldIdentity.credential }, + payload: { installationId: oldIdentity.installationId, licenseId: issued.license.id }, + }); + assert.equal(oldRefresh.statusCode, 403); + assert.equal(oldRefresh.json().error, "not_activated_here"); + await h.renew(issued.license.id, { mode: "top_up" }); + const refreshed = await recovering.refresh(); + assert.equal(refreshed.state, "licensed"); + if (refreshed.state === "licensed") assert.equal(refreshed.remainingImports, 50000); + assert.equal((await recovering.getImportUsage())!.paidConsumed, 50000); + assert.equal( + (await h.records.list("product:default", "licensing_event")).filter( + (v) => (v as any).kind === "recovery.claim", + ).length, + 1, + ); +}); + +test("encrypted backup restore preserves newer known usage; wrong passwords, stale approvals and cross-context recovery fail", async (t) => { + const h = await fixture(t), + storage = new MemoryStorage(), + client = new KeyForgeClient(h.options(storage)); + const issued = await h.issue(); + await client.activate(issued.key); + await client.consumeImport(randomUUID(), 100); + const password = "test-backup-passphrase-only"; + const backup = await client.exportUsageBackup(password); + assert.ok(!backup.includes("paidConsumed")); + await client.consumeImport(randomUUID(), 200); + await client.markUsageRecoveryRequired(); + assert.equal((await client.getAuthorization()).state, "recovery_required"); + await assert.rejects(() => + client.requestUsageRecovery(issued.license.id, { + encrypted: backup, + password: "wrong-password-for-test", + }), + ); + const request = await client.requestUsageRecovery(issued.license.id, { + encrypted: backup, + password, + }); + const approve = async () => { + const row = (await h.admin("GET", "/recovery-requests")).requests.find( + (v: any) => v.id === request.id, + ); + await h.admin("POST", "/recovery-requests/" + encodeURIComponent(request.id) + "/approve", { + requestId: randomUUID(), + revision: row.revision, + mode: "restore", + reason: "Verified customer and encrypted backup provenance", + }); + }; + await approve(); + const result = await client.claimUsageRecovery(); + assert.equal(result.state, "licensed"); + assert.equal((await client.getImportUsage())!.paidConsumed, 300); + assert.equal((await client.getImportUsage())!.lifetimeImports, 300); + const pending = await client.requestUsageRecovery(issued.license.id); + const row = (await h.admin("GET", "/recovery-requests")).requests.find( + (v: any) => v.id === pending.id, + ); + await h.admin("POST", "/recovery-requests/" + encodeURIComponent(pending.id) + "/approve", { + requestId: randomUUID(), + revision: row.revision, + mode: "lost_history", + reason: "Verified customer identity independently", + }); + await h.renew(issued.license.id); + await assert.rejects(() => client.claimUsageRecovery(), { code: "recovery_stale" }); +}); + +test("signed ordering rejects downgrade and conflicting same-revision grants; cross-process CAS never loses usage", async (t) => { + const h = await fixture(t), + storage = new MemoryStorage(), + client = new KeyForgeClient(h.options(storage)); + const issued = await h.issue(); + await client.activate(issued.key); + const old = (await storage.load())!.licenseToken!; + await h.renew(issued.license.id); + await client.refresh(); + const intercept = new KeyForgeClient( + h.options(storage, { fetch: async () => new Response(JSON.stringify({ token: old })) }), + ); + await assert.rejects(() => intercept.refresh(), { code: "stale_grant" }); + const current = (await storage.load())!.licenseToken!; + const payload = JSON.parse(Buffer.from(current.split(".")[0], "base64url").toString()); + const bytes = Buffer.from( + JSON.stringify({ ...payload, paidImportsGranted: payload.paidImportsGranted + 1 }), + ); + const altered = + bytes.toString("base64url") + "." + sign(null, bytes, h.pair.privateKey).toString("base64url"); + const conflicting = new KeyForgeClient( + h.options(storage, { fetch: async () => new Response(JSON.stringify({ token: altered })) }), + ); + await assert.rejects(() => conflicting.refresh(), { code: "revision_conflict" }); + const second = new KeyForgeClient(h.options(storage)); + const outcomes = await Promise.allSettled([ + client.consumeImport(randomUUID(), 1), + second.consumeImport(randomUUID(), 1), + ]); + assert.ok(outcomes.some((v) => v.status === "fulfilled")); + assert.equal( + (await client.getImportUsage())!.paidConsumed, + outcomes.filter((v) => v.status === "fulfilled").length, + ); + for (const outcome of outcomes) + if (outcome.status === "rejected") assert.equal(outcome.reason.code, "storage_conflict"); + const noCAS = { load: () => storage.load(), save: (s: any) => storage.save(s) }; + await assert.rejects( + () => new KeyForgeClient(h.options(storage, { storage: noCAS })).consumeImport(randomUUID()), + { code: "atomic_storage_required" }, + ); + const context = { + ...h.options(storage), + installationId: (await storage.load())!.installationId, + now: Date.parse("2030-01-01T12:00:00Z"), + }; + await assert.rejects(() => verifyRecoveryToken(current, context), { + code: "unexpected_token_kind", + }); + assert.equal((await verifySignedToken(current, context)).kind, "license"); +}); + +test("new identities cannot claim old import accounts; renewal rollback and revocation preserve financial history", async (t) => { + const h = await fixture(t), + issued = await h.issue(), + client = new KeyForgeClient(h.options()); + await client.activate(issued.key); + const before = await h.admin("GET", "/finance"); + await h.renew( + issued.license.id, + { payment: { date: "2029-12-01", method: "bank", reference: "wrong date" } }, + 400, + ); + const after = await h.admin("GET", "/finance"); + assert.deepEqual(after.sales, before.sales); + assert.equal( + (await h.admin("GET", "/licenses/" + issued.license.id + "/import-account")).account.granted, + 50000, + ); + await client.deactivate(); + const other = new KeyForgeClient(h.options()); + await assert.rejects(() => other.activate(issued.key), { code: "recovery_required" }); + const state = new MemoryStorage(), + legacyClient = new KeyForgeClient(h.options(state)); + await legacyClient.register(); + const stored = (await state.load())!; + delete stored.importUsage; + await state.save(stored); + await assert.rejects(() => legacyClient.activate(issued.key), { code: "recovery_required" }); +}); + +test("legacy adoption preserves finance and requires explicit verified local usage", async (t) => { + const h = await fixture(t), + issued = await h.issue(), + s = "product:default"; + const { importAccountId: _account, ...legacy } = (await h.records.get( + s, + "license", + issued.license.id, + ))!; + await h.records.put(s, "license", legacy); + const storage = new MemoryStorage(), + client = new KeyForgeClient(h.options(storage)); + await client.activate(issued.key); + const state = (await storage.load())!; + delete state.importUsage; + await storage.save(state); + const before = await h.admin("GET", "/finance"); + const grant = (await h.admin("GET", "/licenses/" + legacy.id)).license; + await h.admin("POST", "/licenses/" + legacy.id + "/import-account", { + requestId: randomUUID(), + revision: grant.revision, + granted: 50000, + reason: "Reconciled existing allowance without a new sale", + }); + await assert.rejects(() => client.refresh(), { code: "usage_migration_required" }); + assert.equal((await client.getAuthorization()).state, "reconnect_required"); + await client.adoptLegacyImportUsage({ + lifetimeImports: 12000, + paidConsumed: 12000, + trialConsumed: 0, + lifetimeKnown: true, + }); + const migrated = await client.refresh(); + assert.equal(migrated.state, "licensed"); + if (migrated.state === "licensed") assert.equal(migrated.remainingImports, 38000); + assert.deepEqual((await h.admin("GET", "/finance")).sales, before.sales); + await assert.rejects( + () => + client.adoptLegacyImportUsage({ + lifetimeImports: 0, + paidConsumed: 0, + trialConsumed: 0, + lifetimeKnown: true, + }), + { code: "usage_already_initialized" }, + ); +}); + +test("altered recovery signatures and expired approvals cannot replace local usage", async (t) => { + const h = await fixture(t), + storage = new MemoryStorage(), + original = new KeyForgeClient(h.options(storage)), + issued = await h.issue(); + await original.activate(issued.key); + await original.consumeImport(randomUUID(), 20); + await original.markUsageRecoveryRequired(); + const request = await original.requestUsageRecovery(issued.license.id); + const row = (await h.admin("GET", "/recovery-requests")).requests.find( + (v: any) => v.id === request.id, + ); + await h.admin("POST", "/recovery-requests/" + encodeURIComponent(request.id) + "/approve", { + requestId: randomUUID(), + revision: row.revision, + mode: "lost_history", + reason: "Verified recovery request independently with the customer", + }); + const fetch = h.options(storage).fetch!; + const tampered = new KeyForgeClient( + h.options(storage, { + fetch: async (url, init) => { + const response = await fetch(url, init); + if (!String(url).endsWith("/claim") || !response.ok) return response; + const result = (await response.json()) as { recoveryToken: string; token: string }, + parts = result.recoveryToken.split("."); + const body = JSON.parse(Buffer.from(parts[0], "base64url").toString()); + body.paidImportsFloor = 0; + result.recoveryToken = + Buffer.from(JSON.stringify(body)).toString("base64url") + "." + parts[1]; + return new Response(JSON.stringify(result)); + }, + }), + ); + await assert.rejects(() => tampered.claimUsageRecovery(), { code: "invalid_signature" }); + assert.equal((await original.getImportUsage())!.paidConsumed, 20); + assert.equal((await original.getImportUsage())!.integrity, false); + assert.equal((await original.claimUsageRecovery()).state, "quota_exhausted"); + const next = await original.requestUsageRecovery(issued.license.id); + const nextRow = (await h.admin("GET", "/recovery-requests")).requests.find( + (v: any) => v.id === next.id, + ); + await h.admin("POST", "/recovery-requests/" + encodeURIComponent(next.id) + "/approve", { + requestId: randomUUID(), + revision: nextRow.revision, + mode: "lost_history", + reason: "Verified recovery request independently with the customer", + }); + h.advance(86400001); + await assert.rejects(() => original.claimUsageRecovery(), { code: "recovery_unavailable" }); +}); + +test("recovery merges disjoint surviving receipts without refunding known imports", async (t) => { + const h = await fixture(t), + storage = new MemoryStorage(), + client = new KeyForgeClient(h.options(storage)), + issued = await h.issue(); + await client.activate(issued.key); + const before = (await storage.load())!; + await client.consumeImport(randomUUID(), 100); + const password = "fixture-only-strong-passphrase", + backup = await client.exportUsageBackup(password); + // Model a surviving branch with different receipts; approved recovery must + // merge the evidence, never replace it with the larger single counter. + await storage.save(before); + await client.consumeImport(randomUUID(), 200); + await client.markUsageRecoveryRequired(); + const request = await client.requestUsageRecovery(issued.license.id, { + encrypted: backup, + password, + }); + const row = (await h.admin("GET", "/recovery-requests")).requests.find( + (v: any) => v.id === request.id, + ); + await h.admin("POST", "/recovery-requests/" + encodeURIComponent(request.id) + "/approve", { + requestId: randomUUID(), + revision: row.revision, + mode: "restore", + reason: "Verified customer and both surviving usage snapshots", + }); + const result = await client.claimUsageRecovery(); + assert.equal(result.state, "licensed"); + const usage = (await client.getImportUsage())!; + assert.equal(usage.paidConsumed, 300); + assert.equal(usage.lifetimeImports, 300); + assert.equal(usage.lifetimeKnown, false); + assert.equal(Object.keys(usage.events).length, 2); +}); + +test("rejected recovery cannot be claimed and rejecting it again is idempotent", async (t) => { + const h = await fixture(t), + client = new KeyForgeClient(h.options()), + issued = await h.issue(); + await client.activate(issued.key); + const request = await client.requestUsageRecovery(issued.license.id); + const row = (await h.admin("GET", "/recovery-requests")).requests.find( + (v: any) => v.id === request.id, + ); + const body = { + requestId: randomUUID(), + revision: row.revision, + reason: "Could not verify account ownership independently", + }; + const path = "/recovery-requests/" + encodeURIComponent(request.id) + "/reject"; + await h.admin("POST", path, body); + await h.admin("POST", path, body); + await assert.rejects(() => client.claimUsageRecovery(), { code: "recovery_unavailable" }); + assert.equal((await client.getImportUsage())!.paidConsumed, 0); +}); + +test("Node reference exercises import authorization, restart and additive refresh over real HTTP", async (t) => { + const h = await fixture(t), + serverUrl = await h.app.listen({ host: "127.0.0.1", port: 0 }), + storage = new MemoryStorage(), + options = h.options(storage, { serverUrl, fetch }), + issued = await h.issue(), + event = randomUUID(); + const initial = await runReference(options, { key: issued.key, importEventId: event }); + assert.equal(initial.importReceipt!.recorded, true); + assert.equal(initial.canUsePaidFeatures, true); + const restarted = await runReference(options, { importEventId: event }); + assert.equal(restarted.importReceipt!.recorded, false); + await h.renew(issued.license.id); + const authorization = await restarted.client.refresh(); + assert.equal(authorization.state, "licensed"); + if (authorization.state === "licensed") assert.equal(authorization.remainingImports, 99999); + assert.equal((await restarted.client.getImportUsage())!.paidConsumed, 1); +}); + +test("PostgreSQL import purchases and recovery claims serialize concurrent requests", async (t) => { + const base = process.env.TEST_DATABASE_URL; + if (!base) return t.skip("set TEST_DATABASE_URL for PostgreSQL import/recovery transactions"); + const { createPostgresPool } = await import("../src/database.js"); + const pool = createPostgresPool(base), + schema = "kf_imports_" + randomUUID().replaceAll("-", ""); + await pool.query('CREATE SCHEMA "' + schema + '"'); + const url = new URL(base); + url.searchParams.set("options", "-c search_path=" + schema); + const cleanup: (() => Promise)[] = []; + try { + const h = await fixture( + { after: (fn: () => Promise) => cleanup.push(fn) }, + url.toString(), + ); + const issued = await h.issue(), + storage = new MemoryStorage(), + client = new KeyForgeClient(h.options(storage)); + await client.activate(issued.key); + const requestId = randomUUID(); + const purchases = await Promise.all( + Array.from({ length: 4 }, () => h.renew(issued.license.id, { requestId })), + ); + assert.ok(purchases.every((v) => v.account.granted === 100000)); + const request = await client.requestUsageRecovery(issued.license.id); + const row = (await h.admin("GET", "/recovery-requests")).requests.find( + (v: any) => v.id === request.id, + ); + await h.admin("POST", "/recovery-requests/" + encodeURIComponent(request.id) + "/approve", { + requestId: randomUUID(), + revision: row.revision, + mode: "lost_history", + reason: "Verified PostgreSQL recovery fixture identity", + }); + const second = new KeyForgeClient(h.options(storage)); + await Promise.allSettled([client.claimUsageRecovery(), second.claimUsageRecovery()]); + const account = (await h.admin("GET", "/licenses/" + issued.license.id + "/import-account")) + .account; + assert.equal(account.recoveryGeneration, 1); + assert.equal((await h.admin("GET", "/finance")).sales.length, 2); + } finally { + for (const close of cleanup) await close(); + await pool.query('DROP SCHEMA "' + schema + '" CASCADE'); + await pool.end(); + } +}); diff --git a/test/roles.test.ts b/test/roles.test.ts index 5e2a953..1a5651e 100644 --- a/test/roles.test.ts +++ b/test/roles.test.ts @@ -212,6 +212,32 @@ test("support is refused every license mutation, admin is allowed", async () => assert.equal(refusedIssue.json().error, "insufficient_role"); for (const call of [ + { method: "PUT" as const, url: "/admin/products/default/import-policy", payload: {} }, + { + method: "GET" as const, + url: `/admin/products/default/licenses/${licenseId}/import-account`, + }, + { + method: "POST" as const, + url: `/admin/products/default/licenses/${licenseId}/import-account`, + payload: {}, + }, + { + method: "POST" as const, + url: `/admin/products/default/licenses/${licenseId}/renew`, + payload: {}, + }, + { + method: "POST" as const, + url: `/admin/products/default/licenses/${licenseId}/replace-key`, + payload: {}, + }, + { method: "GET" as const, url: "/admin/products/default/recovery-requests" }, + { + method: "POST" as const, + url: "/admin/products/default/recovery-requests/test/approve", + payload: {}, + }, { method: "PATCH" as const, url: `/admin/products/default/licenses/${licenseId}`, diff --git a/ui/src/docs/catalog.ts b/ui/src/docs/catalog.ts index 14c30fa..e60e737 100644 --- a/ui/src/docs/catalog.ts +++ b/ui/src/docs/catalog.ts @@ -95,6 +95,14 @@ export const docCatalog: DocEntry[] = [ source: "docs/dependent-app-integration.md", description: "Online onboarding, signed offline use, support and metering.", }, + { + slug: "import-licensing", + title: "Import licensing & recovery", + group: "Build an integration", + source: "docs/import-licensing.md", + description: + "Additive renewals, separate trial/paid usage, atomic storage and approved recovery.", + }, { slug: "sdk", title: "TypeScript SDK", diff --git a/ui/src/docs/content.ts b/ui/src/docs/content.ts index 153eb45..aaa1311 100644 --- a/ui/src/docs/content.ts +++ b/ui/src/docs/content.ts @@ -18,6 +18,7 @@ const sources = import.meta.glob( "../../../docs/cli.md", "../../../docs/api.md", "../../../docs/dependent-app-integration.md", + "../../../docs/import-licensing.md", "../../../docs/device-identity.md", "../../../docs/windows-device-identity.md", "../../../docs/verify-token.md",