From 0a966e358a701f74ce9a35b888b9ddad1b73f95f Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 11 Aug 2026 08:31:46 +0000 Subject: [PATCH 01/54] HF-307 PR 1: entitlement model, capability registry, gate B (#307) Implements tasks 1.1-1.5 of the HF-307 spec (rev 2.4): the license entitlement model, the capability registry, and gate B in the interpreter's FUNCTION_CALL evaluation. Gate A (existing key-validity check) is untouched. New: - src/license/LicenseEntitlement.ts: FeatureId, LicenseExpiry, LicenseEntitlement, unrestrictedEntitlement() - src/license/capabilities.ts: CapabilityGrant, CAPABILITY_TABLE (placeholder: every built-in under one 'core' token, refreshed from the static function registry on every CapabilityRegistry construction rather than at module load, since src/index.ts registers built-in plugins only after Config/Interpreter have already been evaluated) - src/license/CapabilityRegistry.ts: resolve() (transitive, cycle-safe `implies` expansion), capabilityOf(), allowsFunction(), allowsFeature() Modified: - src/Config.ts: licenseCapabilities/isLicenseGateActive/ capabilityRegistry added to the existing privatePool WeakMap, never exposed through getConfig() - src/interpreter/Interpreter.ts: gate B added after gate A in the FUNCTION_CALL case, with a custom-function exemption predicate (capabilityOf() === undefined) and alias canonicalization so an alias gates identically to its canonical name - src/error-message.ts: ErrorMessage.LicenseCapability Decision deltas applied (Kuba, 2026-08-10): D1 (custom_functions token dropped this release, FeatureId.CustomFunctions kept as reserved vocabulary) and D3 (fail-closed + silent: an entitlement with no recognized token grants only core, without a message, warning, or diagnostics getter - unrestrictedEntitlement() no longer covers that case). D2 and D4 are out of scope for this PR. PR 1 ships without a real license-key payload adapter (PR 3), so Config always resolves an unrestricted entitlement for now - gate B is a correct, independently-testable no-op in production until PR 3 lands. Full PR description, verification notes, and drafted private-repo tests (no credentials available this session for hyperformula-tests): marcin-kb/handoffs/hf-307-pr1-tests/ Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01GuUdq242TtFaepKRNdEkj9 --- src/Config.ts | 63 ++++++++++++++- src/error-message.ts | 1 + src/interpreter/Interpreter.ts | 25 +++++- src/license/CapabilityRegistry.ts | 126 ++++++++++++++++++++++++++++++ src/license/LicenseEntitlement.ts | 91 +++++++++++++++++++++ src/license/capabilities.ts | 56 +++++++++++++ 6 files changed, 357 insertions(+), 5 deletions(-) create mode 100644 src/license/CapabilityRegistry.ts create mode 100644 src/license/LicenseEntitlement.ts create mode 100644 src/license/capabilities.ts diff --git a/src/Config.ts b/src/Config.ts index 8e8a924eee..2eae9aa60b 100644 --- a/src/Config.ts +++ b/src/Config.ts @@ -20,11 +20,24 @@ import {checkLicenseKeyValidity, LicenseKeyValidityState} from './helpers/licens import {HyperFormula} from './HyperFormula' import {TranslationPackage} from './i18n' import {FunctionPluginDefinition} from './interpreter' +import {CapabilityRegistry, ResolvedCapabilities} from './license/CapabilityRegistry' +import {unrestrictedEntitlement} from './license/LicenseEntitlement' import {Maybe} from './Maybe' import {ParserConfig} from './parser/ParserConfig' import {ConfigParams, ConfigParamsList} from './ConfigParams' -const privatePool: WeakMap = new WeakMap() +/** + * The license-derived state kept off the public `ConfigParams` surface — see + * {@link Config.licenseCapabilities}. + */ +interface LicensePrivateState { + licenseKeyValidityState: LicenseKeyValidityState, + licenseCapabilities: ResolvedCapabilities, + isLicenseGateActive: boolean, + capabilityRegistry: CapabilityRegistry, +} + +const privatePool: WeakMap = new WeakMap() export class Config implements ConfigParams, ParserConfig { @@ -266,8 +279,19 @@ export class Config implements ConfigParams, ParserConfig { validateNumberToBeAtLeast(this.maxColumns, 'maxColumns', 1) this.context = context + const licenseKeyValidityState = checkLicenseKeyValidity(this.licenseKey) + const capabilityRegistry = new CapabilityRegistry() + // PR 1 (HF-307) ships the gate infrastructure without a real license-key payload adapter — + // that lands in PR 3 as src/license/payloadAdapter.ts. Until then every entitlement resolves + // as unrestricted, so isLicenseGateActive below reduces to today's licenseKeyValidityState + // check and gate B in the interpreter never actually restricts a function. + const licenseCapabilities = capabilityRegistry.resolve(unrestrictedEntitlement()) + privatePool.set(this, { - licenseKeyValidityState: checkLicenseKeyValidity(this.licenseKey) + licenseKeyValidityState, + licenseCapabilities, + isLicenseGateActive: licenseKeyValidityState !== LicenseKeyValidityState.VALID || !licenseCapabilities.unrestricted, + capabilityRegistry, }) configCheckIfParametersNotInConflict( @@ -305,7 +329,40 @@ export class Config implements ConfigParams, ParserConfig { * @internal */ public get licenseKeyValidityState(): LicenseKeyValidityState { - return (privatePool.get(this) as Config).licenseKeyValidityState + return (privatePool.get(this) as LicensePrivateState).licenseKeyValidityState + } + + /** + * The functions and features this config's license entitles it to, already resolved from + * whatever tokens the license key carries. Proxied to its private counterpart for the same + * reason as {@link licenseKeyValidityState}: it must never become part of {@link getConfig}. + * + * @internal + */ + public get licenseCapabilities(): ResolvedCapabilities { + return (privatePool.get(this) as LicensePrivateState).licenseCapabilities + } + + /** + * Whether gate B (the entitlement check in the interpreter) needs to run at all for this + * config. `false` — the common case, for `gpl-v3`, legacy keys, and an unrestricted typed + * key — is a single boolean read, cheaper than the string-enum comparison it replaces. + * + * @internal + */ + public get isLicenseGateActive(): boolean { + return (privatePool.get(this) as LicensePrivateState).isLicenseGateActive + } + + /** + * The registry used to resolve this config's entitlement into {@link licenseCapabilities}. + * Exposed so the interpreter can tell a custom, instance-registered function apart from a + * built-in outside the capability table without constructing a second registry. + * + * @internal + */ + public get capabilityRegistry(): CapabilityRegistry { + return (privatePool.get(this) as LicensePrivateState).capabilityRegistry } public getConfig(): ConfigParams { diff --git a/src/error-message.ts b/src/error-message.ts index 5e3afdbeab..df6548b97e 100644 --- a/src/error-message.ts +++ b/src/error-message.ts @@ -77,4 +77,5 @@ export class ErrorMessage { public static FunctionName = (arg: string) => `Function name ${arg} not recognized.` public static NamedExpressionName = (arg: string) => `Named expression ${arg} not recognized.` public static LicenseKey = (arg: string) => `License key is ${arg}.` + public static LicenseCapability = (functionName: string) => `Function ${functionName} is not included in your license.` } diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 8edf08f0a9..2c6e39f2a0 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -13,6 +13,7 @@ import {DependencyGraph} from '../DependencyGraph' import {FormulaVertex} from '../DependencyGraph/FormulaVertex' import {ErrorMessage} from '../error-message' import {LicenseKeyValidityState} from '../helpers/licenseKeyValidator' +import {allowsFunction} from '../license/CapabilityRegistry' import {ColumnSearchStrategy} from '../Lookup/SearchStrategy' import {Maybe} from '../Maybe' import {NamedExpressions} from '../NamedExpressions' @@ -61,6 +62,17 @@ export class Interpreter { this.criterionBuilder = new CriterionBuilder(config) } + /** + * Resolves a function id to the name it is covered by in the capability table. A function + * registered purely as an alias of another one (`plugin.aliases`) must gate identically to + * its canonical name — otherwise calling a gated function through its alias would silently + * bypass the entitlement check. + */ + private canonicalFunctionId(functionId: string): string { + const plugin = this.functionRegistry.getFunctionPlugin(functionId) + return plugin?.aliases?.[functionId] ?? functionId + } + public evaluateAst(ast: Ast, state: InterpreterState): InterpreterValue { let val = this.evaluateAstWithoutPostprocessing(ast, state) if (isExtendedNumber(val)) { @@ -177,8 +189,17 @@ export class Interpreter { return this.unaryRangeWrapper(this.percentOp, result, state) } case AstNodeType.FUNCTION_CALL: { - if (this.config.licenseKeyValidityState !== LicenseKeyValidityState.VALID && !FunctionRegistry.functionIsProtected(ast.procedureName)) { - return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(this.config.licenseKeyValidityState)) + if (this.config.isLicenseGateActive && !FunctionRegistry.functionIsProtected(ast.procedureName)) { + const validityState = this.config.licenseKeyValidityState + if (validityState !== LicenseKeyValidityState.VALID) { + return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(validityState)) + } + + const canonicalId = this.canonicalFunctionId(ast.procedureName) + if (this.config.capabilityRegistry.capabilityOf(canonicalId) !== undefined + && !allowsFunction(this.config.licenseCapabilities, canonicalId)) { + return new CellError(ErrorType.LIC, ErrorMessage.LicenseCapability(ast.procedureName)) + } } const pluginFunction = this.functionRegistry.getFunction(ast.procedureName) if (pluginFunction !== undefined) { diff --git a/src/license/CapabilityRegistry.ts b/src/license/CapabilityRegistry.ts new file mode 100644 index 0000000000..61462c82e3 --- /dev/null +++ b/src/license/CapabilityRegistry.ts @@ -0,0 +1,126 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +import {FeatureId, LicenseEntitlement} from './LicenseEntitlement' +import {CAPABILITY_TABLE, CapabilityGrant, refreshCoreGrant} from './capabilities' + +/** + * The capabilities a resolved {@link LicenseEntitlement} grants, ready for gate B (the + * interpreter) and PR 2's `ensureCapability` to query through {@link allowsFunction} and + * {@link allowsFeature}. + */ +export interface ResolvedCapabilities { + /** `true` short-circuits both {@link allowsFunction} and {@link allowsFeature} to `true`. */ + unrestricted: boolean, + functions: ReadonlySet, + features: ReadonlySet, +} + +/** + * Expands a {@link LicenseEntitlement}'s capability tokens against a table of + * {@link CapabilityGrant}s into the concrete functions and features they grant, and answers + * which token, if any, covers a given function id. + */ +export class CapabilityRegistry { + private readonly table: ReadonlyMap + private readonly reverseIndex: ReadonlyMap + + /** + * @param {ReadonlyMap} [table] - capability table to resolve + * against. Omit to use the production {@link CAPABILITY_TABLE}; tests inject their own so the + * suite does not depend on its placeholder content. + */ + constructor(table?: ReadonlyMap) { + if (table === undefined) { + refreshCoreGrant() + } + this.table = table ?? CAPABILITY_TABLE + this.reverseIndex = CapabilityRegistry.buildReverseIndex(this.table) + } + + /** + * Inverts a capability table from token → grant into function id → token, so + * {@link capabilityOf} is a single lookup instead of a scan. The first token that lists a + * given function id wins, in table iteration order. + * + * @param {ReadonlyMap} table - the table to invert + */ + private static buildReverseIndex(table: ReadonlyMap): ReadonlyMap { + const index = new Map() + for (const [token, grant] of table) { + for (const functionId of grant.functions) { + if (!index.has(functionId)) { + index.set(functionId, token) + } + } + } + return index + } + + /** + * Expands an entitlement's capability tokens into the concrete functions and features they + * grant. An `unrestricted` entitlement short-circuits to an unrestricted result without + * consulting the table at all. Expansion through `implies` is transitive and cycle-safe (a + * visited set guards against a token implying itself, directly or through others); an + * unrecognized token is skipped without an error. + * + * @param {LicenseEntitlement} entitlement - the entitlement to resolve, e.g. one built by + * hand in a test or produced by PR 3's license-key payload adapter + */ + public resolve(entitlement: LicenseEntitlement): ResolvedCapabilities { + if (entitlement.unrestricted) { + return {unrestricted: true, functions: new Set(), features: new Set()} + } + + const functions = new Set() + const features = new Set() + const visited = new Set() + const queue = [...entitlement.capabilities] + + while (queue.length > 0) { + const token = queue.shift() as string + if (visited.has(token)) { + continue + } + visited.add(token) + + const grant = this.table.get(token) + if (grant === undefined) { + continue + } + grant.functions.forEach((functionId) => functions.add(functionId)) + grant.features.forEach((feature) => features.add(feature)) + grant.implies?.forEach((impliedToken) => queue.push(impliedToken)) + } + + return {unrestricted: false, functions, features} + } + + /** + * Returns the capability token a function id is covered by, or `undefined` if this registry's + * table does not cover it. The completeness invariant in + * `unit/license/capability-registry.spec.ts` guarantees every built-in registered in the + * static function registry is covered by the table, the core token, or the protected list — + * so `undefined` for a function known to the current instance's function registry means it is + * a custom, instance-registered function rather than an unlisted built-in. + */ + public capabilityOf(functionId: string): string | undefined { + return this.reverseIndex.get(functionId) + } +} + +/** + * Whether a resolved entitlement allows calling the given function. + */ +export function allowsFunction(resolved: ResolvedCapabilities, functionId: string): boolean { + return resolved.unrestricted || resolved.functions.has(functionId) +} + +/** + * Whether a resolved entitlement allows using the given feature area of the public API. + */ +export function allowsFeature(resolved: ResolvedCapabilities, feature: FeatureId): boolean { + return resolved.unrestricted || resolved.features.has(feature) +} diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts new file mode 100644 index 0000000000..9472d13500 --- /dev/null +++ b/src/license/LicenseEntitlement.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Identifies a feature area of the public API that a license entitlement can gate. + * + * `CustomFunctions` and `ImportExport` are reserved vocabulary: they exist so a license payload + * is free to carry them, but no capability grant in this release maps to either of them yet. + * HF-307 decision D1 drops function-registration gating (and the `CustomFunctions` grant) from + * this release; `ImportExport` has no gated methods until HF-107 lands. + */ +export const enum FeatureId { + NamedExpressions = 'named_expressions', + Clipboard = 'clipboard', + Crud = 'crud', + UndoRedo = 'undo_redo', + Batching = 'batching', + CustomFunctions = 'custom_functions', + ImportExport = 'import_export', +} + +/** + * Describes when a license entitlement stops being valid. + * + * Per key-spec rev 3 §1.3, `date` is kept as a calendar string rather than an epoch, and is + * INCLUSIVE of its last valid day: + * - `kind === 'usage'`: `date` is compared against the client's LOCAL calendar date — deliberately + * not UTC, the date means the date, wherever the customer is. + * - `kind === 'release'`: `date` is compared LEXICOGRAPHICALLY, as text, against the library's + * build date; no clock is involved. + * - `kind === 'none'`: the entitlement does not expire. + */ +export interface LicenseExpiry { + kind: 'usage' | 'release' | 'none', + /** ISO 'YYYY-MM-DD', or `null` when `kind` is `'none'`. */ + date: string | null, + noticeDays: number, + graceDays: number, +} + +/** + * The resolved set of things a license grants, independent of how the underlying license key + * was parsed. + * + * This is the contract every later HF-307 task consumes: {@link CapabilityRegistry} turns it + * into a `ResolvedCapabilities` set, gate B in the interpreter reads that set, and PR 2's + * `ensureCapability` reads it for the public API. Until PR 3 lands the real license-key payload + * adapter, instances of this are built by hand in tests rather than read from a real key. + */ +export interface LicenseEntitlement { + /** `true` for every key this library fully understands today (`gpl-v3`, legacy keys). */ + unrestricted: boolean, + /** Capability tokens this entitlement grants, recognized by this library version. */ + capabilities: ReadonlySet, + /** + * Tokens present on the license payload that this library version does not recognize. + * Kept for diagnostics and tests; per HF-307 decision D3 nothing public reads this field — an + * unrecognized token never grants a capability, and it does so silently. + */ + unrecognizedCapabilities: readonly string[], + expiry: LicenseExpiry, + /** + * When `true`, resolving this entitlement must not print a console message of any kind. + * HF-307 decision D3 (fail-closed, silent): a typed key with no recognized token resolves + * like an explicit `capabilities: []` — core and protected functions only, without a message, + * a warning, or a diagnostics getter. + */ + silent: boolean, + isTrial: boolean, +} + +/** + * The unrestricted entitlement: legacy keys and `gpl-v3` resolve to this today. + * + * HF-307 decision D3 (fail-closed, silent) means a typed key whose tokens this library version + * does not recognize at all no longer maps here — it resolves to an entitlement with an empty, + * silent capability set instead of falling back to unrestricted access. Do not reuse this + * function for that case. + */ +export function unrestrictedEntitlement(): LicenseEntitlement { + return { + unrestricted: true, + capabilities: new Set(), + unrecognizedCapabilities: [], + expiry: {kind: 'none', date: null, noticeDays: 0, graceDays: 0}, + silent: false, + isTrial: false, + } +} diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts new file mode 100644 index 0000000000..8584336073 --- /dev/null +++ b/src/license/capabilities.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +import {FunctionRegistry} from '../interpreter/FunctionRegistry' +import {FeatureId} from './LicenseEntitlement' + +/** The single capability token every built-in currently falls under, see {@link CAPABILITY_TABLE}. */ +export const CORE_TOKEN = 'core' + +/** + * Describes what a capability token grants: a set of function ids, a set of {@link FeatureId} + * values, and optionally other tokens it implies. `implies` is expanded recursively by + * `CapabilityRegistry.resolve`, not by anything in this file. + */ +export interface CapabilityGrant { + functions: string[], + features: FeatureId[], + implies?: string[], +} + +const coreGrant: CapabilityGrant = { + functions: [], + features: [FeatureId.NamedExpressions, FeatureId.Clipboard, FeatureId.Crud, FeatureId.UndoRedo, FeatureId.Batching], +} + +/** + * The production capability table. + * + * Placeholder content pending HF-331/HF-329 (the real per-package token vocabulary): every + * built-in function, plus the features already wired for gating in PR 2, fall under the single + * {@link CORE_TOKEN}. `FeatureId.CustomFunctions` and `FeatureId.ImportExport` are deliberately + * absent — reserved vocabulary with no grant yet (HF-307 decision D1; HF-107 for ImportExport). + * + * `coreGrant.functions` starts empty and is refreshed on every {@link refreshCoreGrant} call + * rather than populated once here: `src/index.ts` registers HyperFormula's built-in plugins as a + * side effect of being imported, and it does so AFTER `Config` and `Interpreter` — and so this + * module — have already been fully evaluated. Reading the function registry at module-load time + * would capture an empty registry. + */ +export const CAPABILITY_TABLE: ReadonlyMap = new Map([[CORE_TOKEN, coreGrant]]) + +/** + * Refreshes the placeholder `core` grant with every function currently in the static function + * registry. Called from `CapabilityRegistry`'s constructor every time it is constructed without + * an explicit table — not just the first time: the static registry can change after the first + * engine is built (`HyperFormula.registerFunctionPlugin`/`unregisterFunctionPlugin` are public, + * documented APIs), and a one-time snapshot would silently go stale for every engine built + * afterward. Cheap (a single array copy from an existing map's keys) and only ever runs once per + * `Config`/engine construction, never on the per-formula hot path, so re-running it every time + * costs nothing worth guarding against with memoization. + */ +export function refreshCoreGrant(): void { + coreGrant.functions = FunctionRegistry.getRegisteredFunctionIds() +} From 54ce850deb95ed23280c6e5c234c312ff27041a5 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 22 Sep 2026 11:40:35 +0000 Subject: [PATCH 02/54] refactor(HF-307): drop the unused implication step from capability grants No grant in the table ever named another token, and the table is documented as holding its entries fully expanded, so the recursive walk resolved nothing that a flat pass over the entitlement's own tokens does not. Removing the field takes the queue, the visited set and the cycle guard with it. Repeating a token still grants what it grants once, which the paired suite now pins directly rather than through implication. Co-Authored-By: Claude Opus 5 (1M context) --- src/license/CapabilityRegistry.ts | 17 ++++------------- src/license/capabilities.ts | 7 +++---- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/src/license/CapabilityRegistry.ts b/src/license/CapabilityRegistry.ts index 61462c82e3..6320913db9 100644 --- a/src/license/CapabilityRegistry.ts +++ b/src/license/CapabilityRegistry.ts @@ -62,9 +62,9 @@ export class CapabilityRegistry { /** * Expands an entitlement's capability tokens into the concrete functions and features they * grant. An `unrestricted` entitlement short-circuits to an unrestricted result without - * consulting the table at all. Expansion through `implies` is transitive and cycle-safe (a - * visited set guards against a token implying itself, directly or through others); an - * unrecognized token is skipped without an error. + * consulting the table at all. Every grant in the table stands on its own — a token never + * refers to another — so this is a flat pass over the entitlement's own tokens; an + * unrecognized token is skipped without an error, and a repeated one adds nothing twice. * * @param {LicenseEntitlement} entitlement - the entitlement to resolve, e.g. one built by * hand in a test or produced by PR 3's license-key payload adapter @@ -76,23 +76,14 @@ export class CapabilityRegistry { const functions = new Set() const features = new Set() - const visited = new Set() - const queue = [...entitlement.capabilities] - - while (queue.length > 0) { - const token = queue.shift() as string - if (visited.has(token)) { - continue - } - visited.add(token) + for (const token of entitlement.capabilities) { const grant = this.table.get(token) if (grant === undefined) { continue } grant.functions.forEach((functionId) => functions.add(functionId)) grant.features.forEach((feature) => features.add(feature)) - grant.implies?.forEach((impliedToken) => queue.push(impliedToken)) } return {unrestricted: false, functions, features} diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts index 8584336073..0a32bf3d22 100644 --- a/src/license/capabilities.ts +++ b/src/license/capabilities.ts @@ -10,14 +10,13 @@ import {FeatureId} from './LicenseEntitlement' export const CORE_TOKEN = 'core' /** - * Describes what a capability token grants: a set of function ids, a set of {@link FeatureId} - * values, and optionally other tokens it implies. `implies` is expanded recursively by - * `CapabilityRegistry.resolve`, not by anything in this file. + * Describes what a capability token grants: a set of function ids and a set of {@link FeatureId} + * values. A grant never refers to another token — every one stands alone, so + * `CapabilityRegistry.resolve` reads the table in a single flat pass. */ export interface CapabilityGrant { functions: string[], features: FeatureId[], - implies?: string[], } const coreGrant: CapabilityGrant = { From 40ad18aa56c69c9043eb7f56e2b1a6d0aa597376 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 22 Sep 2026 16:29:01 +0000 Subject: [PATCH 03/54] fix(HF-307): split the unrestricted capability flag into two axes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Kuba Sękowski's review of #1728 (src/license/CapabilityRegistry.ts:16): a single `unrestricted: boolean` cannot express a key that grants every function but not every feature, or the reverse - both axes could only be granted together or neither. ResolvedCapabilities.functions and .features are now each `ReadonlySet | 'all'`, and allowsFunction/allowsFeature check their own axis independently. `unrestricted` carries a fail-open invariant (resolveLicense: a missing, invalid or expired key resolves to an unrestricted entitlement, by design - gate A already stops evaluation on a bad key, so gate B must not turn a lapsed legacy key into a throwing API). Splitting it opens a matching fail-closed trap: an edit that sets 'all' on one axis and forgets the other silently narrows a working install instead of leaking anything. Both axes are set in the same object literal in CapabilityRegistry.resolve() for exactly that reason, and the paired test commit pins each axis separately so a one-axis regression fails only one test. Does not touch LicenseEntitlement.unrestricted, a distinct field on the pre-resolution entitlement that this change leaves alone. Co-Authored-By: Claude Opus 5 (1M context) --- src/Config.ts | 3 ++- src/license/CapabilityRegistry.ts | 32 +++++++++++++++++++++---------- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/src/Config.ts b/src/Config.ts index 2eae9aa60b..6bd96d7615 100644 --- a/src/Config.ts +++ b/src/Config.ts @@ -290,7 +290,8 @@ export class Config implements ConfigParams, ParserConfig { privatePool.set(this, { licenseKeyValidityState, licenseCapabilities, - isLicenseGateActive: licenseKeyValidityState !== LicenseKeyValidityState.VALID || !licenseCapabilities.unrestricted, + isLicenseGateActive: licenseKeyValidityState !== LicenseKeyValidityState.VALID || + licenseCapabilities.functions !== 'all' || licenseCapabilities.features !== 'all', capabilityRegistry, }) diff --git a/src/license/CapabilityRegistry.ts b/src/license/CapabilityRegistry.ts index 6320913db9..adbcfc4f44 100644 --- a/src/license/CapabilityRegistry.ts +++ b/src/license/CapabilityRegistry.ts @@ -12,10 +12,15 @@ import {CAPABILITY_TABLE, CapabilityGrant, refreshCoreGrant} from './capabilitie * {@link allowsFeature}. */ export interface ResolvedCapabilities { - /** `true` short-circuits both {@link allowsFunction} and {@link allowsFeature} to `true`. */ - unrestricted: boolean, - functions: ReadonlySet, - features: ReadonlySet, + /** + * `'all'` short-circuits {@link allowsFunction} to `true` for every function id, independently + * of {@link features}: a key can cover every function without covering every feature, or the + * other way round. A single `unrestricted: boolean` could not express that combination — it + * could only grant both axes together or neither (review of #1728, Kuba Sękowski). + */ + functions: ReadonlySet | 'all', + /** `'all'` short-circuits {@link allowsFeature} to `true` for every {@link FeatureId}. */ + features: ReadonlySet | 'all', } /** @@ -61,17 +66,24 @@ export class CapabilityRegistry { /** * Expands an entitlement's capability tokens into the concrete functions and features they - * grant. An `unrestricted` entitlement short-circuits to an unrestricted result without - * consulting the table at all. Every grant in the table stands on its own — a token never + * grant. An `unrestricted` entitlement short-circuits to `'all'` on BOTH axes without + * consulting the table at all — every grant in the table stands on its own — a token never * refers to another — so this is a flat pass over the entitlement's own tokens; an * unrecognized token is skipped without an error, and a repeated one adds nothing twice. * + * Setting `'all'` on both axes here, in the same object literal, is deliberate: this is the + * only place `entitlement.unrestricted` is read, so a future edit that touches one axis and + * not the other has nowhere else to be caught except the per-axis fail-open tests in + * `unit/license/capability-registry.spec.ts`. The axis a change forgets fails CLOSED, not + * open — silently turning a working gpl-v3/legacy install into a partial denial — which is why + * both are pinned separately rather than with one combined assertion. + * * @param {LicenseEntitlement} entitlement - the entitlement to resolve, e.g. one built by * hand in a test or produced by PR 3's license-key payload adapter */ public resolve(entitlement: LicenseEntitlement): ResolvedCapabilities { if (entitlement.unrestricted) { - return {unrestricted: true, functions: new Set(), features: new Set()} + return {functions: 'all', features: 'all'} } const functions = new Set() @@ -86,7 +98,7 @@ export class CapabilityRegistry { grant.features.forEach((feature) => features.add(feature)) } - return {unrestricted: false, functions, features} + return {functions, features} } /** @@ -106,12 +118,12 @@ export class CapabilityRegistry { * Whether a resolved entitlement allows calling the given function. */ export function allowsFunction(resolved: ResolvedCapabilities, functionId: string): boolean { - return resolved.unrestricted || resolved.functions.has(functionId) + return resolved.functions === 'all' || resolved.functions.has(functionId) } /** * Whether a resolved entitlement allows using the given feature area of the public API. */ export function allowsFeature(resolved: ResolvedCapabilities, feature: FeatureId): boolean { - return resolved.unrestricted || resolved.features.has(feature) + return resolved.features === 'all' || resolved.features.has(feature) } From 954d8c8ef51ef70511ecf1a3c78d75aa59dd0c67 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 24 Sep 2026 19:44:17 +0800 Subject: [PATCH 04/54] HF-307 PR 2: public API guards (ensureCapability) (#1729) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > **Update 2026-09-22 — review round with @sequba.** The sections below are the PR as written > before that round, kept for the reasoning they record. Where a sentence no longer matches the > code it is corrected inline and marked, rather than rewritten away. ### Context HF-307 (feature packages / entitlement gating). This is PR 2 of 4: guards on the public API. Stacked on hf-307-entitlement-gating-pr1 (#1728) - depends on `CapabilityRegistry`/`allowsFeature`/`FeatureId`/`Config.licenseCapabilities` from that PR. Mechanical, public-repo-only, no key-format knowledge needed. New: - `src/errors.ts` - `LicenseCapabilityMissingError`, mirroring the existing ~30 error classes. Now also exported from the public entrypoint (`src/index.ts`) - see finding 6. - `src/HyperFormula.ts` - private `ensureCapability(feature: FeatureId)`, mirroring `ensureEvaluationIsNotSuspended`: a single `isLicenseGateActive` boolean read on the fast path, then `allowsFeature` against the resolved entitlement. - `src/BuildEngineFactory.ts` - private static `ensureNamedExpressionsCapability(config, namedExpressions)`, the build-time counterpart (task 2.3). - ~~`src/CrudOperations.ts` - public `isCutClipboard()`~~ **removed 22.09**: the reviewer accepted the cut-paste bypass, so the second capability check it fed is gone and the wrapper with it. See the correction under finding 6. Modified: `ensureCapability` wired as the **first statement** (before argument validation - a license error should beat a type error) in the ~20 methods from spec §05 task 2.2: - NamedExpressions: `addNamedExpression`, `changeNamedExpression`, `removeNamedExpression` - Clipboard: `copy`, `cut`, `paste` — Clipboard only. (The conditional **Crud** check described under finding 6 was removed 22.09.) - Crud: `addRows`, `removeRows`, `addColumns`, `removeColumns`, `moveCells`, `moveRows`, `moveColumns`, `addSheet`, `removeSheet`, `clearSheet`, `setSheetContent`, `renameSheet`, `setCellContents`, `swapRowIndexes`, `setRowOrder`, `swapColumnIndexes`, `setColumnOrder` - UndoRedo: `undo`, `redo` - Batching: `batch`, `suspendEvaluation` — but **not** `resumeEvaluation`, see finding 4 below `CustomFunctions` is not gated anywhere, per HF-307 decision D1. `ImportExport` has no methods to gate yet (HF-107). **Where the line is drawn** (written into the `ensureCapability` JSDoc so a later change has to move it on purpose): - **Gated** — mutations that create value: the sheet, the clipboard, the undo history, the named-expression set. - **Not gated** — reads (`getCellValue`, `listNamedExpressions`, `getAllNamedExpressionsSerialized`, the `isItPossibleTo*` predicates) and teardown that only ever *removes* state (`clearClipboard`, `clearUndoStack`, `clearRedoStack`, `destroy`). Gating cleanup would let a restricted entitlement strand an integration mid-teardown while giving a licensee nothing. This mirrors gate B, which blocks *calling* a function rather than *reading* an already-computed value. There is a test pinning this, because "we chose not to gate cleanup" is otherwise indistinguishable from "we forgot these" — which is exactly how the reordering gap below survived the first pass, and how the cut/paste gap in finding 6 survived this one. **Open question resolved:** the handoff left "is `getAllNamedExpressions` gated or read-only-exempt?" open. There's no such method today (it's `listNamedExpressions`, `getNamedExpression`, `getAllNamedExpressionsSerialized`) - I left all three ungated. This follows gate B's own precedent: it blocks *calling* a function, not *reading* a cell's already-computed value, so a restricted entitlement can still see named expressions that already exist. Flagging for reviewers in case the intended scope was broader. Task 2.3: `BuildEngineFactory.ensureNamedExpressionsCapability` runs the same `allowsFeature(FeatureId.NamedExpressions)` check when the `namedExpressions` argument to `buildFromSheets`/`buildFromSheet`/`buildEmpty` (what `buildFromArray`/`buildFromSheets`/`buildEmpty` resolve to) is non-empty; an empty list is never checked. Deliberately **not** applied to `rebuildWithConfig` - that path re-serializes named expressions an already-built instance was already allowed to create (e.g. on `updateConfig()`), rather than accepting them fresh from a caller, so a later entitlement change must not retroactively break an existing instance's own state. This ships without a real license-key payload adapter (PR 3), so every entitlement `Config` can produce today is unrestricted - `ensureCapability` and the build-time check are correct, independently-testable no-ops in production until that adapter lands, exactly like gate B in PR 1. ### Self-review findings (after the PR was first opened) Recording these in the open rather than quietly amending, since several are things a reviewer should get to disagree with. Findings 4 and 5 came from Cursor Bugbot's inline comments and were confirmed here before fixing. Finding 6 came from an independent spec-to-ship review run against this PR specifically after it had already been open for review (a 5-dimension multi-agent pass: guard completeness, test-quality-by-mutation, the shipped build artifact, docs/CHANGELOG accuracy, and merge mechanics - each finding adversarially re-verified before being reported). **1. The Crud gate was bypassable — fixed in `8a26e2be7`.** The first pass gated `moveRows`/`moveColumns` but missed four structurally identical methods: `swapRowIndexes`, `setRowOrder`, `swapColumnIndexes`, `setColumnOrder`. A restricted entitlement with no Crud grant could still permute every row and column in a sheet, which defeats the gate for a whole class of structural mutation. All four are now gated *in their own right* rather than relying on the `swap*` method that the `set*Order` pair delegates to — otherwise `set*Order`'s own `mappingFromOrder` validation would run first and a type error would beat the license error, violating task 2.2's first-statement rule. **2. `ensureCapability` checks gate B only, never gate A — deliberate, and now an explicit invariant.** Today a missing or invalid key yields `#LIC!` in cells while the CRUD API keeps working; this PR preserves that exactly. The risk is forward-looking: if PR 3's key adapter resolves an invalid key to a *restricted* entitlement rather than an unrestricted one, every gated method here starts throwing and that becomes a silent breaking API change. This PR is what makes that reachable, so the invariant is documented at the guard itself. **Reviewers: worth confirming this is the intended split before PR 3 lands.** **3. Known evidence gap in the task 2.3 tests.** The `BuildEngineFactory` gate is exercised by calling the private static directly, because the public path (`buildFromArray(sheet, config, namedExpressions)` → throws) *cannot* be reached today — the factories construct their own `Config`, and every `Config` currently resolves unrestricted. So Codecov's 100% patch coverage overstates the evidence for that one check: the integration path is unproven until PR 3 makes a restricted `Config` constructible. Flagging rather than papering over it. **4. Gating `resumeEvaluation` could brick an engine — fixed in `c29a9ba40`.** Raised by Bugbot, confirmed. `resumeEvaluation` is the *only* exit from a suspended engine, and `_evaluationSuspended` survives `rebuildWithConfig`. So: suspend while Batching is granted → `updateConfig` produces an entitlement without Batching → the instance is permanently unusable, because every read throws `EvaluationSuspendedError` and the sole recovery path threw `LicenseCapabilityMissingError`. It is now ungated. `suspendEvaluation` and `batch` stay gated — those are the entry points that make the feature worth licensing, and if you cannot *enter* batching you can never extract value from it. Generalised into a rule on `ensureCapability` so it does not get re-added: **a capability check must never be reachable only on the way *out* of a state it let the caller into** — the same reasoning that leaves teardown ungated. **5. One of PR 1's tests was vacuous — fixed in the paired tests PR.** Also raised by Bugbot. PR 1's custom-function-exemption test built the sheet with `'=CUSTOMFUNC()'` already in it, so the formula was evaluated during `buildFromArray` while the entitlement was still unrestricted; `restrictEngine` then changed nothing that `getCellValue` would re-read, and the assertion passed against a cached value. I verified this rather than assuming it — deleting the exemption from `Interpreter.ts` outright left the test **still passing**. It now writes the formula via `setCellContents` *after* restricting, matching the shape its sibling tests already had, and the same mutation now correctly fails it. The two new `resumeEvaluation` regression tests were verified the same way (re-adding the gate fails them). **6. `paste` was a hard-gating bypass, plus a packaging gap and a documentation gap — found by an independent spec-to-ship review, all fixed.** - **Bypass (HIGH).** `paste()` checked only `FeatureId.Clipboard`, but `CrudOperations.paste()` dispatches to `moveCells()` internally when the clipboard holds a cut - the exact cell-relocating mutation the public `moveCells()` requires **Crud** for. A `Clipboard`-only entitlement could reach it via `cut()`+`paste()`, with no Crud grant ever checked. Reproduced live (the move fully executed, no exception, under a Clipboard-only entitlement) before fixing. Fixed by adding `CrudOperations.isCutClipboard()` and additionally gating `paste()` on `Crud` when the clipboard holds a cut - still checked before argument validation. **Reversed 22.09 at the reviewer's request** ("Drop this check. We accept this bypass"): granting the clipboard is taken to grant what the clipboard does, so this route is deliberately not gated on Crud as well. The check, the wrapper and the stale `@throws` tag are gone; the paired spec now pins the acceptance - a clipboard-only entitlement relocates the cell - so the hole cannot be closed again by accident. - **Packaging gap (HIGH).** `LicenseCapabilityMissingError` was never imported/exported from `src/index.ts`, so it was unreachable from the package's public entrypoint: `import {LicenseCapabilityMissingError} from 'hyperformula'` failed to compile (`TS2614`), the default-export static form was `undefined`, and no deep import worked either (the `exports` map in `package.json` only defines `.` and the i18n subpaths). A consumer had no supported way to catch this error by type - the existing test suite never caught it because it imports the class directly from `src/errors`, bypassing the public entrypoint entirely. Fixed by exporting it alongside the other ~30 error classes already there. - **Documentation gap (MEDIUM).** None of the 27 gated methods carried a `@throws [[LicenseCapabilityMissingError]]` tag, breaking this file's own established per-method `@throws` convention (every *other* exception type already gets one). The class-level `@see` list on `LicenseCapabilityMissingError` itself also wrongly named `resumeEvaluation` (which finding 4 deliberately excludes) and omitted all 17 Crud methods. Fixed: all 27 gated instance methods plus the 3 static build factories now carry the tag, and the `@see` list is corrected and complete. The same review also generalised finding coverage on the test side: mutation-testing every one of the 27 `ensureCapability` call sites found 17 with zero regression protection of their own (the "one test per feature group" strategy only pinned the group representative) - see the paired tests PR for the added coverage. *Process note, since it generalises:* Bugbot's findings 4 and 5 were missed by the automated review tier that scrapes them (a regex looking for `Severity: Medium` against Bugbot's actual `**Medium Severity**`), which reported a clean PASS. Finding 6 was missed by both Bugbot and a prior manual review pass (which had only caught the narrower, single-method version of the test-coverage gap). Worth reading Bugbot's inline comments directly rather than trusting an aggregator, and worth an independent adversarial pass even after a PR looks clean. ### How did you test your changes? - `tsc --noEmit` and `tsc -p tsconfig.test.json`: clean. - `eslint` on all changed files: 0 errors (pre-existing warning categories only, none introduced by this change). - Manual verification against the built engine (ts-node scratch script, not committed): every gated method throws `LicenseCapabilityMissingError` under a simulated restricted entitlement, an unrestricted entitlement (today's default) is unaffected, and `buildFromArray` with named expressions under the default unrestricted entitlement does not throw. Re-verified against a freshly rebuilt `commonjs` package for finding 6 specifically (the cut+paste fix and the `index.ts` export). - Private test suite pushed: [hyperformula-tests#31](https://github.com/handsontable/hyperformula-tests/pull/31) - `unit/license/public-api-guards.spec.ts` (42 tests: one positive + one negative per feature group, a validation-order test, the build-time bypass pair, five covering the reordering gap, one pinning the ungated-cleanup rule, two for the `resumeEvaluation` deadlock, one dedicated throw test per previously-group-only-covered method (15 of them), the cut/paste bypass control+regression pairs, and one proving `LicenseCapabilityMissingError` is reachable from the public entrypoint) plus fixes to PR 1's `unit/licence.spec.ts` (the test-helper interaction described in that PR, and the vacuous exemption test in finding 5). - **Mutation-checked, not just green:** the two `resumeEvaluation` tests, the repaired custom-function test, the cut+paste bypass fix itself, and a sample of the newly-added per-method tests (`removeRows`, `changeNamedExpression`) were each verified by reverting the corresponding source line and confirming the new test fails, then restoring. - Full suite against the paired branch: **511 suites / 6373 tests, 6370 passed, 3 pre-existing skips, 0 failures.** ### Types of changes - [ ] Breaking change - [x] New feature or improvement - [x] Bug fix - [ ] Additional language file, or a change to an existing language file (translations) - [ ] Change to the documentation ### Related issues: 1. HF-307 (internal tracker; no public GitHub issue for this one) ### Checklist: - [x] I have reviewed the guidelines about Contributing to HyperFormula and I confirm that my code follows the code style of this project. - [ ] I have signed the Contributor License Agreement. *(please confirm/attach on your end - I can't verify this from here)* - [ ] My change is compliant with the OpenDocument standard. *(N/A - no worksheet function behaviour changes in this PR)* - [ ] My change is compatible with Microsoft Excel. *(N/A - same reason)* - [ ] My change is compatible with Google Sheets. *(N/A - same reason)* - [ ] I described my changes in the CHANGELOG.md file. *(intentionally not done - internal-only change, no user-visible behaviour yet; a CHANGELOG entry lands with the PR that actually activates the gates for customers)* - [x] My changes require a documentation update. *(done - @throws tags and the @see list on LicenseCapabilityMissingError, see finding 6)* - [ ] My changes require a migration guide. *(no)* --- > [!NOTE] > **Medium Risk** > Wide API surface change: many mutation entry points can throw when restricted entitlements land in PR 3; deliberate exclusions (ungated `resumeEvaluation`, Clipboard-only paste) affect runtime behavior under partial licenses. > > **Overview** > Adds **license entitlement guards (HF-307 PR 2)** on the public HyperFormula API so restricted entitlements throw `LicenseCapabilityMissingError` instead of mutating the engine. > > A private `ensureCapability` runs as the **first statement** on gated instance methods when `isLicenseGateActive` is true: **Crud** (sheet/cell/row/column moves and structural edits), **UndoRedo**, **Clipboard** (`copy`/`cut`/`paste`—paste is Clipboard-only even when a cut relocates cells), **Batching** (`batch`, `suspendEvaluation` only; **`resumeEvaluation` stays ungated** so entitlement changes cannot strand a suspended instance), and **NamedExpressions** (add/change/remove). Reads, `isItPossibleTo*` helpers, and teardown (`clearClipboard`, undo/redo stack clears, `destroy`) stay ungated. > > **Build-time:** `BuildEngineFactory.ensureNamedExpressionsCapability` rejects non-empty initial `namedExpressions` without the feature on `buildFromSheets`/`buildFromSheet`/`buildEmpty`, but not on `rebuildWithConfig`. The new error is exported from `src/index.ts`, with `@throws` docs on affected methods. Until PR 3 supplies restricted entitlements, these checks are no-ops for today’s default configs. > > Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 690ef69d758a09c51e7e5ab97b203e137c52e632. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot). --------- Co-authored-by: Claude Sonnet 5 --- src/BuildEngineFactory.ts | 27 ++++++++- src/HyperFormula.ts | 114 ++++++++++++++++++++++++++++++++++++++ src/errors.ts | 49 ++++++++++++++++ src/index.ts | 3 + 4 files changed, 191 insertions(+), 2 deletions(-) diff --git a/src/BuildEngineFactory.ts b/src/BuildEngineFactory.ts index 62202a78c1..69b74eaea3 100644 --- a/src/BuildEngineFactory.ts +++ b/src/BuildEngineFactory.ts @@ -10,7 +10,7 @@ import {Config} from './Config' import {CrudOperations} from './CrudOperations' import {DateTimeHelper} from './DateTimeHelper' import {DependencyGraph} from './DependencyGraph' -import {SheetSizeLimitExceededError} from './errors' +import {LicenseCapabilityMissingError, SheetSizeLimitExceededError} from './errors' import {Evaluator} from './Evaluator' import {Exporter} from './Exporter' import {GraphBuilder} from './GraphBuilder' @@ -19,6 +19,8 @@ import {ArithmeticHelper} from './interpreter/ArithmeticHelper' import {FunctionRegistry} from './interpreter/FunctionRegistry' import {Interpreter} from './interpreter/Interpreter' import {LazilyTransformingAstService} from './LazilyTransformingAstService' +import {allowsFeature} from './license/CapabilityRegistry' +import {FeatureId} from './license/LicenseEntitlement' import {buildColumnSearchStrategy, ColumnSearchStrategy} from './Lookup/SearchStrategy' import {NamedExpressions} from './NamedExpressions' import {NumberLiteralHelper} from './NumberLiteralHelper' @@ -50,23 +52,44 @@ export type EngineState = { export class BuildEngineFactory { public static buildFromSheets(sheets: Sheets, configInput: Partial = {}, namedExpressions: SerializedNamedExpression[] = []): EngineState { const config = new Config(configInput) + this.ensureNamedExpressionsCapability(config, namedExpressions) return this.buildEngine(config, sheets, namedExpressions) } public static buildFromSheet(sheet: Sheet, configInput: Partial = {}, namedExpressions: SerializedNamedExpression[] = []): EngineState { const config = new Config(configInput) + this.ensureNamedExpressionsCapability(config, namedExpressions) const newsheetprefix = config.translationPackage.getUITranslation(UIElement.NEW_SHEET_PREFIX) + '1' return this.buildEngine(config, {[newsheetprefix]: sheet}, namedExpressions) } public static buildEmpty(configInput: Partial = {}, namedExpressions: SerializedNamedExpression[] = []): EngineState { - return this.buildEngine(new Config(configInput), {}, namedExpressions) + const config = new Config(configInput) + this.ensureNamedExpressionsCapability(config, namedExpressions) + return this.buildEngine(config, {}, namedExpressions) } public static rebuildWithConfig(config: Config, sheets: Sheets, namedExpressions: SerializedNamedExpression[], stats: Statistics): EngineState { return this.buildEngine(config, sheets, namedExpressions, stats) } + /** + * Throws if `namedExpressions` is non-empty and `config`'s entitlement does not grant + * {@link FeatureId.NamedExpressions} (HF-307 PR 2, task 2.3 - the build-time counterpart of + * {@link HyperFormula.ensureCapability}). An empty list is never checked: building an engine + * with no named expressions never touches the feature. Deliberately not called from + * {@link rebuildWithConfig}, which re-serializes named expressions an already-built instance + * created (and was allowed to create) rather than accepting them fresh from a caller. + */ + private static ensureNamedExpressionsCapability(config: Config, namedExpressions: SerializedNamedExpression[]): void { + if (namedExpressions.length === 0) { + return + } + if (config.isLicenseGateActive && !allowsFeature(config.licenseCapabilities, FeatureId.NamedExpressions)) { + throw new LicenseCapabilityMissingError(FeatureId.NamedExpressions) + } + } + private static buildEngine(config: Config, sheets: Sheets = {}, inputNamedExpressions: SerializedNamedExpression[] = [], stats: Statistics = config.useStats ? new Statistics() : new EmptyStatistics()): EngineState { stats.start(StatType.BUILD_ENGINE_TOTAL) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 522d7b1509..c66de99d5e 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -38,11 +38,14 @@ import { ExpectedValueOfTypeError, LanguageAlreadyRegisteredError, LanguageNotRegisteredError, + LicenseCapabilityMissingError, NotAFormulaError, } from './errors' import {Evaluator} from './Evaluator' import {ExportedChange, Exporter} from './Exporter' import {LicenseKeyValidityState} from './helpers/licenseKeyValidator' +import {allowsFeature} from './license/CapabilityRegistry' +import {FeatureId} from './license/LicenseEntitlement' import {buildTranslationPackage, RawTranslationPackage, TranslationPackage} from './i18n' import {FunctionPluginDefinition} from './interpreter' import {FUNCTION_DOCS} from './interpreter/functionMetadata' @@ -253,6 +256,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits * @throws [[InvalidArgumentsError]] when sheet is not an array of arrays * @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata + * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the current license entitlement does not grant the NamedExpressions feature * * @example * ```js @@ -293,6 +297,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits * @throws [[InvalidArgumentsError]] when any sheet is not an array of arrays * @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata + * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the current license entitlement does not grant the NamedExpressions feature * * @example * ```js @@ -335,6 +340,8 @@ export class HyperFormula implements TypedEmitter { * @param {Partial} configInput - engine configuration * @param {SerializedNamedExpression[]} namedExpressions - starting named expressions * + * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the current license entitlement does not grant the NamedExpressions feature + * * @example * ```js * const namedExpressions = [ @@ -1219,6 +1226,7 @@ export class HyperFormula implements TypedEmitter { * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoOperationToUndoError]] when there is no operation running that can be undone + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the UndoRedo feature * * @example * ```js @@ -1237,6 +1245,7 @@ export class HyperFormula implements TypedEmitter { * @category Undo and Redo */ public undo(): ExportedChange[] { + this.ensureCapability(FeatureId.UndoRedo) this._crudOperations.undo() return this.recomputeIfDependencyGraphNeedsIt() } @@ -1253,6 +1262,7 @@ export class HyperFormula implements TypedEmitter { * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoOperationToRedoError]] when there is no operation running that can be re-done + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the UndoRedo feature * * @example * ```js @@ -1275,6 +1285,7 @@ export class HyperFormula implements TypedEmitter { * @category Undo and Redo */ public redo(): ExportedChange[] { + this.ensureCapability(FeatureId.UndoRedo) this._crudOperations.redo() return this.recomputeIfDependencyGraphNeedsIt() } @@ -1389,6 +1400,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[InvalidArgumentsError]] when the value is not an array of arrays or a raw cell value * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding * @throws [[ExpectedValueOfTypeError]] if topLeftCornerAddress argument is of wrong type + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1407,6 +1419,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public setCellContents(topLeftCornerAddress: SimpleCellAddress, cellContents: RawCellContent[][] | RawCellContent): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) this._crudOperations.setCellContents(topLeftCornerAddress, cellContents) return this.recomputeIfDependencyGraphNeedsIt() } @@ -1427,6 +1440,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1459,6 +1473,7 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public swapRowIndexes(sheetId: number, rowMapping: [number, number][]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.setRowOrder(sheetId, rowMapping) return this.recomputeIfDependencyGraphNeedsIt() @@ -1522,6 +1537,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1542,6 +1558,7 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public setRowOrder(sheetId: number, newRowOrder: number[]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') const mapping = this._crudOperations.mappingFromOrder(sheetId, newRowOrder, 'row') return this.swapRowIndexes(sheetId, mapping) @@ -1604,6 +1621,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1635,6 +1653,7 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public swapColumnIndexes(sheetId: number, columnMapping: [number, number][]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.setColumnOrder(sheetId, columnMapping) return this.recomputeIfDependencyGraphNeedsIt() @@ -1695,6 +1714,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1713,6 +1733,7 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public setColumnOrder(sheetId: number, newColumnOrder: number[]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') const mapping = this._crudOperations.mappingFromOrder(sheetId, newColumnOrder, 'column') return this.swapColumnIndexes(sheetId, mapping) @@ -1808,6 +1829,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1824,6 +1846,7 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public addRows(sheetId: number, ...indexes: ColumnRowIndex[]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.addRows(sheetId, ...indexes) return this.recomputeIfDependencyGraphNeedsIt() @@ -1881,6 +1904,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1896,6 +1920,7 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public removeRows(sheetId: number, ...indexes: ColumnRowIndex[]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.removeRows(sheetId, ...indexes) return this.recomputeIfDependencyGraphNeedsIt() @@ -1953,6 +1978,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -1972,6 +1998,7 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public addColumns(sheetId: number, ...indexes: ColumnRowIndex[]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.addColumns(sheetId, ...indexes) return this.recomputeIfDependencyGraphNeedsIt() @@ -2028,6 +2055,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2047,6 +2075,7 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public removeColumns(sheetId: number, ...indexes: ColumnRowIndex[]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.removeColumns(sheetId, ...indexes) return this.recomputeIfDependencyGraphNeedsIt() @@ -2117,6 +2146,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2140,6 +2170,7 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public moveCells(source: SimpleCellRange, destinationLeftCorner: SimpleCellAddress): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) if (!isSimpleCellAddress(destinationLeftCorner)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'destinationLeftCorner') } @@ -2210,6 +2241,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2226,6 +2258,7 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public moveRows(sheetId: number, startRow: number, numberOfRows: number, targetRow: number): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') validateArgToType(startRow, 'number', 'startRow') validateArgToType(numberOfRows, 'number', 'numberOfRows') @@ -2292,6 +2325,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2314,6 +2348,7 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public moveColumns(sheetId: number, startColumn: number, numberOfColumns: number, targetColumn: number): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') validateArgToType(startColumn, 'number', 'startColumn') validateArgToType(numberOfColumns, 'number', 'numberOfColumns') @@ -2333,6 +2368,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Clipboard feature * * @example * ```js @@ -2352,6 +2388,7 @@ export class HyperFormula implements TypedEmitter { * @category Clipboard */ public copy(source: SimpleCellRange): CellValue[][] { + this.ensureCapability(FeatureId.Clipboard) if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } @@ -2373,6 +2410,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Clipboard feature * * @example * ```js @@ -2392,6 +2430,7 @@ export class HyperFormula implements TypedEmitter { * @category Clipboard */ public cut(source: SimpleCellRange): CellValue[][] { + this.ensureCapability(FeatureId.Clipboard) if (!isSimpleCellRange(source)) { throw new ExpectedValueOfTypeError('SimpleCellRange', 'source') } @@ -2421,6 +2460,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NothingToPasteError]] when clipboard is empty * @throws [[TargetLocationHasArrayError]] when the selected target area has array inside * @throws [[ExpectedValueOfTypeError]] if targetLeftCorner is of wrong type + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Clipboard feature * * @example * ```js @@ -2443,6 +2483,10 @@ export class HyperFormula implements TypedEmitter { * @category Clipboard */ public paste(targetLeftCorner: SimpleCellAddress): ExportedChange[] { + // Clipboard alone is enough, including for pasting a CUT - which relocates cells, the same + // mutation the public moveCells() requires Crud for. Granting the clipboard is taken to grant + // what the clipboard does, so this route is deliberately not gated on Crud as well. + this.ensureCapability(FeatureId.Clipboard) if (!isSimpleCellAddress(targetLeftCorner)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'targetLeftCorner') } @@ -2750,6 +2794,7 @@ export class HyperFormula implements TypedEmitter { * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[SheetNameAlreadyTakenError]] when sheet with a given name already exists + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2769,6 +2814,7 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public addSheet(sheetName?: string): string { + this.ensureCapability(FeatureId.Crud) if (sheetName !== undefined) { validateArgToType(sheetName, 'string', 'sheetName') } @@ -2824,6 +2870,7 @@ export class HyperFormula implements TypedEmitter { * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2844,6 +2891,7 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public removeSheet(sheetId: number): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') const displayName = this.sheetMapping.getSheetName(sheetId) as string this._crudOperations.removeSheet(sheetId) @@ -2897,6 +2945,7 @@ export class HyperFormula implements TypedEmitter { * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2917,6 +2966,7 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public clearSheet(sheetId: number): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.clearSheet(sheetId) return this.recomputeIfDependencyGraphNeedsIt() @@ -2968,6 +3018,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when values argument is not an array of arrays + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -2984,6 +3035,7 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public setSheetContent(sheetId: number, values: RawCellContent[][]): ExportedChange[] { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') this._crudOperations.setSheetContent(sheetId, values) return this.recomputeIfDependencyGraphNeedsIt() @@ -3656,6 +3708,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[SheetNameAlreadyTakenError]] when the provided sheet name already exists + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature * * @example * ```js @@ -3671,6 +3724,7 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public renameSheet(sheetId: number, newName: string): void { + this.ensureCapability(FeatureId.Crud) validateArgToType(sheetId, 'number', 'sheetId') validateArgToType(newName, 'string', 'newName') const oldName = this._crudOperations.renameSheet(sheetId, newName) @@ -3693,6 +3747,8 @@ export class HyperFormula implements TypedEmitter { * @fires [[evaluationSuspended]] always * @fires [[evaluationResumed]] after the recomputation of necessary values * + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Batching feature + * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ @@ -3712,6 +3768,7 @@ export class HyperFormula implements TypedEmitter { * @category Batch */ public batch(batchOperations: () => void): ExportedChange[] { + this.ensureCapability(FeatureId.Batching) this.suspendEvaluation() this._crudOperations.beginUndoRedoBatchMode() try { @@ -3734,6 +3791,8 @@ export class HyperFormula implements TypedEmitter { * * @fires [[evaluationSuspended]] always * + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Batching feature + * * @example * ```js * const hfInstance = HyperFormula.buildFromSheets({ @@ -3759,6 +3818,7 @@ export class HyperFormula implements TypedEmitter { * @category Batch */ public suspendEvaluation(): void { + this.ensureCapability(FeatureId.Batching) this._evaluationSuspended = true this._emitter.emit(Events.EvaluationSuspended) } @@ -3795,6 +3855,15 @@ export class HyperFormula implements TypedEmitter { * @category Batch */ public resumeEvaluation(): ExportedChange[] { + // Deliberately NOT gated, unlike suspendEvaluation and batch. This is the only exit from + // a suspended engine, and _evaluationSuspended survives rebuildWithConfig: an instance + // suspended while Batching was granted, whose entitlement then loses Batching via + // updateConfig, would be stuck suspended forever - every read throws + // EvaluationSuspendedError and the sole recovery path would throw + // LicenseCapabilityMissingError. Gating the two entry points is what makes the feature + // licensable; gating the release valve only strands the caller, which is the same reason + // teardown (clearClipboard, clearUndoStack, clearRedoStack) is ungated. See the note on + // ensureCapability. this._evaluationSuspended = false const changes = this.recomputeIfDependencyGraphNeedsIt() this._emitter.emit(Events.EvaluationResumed, changes) @@ -3882,6 +3951,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NamedExpressionNameIsInvalidError]] when the named-expression name is not valid * @throws [[NoRelativeAddressesAllowedError]] when the named-expression formula contains relative references * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the NamedExpressions feature * * @example * ```js @@ -3902,6 +3972,7 @@ export class HyperFormula implements TypedEmitter { * @category Named Expressions */ public addNamedExpression(expressionName: string, expression: RawCellContent, scope?: number, options?: NamedExpressionOptions): ExportedChange[] { + this.ensureCapability(FeatureId.NamedExpressions) validateArgToType(expressionName, 'string', 'expressionName') if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') @@ -4107,6 +4178,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * @throws [[ArrayFormulasNotSupportedError]] when the named expression formula is an array formula * @throws [[NoRelativeAddressesAllowedError]] when the named expression formula contains relative references + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the NamedExpressions feature * * @example * ```js @@ -4124,6 +4196,7 @@ export class HyperFormula implements TypedEmitter { * @category Named Expressions */ public changeNamedExpression(expressionName: string, newExpression: RawCellContent, scope?: number, options?: NamedExpressionOptions): ExportedChange[] { + this.ensureCapability(FeatureId.NamedExpressions) validateArgToType(expressionName, 'string', 'expressionName') if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') @@ -4188,6 +4261,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NamedExpressionDoesNotExistError]] when the given expression does not exist. * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists + * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the NamedExpressions feature * * @example * ```js @@ -4205,6 +4279,7 @@ export class HyperFormula implements TypedEmitter { * @category Named Expressions */ public removeNamedExpression(expressionName: string, scope?: number): ExportedChange[] { + this.ensureCapability(FeatureId.NamedExpressions) validateArgToType(expressionName, 'string', 'expressionName') if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') @@ -4767,6 +4842,45 @@ export class HyperFormula implements TypedEmitter { } } + /** + * Throws an error if the current license entitlement does not grant the given feature. + * A no-op read (`isLicenseGateActive === false`) whenever this instance's entitlement is + * unrestricted, i.e. for every key this library fully understands today (HF-307 PR 1); the + * check only does work once a real license-key payload adapter (a later HF-307 PR) can + * produce a restricted entitlement. + * + * Where the line is drawn, so a later change does not move it by accident: + * - **Gated:** methods that create value by mutating the sheet, the clipboard, the undo + * history, or the named-expression set. + * - **Not gated:** reads (`getCellValue`, `listNamedExpressions`, + * `getAllNamedExpressionsSerialized`, the `isItPossibleTo*` predicates) and teardown or + * cleanup that only ever removes state (`clearClipboard`, `clearUndoStack`, + * `clearRedoStack`, `destroy`). Gating cleanup would let a restricted entitlement strand + * an integration mid-teardown while giving a licensee nothing, and mirrors gate B, which + * blocks *calling* a function rather than *reading* an already-computed value. + * - **Not gated, for the same reason:** `resumeEvaluation`, the sole exit from a suspended + * engine. Gate the entry points (`suspendEvaluation`, `batch`) and the feature is + * licensable; gate the release valve too and an entitlement change mid-suspension leaves + * the instance permanently unusable. A capability check must never be reachable only on + * the way out of a state it let the caller into. + * + * Note this checks gate B (entitlement) only, never gate A (key validity). That asymmetry + * with the interpreter's gate B - which checks key validity first - is deliberate: it keeps + * today's behaviour for a missing or invalid key, where formulas yield `#LIC!` but the CRUD + * API keeps working. A later PR that resolves an invalid key to a *restricted* entitlement + * rather than an unrestricted one would silently turn that into a breaking API change. + * + * @internal + */ + private ensureCapability(feature: FeatureId): void { + if (!this._config.isLicenseGateActive) { + return + } + if (!allowsFeature(this._config.licenseCapabilities, feature)) { + throw new LicenseCapabilityMissingError(feature) + } + } + /** * Parses a formula string and extracts its AST and dependencies. * diff --git a/src/errors.ts b/src/errors.ts index 66a73a2add..7c0778d71d 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -4,6 +4,7 @@ */ import {SimpleCellAddress} from './Cell' +import {FeatureId} from './license/LicenseEntitlement' /** * Error thrown when the sheet of a given ID does not exist. @@ -392,3 +393,51 @@ export class AliasAlreadyExisting extends Error { super(`Alias id ${name} in plugin ${pluginName} already defined as a function or alias.`) } } + +/** + * Error thrown when a public API method is called for a {@link FeatureId} that the current + * license entitlement does not grant. Mirrors gate B's `ErrorMessage.LicenseCapability`, but + * this one guards the API surface itself (HF-307 PR 2) rather than a formula evaluation, so it + * is thrown synchronously instead of surfacing as a cell error. + * + * This list names every method that can throw it - `resumeEvaluation` is deliberately NOT among + * them: it is the sole exit from a suspended engine, so gating it could strand an instance + * permanently if the entitlement changes mid-suspension (see the note on `HyperFormula. + * ensureCapability`). + * + * @see [[HyperFormula.buildFromArray]] + * @see [[HyperFormula.buildFromSheets]] + * @see [[HyperFormula.buildEmpty]] + * @see [[addNamedExpression]] + * @see [[changeNamedExpression]] + * @see [[removeNamedExpression]] + * @see [[copy]] + * @see [[cut]] + * @see [[paste]] + * @see [[setCellContents]] + * @see [[addRows]] + * @see [[removeRows]] + * @see [[addColumns]] + * @see [[removeColumns]] + * @see [[moveCells]] + * @see [[moveRows]] + * @see [[moveColumns]] + * @see [[swapRowIndexes]] + * @see [[setRowOrder]] + * @see [[swapColumnIndexes]] + * @see [[setColumnOrder]] + * @see [[addSheet]] + * @see [[removeSheet]] + * @see [[clearSheet]] + * @see [[setSheetContent]] + * @see [[renameSheet]] + * @see [[undo]] + * @see [[redo]] + * @see [[batch]] + * @see [[suspendEvaluation]] + */ +export class LicenseCapabilityMissingError extends Error { + constructor(feature: FeatureId) { + super(`Feature ${feature} is not included in your license.`) + } +} diff --git a/src/index.ts b/src/index.ts index 23b060cf49..fa0db7f306 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,6 +26,7 @@ import { InvalidArgumentsError, LanguageAlreadyRegisteredError, LanguageNotRegisteredError, + LicenseCapabilityMissingError, MissingTranslationError, NamedExpressionDoesNotExistError, NamedExpressionNameIsAlreadyTakenError, @@ -86,6 +87,7 @@ class HyperFormulaNS extends HyperFormula { public static InvalidArgumentsError = InvalidArgumentsError public static LanguageNotRegisteredError = LanguageNotRegisteredError public static LanguageAlreadyRegisteredError = LanguageAlreadyRegisteredError + public static LicenseCapabilityMissingError = LicenseCapabilityMissingError public static MissingTranslationError = MissingTranslationError public static NamedExpressionDoesNotExistError = NamedExpressionDoesNotExistError public static NamedExpressionNameIsAlreadyTakenError = NamedExpressionNameIsAlreadyTakenError @@ -169,6 +171,7 @@ export { InvalidArgumentsError, LanguageAlreadyRegisteredError, LanguageNotRegisteredError, + LicenseCapabilityMissingError, MissingTranslationError, NamedExpressionDoesNotExistError, NamedExpressionNameIsAlreadyTakenError, From 6502eab330b63a7f52f14c199dd7ca62770d5213 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 24 Sep 2026 19:45:56 +0800 Subject: [PATCH 05/54] HF-307: license key reader (entitlement key format, rev 6), resolution, and capability table (#1730) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > **Update 2026-09-22 — review round with @sequba.** The sections below are the PR as written > before that round, kept for the reasoning they record. Where a sentence no longer matches the > code it is corrected inline and marked, rather than rewritten away. ## Update 2026-09-18 — folded #1731, #1736, #1737, #1740, #1741 into this PR So that no PR in this stack shows code a later PR rewrites, this PR now contains, squashed with no loss of content: the entitlement reader (rev 6, was #1740), the notice-window warning (was #1736), the two add-on tokens (was #1737), the function-metadata filtering (was #1731), and both capability-token dialects (was #1741). Those five PRs are closed, folded here. The stack is now `#1728 → #1729 → this PR → #1743`. Two things below are stale as a result and are corrected here rather than edited in place, so the history stays legible: the title above (fixed), and every PR-number reference in the body below still says `#1740`/`#1741`/etc. — read those as "now #1730". The CHANGELOG entries in the diff are already repointed to #1730. Everything below this line is the PR as it was written across 2026-08-11 through 2026-08-26, before the fold — the decisions and verification it documents did not change. --- Third of four. Stacked on PR 2 (#1729), so review the commits on top of it. **Paired tests: handsontable/hyperformula-tests#32 — merge that first.** ## Why this PR exists at all **A genuine typed license key did not work before this.** `checkLicenseKeyValidity` recognizes three fixed strings and the older 25-character format; a typed key matches none of them and falls through to `INVALID`. I verified this by building an engine with a real, unexpired `[SUB]` key before touching anything: ``` validityState = "invalid" C1 = #LIC! "License key is invalid." ``` So a paying customer pasting a valid key got `#LIC!` in every cell plus a console warning. An entitlement adapter alone would not have helped — gate A kills the formulas first. ## What lands here **1. Vendor the typed-key reader** into `src/license/handsontable-license-key-parser/` (~~`src/license/vendor/`~~, **renamed 22.09** at the reviewer's request so the directory names the repository it mirrors) as TypeScript (`allowJs` is off, `strict` is on, so this is a port, not a copy). This follows the key spec's own recommendation of a vendored copy plus a drift check rather than a shared package: a private dependency would break `npm install` for open-source users of this GPL package. `PROVENANCE.md` records the upstream commit and a per-file sha256, so drift is detectable by re-cloning and re-hashing, and lists the deliberate divergences. **2. Resolve typed keys into both gates.** `resolveLicense` reads the key once and answers both gates from that single reading, so they cannot disagree about what the string says. Anything that is not a typed key — `gpl-v3`, an older-format key, an empty string, a typed key with a broken checksum — falls through to `checkLicenseKeyValidity` with its **verdict unchanged**. That function is extracted from rather than rewritten, so both paths share one warning-per-page flag instead of each getting their own. Two additive edits to the file it lives in, both affecting the legacy path too and both deliberate: `formatDate` now reads its date in UTC (it printed the expiry a day early west of UTC — a latent bug on the legacy path as well), and an `@internal` reset for the warn-once flag was added because it made the console path untestable. **3. The real capability table**, plus reading both payload shapes. ## Please confirm two things **The gate-A/gate-B invariant.** Only a VALID typed key resolves to a restricted entitlement; missing, invalid and expired all resolve to `unrestrictedEntitlement()`. Gate A already stops formula evaluation on its own — letting a bad key restrict the entitlement *as well* would make PR 2's `ensureCapability` throw from the CRUD API, turning today's "formulas fail, the API still works" into a silent breaking change for every user whose key lapsed. Mutation-tested. **The capability table is a DRAFT.** Membership is transcribed from the packaging design's own per-function evidence file rather than invented, and the transcript is checked two ways: it reproduces that file's five published counts exactly (370 rows; 17 / 51 / 127 / 355 cumulative plus 15 operators), and all 423 registered function ids resolve into the 370 canonical entries once the 53 declared aliases are canonicalised, with zero uncovered. But the design is still under review — the free tier's exact contents and the placement of several function families are not settled. Landing it now was a deliberate call, not a claim that it is final. ## Judgement calls worth a reviewer's eye - **Both payload shapes are read**, detected per product entry by the presence of `capabilities`: the shipped shape (`tier`/`addons`/`exp`) and the newer specified shape (`capabilities`/`usage_until`/`release_until`/`notice`/`flags`). They disagree about nearly every field, the newer one is still under review, and only the first can be minted today. The newer spec also contradicts itself on whether its dates are `YYYY-MM-DD` strings or numeric timestamps, so both are accepted. - **Feature gating is REAL** (updated 12.08, per Kuba's answers on the task). An earlier revision of this PR granted all five feature areas from the `core` token, which made feature gating inert by construction. The five features now live on their own `feat:*` tokens: a rev-5 key grants exactly the `feat:*` tokens it carries; the shipped shape — whose vocabulary predates feature tokens — is granted all five by the adapter, so a shipped-shape key's API behaviour is unchanged; legacy keys resolve unrestricted (Kuba's carve-out). The exits stay ungated (`resumeEvaluation`, teardown), per the never-gate-the-exit rule. - **An unrecognized token no longer silences the key** (updated 12.08). Silence comes solely from the key's `flags`; the earlier coupling (`silent || unrecognized > 0`) suppressed strictly more than D3 asks for and was confirmed an implementation error by Kuba. - **The two add-on tokens are recognized but empty.** `spreadsheet` has no agreed content — the packaging design names a *package* "Spreadsheet" and the pricing work names a "Spreadsheet Bundle" *add-on*, and whether those are the same set is unsettled; guessing either way silently sells an empty add-on or duplicates a whole tier. Pinned by a test so filling it has to be deliberate. - **`noticeDays` is 0 for the shipped shape**, which has no notice field. Inventing a default in the parser would put a product decision in the wrong place. The newer shape carries `notice` and it is used. - **`PROVENANCE.md` names the upstream private repo and commit.** That is what makes the documented drift check runnable. Ratified by Kuba on the task (D7-A, 12.08): kept as-is. ## Update 13.08 — key spec rev 5 read against the code Reading rev 5 ([doc](https://app.clickup.com/9015210959/docs/8cnjcyf-31675/8cnjcyf-48155), updated 12.08) and running its own example payload through this branch turned up three things, all fixed in the last commit: - **Feature tokens are now OPT-IN.** §2.2 lists HyperFormula's entire token vocabulary as `functions_1..4`, `spreadsheet`, `import_export` — there is no `feat:*` entry at all. So a key that names no feature token cannot be saying "no features"; nothing in circulation can express one. Minting the spec's own §2 payload and running it: `setCellContents`, `addRows`, `copy`, `undo`, `addNamedExpression` and `batch` **all threw**. The same hole hit Handsontable-only keys and keys with `hyperformula: null`, which lost the API that `core` used to give them, silently (gate-A VALID = no console warning). A key that *does* name a `feat:*` token still gets exactly what it names, which is the gating Kuba asked for. - **`no-console-warns` is honoured.** rev 5 spells the flag three ways — §2.3 and the §2 example say `no-console-warns`, §4.3/§5.2 say `silent-console`, earlier revisions said `silent`. Only the last two were recognised, so a doc-conformant SaaS key printed console warnings it had explicitly asked to suppress. - **An unreadable `capabilities` rejects the key.** Present-but-not-an-array fell through to the shipped-shape branch, which was a free pass twice: every feature granted, and the rev-5 dates never read — a subscription expired in 2020 resolved as perpetual. **Still divergent from rev 5, deliberately:** §4.1 says a non-trial key never hard-blocks, even past grace ("Trial: block. Non-trial: error only (18.1)"). This branch keeps EXPIRED → `#LIC!`, per Kuba's D5=A (hard blocking stays this release; the notice/soft-stop/hard-stop model is a follow-up). ## Verification Full unit suite green — **512 suites, 6344 tests** (after the 13.08 update). Each of the three fixes above is mutation-verified: removing the opt-in rule fails 9 tests, removing `no-console-warns` fails 1, removing the `capabilities` guard fails 2, and cutting the console notification fails 1 (it used to fail none). Beyond that, the parts that matter were mutation-tested rather than trusted: a wrong SHA-512 round constant, a one-bit UTF-8 error, a broken invariant and a moved package boundary each fail the tests that are supposed to catch them. --- > [!NOTE] > **High Risk** > Changes commercial licensing, formula evaluation, and API gating paths; incorrect gate-A/gate-B or capability resolution could block paying customers or expose paid features. > > **Overview** > Adds **proprietary license entitlements**: vendored **entitlement-key** parsing (rev 6) and **`resolveLicense`** wire `Config` to gate A (key validity → `#LIC!` on function calls) and gate B (capability tokens → restricted functions/API). Legacy/`gpl-v3` paths stay on **`checkLicenseKeyValidity`**; only **valid** entitlement keys get a restricted entitlement—missing/invalid/expired keys still resolve **unrestricted** so the CRUD API does not start throwing while formulas fail. > > Replaces the placeholder **`core`** grant with a static **`fun:*` / `feat:*`** capability table (group tokens, per-function tokens, **`spreadsheet`** and **`import_export`** add-ons), case-insensitive token normalization, and shared **`licenseAllowsFunction`** for the interpreter and **`getAvailableFunctions()` / `getFunctionDetails()`** (lists shrink only for valid partial keys, not for bad keys). > > **Console licensing UX**: split expired messaging for usage vs release axes, UTC date formatting, one-time approaching-expiry notice per key, optional silence via config rebuild and key flags; docs/changelog describe feature packages and `#LIC!` semantics. > > Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 15d7231c62a94fe10ac60ca17e92807efe7ce86b. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot). ## ⛔ Update 18.08 — upstream retired this key format the same day, and one claim above is wrong A scoped spec-to-ship review of this PR (5 dimensions, every finding adversarially verified) confirmed 5 findings. Four are test-hardening and are fixed in the paired PR — see [hyperformula-tests#32](https://github.com/handsontable/hyperformula-tests/pull/32)'s "Update 18.08". The fifth needs a decision, not a patch, so nothing here has been changed for it yet. **The vendored reader cannot read the format upstream now ships.** `handsontable/license-key` commit `01eae6530d4f` (2026-08-18 08:44 UTC, DEV-2512, "Replace typed license keys with the entitlement key format (rev 6)"), released as **4.0.0**, **deletes `src/typed-key/` outright** — the exact five files `PROVENANCE.md` pins and hashes. Its own docs are explicit: "The typed key format was **removed**, not deprecated… this package cannot read a typed key." The replacement differs in three ways this reader gates on: | | this branch | entitlement format (rev 6 / 4.0.0) | |---|---|---| | format marker | requires a leading `[SUB]_`/`[FREE]_`/`[TRIAL]_`/`[PERP]_` tag (`extractKeyData.ts:147`) | **no tag** — the key *ends* with a bracketed block, which is the only marker | | payload version | requires `v: 1` (`extractKeyData.ts:199`) | **no `v` field at all** — payload is exactly `{"products":{…}}` | | checksum domain | SHA-512 over the whole key body, prose included | over the **encoded payload only** — an explicit reversal, so the prose becomes editable | | unknown product | invalidates the key (`extractKeyData.ts:105`) | tolerated — "kept, and ignored" | Measured, not inferred: an authentic 4.0.0-format key built per upstream's own `build-payload.js` gives `extractTypedKeyData(key)` → `null`, `resolveLicense(key).validityState` → `invalid`, and `C1` → `#LIC!` "License key is invalid.". Passing only the `[…]` block behaves the same. The retired tagged format still resolves correctly on the same build — so this is a format gap, not a robustness one. Independently, Budzio published the byte-level spec for that format this morning as a new page under key-spec rev 6 ("Technical implementation", sections `T1`–`T8`, created 09:45 UTC). It matches upstream and confirms all four rows above. Three of its rules this branch **already satisfies**: checksum verified before any decode or parse ("order is normative"), uppercase hex rejected rather than normalised, and `__proto__`-safe result construction. **What is genuinely at stake, and what is not.** The invariant holds throughout: a rev-6 key resolves INVALID and therefore to `unrestrictedEntitlement()`, so the CRUD API keeps working and only formulas fail (verified). And myHOT PR #73 (merged to `master` 12:37 UTC today, pinning `license-key#4.0.0`) states **"the typed keys never reached production"**, with the legacy 25-character keys still generated in parallel and validating exactly as before — that path is untouched here. So the correction owed to this PR's own opening claim: no customer ever held a typed key, so "a paying customer pasting a valid key got `#LIC!`" describes a format that was never issued. The live exposure is narrower but real — per that PR's surfacing table, **trial orders and the HubSpot trial webhook now surface the entitlement key**, while commercial orders and transactional emails still show the legacy key only. **Why this is not fixed in this PR.** Re-porting is the obvious move and upstream made it cheaper than the original port (`sha512.js` and `utils.js` are unchanged; the new `extractEntitlementKeyData` is deliberately schema-free and built to be vendored, so only the extractor, schema and constants need re-porting). But it is not a patch to slip in: adopting the new shape rules verbatim also makes `capabilities` mandatory and **invalidates every payload shape this branch currently reads**, rev 6 is still status "for review", and the work is arguably [HF-329](https://app.clickup.com/t/86cb119tz)'s (unassigned, due 21.08, untouched since 04.08 — it now has concrete content). Raised on the task as **D9**; the merge freeze until the spec owner returns means escalating is the action, not a delay. Also worth a reviewer's eye, since it sharpens the still-unanswered **D8**: rev 6's own examples use `capabilities: ["functions_1", "spreadsheet"]` / `["core"]` — i.e. **exactly the token names this branch implements** — while the packaging design published 12.08 states its vocabulary is `fun:.` and that "nothing else about packaging exists at the technical layer". The two documents disagree, and this branch conforms to the key spec rather than to the packaging doc. A key minted in the packaging vocabulary resolves VALID with the whole gated API and **zero functions**, silently (gate A says VALID, so nothing prints, and `unrecognizedCapabilities` is exposed nowhere). That outcome is now pinned by a test in the paired PR — pinned, not endorsed, so whichever way D8 lands has to change it. --- ### Changed in the 2026-09-22 review round - The guide no longer describes the key formats, and the validation section points at the terms of the contract instead of enumerating the two date axes. The changelog entry for the parser change was reworded the same way, since it carried the same description. - `PROVENANCE.md`: two paragraphs about the superseded `src/typed-key/` port removed; the divergence list corrected. Its item 3 described *upstream's* date check as if it were this port's, which has not been true since a type guard was added, and that guard — the only divergence that changes which keys are accepted — was missing from the list entirely. - The expired-key console message no longer blames the installed version when the key ran out on the usage axis. That wording predates this axis and was correct for every key `develop` can see; it is not for a subscription key. - The `implies` field and its recursive expansion are gone (see #1728), so no capability token refers to another. --------- Co-authored-by: Claude Sonnet 5 Co-authored-by: Kuba Sekowski --- CHANGELOG.md | 13 + docs/guide/license-key.md | 63 ++- docs/guide/types-of-errors.md | 2 +- src/Config.ts | 20 +- src/HyperFormula.ts | 91 +++- src/helpers/licenseKeyValidator.ts | 151 ++++++- src/interpreter/Interpreter.ts | 5 +- src/license/CapabilityRegistry.ts | 63 ++- src/license/LicenseEntitlement.ts | 38 +- src/license/capabilities.ts | 290 +++++++++++-- .../PROVENANCE.md | 97 +++++ .../constants.ts | 28 ++ .../detectFormat.ts | 70 ++++ .../extractKeyData.ts | 284 +++++++++++++ .../handsontable-license-key-parser/sha512.ts | 217 ++++++++++ .../handsontable-license-key-parser/utils.ts | 218 ++++++++++ src/license/licenseResolution.ts | 391 ++++++++++++++++++ 17 files changed, 1932 insertions(+), 109 deletions(-) create mode 100644 src/license/handsontable-license-key-parser/PROVENANCE.md create mode 100644 src/license/handsontable-license-key-parser/constants.ts create mode 100644 src/license/handsontable-license-key-parser/detectFormat.ts create mode 100644 src/license/handsontable-license-key-parser/extractKeyData.ts create mode 100644 src/license/handsontable-license-key-parser/sha512.ts create mode 100644 src/license/handsontable-license-key-parser/utils.ts create mode 100644 src/license/licenseResolution.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index aeea8dd511..5a617907e2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] +### Added + +- Added support for proprietary license keys that grant a subset of the library ("feature packages and add-ons"). A function your key does not include evaluates to a `#LIC!` error, and the corresponding parts of the API throw a `LicenseCapabilityMissingError`. Keys that grant everything, including `gpl-v3`, are unaffected. [#1728](https://github.com/handsontable/hyperformula/pull/1728) [#1729](https://github.com/handsontable/hyperformula/pull/1729) [#1730](https://github.com/handsontable/hyperformula/pull/1730) +- Added a one-time console notice when a license key's usage-based expiry date falls within its configured notice period, naming the key's last covered day ("valid until … (UTC)"). The notice is silenced by the key's own silent flag, and never fires for a key expiring on the perpetual (`release_until`) axis. Blocking behavior at and after expiry is unchanged. [#1730](https://github.com/handsontable/hyperformula/pull/1730) +- Added grants to the two commercial add-on tokens: `spreadsheet` (the Spreadsheet Bundle) now grants the CRUD, undo/redo, clipboard, and batching feature areas, and `import_export` grants the reserved import/export feature that nothing gates on until the feature ships. A key naming neither add-on keeps every feature area it has today. [#1730](https://github.com/handsontable/hyperformula/pull/1730) + +### Changed + +- Changed `getAvailableFunctions()` and `getFunctionDetails()` to describe only the functions the instance's license key includes, so they no longer advertise a function that would evaluate to a `#LIC!` error. A missing, invalid, or expired key does not shorten the list. [#1730](https://github.com/handsontable/hyperformula/pull/1730) +- Changed the console message for an expired proprietary license key to stop naming the installed version when the key ran out on the usage axis rather than the maintenance axis. A maintenance key stops covering releases, so an older build keeps working; a usage-based key stops being valid at all, and there is no version to fall back to. Classic 25-character license keys have only the maintenance axis, so their message is unchanged. [#1730](https://github.com/handsontable/hyperformula/pull/1730) +- Changed the parser for the new proprietary license keys to the entitlement key format, following its upstream specification. This replaces the tagged key format, which was never issued to anyone. Classic 25-character license keys and `gpl-v3` are unaffected. [#1730](https://github.com/handsontable/hyperformula/pull/1730) +- Changed the license capability tokens to be matched case-insensitively, and to grant functions through the packaging group-token vocabulary only: `fun:all`, `fun:.`, and per-function `fun:` tokens. A key names the capabilities it grants, and the engine grants their union; it keeps no notion of which tokens make up a package. The callable forms of the calculation operators, such as `HF.ADD`, are granted by `fun:operator.A`, while the infix operators themselves work under any key. [#1730](https://github.com/handsontable/hyperformula/pull/1730) + ### Fixed - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index 731c5cd08a..db8321b3ac 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -46,19 +46,70 @@ const options = { HyperFormula doesn't use an internet connection to validate your proprietary license key. ::: -To determine whether a user is still entitled to use a particular -version of the software, HyperFormula compares the time between -two dates: -* The HyperFormula build date -* The date in your proprietary license key +Which versions of HyperFormula a key covers, and for how long, follows from the +terms of your contract. Your key carries those terms, and HyperFormula applies +them locally, without any connection to a server. + +## Feature packages and add-ons + +A proprietary license key may grant the whole library, or only part of it. If your key covers +everything you buy nothing new to think about, and neither does the GPLv3 key `gpl-v3`, which +always grants everything. + +If your key grants only part of the library, then: + +* A function your key doesn't include evaluates to a `#LIC!` error, in the same way as any other + [error value](types-of-errors.md). Everything else in the sheet keeps calculating. +* An API method your key doesn't include throws a `LicenseCapabilityMissingError` when you call + it. Getters never throw; `copy()` and `cut()` do, because they belong to the clipboard feature. +* [`getAvailableFunctions()`](../api/classes/hyperformula.md#getavailablefunctions) and + [`getFunctionDetails()`](../api/classes/hyperformula.md#getfunctiondetails) describe only the + functions your key includes, so a function picker built from them never offers a function that + then fails. + +Custom functions you register yourself are available whatever your key grants, as long as they use +an id of their own. The licence covers built-in ids, so a plugin registered under a built-in id your +key does not include is treated as that built-in and stays unavailable — it will not be described and +it evaluates to `#LIC!`. Pick an id the built-in catalogue does not use and this cannot happen. + +Two commercial add-ons build on top of a package: + +* **Spreadsheet Bundle** grants the CRUD API (adding, removing, and moving rows, columns, sheets, + and cell contents), undo/redo, clipboard operations, and batching (`batch()` / + `suspendEvaluation()`; `resumeEvaluation()` is deliberately never gated, so an engine can always + leave a suspended state). It does not grant named expressions, which stay outside both add-ons. +* **Import/export** is reserved for a future release. HyperFormula doesn't have an import/export + feature yet, so this add-on doesn't grant or restrict anything today. + +In this release, not having either add-on doesn't restrict anything either: a key that names no +feature token at all is granted every feature area — CRUD, undo/redo, clipboard, named expressions +and batching — regardless of whether it names these add-ons. Every key issued today is of that +shape, so the add-on tokens describe what was sold rather than changing what the engine allows. -This process doesn't require any connection to the server. +::: tip +To find out which package your key includes, check your order confirmation or +[contact our team](contact.md). HyperFormula deliberately reports nothing about the contents of +your key at runtime. +::: ## License key notifications If your license key is missing, invalid, or expired, you see a corresponding notification in the console. +In that case every licence-gated function call evaluates to a `#LIC!` error — but no API method +starts throwing, and `getAvailableFunctions()` still describes the full set of functions. A key +problem never narrows what the library reports it can do. + +Arithmetic keeps working: operators such as `=A1+B1` are not function calls, so nothing gates them. +`VERSION()` and `OFFSET()` are function calls, but they are protected built-ins that sit outside the +licence system entirely, so they keep evaluating too. A sheet with a key problem therefore does not +go blank. + +A **valid** key can print one notification too: if it expires on a set date and that date is +within the notice period your license carries, the console names the last day the key covers. It +is a heads-up only — nothing is restricted while a key is valid, and the message appears once. + ## License key support If you have any issues with your license key, [contact our team](contact.md). \ No newline at end of file diff --git a/docs/guide/types-of-errors.md b/docs/guide/types-of-errors.md index 4c524877ee..3a0ab3b45c 100644 --- a/docs/guide/types-of-errors.md +++ b/docs/guide/types-of-errors.md @@ -37,4 +37,4 @@ according to the language settings. | #VALUE! | Wrong type of argument | It occurs when a formula tries to improperly use different types of data. For example, you will see this error when you will try to add a string to a number. | | #CYCLE! | Circular reference | It occurs when a formula refers to its own cell, both directly and indirectly. | | #ERROR! | An error occurred | It indicates that there is an unknown error in a formula. | -| #LIC! | Invalid license key | It occurs when the license key is invalid, expired, or missing. | \ No newline at end of file +| #LIC! | License key problem | It occurs when the license key is invalid, expired, or missing, or when the function is not included in the [feature package](license-key.md#feature-packages-and-add-ons) your license key grants. | \ No newline at end of file diff --git a/src/Config.ts b/src/Config.ts index 6bd96d7615..3505fb1415 100644 --- a/src/Config.ts +++ b/src/Config.ts @@ -16,12 +16,12 @@ import {DateTime, instanceOfSimpleDate, SimpleDate, SimpleDateTime, SimpleTime} import {AlwaysDense, ChooseAddressMapping} from './DependencyGraph/AddressMapping/ChooseAddressMappingPolicy' import {ConfigValueEmpty, ExpectedValueOfTypeError} from './errors' import {defaultStringifyCurrency, defaultStringifyDateTime, defaultStringifyDuration} from './format/format' -import {checkLicenseKeyValidity, LicenseKeyValidityState} from './helpers/licenseKeyValidator' +import {LicenseKeyValidityState} from './helpers/licenseKeyValidator' import {HyperFormula} from './HyperFormula' import {TranslationPackage} from './i18n' import {FunctionPluginDefinition} from './interpreter' import {CapabilityRegistry, ResolvedCapabilities} from './license/CapabilityRegistry' -import {unrestrictedEntitlement} from './license/LicenseEntitlement' +import {resolveLicense} from './license/licenseResolution' import {Maybe} from './Maybe' import {ParserConfig} from './parser/ParserConfig' import {ConfigParams, ConfigParamsList} from './ConfigParams' @@ -180,7 +180,7 @@ export class Config implements ConfigParams, ParserConfig { /** @inheritDoc */ public readonly matchWholeCell: boolean - constructor(options: Partial = {}, showDeprecatedWarns: boolean = true) { + constructor(options: Partial = {}, showDeprecatedWarns: boolean = true, notifyLicenseMessages: boolean = true) { const { accentSensitive, caseSensitive, @@ -279,13 +279,9 @@ export class Config implements ConfigParams, ParserConfig { validateNumberToBeAtLeast(this.maxColumns, 'maxColumns', 1) this.context = context - const licenseKeyValidityState = checkLicenseKeyValidity(this.licenseKey) + const {validityState: licenseKeyValidityState, entitlement} = resolveLicense(this.licenseKey, notifyLicenseMessages) const capabilityRegistry = new CapabilityRegistry() - // PR 1 (HF-307) ships the gate infrastructure without a real license-key payload adapter — - // that lands in PR 3 as src/license/payloadAdapter.ts. Until then every entitlement resolves - // as unrestricted, so isLicenseGateActive below reduces to today's licenseKeyValidityState - // check and gate B in the interpreter never actually restricts a function. - const licenseCapabilities = capabilityRegistry.resolve(unrestrictedEntitlement()) + const licenseCapabilities = capabilityRegistry.resolve(entitlement) privatePool.set(this, { licenseKeyValidityState, @@ -346,7 +342,7 @@ export class Config implements ConfigParams, ParserConfig { /** * Whether gate B (the entitlement check in the interpreter) needs to run at all for this - * config. `false` — the common case, for `gpl-v3`, legacy keys, and an unrestricted typed + * config. `false` — the common case, for `gpl-v3`, legacy keys, and an unrestricted entitlement * key — is a single boolean read, cheaper than the string-enum comparison it replaces. * * @internal @@ -370,12 +366,12 @@ export class Config implements ConfigParams, ParserConfig { return getFullConfigFromPartial(this) } - public mergeConfig(init: Partial): Config { + public mergeConfig(init: Partial, notifyLicenseMessages: boolean = true): Config { const mergedConfig: ConfigParams = Object.assign({}, this.getConfig(), init) Config.warnDeprecatedOptions(init) - return new Config(mergedConfig, false) + return new Config(mergedConfig, false, notifyLicenseMessages) } private static warnDeprecatedOptions(options: Partial) { diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index c66de99d5e..7723687996 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -44,7 +44,7 @@ import { import {Evaluator} from './Evaluator' import {ExportedChange, Exporter} from './Exporter' import {LicenseKeyValidityState} from './helpers/licenseKeyValidator' -import {allowsFeature} from './license/CapabilityRegistry' +import {allowsFeature, licenseAllowsFunction} from './license/CapabilityRegistry' import {FeatureId} from './license/LicenseEntitlement' import {buildTranslationPackage, RawTranslationPackage, TranslationPackage} from './i18n' import {FunctionPluginDefinition} from './interpreter' @@ -706,26 +706,58 @@ export class HyperFormula implements TypedEmitter { return {doc, metadata, aliasOf: metadataKey !== functionId ? metadataKey : undefined} } + /** + * Whether an instance's license lets it evaluate the given function id, and therefore whether the + * metadata API may describe it. Mirrors the gate-B branch the interpreter runs per function call + * (`Interpreter.evaluateAstWithoutPostprocessing`, the `FUNCTION_CALL` case), through the same + * [[licenseAllowsFunction]] rule and the same alias canonicalisation, so a listed function is + * always one that actually evaluates. + * + * Gate B only, deliberately — never the license key's validity state. A missing, invalid or expired + * key resolves to an unrestricted entitlement (the invariant `resolveLicense` documents), so it + * reaches this method with both `licenseCapabilities` axes set to `'all'` and every function + * stays listed. + * That is the intended answer: a key problem is reported on the console and by `#LIC!` in cells, + * and narrowing the catalogue to the two protected built-ins would leave an integrator who has not + * wired up their key yet with an empty function picker and no clue why. The list narrows only for + * a *valid* key that genuinely does not include a function — the case where the answer is useful. + * + * @param {string} functionId - the id as registered, which may be an alias + * @param {FunctionRegistry} functionRegistry - the engine's registry, which resolves the alias map + * @param {Config} config - the instance's config, holding its resolved entitlement + */ + private static licenseListsFunction(functionId: string, functionRegistry: FunctionRegistry, config: Config): boolean { + if (!config.isLicenseGateActive || FunctionRegistry.functionIsProtected(functionId)) { + return true + } + const plugin = functionRegistry.getFunctionPlugin(functionId) + const canonicalId = plugin?.aliases?.[functionId] ?? functionId + return licenseAllowsFunction(config.capabilityRegistry, config.licenseCapabilities, canonicalId) + } + /** * Builds the function list for every id registered in an engine's own registry. Documented functions use their * catalogue entry; custom functions are listed with their name only. Sorted by localized name with * `localeCompare`, so the order follows the host's collation rules, with the language-independent canonical name * as a stable tiebreaker for entries that share a localized name. * - * Takes the [[TranslationPackage]] rather than deriving it from a language code: an instance must describe its - * functions under the package its own evaluator uses (`Config.translationPackage`), which is a snapshot taken + * Takes the instance's whole [[Config]] rather than a language code: an instance must describe its functions + * under the translation package its own evaluator uses (`Config.translationPackage`), which is a snapshot taken * when the instance was built and can differ from whatever is registered globally for the same code today. - * Deriving it here instead would let this method report a localized name the instance refuses to evaluate. + * Deriving it here instead would let this method report a localized name the instance refuses to evaluate. The + * config also carries the resolved entitlement, for the same reason — see [[licenseListsFunction]]. * * @param {FunctionRegistry} functionRegistry - the engine's registry, the source of both the ids and their plugins - * @param {TranslationPackage} language - the translation package to translate the names under + * @param {Config} config - the instance's config: the translation package and the resolved license entitlement */ - private static buildAvailableFunctions(functionRegistry: FunctionRegistry, language: TranslationPackage): FunctionListEntry[] { + private static buildAvailableFunctions(functionRegistry: FunctionRegistry, config: Config): FunctionListEntry[] { + const language = config.translationPackage const translate = (id: string) => language.getMaybeFunctionTranslation(id) return functionRegistry.getListableFunctionIds() // The interpreter refuses to evaluate ids the active language has no translation entry for // (FunctionRegistry.getFunction), so an untranslated function would be advertised but uncallable. .filter(id => language.isFunctionTranslated(id)) + .filter(id => HyperFormula.licenseListsFunction(id, functionRegistry, config)) .map(id => { const resolved = HyperFormula.resolveFunctionMetadata(id, functionRegistry.getFunctionPlugin(id)) if (resolved === undefined) { @@ -749,14 +781,19 @@ export class HyperFormula implements TypedEmitter { * * @param {string} functionId - the language-independent function id (canonical id or alias) * @param {FunctionRegistry} functionRegistry - the engine's registry, which resolves the id to its plugin - * @param {TranslationPackage} language - the translation package to translate the names under + * @param {Config} config - the instance's config: the translation package and the resolved license entitlement */ - private static buildFunctionDetailsFor(functionId: string, functionRegistry: FunctionRegistry, language: TranslationPackage): FunctionDetails | undefined { - // Mirrors the filter in buildAvailableFunctions: an id the active language cannot evaluate - // (no translation entry) gets no details either, so the list and the details always agree. + private static buildFunctionDetailsFor(functionId: string, functionRegistry: FunctionRegistry, config: Config): FunctionDetails | undefined { + const language = config.translationPackage + // Mirrors the filters in buildAvailableFunctions: an id the active language cannot evaluate + // (no translation entry), or one this instance's license does not grant, gets no details + // either, so the list and the details always agree. if (!language.isFunctionTranslated(functionId)) { return undefined } + if (!HyperFormula.licenseListsFunction(functionId, functionRegistry, config)) { + return undefined + } const resolved = HyperFormula.resolveFunctionMetadata(functionId, functionRegistry.getFunctionPlugin(functionId)) if (resolved === undefined) { return undefined @@ -4592,6 +4629,18 @@ export class HyperFormula implements TypedEmitter { * plugin registered without translations for that language. A translation set to an empty string is not a missing * entry: it falls back to the canonical id, so the function stays listed under its canonical name. * + * A function the instance's license key does not include is omitted for the same reason: it would evaluate to a + * `#LIC!` error. The list therefore answers "what can this engine compute", not "what does this package contain". + * Two consequences worth knowing: + * - A missing, invalid or expired license key does **not** shorten the list. Such a key restricts nothing by + * entitlement — it is reported on the console, and every licence-gated function call evaluates to `#LIC!` — so + * the full catalogue is still described. `VERSION()` and `OFFSET()` are protected built-ins outside the licence + * system, so they keep evaluating. Use it to build a function picker before a key is configured. + * - A custom (user-registered) function is omitted only if it took a built-in id the key excludes. The rule is + * "not covered by the capability table", not "not user-registered", so a plugin registered under an id the + * built-in catalogue already uses is treated as that built-in. Registered under an id of its own, a custom + * function is never omitted. See {@link getFunctionDetails}, which states the same exception. + * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); @@ -4605,9 +4654,9 @@ export class HyperFormula implements TypedEmitter { public getAvailableFunctions(): FunctionListEntry[] { return HyperFormula.buildAvailableFunctions( this._functionRegistry, - // The instance's own package, the one its evaluator uses — not a fresh global lookup, which could describe - // the functions under a package this instance never adopted. - this._config.translationPackage, + // The instance's own config: its translation package (not a fresh global lookup, which could describe the + // functions under a package this instance never adopted) and its resolved license entitlement. + this._config, ) } @@ -4618,9 +4667,10 @@ export class HyperFormula implements TypedEmitter { * documentation link (`documentationUrl`) and usage examples (`examples`) — every built-in authors both. * Resolves both built-in and custom (user-registered) functions, as well as aliases. An alias reports its * target's metadata (including examples, which spell the target's name) under the alias id, with the target id - * exposed as `aliasOf`. Returns `undefined` when the function id is unknown, not registered in this instance, or - * has no translation entry for the configured language (an untranslated id cannot be evaluated, so it is not - * described either, which keeps this method consistent with [[getAvailableFunctions]]). + * exposed as `aliasOf`. Returns `undefined` when the function id is unknown, not registered in this instance, has + * no translation entry for the configured language, or is not included in this instance's license key (neither an + * untranslated nor an unlicensed id can be evaluated, so neither is described — which keeps this method consistent + * with [[getAvailableFunctions]], including its behaviour for a missing, invalid or expired key). * For a custom function, `category` is `'Custom'`, there is no `shortDescription`, `documentationUrl` or * `examples`, and parameters are reported positionally (`Arg1`, `Arg2`, ...). A custom plugin registered over a * built-in id is the exception: the catalogue is keyed by function id, so it reports that built-in's authored @@ -4649,8 +4699,8 @@ export class HyperFormula implements TypedEmitter { */ public getFunctionDetails(canonicalName: string): FunctionDetails | undefined { validateArgToType(canonicalName, 'string', 'canonicalName') - // The instance's own package, the one its evaluator uses — see getAvailableFunctions. - return HyperFormula.buildFunctionDetailsFor(canonicalName, this._functionRegistry, this._config.translationPackage) + // The instance's own config, for the same reasons as getAvailableFunctions. + return HyperFormula.buildFunctionDetailsFor(canonicalName, this._functionRegistry, this._config) } /** @@ -4907,7 +4957,10 @@ export class HyperFormula implements TypedEmitter { */ private rebuildWithConfig(newParams: Partial): void { const newConfig = this._config.mergeConfig(newParams) - const configNewLanguage = this._config.mergeConfig({language: newParams.language}) + // The second argument silences license console messages for this transient Config: it is + // built from the OUTGOING config purely to reserialize sheets, and must not print an expiry + // notice for the key the caller may be replacing in this very call. + const configNewLanguage = this._config.mergeConfig({language: newParams.language}, false) const serializedSheets = this._serialization.withNewConfig(configNewLanguage, this._namedExpressions).getAllSheetsSerialized() const serializedNamedExpressions = this._serialization.getAllNamedExpressionsSerialized() diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 72ae003241..76f9c0a65a 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -3,6 +3,7 @@ * Copyright (c) 2025 Handsoncode. All rights reserved. */ +import {ENTITLEMENT_KEY_CHECKSUM_LENGTH} from '../license/handsontable-license-key-parser/constants' import {checkKeySchema, extractTime} from './licenseKeyHelper' /** @@ -17,6 +18,12 @@ export const enum LicenseKeyValidityState { type LicenseKeyInvalidState = Exclude +/** + * Which deadline a key ran out against: the date of the build in use (`release`) or the wall + * clock (`usage`). + */ +export type LicenseExpiryAxis = 'release' | 'usage' + interface TemplateVars { [key: string]: string, } @@ -27,7 +34,7 @@ type ConsoleMessages = { type MessageDescriptor = { template: LicenseKeyValidityState, - vars: TemplateVars, + expiryDate?: Date, } /** @@ -35,13 +42,128 @@ type MessageDescriptor = { */ const consoleMessages: ConsoleMessages = { invalid: () => 'The license key for HyperFormula is invalid.', - expired: ({keyValidityDate}) => 'The license key for HyperFormula expired' + - ` on ${keyValidityDate}, and is not valid for the installed version.`, + // Two wordings, because a key can run out along either of two axes and only one of them is + // about the build you installed. A maintenance key stops covering RELEASES after its date, so + // an older version keeps working and the fix is to install one; a usage-based key stops being + // valid at all, and telling its holder the key "is not valid for the installed version" sends + // them to downgrade, which changes nothing. + expired: ({keyValidityDate, axis}) => axis === 'usage' + ? `The license key for HyperFormula expired on ${keyValidityDate}.` + : `The license key for HyperFormula expired on ${keyValidityDate}, and is not valid for the installed version.`, missing: () => 'The license key for HyperFormula is missing.', } let _notified = false +/** + * Identities (see {@link noticeIdentityOf}) of license keys that have already printed their + * expiry-approaching notice. + * + * Deliberately keyed per key rather than a single boolean like {@link _notified} + * above: that flag reports one of a handful of states that mean the same thing regardless of + * which key triggered them ("a key is invalid", "a key is missing"), so once-per-page-load is the + * right behaviour for it. Two different keys approaching their OWN expiry are two different + * events, and a page that swaps keys (or a test suite that builds one engine per key) must still + * warn for the second one even though the first already consumed a shared flag. + */ +const _noticedKeys = new Set() + +/** + * Clears the once-per-page-load flag {@link notifyLicenseKeyState} keeps, and the per-key set + * {@link notifyLicenseKeyNotice} keeps. + * + * Exists for tests only. Both are module-level and never otherwise reset, so without this the + * whole console-message path is unobservable: the first spec to build any engine consumes the single + * warning and every later assertion sees silence regardless of what the code does. Making the reset + * explicit beats the alternatives — depending on spec-file order is flaky, and under Karma every + * spec shares one browser context, so order tricks do not work there at all. + * + * @internal + */ +export function resetLicenseKeyNotificationForTests(): void { + _notified = false + _noticedKeys.clear() +} + +/** + * Prints the console message for a non-valid license key state, at most once per page load. + * + * Extracted so the entitlement-key path in `src/license/licenseResolution.ts` reports the same states + * with the same wording and the same once-only behaviour, without duplicating the message table + * or getting a second `_notified` flag of its own — two flags would let a page print two + * warnings for one key. + * + * @param {LicenseKeyValidityState} state - the state to report; `VALID` prints nothing + * @param {Date} [keyValidityDate] - the day the key stopped being valid, used by the `expired` + * message + * @param {LicenseExpiryAxis} [expiryAxis] - which axis the key ran out along. Defaults to + * `release`, which is the only axis the classic 25-character format has, so its message is + * unchanged. + */ +export function notifyLicenseKeyState( + state: LicenseKeyValidityState, + keyValidityDate?: Date, + expiryAxis: LicenseExpiryAxis = 'release', +): void { + if (_notified || state === LicenseKeyValidityState.VALID) { + return + } + + const vars: TemplateVars = keyValidityDate === undefined + ? {} + : {keyValidityDate: formatDate(keyValidityDate), axis: expiryAxis} + + console.warn(consoleMessages[state](vars)) + _notified = true +} + +/** + * Prints a one-time notice that a VALID entitlement key's usage-until expiry is approaching, at + * most once per distinct license key. + * + * Called from `src/license/licenseResolution.ts`'s `resolveLicense`, alongside + * {@link notifyLicenseKeyState} — see that function's doc for why the two share this module + * instead of each keeping a message table and a flag of their own. + * + * The wording is rev 5 §3.2's own subscription clause ("valid until {date} (UTC)"), naming the + * key's LAST covered day. It deliberately does not say "expires on": the pre-existing expired + * message reports the first day NOT covered (`validityOf`'s convention, +1 day), and two messages + * for the same key must not name two different days for the same boundary. "Valid until Aug 25" + * followed later by "expired on Aug 26" is consistent; "expires on Aug 25" followed by + * "expired on Aug 26" is a support ticket. + * + * @param {string} licenseKey - the raw key string; only its identity is retained, see below + * @param {Date} expiryDate - the last covered day of the key's usage-until axis, at UTC midnight + */ +export function notifyLicenseKeyNotice(licenseKey: string, expiryDate: Date): void { + const identity = noticeIdentityOf(licenseKey) + + if (_noticedKeys.has(identity)) { + return + } + + console.warn(`The HyperFormula license key is valid until ${formatDate(expiryDate)} (UTC). To renew the license, contact sales@handsontable.com.`) + _noticedKeys.add(identity) +} + +/** + * The warn-once identity of a key: its trailing 129 characters, after trimming — for an intact + * entitlement key, the sha512 checksum plus the closing bracket that ends the machine-readable + * block, unique per distinct key content. + * + * Trimmed because the reader ignores trailing whitespace (it looks for the block, not for the end + * of the string), so `'KEY'` and `'KEY\n'` are one license and must be one identity here too. + * Reading from the END rather than the start also makes the whole artifact and its bare `[...]` + * block — which the format says are equally valid spellings of the same license — one identity. + * + * Truncated because the set retains its entries for the life of the process: a multi-tenant server + * building one engine per customer-supplied key would otherwise accumulate every full key string + * it has ever warned about; 129 characters per entry bounds that to the checksum alone. + */ +function noticeIdentityOf(licenseKey: string): string { + return licenseKey.trim().slice(-(ENTITLEMENT_KEY_CHECKSUM_LENGTH + 1)) +} + /** * Checks if the provided license key is grammatically valid or not expired. * @@ -51,7 +173,6 @@ let _notified = false export function checkLicenseKeyValidity(licenseKey: string): LicenseKeyValidityState { const messageDescriptor: MessageDescriptor = { template: LicenseKeyValidityState.MISSING, - vars: {}, } if (licenseKey === 'gpl-v3' || licenseKey === 'internal-use-in-handsontable' || licenseKey === 'hftrial-0168e-1f2b7-47158-70b05-0842f') { @@ -62,7 +183,7 @@ export function checkLicenseKeyValidity(licenseKey: string): LicenseKeyValidityS const releaseDays = Math.floor(new Date(`${month}/${day}/${year}`).getTime() / 8.64e7) const keyValidityDays = extractTime(licenseKey) - messageDescriptor.vars.keyValidityDate = formatDate(new Date((keyValidityDays + 1) * 8.64e7)) + messageDescriptor.expiryDate = new Date((keyValidityDays + 1) * 8.64e7) if (releaseDays > keyValidityDays) { messageDescriptor.template = LicenseKeyValidityState.EXPIRED @@ -74,10 +195,7 @@ export function checkLicenseKeyValidity(licenseKey: string): LicenseKeyValidityS messageDescriptor.template = LicenseKeyValidityState.INVALID } - if (!_notified && messageDescriptor.template !== LicenseKeyValidityState.VALID) { - console.warn(consoleMessages[messageDescriptor.template](messageDescriptor.vars)) - _notified = true - } + notifyLicenseKeyState(messageDescriptor.template, messageDescriptor.expiryDate) return messageDescriptor.template } @@ -85,16 +203,21 @@ export function checkLicenseKeyValidity(licenseKey: string): LicenseKeyValidityS /** * Formats a Date instance to hard-coded format MMMM DD, YYYY. * - * @param {Date} date The date to format. - * @returns {string} + * Read in UTC, not local time. Every date reaching this function is built at UTC midnight — the + * legacy path from a whole number of days since the epoch, the entitlement-key path from a calendar + * date in the payload — so local getters shifted the day backwards for anyone west of UTC and + * printed an expiry one day earlier than the one the key actually carries. + * + * @param {Date} date The date to format, at UTC midnight. + * @returns {string} The date as `MMMM DD, YYYY`. */ function formatDate(date: Date): string { const monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ] - const month = monthNames[date.getMonth()] - const day = date.getDate() - const year = date.getFullYear() + const month = monthNames[date.getUTCMonth()] + const day = date.getUTCDate() + const year = date.getUTCFullYear() return `${month} ${day}, ${year}` } diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 2c6e39f2a0..39ef01b6b1 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -13,7 +13,7 @@ import {DependencyGraph} from '../DependencyGraph' import {FormulaVertex} from '../DependencyGraph/FormulaVertex' import {ErrorMessage} from '../error-message' import {LicenseKeyValidityState} from '../helpers/licenseKeyValidator' -import {allowsFunction} from '../license/CapabilityRegistry' +import {licenseAllowsFunction} from '../license/CapabilityRegistry' import {ColumnSearchStrategy} from '../Lookup/SearchStrategy' import {Maybe} from '../Maybe' import {NamedExpressions} from '../NamedExpressions' @@ -196,8 +196,7 @@ export class Interpreter { } const canonicalId = this.canonicalFunctionId(ast.procedureName) - if (this.config.capabilityRegistry.capabilityOf(canonicalId) !== undefined - && !allowsFunction(this.config.licenseCapabilities, canonicalId)) { + if (!licenseAllowsFunction(this.config.capabilityRegistry, this.config.licenseCapabilities, canonicalId)) { return new CellError(ErrorType.LIC, ErrorMessage.LicenseCapability(ast.procedureName)) } } diff --git a/src/license/CapabilityRegistry.ts b/src/license/CapabilityRegistry.ts index adbcfc4f44..3e95b891c1 100644 --- a/src/license/CapabilityRegistry.ts +++ b/src/license/CapabilityRegistry.ts @@ -4,7 +4,7 @@ */ import {FeatureId, LicenseEntitlement} from './LicenseEntitlement' -import {CAPABILITY_TABLE, CapabilityGrant, refreshCoreGrant} from './capabilities' +import {CAPABILITY_TABLE, CapabilityGrant, normalizeCapabilityToken} from './capabilities' /** * The capabilities a resolved {@link LicenseEntitlement} grants, ready for gate B (the @@ -38,9 +38,6 @@ export class CapabilityRegistry { * suite does not depend on its placeholder content. */ constructor(table?: ReadonlyMap) { - if (table === undefined) { - refreshCoreGrant() - } this.table = table ?? CAPABILITY_TABLE this.reverseIndex = CapabilityRegistry.buildReverseIndex(this.table) } @@ -67,9 +64,10 @@ export class CapabilityRegistry { /** * Expands an entitlement's capability tokens into the concrete functions and features they * grant. An `unrestricted` entitlement short-circuits to `'all'` on BOTH axes without - * consulting the table at all — every grant in the table stands on its own — a token never - * refers to another — so this is a flat pass over the entitlement's own tokens; an - * unrecognized token is skipped without an error, and a repeated one adds nothing twice. + * consulting the table at all. Tokens are matched case-insensitively (the table is keyed by + * the normalized spelling — see {@link normalizeCapabilityToken}). Every grant stands on its + * own — a token never refers to another — so this is a flat pass over the entitlement's own + * tokens; an unrecognized token is skipped without an error, and a repeated one adds nothing. * * Setting `'all'` on both axes here, in the same object literal, is deliberate: this is the * only place `entitlement.unrestricted` is read, so a future edit that touches one axis and @@ -79,7 +77,7 @@ export class CapabilityRegistry { * both are pinned separately rather than with one combined assertion. * * @param {LicenseEntitlement} entitlement - the entitlement to resolve, e.g. one built by - * hand in a test or produced by PR 3's license-key payload adapter + * hand in a test or produced by the license-key payload adapter */ public resolve(entitlement: LicenseEntitlement): ResolvedCapabilities { if (entitlement.unrestricted) { @@ -88,8 +86,18 @@ export class CapabilityRegistry { const functions = new Set() const features = new Set() + // A key may carry a great many tokens - the format sets no size limit - and a repeated one + // grants nothing new, so each distinct spelling is expanded once. Expansion itself is a single + // pass: no grant refers to another, so there is nothing to walk. + const visited = new Set() + + for (const rawToken of entitlement.capabilities) { + const token = normalizeCapabilityToken(rawToken) + if (visited.has(token)) { + continue + } + visited.add(token) - for (const token of entitlement.capabilities) { const grant = this.table.get(token) if (grant === undefined) { continue @@ -103,9 +111,9 @@ export class CapabilityRegistry { /** * Returns the capability token a function id is covered by, or `undefined` if this registry's - * table does not cover it. The completeness invariant in - * `unit/license/capability-registry.spec.ts` guarantees every built-in registered in the - * static function registry is covered by the table, the core token, or the protected list — + * table does not cover it. The completeness invariant in the paired `hyperformula-tests` suite + * (`unit/license/capability-registry.spec.ts`) guarantees every built-in registered in the + * static function registry is covered by the table or the protected list — * so `undefined` for a function known to the current instance's function registry means it is * a custom, instance-registered function rather than an unlisted built-in. */ @@ -127,3 +135,34 @@ export function allowsFunction(resolved: ResolvedCapabilities, functionId: strin export function allowsFeature(resolved: ResolvedCapabilities, feature: FeatureId): boolean { return resolved.features === 'all' || resolved.features.has(feature) } + +/** + * Whether the license lets an instance evaluate — and therefore describe — the given function. + * + * The rule both gate-B function call sites share: a function the capability table does not cover + * at all is allowed. {@link CapabilityRegistry.capabilityOf} returns `undefined` only for an id no + * token lists, which the completeness invariant in `unit/license/capability-registry.spec.ts` + * guarantees is not an unlisted built-in but a custom, instance-registered function — exempt from + * gate B by decision D1. Everything the table does cover has to be granted by the entitlement. + * + * Extracted so the interpreter and the function metadata API cannot drift apart. The metadata API + * exists to describe the functions an instance can actually evaluate, so a second spelling of this + * rule would eventually let it advertise a function that then returns `#LIC!` — the exact failure + * removing the static metadata methods (HF-349) was meant to prevent. + * + * Note this is gate B only: it says nothing about {@link LicenseKeyValidityState}. Callers that + * also need gate A check it separately, because the two gates have different answers for the same + * key — see the comment on `resolveLicense`. + * + * @param {CapabilityRegistry} registry - the registry the capabilities were resolved against + * @param {ResolvedCapabilities} resolved - the instance's resolved capabilities + * @param {string} canonicalFunctionId - the function id, already resolved through the alias map + */ +export function licenseAllowsFunction( + registry: CapabilityRegistry, + resolved: ResolvedCapabilities, + canonicalFunctionId: string, +): boolean { + return registry.capabilityOf(canonicalFunctionId) === undefined + || allowsFunction(resolved, canonicalFunctionId) +} diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index 9472d13500..01202acac8 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -6,10 +6,13 @@ /** * Identifies a feature area of the public API that a license entitlement can gate. * - * `CustomFunctions` and `ImportExport` are reserved vocabulary: they exist so a license payload - * is free to carry them, but no capability grant in this release maps to either of them yet. - * HF-307 decision D1 drops function-registration gating (and the `CustomFunctions` grant) from - * this release; `ImportExport` has no gated methods until HF-107 lands. + * `CustomFunctions` is reserved vocabulary: it exists so a license payload is free to carry it, + * but HF-307 decision D1 drops function-registration gating (and the `CustomFunctions` grant) + * from this release, so no capability grant maps to it. + * + * `ImportExport` IS granted, by the `import_export` add-on token (2026-08-12 packages meeting) — + * but it gates no public method yet, because HF-107 hasn't shipped the import/export feature it + * would gate. The grant exists; the gate does not, yet. */ export const enum FeatureId { NamedExpressions = 'named_expressions', @@ -24,12 +27,15 @@ export const enum FeatureId { /** * Describes when a license entitlement stops being valid. * - * Per key-spec rev 3 §1.3, `date` is kept as a calendar string rather than an epoch, and is - * INCLUSIVE of its last valid day: - * - `kind === 'usage'`: `date` is compared against the client's LOCAL calendar date — deliberately - * not UTC, the date means the date, wherever the customer is. - * - `kind === 'release'`: `date` is compared LEXICOGRAPHICALLY, as text, against the library's - * build date; no clock is involved. + * `date` is kept as a calendar string rather than an epoch, and is INCLUSIVE of its last valid + * day: + * - `kind === 'usage'`: compared against the current instant in **UTC**. An earlier revision of + * the key spec called for the client's LOCAL calendar date; that was reversed, because the + * offline check and a future online check have to return the same verdict for the same key at + * the same instant, and any rule that reads a local clock breaks that parity. The practical + * cost is that a customer far west of UTC loses the tail of their last local day. + * - `kind === 'release'`: compared against the library's build date; no clock is involved, which + * is what keeps an air-gapped install with a wrong system clock working. * - `kind === 'none'`: the entitlement does not expire. */ export interface LicenseExpiry { @@ -63,9 +69,13 @@ export interface LicenseEntitlement { expiry: LicenseExpiry, /** * When `true`, resolving this entitlement must not print a console message of any kind. - * HF-307 decision D3 (fail-closed, silent): a typed key with no recognized token resolves - * like an explicit `capabilities: []` — core and protected functions only, without a message, - * a warning, or a diagnostics getter. + * + * Set from the key's own flags ONLY — the key spec spells that flag three different ways across + * revisions and even within one revision, and all are honoured. An unrecognized token does NOT + * set it: HF-307 decision D3 makes the *grant* silent (an unknown token grants nothing, with no + * message and no diagnostics getter), which is a different thing from muting the key's console + * output. Coupling them suppressed expiry notices as a side effect of a vocabulary mismatch, and + * was confirmed an implementation error. */ silent: boolean, isTrial: boolean, @@ -74,7 +84,7 @@ export interface LicenseEntitlement { /** * The unrestricted entitlement: legacy keys and `gpl-v3` resolve to this today. * - * HF-307 decision D3 (fail-closed, silent) means a typed key whose tokens this library version + * HF-307 decision D3 (fail-closed, silent) means an entitlement key whose tokens this library version * does not recognize at all no longer maps here — it resolves to an entitlement with an empty, * silent capability set instead of falling back to unrestricted access. Do not reuse this * function for that case. diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts index 0a32bf3d22..da6d7393ad 100644 --- a/src/license/capabilities.ts +++ b/src/license/capabilities.ts @@ -3,11 +3,68 @@ * Copyright (c) 2025 Handsoncode. All rights reserved. */ -import {FunctionRegistry} from '../interpreter/FunctionRegistry' import {FeatureId} from './LicenseEntitlement' -/** The single capability token every built-in currently falls under, see {@link CAPABILITY_TABLE}. */ -export const CORE_TOKEN = 'core' +// The engine reads CAPABILITIES, never packages. A license key carries a list of capability +// tokens and the engine grants the union of what those tokens name; which tokens make up which +// commercial package is decided where keys are minted, not here. In the words of the packaging +// design: "Nothing else about packaging exists at the technical layer." + +/** Grants {@link FeatureId.Crud} — the mutating CRUD surface of the public API. */ +export const CRUD_FEATURE_TOKEN = 'feat:crud' +/** Grants {@link FeatureId.UndoRedo}. */ +export const UNDO_REDO_FEATURE_TOKEN = 'feat:undo_redo' +/** Grants {@link FeatureId.Clipboard}. */ +export const CLIPBOARD_FEATURE_TOKEN = 'feat:clipboard' +/** Grants {@link FeatureId.NamedExpressions}. */ +export const NAMED_EXPRESSIONS_FEATURE_TOKEN = 'feat:named_expressions' +/** Grants {@link FeatureId.Batching}. */ +export const BATCHING_FEATURE_TOKEN = 'feat:batching' + +/** + * Every feature token, in one list, for the opt-in rule in `licenseTermsOf`: a key naming no + * `feat:*` token at all is granted all of these, because no key vocabulary in circulation can + * express "no features" — see that function for the reasoning. + */ +export const ALL_FEATURE_TOKENS = [ + CRUD_FEATURE_TOKEN, UNDO_REDO_FEATURE_TOKEN, CLIPBOARD_FEATURE_TOKEN, + NAMED_EXPRESSIONS_FEATURE_TOKEN, BATCHING_FEATURE_TOKEN, +] + +/** The whole implemented catalog of built-in functions, operator callable forms included. */ +export const FUN_ALL_TOKEN = 'fun:all' +/** + * Spreadsheet Bundle add-on (2026-08-12 packages meeting). Grants {@link FeatureId.Crud}, + * {@link FeatureId.UndoRedo}, {@link FeatureId.Clipboard} and {@link FeatureId.Batching} — see + * {@link CAPABILITY_TABLE}. + */ +export const SPREADSHEET_ADDON_TOKEN = 'spreadsheet' +/** + * Import/export add-on (2026-08-12 packages meeting). Grants {@link FeatureId.ImportExport}, a + * RESERVED grant: nothing in the public API is gated on it yet, because HF-107 hasn't shipped the + * import/export feature it would gate. + */ +export const IMPORT_EXPORT_ADDON_TOKEN = 'import_export' + +/** + * The canonical spelling of a capability token for table lookups. + * + * Token names are case-insensitive — the packaging doc states it outright for its `fun:*` + * vocabulary, and tolerating case on the other tokens costs nothing since none of them collide + * under lowercasing. Surrounding whitespace is trimmed for a sharper reason than tidiness: every + * rule that reads a token has to read the SAME token, and a padded one used to be read two + * different ways at once — `' feat:crud'` failed the `feat:` prefix test that decides whether a key + * speaks the feature vocabulary, so the key was granted all five feature areas instead of the one + * it named, while `'feat:crud '` passed that test and then missed the table, granting none. + * + * Normalization happens at LOOKUP, never at storage: an entitlement carries the key's own + * spellings (they are diagnostics), and {@link CAPABILITY_TABLE} is keyed by the normalized form. + * + * @param {string} token - a capability token as the key spells it + */ +export function normalizeCapabilityToken(token: string): string { + return token.trim().toLowerCase() +} /** * Describes what a capability token grants: a set of function ids and a set of {@link FeatureId} @@ -19,37 +76,214 @@ export interface CapabilityGrant { features: FeatureId[], } -const coreGrant: CapabilityGrant = { - functions: [], - features: [FeatureId.NamedExpressions, FeatureId.Clipboard, FeatureId.Crud, FeatureId.UndoRedo, FeatureId.Batching], -} +/** + * The `HF.*` callable forms of the calculation operators — the members of `fun:operator.a`. + * + * They are gated like every other function: a key reaches them through `fun:operator.a`, a + * single-function token, or `fun:all`. Only the callable forms are affected. The infix operators + * themselves (`=A1+B1`) are not function calls, never reach gate B, and work under any key. + */ +const OPERATOR_FUNCTIONS = [ + 'HF.ADD', 'HF.CONCAT', 'HF.DIVIDE', 'HF.EQ', 'HF.GT', 'HF.GTE', 'HF.LT', 'HF.LTE', 'HF.MINUS', + 'HF.MULTIPLY', 'HF.NE', 'HF.POW', 'HF.UMINUS', 'HF.UNARY_PERCENT', 'HF.UPLUS', +] + +/** + * The two protected built-ins. Both are named by the packaging doc (`fun:lookup.A`, `fun:info.A`) + * but sit OUTSIDE the token system today — the interpreter never gate-checks a protected + * function, so granting them would be dead weight that implies a restriction that does not exist. + * The doc calls this a "technical limitation" on both; their tokens below are recognized but + * grant nothing. + */ +const PROTECTED_BUILT_INS = ['OFFSET', 'VERSION'] /** - * The production capability table. + * The 21 function groups of the packaging doc, keyed by their group tokens in normalized + * (lowercase) spelling — the doc writes them `fun:.` and declares all token names + * case-insensitive. * - * Placeholder content pending HF-331/HF-329 (the real per-package token vocabulary): every - * built-in function, plus the features already wired for gating in PR 2, fall under the single - * {@link CORE_TOKEN}. `FeatureId.CustomFunctions` and `FeatureId.ImportExport` are deliberately - * absent — reserved vocabulary with no grant yet (HF-307 decision D1; HF-107 for ImportExport). + * Transcribed 1:1 from section 6 of the internal packaging design document ("HF function groups + * and packages"), INCLUDING the members that resolve to no grant here: the protected built-ins, + * which sit outside the token system (see {@link PROTECTED_BUILT_INS}). Keeping the doc's own + * membership verbatim is what lets `capability-table.spec.ts` pin each group's size against the + * doc's published counts, so a re-transcription is a reviewable diff. * - * `coreGrant.functions` starts empty and is refreshed on every {@link refreshCoreGrant} call - * rather than populated once here: `src/index.ts` registers HyperFormula's built-in plugins as a - * side effect of being imported, and it does so AFTER `Config` and `Interpreter` — and so this - * module — have already been fully evaluated. Reading the function registry at module-load time - * would capture an empty registry. + * The doc freezes group names as API surface: once shipped inside license keys, a rename is a + * breaking change. */ -export const CAPABILITY_TABLE: ReadonlyMap = new Map([[CORE_TOKEN, coreGrant]]) +export const FUNCTION_GROUPS: ReadonlyMap = new Map([ + ['fun:math.a', ['ABS', 'LOG', 'MOD', 'POWER', 'PRODUCT', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'SQRT', 'SUM']], + ['fun:stat.a', ['AVERAGE', 'COUNT', 'MAX', 'MIN']], + ['fun:logic.a', ['IF']], + ['fun:operator.a', [...OPERATOR_FUNCTIONS]], + ['fun:info.a', ['VERSION']], + ['fun:lookup.a', ['OFFSET']], + ['fun:time.b', [ + 'DATE', 'DATEDIF', 'DATEVALUE', 'DAY', 'DAYS', 'EOMONTH', 'HOUR', 'ISOWEEKNUM', 'MINUTE', 'MONTH', + 'NETWORKDAYS', 'SECOND', 'TODAY', 'WEEKDAY', 'WEEKNUM', 'WORKDAY', 'YEAR', + ]], + ['fun:text.b', [ + 'CONCATENATE', 'EXACT', 'LEFT', 'LEN', 'LOWER', 'MID', 'REPLACE', 'REPT', 'RIGHT', 'SEARCH', + 'SUBSTITUTE', 'TEXT', 'TRIM', 'UPPER', 'VALUE', + ]], + ['fun:logic.b', ['AND', 'FALSE', 'IFS', 'NOT', 'OR', 'SWITCH', 'TRUE', 'XOR']], + ['fun:math.b', ['RAND', 'RANDBETWEEN', 'SUMIF', 'SUMIFS']], + ['fun:stat.b', ['AVERAGEIF', 'COUNTIF', 'STDEV.S']], + ['fun:lookup.c', [ + 'ADDRESS', 'CHOOSE', 'COLUMN', 'COLUMNS', 'FILTER', 'HLOOKUP', 'HSTACK', 'HYPERLINK', 'INDEX', 'MATCH', + 'ROW', 'ROWS', 'SORT', 'TRANSPOSE', 'UNIQUE', 'VLOOKUP', 'VSTACK', 'XLOOKUP', + ]], + ['fun:math.c', [ + 'ACOS', 'ASIN', 'ATAN', 'ATAN2', 'CEILING', 'COS', 'EVEN', 'EXP', 'FLOOR', 'INT', 'LN', 'MROUND', 'ODD', + 'PI', 'QUOTIENT', 'SEQUENCE', 'SIGN', 'SIN', 'SUBTOTAL', 'SUMPRODUCT', 'SUMSQ', 'SUMXMY2', 'TAN', + ]], + ['fun:stat.c', [ + 'AVERAGEA', 'COUNTA', 'COUNTBLANK', 'COUNTIFS', 'LARGE', 'MAXIFS', 'MEDIAN', 'MINIFS', 'PERCENTILE.INC', + 'SMALL', 'STDEV.P', 'STDEVA', 'STDEVPA', 'VAR.P', 'VAR.S', + ]], + ['fun:time.c', ['DAYS360', 'EDATE', 'NOW', 'TIME', 'YEARFRAC']], + ['fun:text.c', ['CHAR', 'CLEAN', 'CODE', 'FIND', 'PROPER', 'T', 'TEXTJOIN', 'UNICHAR']], + ['fun:info.c', [ + 'ISBLANK', 'ISERR', 'ISERROR', 'ISEVEN', 'ISLOGICAL', 'ISNA', 'ISNUMBER', 'ISODD', 'ISTEXT', 'N', 'NA', + ]], + ['fun:logic.c', ['IFERROR', 'IFNA']], + ['fun:finance.c', ['FV', 'IPMT', 'IRR', 'NPV', 'PMT', 'PPMT', 'PV', 'RATE', 'SLN', 'XIRR', 'XNPV']], + ['fun:engineer.c', ['DEC2HEX', 'HEX2DEC']], + ['fun:array.c', ['ARRAYFORMULA', 'ARRAY_CONSTRAIN']], +]) /** - * Refreshes the placeholder `core` grant with every function currently in the static function - * registry. Called from `CapabilityRegistry`'s constructor every time it is constructed without - * an explicit table — not just the first time: the static registry can change after the first - * engine is built (`HyperFormula.registerFunctionPlugin`/`unregisterFunctionPlugin` are public, - * documented APIs), and a one-time snapshot would silently go stale for every engine built - * afterward. Cheap (a single array copy from an existing map's keys) and only ever runs once per - * `Config`/engine construction, never on the per-formula hot path, so re-running it every time - * costs nothing worth guarding against with memoization. + * The members of a group that a grant can carry: the group verbatim, minus the protected + * built-ins, which are always available and must never become table-covered (a covered function + * is gated for every key not granting it). + * + * @param {string} groupToken - a group token, in normalized spelling */ -export function refreshCoreGrant(): void { - coreGrant.functions = FunctionRegistry.getRegisteredFunctionIds() +function gatableMembersOf(groupToken: string): string[] { + return (FUNCTION_GROUPS.get(groupToken) ?? []).filter((name) => PROTECTED_BUILT_INS.indexOf(name) === -1) } + +/** Every function some group names, the operator callable forms included. The groups are disjoint. */ +const GROUPED_FUNCTIONS = Array.from(FUNCTION_GROUPS.keys()).reduce( + (members, groupToken) => members.concat(gatableMembersOf(groupToken)), + [], +) + +/** + * The implemented functions no group names — the packaging design's niche tail, reachable only + * through {@link FUN_ALL_TOKEN} or their own single-function token. + * + * Enumerated rather than taken from the function registry at run time, even though "everything + * not in a group" would be the shorter way to say it. Reading the registry would sweep in + * functions registered through `HyperFormula.registerFunctionPlugin`, putting a user's OWN custom + * function under a licence token and returning `#LIC!` for it — the opposite of HF-307 decision + * D1, which drops custom-function gating entirely. A function this table does not list is not + * gated at all, which is exactly the treatment a custom function should get. + */ +const UNGROUPED_FUNCTIONS = [ + 'ACOSH', 'ACOT', 'ACOTH', 'ARABIC', 'ASINH', 'ATANH', 'AVEDEV', 'BASE', 'BESSELI', 'BESSELJ', 'BESSELK', + 'BESSELY', 'BETA.DIST', 'BETA.INV', 'BIN2DEC', 'BIN2HEX', 'BIN2OCT', 'BINOM.DIST', 'BINOM.INV', 'BITAND', + 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'CEILING.MATH', 'CEILING.PRECISE', 'CHISQ.DIST', + 'CHISQ.DIST.RT', 'CHISQ.INV', 'CHISQ.INV.RT', 'CHISQ.TEST', 'COMBIN', 'COMBINA', 'COMPLEX', + 'CONFIDENCE.NORM', 'CONFIDENCE.T', 'CORREL', 'COSH', 'COT', 'COTH', 'COUNTUNIQUE', 'COVARIANCE.P', + 'COVARIANCE.S', 'CSC', 'CSCH', 'CUMIPMT', 'CUMPRINC', 'DAVERAGE', 'DB', 'DCOUNT', 'DCOUNTA', 'DDB', + 'DEC2BIN', 'DEC2OCT', 'DECIMAL', 'DEGREES', 'DELTA', 'DEVSQ', 'DGET', 'DMAX', 'DMIN', 'DOLLARDE', + 'DOLLARFR', 'DPRODUCT', 'DSTDEV', 'DSTDEVP', 'DSUM', 'DVAR', 'DVARP', 'EFFECT', 'ERF', 'ERFC', + 'EXPON.DIST', 'F.DIST', 'F.DIST.RT', 'F.INV', 'F.INV.RT', 'F.TEST', 'FACT', 'FACTDOUBLE', 'FISHER', + 'FISHERINV', 'FLOOR.MATH', 'FLOOR.PRECISE', 'FORMULATEXT', 'FVSCHEDULE', 'GAMMA', 'GAMMA.DIST', + 'GAMMA.INV', 'GAMMALN', 'GAUSS', 'GCD', 'GEOMEAN', 'HARMEAN', 'HEX2BIN', 'HEX2OCT', 'HYPGEOM.DIST', + 'IMABS', 'IMAGINARY', 'IMARGUMENT', 'IMCONJUGATE', 'IMCOS', 'IMCOSH', 'IMCOT', 'IMCSC', 'IMCSCH', 'IMDIV', + 'IMEXP', 'IMLN', 'IMLOG10', 'IMLOG2', 'IMPOWER', 'IMPRODUCT', 'IMREAL', 'IMSEC', 'IMSECH', 'IMSIN', + 'IMSINH', 'IMSQRT', 'IMSUB', 'IMSUM', 'IMTAN', 'INTERVAL', 'ISBINARY', 'ISFORMULA', 'ISNONTEXT', 'ISPMT', + 'ISREF', 'LCM', 'LOG10', 'LOGNORM.DIST', 'LOGNORM.INV', 'MAXA', 'MAXPOOL', 'MEDIANPOOL', 'MINA', 'MIRR', + 'MMULT', 'MULTINOMIAL', 'NEGBINOM.DIST', 'NETWORKDAYS.INTL', 'NOMINAL', 'NORM.DIST', 'NORM.INV', + 'NORM.S.DIST', 'NORM.S.INV', 'NPER', 'OCT2BIN', 'OCT2DEC', 'OCT2HEX', 'PDURATION', 'PERCENTILE.EXC', + 'PHI', 'POISSON.DIST', 'QUARTILE.EXC', 'QUARTILE.INC', 'RADIANS', 'ROMAN', 'RRI', 'RSQ', 'SEC', 'SECH', + 'SERIESSUM', 'SHEET', 'SHEETS', 'SINH', 'SKEW', 'SKEW.P', 'SLOPE', 'SPLIT', 'SQRTPI', 'STANDARDIZE', + 'STEYX', 'SUMX2MY2', 'SUMX2PY2', 'SYD', 'T.DIST', 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'T.TEST', + 'TANH', 'TBILLEQ', 'TBILLPRICE', 'TBILLYIELD', 'TDIST', 'TIMEVALUE', 'UNICODE', 'VARA', 'VARPA', + 'WEIBULL.DIST', 'WORKDAY.INTL', 'Z.TEST', +] + +/** The whole gatable catalog: what {@link FUN_ALL_TOKEN} grants. */ +const ALL_GATABLE_FUNCTIONS = GROUPED_FUNCTIONS.concat(UNGROUPED_FUNCTIONS) + +/** + * One table entry per group token, granting the group's gatable members. `fun:info.a` and + * `fun:lookup.a` resolve to + * EMPTY grants on purpose — their members are the protected built-ins, which are always available + * and must never become table-covered (a covered function is gated for every key not granting + * it). The tokens stay recognized either way, so a key carrying them is never reported as + * unrecognized: they are the doc's bookkeeping identifiers for functionality every key gets. + */ +const groupEntries: [string, CapabilityGrant][] = Array.from(FUNCTION_GROUPS.keys()).map((groupToken) => [ + groupToken, + {functions: gatableMembersOf(groupToken), features: []}, +]) + +/** + * One table entry per canonical function name: the packaging doc's single-function tokens + * (`fun:`), "for surgical grants: custom deals, previews, per-function + * exceptions". One exists for EVERY canonical name — including the operator callable forms and + * the protected built-ins (empty grants, as above). Alias names get no + * token of their own: tokens reference canonical names, and an alias travels with its canonical + * function because the gates canonicalize before consulting the table. + */ +const singleFunctionEntries: [string, CapabilityGrant][] = ALL_GATABLE_FUNCTIONS + .concat(PROTECTED_BUILT_INS) + .map((name) => [ + `fun:${normalizeCapabilityToken(name)}`, + {functions: PROTECTED_BUILT_INS.indexOf(name) === -1 ? [name] : [], features: []}, + ]) + +/** + * The production capability table, keyed by NORMALIZED token spelling — look up through + * {@link normalizeCapabilityToken}, never with a raw key string. + * + * The vocabulary, and nothing else: + * + * - function tokens, per §6 of the packaging design: `fun:all`, the group tokens + * `fun:.`, and one `fun:` per canonical function; + * - one `feat:*` token per gated API area; + * - the two add-on tokens the key generator's schema mints, each naming the features it grants. + * + * No token here names a package, and no grant refers to another token. Which tokens a commercial + * package consists of is the generator's knowledge, expressed by the bigger licence simply + * listing more tokens — so a key's function set is the union of everything it names that this + * table recognizes, and an unrecognized token is inert (strict-shape/lenient-vocabulary, T7). + * + * Every grant is STATIC. Nothing here is derived from the function registry at run time, so a + * function registered by a user through `HyperFormula.registerFunctionPlugin` can never be gated + * — see {@link UNGROUPED_FUNCTIONS}. The cost is that a newly implemented built-in is ungated until + * it is added here, which the completeness invariant in `unit/license/capability-registry.spec.ts` + * fails on. + * + * The five `feat:*` tokens carry the gated API areas, one feature each. A key may state them + * explicitly; a key naming none is granted all five (the opt-in rule in `licenseTermsOf`); legacy + * keys resolve to the unrestricted entitlement and never consult this table. + * + * The two add-on tokens, wired per the 2026-08-12 packages meeting: `spreadsheet` backs the + * 'Spreadsheet Bundle' add-on and grants {@link FeatureId.Crud}, {@link FeatureId.UndoRedo}, + * {@link FeatureId.Clipboard} and {@link FeatureId.Batching}. `import_export` backs the + * import-export add-on and grants {@link FeatureId.ImportExport} — a RESERVED grant, since nothing + * in the public API is gated on it yet: HF-107 hasn't shipped the feature it would gate. + */ +export const CAPABILITY_TABLE: ReadonlyMap = new Map([ + [CRUD_FEATURE_TOKEN, {functions: [], features: [FeatureId.Crud]}], + [UNDO_REDO_FEATURE_TOKEN, {functions: [], features: [FeatureId.UndoRedo]}], + [CLIPBOARD_FEATURE_TOKEN, {functions: [], features: [FeatureId.Clipboard]}], + [NAMED_EXPRESSIONS_FEATURE_TOKEN, {functions: [], features: [FeatureId.NamedExpressions]}], + [BATCHING_FEATURE_TOKEN, {functions: [], features: [FeatureId.Batching]}], + // NamedExpressions is absent on purpose: the Spreadsheet Bundle was scoped at the 12.08 packages + // meeting to the four areas below, and named expressions was not among them. It is recorded here + // so the omission reads as the decision it is rather than as a transcription slip, and so that + // moving it into the bundle stays a product call rather than a silent edit. + [SPREADSHEET_ADDON_TOKEN, { + functions: [], + features: [FeatureId.Crud, FeatureId.UndoRedo, FeatureId.Clipboard, FeatureId.Batching], + }], + [IMPORT_EXPORT_ADDON_TOKEN, {functions: [], features: [FeatureId.ImportExport]}], + [FUN_ALL_TOKEN, {functions: [...ALL_GATABLE_FUNCTIONS], features: []}], + ...groupEntries, + ...singleFunctionEntries, +]) diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md new file mode 100644 index 0000000000..52e866ca46 --- /dev/null +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -0,0 +1,97 @@ +# Vendored entitlement-key reader — provenance and drift control + +The files in this directory are a **TypeScript port of code owned by another Handsoncode +repository**, not original HyperFormula code. Treat them as a mirror: fix bugs upstream first, +then re-port. A local-only fix here silently forks the two copies, and a forked checksum or +parser rejects genuine customer keys. + +## Upstream + +| | | +|---|---| +| Repository | `handsontable/license-key` (private) | +| Tag | `4.0.0` | +| Commit | `c50ef40a6` (the `4.0.0` release commit; on `develop` as `1acddafa8`) | +| Ported on | 2026-08-20 | +| Reference docs | the format and design notes kept alongside the upstream sources; the byte-level rules are also specified in the key spec's "Technical implementation" addendum (T1–T14) | + +## Files + +Hashes are of the **upstream** `.js` sources at the tag above, so drift is detectable without +storing a copy of them here. + +| This directory | Upstream `src/entitlement-key/` | Upstream sha256 | +|---|---|---| +| `constants.ts` | `constants.js` | `6e2ad68d1a316abdec3f89bf04260a2cc4098f76525427d919f22cb25fb077d6` | +| `detectFormat.ts` | `detect-format.js` | `7dc037fd70e7c64078a0fe29b42cb33ecf25e8f4d8963ae9bfb16b69479d267f` | +| `extractKeyData.ts` | `extract-key-data.js` | `afd0858768879764ea016d2bc4fca692a0cd12214c1dfda6932d7ed9e4f32e45` | +| `utils.ts` | `utils.js` | `135a8396bb22f424160fc651e899931d4be807df9b94c6dd24bb1cf6526e0541` | +| `sha512.ts` | `sha512.js` | `668dd1109160b92965a1f9a9c5fb78dfdc1e5b7e93f635a147ae8a6bb2a5d837` | + +### Checking for drift + +The check is manual and needs read access to the private repository — HyperFormula's own CI +cannot do it, which is exactly why the hashes are written down here. + +```bash +git clone git@github.com:handsontable/license-key.git +cd license-key/src/entitlement-key +sha256sum constants.js detect-format.js extract-key-data.js utils.js sha512.js +``` + +Any hash that differs from the table means upstream moved. Re-read the changed file and re-port +it, then update this table together with the code in the same commit. + +## Not vendored, on purpose + +The entitlement reader is deliberately schema-free upstream (unknown products, tokens and flags +are tolerated, so nothing about *reading* a key depends on the vocabulary), which keeps the +vendored surface small: everything schema- and generation-side stays out. + +| Upstream file | Why not | +|---|---| +| `generate-key.js`, `build-payload.js`, `build-prose.js` | Mint keys. HyperFormula only ever reads them. | +| `default-schema.js` | The generator's vocabulary (packages, add-ons, wordings, templates). The reader needs no schema; the only name this library reads is its own product entry, kept as `HYPERFORMULA_PRODUCT_NAME` in `src/license/licenseResolution.ts`. | +| `create-engine.js`, `resolve-schema.js`, `validate-schema.js`, `validate-record.js` | Bind and verify a caller's schema/record at generation time — generator-side. | +| `validate-key.js` | A two-line boolean wrapper over `extractEntitlementKeyData`; the extractor is called directly. | + +From `utils.js`, the two generation-side helpers `bytesToBase64` and `stringToBase64Url` are +also left out. Everything else in that file is ported. + +## Deliberate divergences from upstream + +`allowJs` is off in HyperFormula's `tsconfig.json` and `strict` is on, so these files are a port +rather than a copy. Beyond adding types, the semantics were kept identical except for the +following, which a drift review should expect to see: + +1. **`detectFormat.ts` keeps its literals in a `Map`,** where upstream uses an object literal + behind a `hasOwnProperty` guard. Same behaviour for every input (including `constructor` and + `__proto__`); the `Map` is this repository's idiom for lookups keyed by untrusted strings. +2. **`stringToUtf8Bytes`'s parameter is named `text`, not `string`,** which is a type keyword in + TypeScript. +3. **The normalized product entry is typed** (`EntitlementProductGrant`), which upstream's plain + JavaScript does not do. The types state what the reader CHECKS, and the checks are upstream's: + `capabilities` and `flags` are verified element by element, and `notice` and `grace` are verified + as non-negative integers. Everything the reader does not verify — unknown fields are preserved on + purpose — sits behind an `unknown`-valued index signature, so consumers must narrow before use. +4. **The date field is checked for type, not only for shape** (`isIsoDate` in `extractKeyData.ts`). + Upstream matches `String(value)` against `YYYY-MM-DD`, so a `usage_until` that is a single-element + array of the right string passes its shape check and the declared `string` type ends up wider than + the value. Here a non-string is rejected outright. This is the one divergence that CHANGES which + keys are accepted, so it is called out separately: a malformed key that upstream would carry into + a RESTRICTED entitlement takes the invalid-key path instead. The key spec's addendum (T7) makes + the field a real calendar date, so the stricter reading is the specified one and it is upstream + that deviates — but upstream has not adopted it (checked at `c50ef40a`, `develop` and `master`; + no pull request or issue proposes it), so this is a live fork of behaviour, not a re-port waiting + to happen. Re-check it at every drift review. + +Upstream's `/* eslint-disable */` pragmas were dropped where HyperFormula's own ESLint config +does not need them. + +## Related + +- `src/helpers/licenseKeyHelper.ts` — the validator for the legacy 25-character key format, + untouched here (upstream 4.0.0 still exports it too). +- `src/license/licenseResolution.ts` — the consumer: routes on `detectLicenseKeyFormat` and turns + the extracted payload into an entitlement. +- `src/license/capabilities.ts` — the capability table the payload's tokens are resolved against. diff --git a/src/license/handsontable-license-key-parser/constants.ts b/src/license/handsontable-license-key-parser/constants.ts new file mode 100644 index 0000000000..270be27fe1 --- /dev/null +++ b/src/license/handsontable-license-key-parser/constants.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Vendored from `handsontable/license-key`, `src/entitlement-key/constants.js`. + * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. + */ + +/** + * The length of the checksum (SHA-512 as hex) which postfixes the payload inside the + * machine-readable block of every entitlement license key. + */ +export const ENTITLEMENT_KEY_CHECKSUM_LENGTH = 128 + +/** + * The two mutually exclusive date fields of a product entry. Exactly one of them has to be + * present: + * + * - `usage_until` — the last licensed day (inclusive, compared in UTC), + * - `release_until` — builds released on or before that day may be used forever (compared + * against the build release date as text, no clock involved). + * + * The pair replaces the contract type — nothing in the payload says "subscription" or + * "perpetual". + */ +export const DATE_FIELDS: readonly string[] = ['usage_until', 'release_until'] diff --git a/src/license/handsontable-license-key-parser/detectFormat.ts b/src/license/handsontable-license-key-parser/detectFormat.ts new file mode 100644 index 0000000000..183afc66e1 --- /dev/null +++ b/src/license/handsontable-license-key-parser/detectFormat.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Vendored from `handsontable/license-key`, `src/entitlement-key/detect-format.js`. + * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. + */ + +/** + * The name of each license key format {@link detectLicenseKeyFormat} can answer with. + */ +export type LicenseKeyFormat = + | 'entitlement' + | 'legacy' + | 'non-commercial-and-evaluation' + | 'gpl-v3' + | 'unknown' + +/** + * The literal keys that stand for a licence rather than encode one. + */ +const LITERAL_KEYS: ReadonlyMap = new Map([ + ['non-commercial-and-evaluation', 'non-commercial-and-evaluation'], + ['gpl-v3', 'gpl-v3'], +]) + +/** + * The classic 25-character key, once its dashes are stripped. + */ +const LEGACY_KEY = /^[0-9a-fA-F]{25}$/ + +/** + * Tells which license key format a string is in, without validating it. + * + * The entitlement key format removed the leading type tag, so a key no longer announces itself + * in its first characters — it now ends with the bracketed machine-readable block instead. + * Products that accept several formats need one place that makes the distinction, and this is it. + * + * The answer is about SHAPE only. A returned `'entitlement'` means "route this to the + * entitlement validator", not "this key is valid". + * + * @param {unknown} licenseKey - the license key to inspect + */ +export function detectLicenseKeyFormat(licenseKey: unknown): LicenseKeyFormat { + if (typeof licenseKey !== 'string') { + return 'unknown' + } + + const key = licenseKey.trim() + const literal = LITERAL_KEYS.get(key.toLowerCase()) + + if (literal !== undefined) { + return literal + } + + // The bracketed block closes an entitlement key. Its presence is what separates the new format + // from everything else, so it is checked before the shape-based ones. + const blockStart = key.lastIndexOf('[') + + if (blockStart !== -1 && key.indexOf(']', blockStart) !== -1) { + return 'entitlement' + } + if (LEGACY_KEY.test(key.replace(/-/g, ''))) { + return 'legacy' + } + + return 'unknown' +} diff --git a/src/license/handsontable-license-key-parser/extractKeyData.ts b/src/license/handsontable-license-key-parser/extractKeyData.ts new file mode 100644 index 0000000000..6a71b3f310 --- /dev/null +++ b/src/license/handsontable-license-key-parser/extractKeyData.ts @@ -0,0 +1,284 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Vendored from `handsontable/license-key`, `src/entitlement-key/extract-key-data.js`. + * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. + * + * Unlike the typed-key reader this file replaces, the entitlement reader is deliberately + * SCHEMA-FREE upstream: unknown products, capabilities and flags are all tolerated, so nothing + * about reading a key depends on the vocabulary — which is what lets a product vendor this + * parser on its own. + */ + +import {DATE_FIELDS, ENTITLEMENT_KEY_CHECKSUM_LENGTH} from './constants' +import {sha512} from './sha512' +import {base64ToString, parseIsoDate, stringToUtf8Bytes} from './utils' + +/** + * The alphabet of the encoded payload — URL-safe base64 without padding. The checksum (lowercase + * hex) is a subset of it, which is what lets the two be split by a fixed length from the right. + */ +const ENCODED_PAYLOAD = /^[A-Za-z0-9\-_]+$/ +const CHECKSUM = /^[0-9a-f]+$/ + +/** + * One normalized product entry of an entitlement key payload. + * + * The named fields are guaranteed by {@link normalizeProductEntry}: `capabilities` and `flags` + * are arrays of strings (`flags` normalized to `[]` when absent), `notice` and `grace` are + * non-negative integers, and exactly one of `usage_until` / `release_until` is present and is a + * real `YYYY-MM-DD` calendar date. Any OTHER field the entry carries is preserved verbatim under + * its own name — a field added to the format later must reach an application running an older + * vendored parser — which is what the index signature is for. + */ +export interface EntitlementProductGrant { + readonly capabilities: readonly string[], + readonly usage_until?: string, + readonly release_until?: string, + readonly notice: number, + readonly grace: number, + readonly flags: readonly string[], + readonly [field: string]: unknown, +} + +/** + * The machine-readable content of an intact entitlement license key: the granted products, each + * with its capabilities, its single date (`usage_until` or `release_until`), its `notice` and + * `grace` windows in days, and its `flags`. + */ +export interface EntitlementKeyData { + readonly products: Readonly>, +} + +/** + * Returns `true` when the value is a plain object. + * + * @param {unknown} value - the value to check + */ +function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value) +} + +/** + * Returns `true` when the value is a non-negative integer. + * + * @param {unknown} value - the value to check + */ +function isNonNegativeInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value && value >= 0 +} + +/** + * Returns `true` when the value is an array of strings. + * + * @param {unknown} value - the value to check + */ +function isStringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every((item) => typeof item === 'string') +} + +/** + * Returns `true` when the value is a real calendar date in the `YYYY-MM-DD` format. A time + * component, an offset, a numeric timestamp and a date that does not exist are all rejected — + * the format is the whole contract, and a validator that accepted two spellings would hide a + * timezone bug at generation instead of surfacing it. + * + * @param {unknown} value - the value to check + */ +function isIsoDate(value: unknown): boolean { + // `parseIsoDate` stringifies its argument before matching the `YYYY-MM-DD` shape, so a value + // that is not a string but spells a date once stringified — a single-element array is the + // realistic case — would pass a shape check the format makes fatal, and a malformed key would + // end up granting a RESTRICTED entitlement instead of taking the invalid-key path. The type is + // part of the shape, so it is rejected here rather than left to the stringifying matcher. + if (typeof value !== 'string') { + return false + } + + try { + parseIsoDate(value, 'license') + + return true + } catch (error) { + return false + } +} + +/** + * Adds an own, ordinary property. + * + * Both the product names and the field names of a product entry come from JSON, so `__proto__` + * is a name an attacker can put in a key. A plain assignment would go through the + * `Object.prototype` setter: the value would vanish from `Object.keys` while still resolving + * through the chain. + * + * @param {object} target - the object to add the property to + * @param {string} key - the property name + * @param {unknown} value - the property value + */ +function defineOwn(target: object, key: string, value: unknown): void { + Object.defineProperty(target, key, { + value, enumerable: true, writable: true, configurable: true, + }) +} + +/** + * Verifies and normalizes one product entry. + * + * Strict about SHAPE: exactly one of the two dates, a real date, and the two window sizes. A key + * that gets this wrong is malformed, not merely unknown, and reading it would mean guessing what + * was licensed. + * + * Lenient about VOCABULARY: an unrecognised capability token, an unrecognised flag and an + * unrecognised extra field are all kept and ignored. Without that leniency every token added on + * the issuing side would break every library version already deployed in the field. + * + * Returns `null` when the entry is malformed. + * + * @param {unknown} entry - the product entry of the payload + */ +function normalizeProductEntry(entry: unknown): EntitlementProductGrant | null { + if (!isPlainObject(entry)) { + return null + } + if (!isStringArray(entry.capabilities)) { + return null + } + + const presentDateFields = DATE_FIELDS.filter((field) => entry[field] !== undefined) + + // Exactly one date per product. "Both" and "neither" are each a different commercial shape + // that the format cannot express, so neither may be silently resolved by whichever field the + // parser happens to read first. + if (presentDateFields.length !== 1) { + return null + } + if (!isIsoDate(entry[presentDateFields[0]])) { + return null + } + if (!isNonNegativeInteger(entry.notice) || !isNonNegativeInteger(entry.grace)) { + return null + } + if (entry.flags !== undefined && !isStringArray(entry.flags)) { + return null + } + + // Start from everything the entry carries, so a field this version does not know survives + // into the result instead of being silently dropped. A field added to the format later is + // exactly the case an already-vendored parser has to survive, and a reader that quietly + // discards it makes the field invisible to the application on top. + const normalized = {} + + Object.keys(entry).forEach((field) => defineOwn(normalized, field, entry[field])) + + defineOwn(normalized, 'capabilities', entry.capabilities.slice()) + defineOwn(normalized, 'notice', entry.notice) + defineOwn(normalized, 'grace', entry.grace) + // An absent array and an empty one mean the same thing. Normalizing here keeps + // `flags.indexOf('trial')` safe at every call site. + defineOwn(normalized, 'flags', entry.flags === undefined ? [] : entry.flags.slice()) + defineOwn(normalized, presentDateFields[0], entry[presentDateFields[0]]) + + return normalized as EntitlementProductGrant +} + +/** + * Extracts the machine-readable data from an entitlement license key. + * + * The checksum is verified first, so the returned data is guaranteed to belong to an intact + * block. For a malformed or tampered key `null` is returned — reporting an invalid key is the + * caller's job, not this function's. + * + * Only the bracketed block matters. The prose in front of it is neither parsed nor covered by + * the checksum, so the caller may pass the whole artifact or just the `[...]` block, and + * rewrapped or re-pasted text still validates. + * + * No schema is needed. Unknown products, capabilities and flags are all tolerated, so nothing + * about reading a key depends on the vocabulary — which is what lets a product vendor this + * parser on its own. + * + * @param {string} licenseKey - the license key to extract the data from + */ +export function extractEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { + if (typeof licenseKey !== 'string') { + return null + } + + // The machine-readable block closes the key. Searching backwards means a bracket inside the + // prose cannot shadow it. + const blockStart = licenseKey.lastIndexOf('[') + + if (blockStart === -1) { + return null + } + + const blockEnd = licenseKey.indexOf(']', blockStart) + + if (blockEnd === -1) { + return null + } + + const content = licenseKey.slice(blockStart + 1, blockEnd) + + if (content.length <= ENTITLEMENT_KEY_CHECKSUM_LENGTH) { + return null + } + + const encodedPayload = content.slice(0, -ENTITLEMENT_KEY_CHECKSUM_LENGTH) + const checksum = content.slice(-ENTITLEMENT_KEY_CHECKSUM_LENGTH) + + if (!ENCODED_PAYLOAD.test(encodedPayload) || !CHECKSUM.test(checksum)) { + return null + } + if (sha512(stringToUtf8Bytes(encodedPayload)) !== checksum) { + return null + } + + const payloadJson = base64ToString(encodedPayload) + + if (payloadJson === null) { + return null + } + + let payload: unknown + + try { + payload = JSON.parse(payloadJson) + } catch (error) { + return null + } + + if (!isPlainObject(payload)) { + return null + } + + const rawProducts = payload.products + + if (!isPlainObject(rawProducts)) { + return null + } + + const products = {} + let malformed = false + + Object.keys(rawProducts).forEach((name) => { + const entry = normalizeProductEntry(rawProducts[name]) + + if (entry === null) { + malformed = true + + return + } + + defineOwn(products, name, entry) + }) + + if (malformed) { + return null + } + + return {products} +} diff --git a/src/license/handsontable-license-key-parser/sha512.ts b/src/license/handsontable-license-key-parser/sha512.ts new file mode 100644 index 0000000000..e65aee16ea --- /dev/null +++ b/src/license/handsontable-license-key-parser/sha512.ts @@ -0,0 +1,217 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Vendored from `handsontable/license-key`, `src/entitlement-key/sha512.js`. + * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. + */ + +/** + * The SHA-512 round constants. Each 64-bit constant is stored as a pair of 32-bit integers + * (high word first, low word second). + */ +const K: number[] = [ + 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, + 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, + 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, + 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, + 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, + 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, + 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, + 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, + 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, + 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, + 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, + 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, + 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, + 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, + 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, + 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, + 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, + 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, + 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, + 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, + 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, + 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, + 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, + 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, + 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, + 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, + 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, + 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, + 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, + 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, + 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, + 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, + 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, + 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, + 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, + 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, + 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, + 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, + 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, + 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817, +] + +/** + * Converts a 32-bit integer to a zero-padded 8-character hex string. + * + * @param {number} value - the 32-bit integer value + */ +function toHex32(value: number): string { + return `00000000${(value >>> 0).toString(16)}`.slice(-8) +} + +/** + * Calculates the SHA-512 checksum of the passed bytes. The implementation is a plain (pure JS) + * one on purpose. It does not depend on the Web Crypto API (`crypto.subtle`), which browsers + * expose only on secure origins (https). Thanks to that, the checksum can be verified on plain + * http:// pages, for example, intranets of big companies. + * + * A second reason applies on HyperFormula's side: `crypto.subtle.digest` is asynchronous, and + * the license key is read from `Config`'s constructor, which is not. + * + * @param {number[] | Uint8Array} bytes - the bytes to calculate the checksum from + */ +export function sha512(bytes: number[] | Uint8Array): string { + const byteLength = bytes.length + // The message is padded with the 0x80 byte, zeros, and the 128-bit big-endian bit length so + // the total length is a multiple of 128 bytes. + const blockCount = Math.ceil((byteLength + 17) / 128) + const buffer = new Uint8Array(blockCount * 128) + + buffer.set(bytes) + buffer[byteLength] = 0x80 + + const bitLength = byteLength * 8 + const bufferLength = buffer.length + + // The supported message sizes fit well within 2^53 bits, so only the two lowest 32-bit words + // of the 128-bit length field are ever non-zero. + buffer[bufferLength - 7] = Math.floor(bitLength / 0x1000000000000) & 0xff // bits 48-55 + buffer[bufferLength - 6] = Math.floor(bitLength / 0x10000000000) & 0xff // bits 40-47 + buffer[bufferLength - 5] = Math.floor(bitLength / 0x100000000) & 0xff // bits 32-39 + buffer[bufferLength - 4] = (bitLength >>> 24) & 0xff // bits 24-31 + buffer[bufferLength - 3] = (bitLength >>> 16) & 0xff // bits 16-23 + buffer[bufferLength - 2] = (bitLength >>> 8) & 0xff // bits 8-15 + buffer[bufferLength - 1] = bitLength & 0xff // bits 0-7 + + // The initial hash values, stored as [high, low] 32-bit pairs. + const H: number[] = [ + 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, + 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, + 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, + 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, + ] + const wh = new Array(80) + const wl = new Array(80) + + for (let block = 0; block < blockCount; block += 1) { + const offset = block * 128 + + // Prepare the message schedule. + for (let i = 0; i < 16; i += 1) { + const o = offset + i * 8 + + wh[i] = ((buffer[o] << 24) | (buffer[o + 1] << 16) | (buffer[o + 2] << 8) | buffer[o + 3]) >>> 0 + wl[i] = ((buffer[o + 4] << 24) | (buffer[o + 5] << 16) | (buffer[o + 6] << 8) | buffer[o + 7]) >>> 0 + } + + for (let i = 16; i < 80; i += 1) { + const x2h = wh[i - 2] + const x2l = wl[i - 2] + const x15h = wh[i - 15] + const x15l = wl[i - 15] + // smallSigma1 = ROTR^19(x) XOR ROTR^61(x) XOR SHR^6(x) + const s1h = ((x2h >>> 19) | (x2l << 13)) ^ ((x2l >>> 29) | (x2h << 3)) ^ (x2h >>> 6) + const s1l = ((x2l >>> 19) | (x2h << 13)) ^ ((x2h >>> 29) | (x2l << 3)) ^ ((x2l >>> 6) | (x2h << 26)) + // smallSigma0 = ROTR^1(x) XOR ROTR^8(x) XOR SHR^7(x) + const s0h = ((x15h >>> 1) | (x15l << 31)) ^ ((x15h >>> 8) | (x15l << 24)) ^ (x15h >>> 7) + const s0l = ((x15l >>> 1) | (x15h << 31)) ^ ((x15l >>> 8) | (x15h << 24)) ^ ((x15l >>> 7) | (x15h << 25)) + + const lowSum = (s1l >>> 0) + (wl[i - 7] >>> 0) + (s0l >>> 0) + (wl[i - 16] >>> 0) + + wl[i] = lowSum >>> 0 + wh[i] = ((s1h >>> 0) + (wh[i - 7] >>> 0) + (s0h >>> 0) + (wh[i - 16] >>> 0) + + Math.floor(lowSum / 0x100000000)) >>> 0 + } + + let ah = H[0] + let al = H[1] + let bh = H[2] + let bl = H[3] + let ch = H[4] + let cl = H[5] + let dh = H[6] + let dl = H[7] + let eh = H[8] + let el = H[9] + let fh = H[10] + let fl = H[11] + let gh = H[12] + let gl = H[13] + let hh = H[14] + let hl = H[15] + + for (let i = 0; i < 80; i += 1) { + // bigSigma1 = ROTR^14(e) XOR ROTR^18(e) XOR ROTR^41(e) + const bs1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((el >>> 9) | (eh << 23)) + const bs1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((eh >>> 9) | (el << 23)) + // bigSigma0 = ROTR^28(a) XOR ROTR^34(a) XOR ROTR^39(a) + const bs0h = ((ah >>> 28) | (al << 4)) ^ ((al >>> 2) | (ah << 30)) ^ ((al >>> 7) | (ah << 25)) + const bs0l = ((al >>> 28) | (ah << 4)) ^ ((ah >>> 2) | (al << 30)) ^ ((ah >>> 7) | (al << 25)) + // ch = (e AND f) XOR (NOT e AND g) + const chh = (eh & fh) ^ (~eh & gh) + const chl = (el & fl) ^ (~el & gl) + // maj = (a AND b) XOR (a AND c) XOR (b AND c) + const majh = (ah & bh) ^ (ah & ch) ^ (bh & ch) + const majl = (al & bl) ^ (al & cl) ^ (bl & cl) + + const t1LowSum = (hl >>> 0) + (bs1l >>> 0) + (chl >>> 0) + (K[i * 2 + 1] >>> 0) + (wl[i] >>> 0) + const t1l = t1LowSum >>> 0 + const t1h = ((hh >>> 0) + (bs1h >>> 0) + (chh >>> 0) + (K[i * 2] >>> 0) + + (wh[i] >>> 0) + Math.floor(t1LowSum / 0x100000000)) >>> 0 + + const t2LowSum = (bs0l >>> 0) + (majl >>> 0) + const t2l = t2LowSum >>> 0 + const t2h = ((bs0h >>> 0) + (majh >>> 0) + Math.floor(t2LowSum / 0x100000000)) >>> 0 + + hh = gh + hl = gl + gh = fh + gl = fl + fh = eh + fl = el + + const eLowSum = (dl >>> 0) + t1l + + el = eLowSum >>> 0 + eh = ((dh >>> 0) + t1h + Math.floor(eLowSum / 0x100000000)) >>> 0 + + dh = ch + dl = cl + ch = bh + cl = bl + bh = ah + bl = al + + const aLowSum = t1l + t2l + + al = aLowSum >>> 0 + ah = (t1h + t2h + Math.floor(aLowSum / 0x100000000)) >>> 0 + } + + const stateWords = [ah, al, bh, bl, ch, cl, dh, dl, eh, el, fh, fl, gh, gl, hh, hl] + + for (let i = 0; i < 16; i += 2) { + const stateLowSum = (H[i + 1] >>> 0) + (stateWords[i + 1] >>> 0) + + H[i + 1] = stateLowSum >>> 0 + H[i] = ((H[i] >>> 0) + (stateWords[i] >>> 0) + Math.floor(stateLowSum / 0x100000000)) >>> 0 + } + } + + return H.map(toHex32).join('') +} diff --git a/src/license/handsontable-license-key-parser/utils.ts b/src/license/handsontable-license-key-parser/utils.ts new file mode 100644 index 0000000000..1a1a46d99b --- /dev/null +++ b/src/license/handsontable-license-key-parser/utils.ts @@ -0,0 +1,218 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Vendored from `handsontable/license-key`, `src/entitlement-key/utils.js`. + * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. + * + * The two generation-side helpers of the upstream file (`bytesToBase64`, `stringToBase64Url`) are + * deliberately not ported: HyperFormula reads keys, it never mints them. + */ + +/** + * The base64 alphabet. + */ +const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + +/** + * Recursively freezes the value (and every nested object). Used to make a verified schema + * immutable so it cannot drift from what was validated. + * + * @param {*} value - the value to freeze + */ +export function deepFreeze(value: T): T { + if (value !== null && typeof value === 'object') { + Object.keys(value as unknown as Record).forEach( + (key) => deepFreeze((value as unknown as Record)[key]) + ) + Object.freeze(value) + } + + return value +} + +/** + * A calendar date decomposed into its numeric parts plus the epoch milliseconds of its UTC + * midnight. + */ +export interface ParsedIsoDate { + year: number, + month: number, + day: number, + timestamp: number, +} + +/** + * Parses the date in the `YYYY-MM-DD` format into its numeric parts and the epoch milliseconds + * of its UTC midnight. Throws when the date is malformed or does not exist in the calendar. + * + * @param {string} isoDate - the date to parse + * @param {string} dateLabel - the date name used in the error message + */ +export function parseIsoDate(isoDate: string, dateLabel: string): ParsedIsoDate { + const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(`${isoDate}`) + + if (match === null) { + throw new Error(`The ${dateLabel} date (${isoDate}) has to be passed in the "YYYY-MM-DD" format.`) + } + + const year = parseInt(match[1], 10) + const month = parseInt(match[2], 10) + const day = parseInt(match[3], 10) + + // Date.UTC maps years 0-99 to 1900-1999, which would make the round-trip check below report a + // "not a valid calendar date" lie. + if (year < 100) { + throw new Error(`The ${dateLabel} date (${isoDate}) has to use a four-digit year of 100 or later.`) + } + + const timestamp = Date.UTC(year, month - 1, day) + const date = new Date(timestamp) + + // An impossible date (e.g. "2027-02-30") makes `Date.UTC` roll over to the next month, so a + // round-trip comparison catches it. + if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) { + throw new Error(`The ${dateLabel} date (${isoDate}) is not a valid calendar date.`) + } + + return { + year, month, day, timestamp, + } +} + +/** + * Encodes the string as UTF-8 bytes. The plain implementation is used on purpose. It does not + * depend on `TextEncoder` or `Buffer`, so the same code works in Node.js and in every browser, + * including plain http:// pages. + * + * @param {string} text - the string to encode + */ +export function stringToUtf8Bytes(text: string): number[] { + const bytes: number[] = [] + + for (let i = 0; i < text.length; i += 1) { + let codePoint = text.charCodeAt(i) + + // Combine a surrogate pair into a single code point. + if (codePoint >= 0xd800 && codePoint <= 0xdbff && i + 1 < text.length) { + const lowSurrogate = text.charCodeAt(i + 1) + + if (lowSurrogate >= 0xdc00 && lowSurrogate <= 0xdfff) { + codePoint = ((codePoint - 0xd800) * 0x400) + (lowSurrogate - 0xdc00) + 0x10000 + i += 1 + } + } + + if (codePoint < 0x80) { + bytes.push(codePoint) + } else if (codePoint < 0x800) { + bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f)) + } else if (codePoint < 0x10000) { + bytes.push( + 0xe0 | (codePoint >> 12), + 0x80 | ((codePoint >> 6) & 0x3f), + 0x80 | (codePoint & 0x3f), + ) + } else { + bytes.push( + 0xf0 | (codePoint >> 18), + 0x80 | ((codePoint >> 12) & 0x3f), + 0x80 | ((codePoint >> 6) & 0x3f), + 0x80 | (codePoint & 0x3f), + ) + } + } + + return bytes +} + +/** + * Decodes UTF-8 bytes back into a string. + * + * @param {number[]} bytes - the bytes to decode + */ +export function utf8BytesToString(bytes: number[]): string { + let text = '' + let i = 0 + + while (i < bytes.length) { + const byte = bytes[i] + let codePoint + + if (byte < 0x80) { + codePoint = byte + i += 1 + } else if (byte < 0xe0) { + codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f) + i += 2 + } else if (byte < 0xf0) { + codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f) + i += 3 + } else { + codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) + | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f) + i += 4 + } + + if (codePoint >= 0x10000) { + // Split the code point back into a surrogate pair. + codePoint -= 0x10000 + text += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) + } else { + text += String.fromCharCode(codePoint) + } + } + + return text +} + +/** + * Decodes a base64 string (standard or URL-safe alphabet, padding optional) back into bytes. + * Returns `null` when the string is not valid base64. + * + * @param {string} base64 - the base64 string to decode + */ +export function base64ToBytes(base64: string): number[] | null { + const normalized = `${base64}`.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '') + + if (!/^[A-Za-z0-9+/]*$/.test(normalized) || normalized.length % 4 === 1) { + return null + } + + const bytes: number[] = [] + + for (let i = 0; i < normalized.length; i += 4) { + const chunk = [0, 1, 2, 3].map((offset) => { + const char = normalized.charAt(i + offset) + + // `indexOf('')` would return 0, so the missing characters of the last chunk have to be + // mapped to -1 explicitly. + return char === '' ? -1 : BASE64_ALPHABET.indexOf(char) + }) + + bytes.push((chunk[0] << 2) | (chunk[1] >> 4)) + + if (chunk[2] !== -1) { + bytes.push(((chunk[1] & 0x0f) << 4) | (chunk[2] >> 2)) + } + if (chunk[3] !== -1) { + bytes.push(((chunk[2] & 0x03) << 6) | chunk[3]) + } + } + + return bytes +} + +/** + * Decodes a base64 (standard or URL-safe) string back into a string. Returns `null` when the + * input is not valid base64. + * + * @param {string} base64 - the base64 string to decode + */ +export function base64ToString(base64: string): string | null { + const bytes = base64ToBytes(base64) + + return bytes === null ? null : utf8BytesToString(bytes) +} diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts new file mode 100644 index 0000000000..c8338c17eb --- /dev/null +++ b/src/license/licenseResolution.ts @@ -0,0 +1,391 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +import { + checkLicenseKeyValidity, + LicenseKeyValidityState, + notifyLicenseKeyNotice, + notifyLicenseKeyState, +} from '../helpers/licenseKeyValidator' +import {ALL_FEATURE_TOKENS, CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' +import {LicenseEntitlement, LicenseExpiry, unrestrictedEntitlement} from './LicenseEntitlement' +import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detectFormat' +import {EntitlementKeyData, EntitlementProductGrant, extractEntitlementKeyData} from './handsontable-license-key-parser/extractKeyData' +import {parseIsoDate} from './handsontable-license-key-parser/utils' + +/** Milliseconds in a day, used to turn a grace period in days into a deadline. */ +const MILLISECONDS_PER_DAY = 86400000 + +/** + * The name of HyperFormula's own product entry in an entitlement key payload. Every product + * entry carries its own capabilities, dates and windows, so this is the only entry this library + * reads — a key granting other products alongside (or instead of) HyperFormula is a valid key + * whose other entries are simply not for us. + */ +export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' + +/** + * The prefix marking a capability token as granting a public-API feature area. + * + * Used to tell "this key names its feature grants" from "this key's vocabulary cannot express + * one" — see the opt-in rule in {@link licenseTermsOf}. + */ +const FEATURE_TOKEN_PREFIX = 'feat:' + +/** + * Flag spellings that suppress console output. + * + * Three, because the key spec is not self-consistent: its normative flags table and its example + * payload (rev 6 §2.3 and §2) say `no-console-warns`, while the runtime-behaviour sections of the + * same revision (§4.3, §5.2) say `silent-console`, and earlier revisions said plain `silent`. A key + * minted against any of those readings must be honoured — a SaaS deployment that asked for silence + * and got console warnings is the failure this list exists to prevent. + */ +const SILENT_CONSOLE_FLAGS = ['silent', 'silent-console', 'no-console-warns'] + +/** + * Both halves of the license decision, resolved from one reading of the key. + * + * They are deliberately produced together: the two gates ask different questions of the same + * string, and parsing it twice would let them disagree about what it says. + */ +export interface ResolvedLicense { + /** Gate A — may this instance evaluate formulas at all. */ + validityState: LicenseKeyValidityState, + /** Gate B — which functions and API features the key grants. */ + entitlement: LicenseEntitlement, +} + +/** + * What HyperFormula needs from an entitlement key, read from its own product entry. + * + * The entry's shape is guaranteed by the vendored reader ({@link extractEntitlementKeyData} + * returns `null` for anything malformed), so unlike the typed-key adapter this replaces, nothing + * here re-checks field types or reconciles competing payload shapes: the entitlement format is + * the only shape there is, and a key granting HyperFormula nothing is simply a key with no + * `hyperformula` entry. + */ +interface LicenseTerms { + capabilityTokens: string[], + expiry: LicenseExpiry, + /** Epoch milliseconds of the last licensed day, or `null` when the key never expires. */ + expiryTimestamp: number | null, + /** `true` compares against the build release date, `false` against the clock. */ + comparedAgainstReleaseDate: boolean, + graceDays: number, + isTrial: boolean, + silent: boolean, +} + +/** + * The build's release date as epoch milliseconds (UTC midnight), or `null` when it is unknown or + * malformed. + * + * Read from the same `HT_RELEASE_DATE` (`DD/MM/YYYY`) the legacy validator uses, but **parsed + * differently on purpose**, and the difference is observable — so do not "simplify" either one to + * match the other without reading this. + * + * This function uses `Date.UTC`. The legacy validator builds the same value with + * `new Date(month/day/year)`, which is parsed in the host's LOCAL zone. East of UTC the two land on + * different day numbers for one and the same release date: + * + * ```text + * HT_RELEASE_DATE=10/08/2026 legacy (local) this function (UTC) + * TZ=UTC, TZ=America/Los_Angeles 20675 20675 agree + * TZ=Asia/Tokyo 20674 20675 differ by a day + * TZ=Pacific/Kiritimati 20674 20675 differ by a day + * ``` + * + * UTC is the required reading for an entitlement key: key spec rev 6 §1.2 makes offline/online + * parity a hard rule — the offline check and a future online check must return the same verdict + * for the same key at the same instant — and any rule reading a local clock breaks it. The legacy + * path keeps its local parse because legacy behaviour is frozen for this release; switching it + * would move the expiry verdict of already-issued legacy keys by a day for every customer east + * of UTC. + * + * The consequence, flagged rather than hidden: two customers east of UTC, one on a legacy key and + * one on an equivalent entitlement key, can disagree by a day about whether this build is covered. + * Reconciling them is a product decision, not a refactor. + */ +function releaseDateTimestamp(): number | null { + const [day, month, year] = (process.env.HT_RELEASE_DATE ?? '').split('/') + const timestamp = Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10)) + + return isNaN(timestamp) ? null : timestamp +} + +/** + * Reads HyperFormula's terms out of an intact entitlement key payload. + * + * Total on purpose: the vendored reader has already rejected every malformed shape, so every + * field read here is exactly what {@link EntitlementProductGrant} promises. A payload without a + * `hyperformula` entry — including `products: {}` — is a VALID key that grants this library + * nothing and never expires for it; per HF-307 decision D6-A that cliff is silent. Note this + * differs from the typed-key format this replaces, where a key licensed to another product + * carried the expiry HyperFormula was checked against: an entitlement key's product entries each + * carry their own terms, so another product's dates are not ours to read. + * + * @param {EntitlementKeyData} data - the extracted key data + */ +function licenseTermsOf(data: EntitlementKeyData): LicenseTerms { + const grant: EntitlementProductGrant | undefined = data.products[HYPERFORMULA_PRODUCT_NAME] + + // Nothing is granted implicitly: a key's functions are exactly what its own tokens name. A key + // whose tokens this build does not recognize therefore still evaluates the infix operators (they + // are not function calls) and the protected built-ins, and returns #LIC! for every function call, + // silently, per HF-307 decision D3. That cliff is ratified as-is (D6-A): "this situation should + // never happen. There is no point in issuing a key if empty capabilities." + const capabilityTokens: string[] = [] + + if (grant !== undefined) { + // Appended one by one rather than with `push(...grant.capabilities)`. The array comes from an + // attacker-influenced payload and the format sets no size limit (the spec addendum lists + // "payload size" as an open question on its own page), and spreading an array into a call puts + // one argument per stack slot: measured, a checksum-valid key carrying 125 000 tokens threw + // `RangeError: Maximum call stack size exceeded` out of `HyperFormula.buildFromArray` instead + // of resolving to a verdict. A malformed or hostile key must produce INVALID, never a throw. + grant.capabilities.forEach((token) => capabilityTokens.push(token)) + } + + // Feature tokens are OPT-IN, never opt-out. A key carrying at least one `feat:*` token demonstrably + // speaks the feature vocabulary, so it gets exactly the areas it names - that is what makes feature + // gating real (the ratified decision: "Feature gating should work"). A key carrying NONE cannot + // be saying "no features", because no vocabulary in circulation can express one: the key spec's + // current HyperFormula token list (rev 6 §2.2 - `functions_1..4`, `spreadsheet`, + // `import_export`) contains no `feat:*` entry at all. So absence means "this key does not talk + // about features", and the task's additive-safety rule - a grant may grow between versions, + // never shrink - makes the whole gated API the only safe reading. + // + // Reading absence as denial instead would hand a dead public API to every key myHOT can mint + // today, HyperFormula-only and Handsontable-only alike; both were verified doing exactly that + // before this rule existed. + // The trigger is a feature token this version RECOGNIZES, not merely one that looks like a + // feature token. An unrecognized `feat:*` token has to be inert (D3: "unrecognized token should + // not grant the capability (silently ignored)"), and a purely syntactic prefix test makes it the + // opposite of inert - it suppresses the fallback, so the key ends up with ZERO of the five areas. + // Measured before this guard existed: a key carrying `functions_1` plus a single unknown + // `feat:teleport` had CRUD, undo, clipboard, named expressions and batching all throwing, while + // the same key without that token had all five. That is the additive-safety rule inverted - an + // older build meeting a key minted by a newer generator, or a one-character typo at issuing time, + // would revoke the whole gated API rather than ignore a word it does not know. + const namesAKnownFeature = capabilityTokens.some((token) => { + const normalized = normalizeCapabilityToken(token) + + return normalized.indexOf(FEATURE_TOKEN_PREFIX) === 0 && CAPABILITY_TABLE.has(normalized) + }) + + if (!namesAKnownFeature) { + capabilityTokens.push(...ALL_FEATURE_TOKENS) + } + + // Exactly one of the two date fields is present on an intact entry (the reader enforces it), + // and the date used and the axis it is compared against come from that same field. The date is + // carried as the payload's own `YYYY-MM-DD` string, never routed through `Date` formatting - + // the key spec's fixture J11 exists because `toISOString()` shortens every licence issued east + // of UTC by a day. + const expiryDate = grant === undefined ? undefined : (grant.usage_until ?? grant.release_until) + const comparedAgainstReleaseDate = grant !== undefined && grant.release_until !== undefined + const expiryTimestamp = expiryDate === undefined ? null : parseIsoDate(expiryDate, 'expiration').timestamp + const flags = grant === undefined ? [] : grant.flags + // A release-date comparison has no grace period: it is static, so there is no window to be + // inside of. + const graceDays = comparedAgainstReleaseDate || grant === undefined ? 0 : grant.grace + + return { + capabilityTokens, + expiry: expiryDate === undefined || expiryTimestamp === null + ? {kind: 'none', date: null, noticeDays: 0, graceDays: 0} + : { + kind: comparedAgainstReleaseDate ? 'release' : 'usage', + date: expiryDate, + // Read off HyperFormula's OWN entry, which is what makes the shape gate structural here: + // the tagged format took its terms from the LICENSED product's entry, so a `notice` field + // another product added for its own purposes could switch HyperFormula's console output + // on (fixed under gate in the previous PR). An entitlement key carries per-entry terms, so + // another product's `notice` is not reachable from here at all. + noticeDays: grant === undefined ? 0 : grant.notice, + graceDays, + }, + expiryTimestamp, + comparedAgainstReleaseDate, + graceDays, + isTrial: flags.indexOf('trial') !== -1, + // Every spelling the key spec uses for "suppress console output" - see SILENT_CONSOLE_FLAGS. + // The key's flags are the ONLY source of silence: an earlier revision also silenced any key + // carrying an unrecognized token, which suppressed strictly more than D3 asks for (it would + // have swallowed expiry notices too). That was confirmed an implementation error. + silent: flags.some((flag) => SILENT_CONSOLE_FLAGS.indexOf(flag) !== -1), + } +} + +/** + * Whether an intact entitlement key is still valid, and if not, the day it stopped being valid. + * + * A key with no expiry never expires. Otherwise the expiration date is INCLUSIVE of its last + * valid day, and a grace period extends it further. A date compared against the build's release + * date involves no clock at all, which is what keeps an air-gapped install with a wrong system + * clock working. + * + * An unknown release date resolves to "not expired", matching what the legacy validator already + * does when `HT_RELEASE_DATE` is missing: a build that cannot tell its own age must not start + * rejecting keys that customers paid for. + * + * @param {LicenseTerms} terms - the terms of the key + */ +function validityOf(terms: LicenseTerms): {state: LicenseKeyValidityState, expiredOn?: Date} { + if (terms.expiryTimestamp === null) { + return {state: LicenseKeyValidityState.VALID} + } + + const now = terms.comparedAgainstReleaseDate ? releaseDateTimestamp() : Date.now() + + if (now === null) { + return {state: LicenseKeyValidityState.VALID} + } + + const deadline = terms.expiryTimestamp + MILLISECONDS_PER_DAY + (terms.graceDays * MILLISECONDS_PER_DAY) + + return now < deadline + ? {state: LicenseKeyValidityState.VALID} + // The reported day is the first day NOT covered, which is the convention the legacy validator + // already uses for the same message (it reports `keyValidityDays + 1`). + : {state: LicenseKeyValidityState.EXPIRED, expiredOn: new Date(deadline)} +} + +/** + * The day a VALID key's usage-until expiry falls on, if the current UTC instant is within its + * notice window — `null` otherwise, which covers "no notice window configured" (`noticeDays` is + * `0`, which is also what a key with no HyperFormula entry resolves to) just as much as "not close + * enough yet" or "already past its usage-until day". + * + * Deliberately blind to `graceDays`: notice is about the usage_until axis itself, not about the + * grace extension past it. Key spec rev 6 §4.1 sequences notice, then a soft-stop window, then the + * hard-stop this build already enforces; only the hard stop and this notice are built for 3.5.0 + * (decision D5-A), so the window checked here ends exactly where the soft-stop phase would + * begin, rather than reaching into grace and printing a notice for a key already past its expiry. + * + * `release_until`-axis keys never reach here with a non-`null` result — `kind` is `'usage'` only + * when the date came from `usage_until` (see {@link licenseTermsOf}) — matching the spec's rule + * that notice and grace have no effect on that axis. The converse holds too now: the tagged + * format let an entry with no date of its own fall through to the key envelope's `exp`, so + * `'usage'` did not imply `usage_until`; an entitlement key has no envelope date to fall back to. + * + * @param {LicenseTerms} terms - the terms of the key + */ +function expiryWithinNoticeWindow(terms: LicenseTerms): Date | null { + if (terms.expiry.kind !== 'usage' || terms.expiry.noticeDays <= 0 || terms.expiryTimestamp === null) { + return null + } + + // The window ends at the first instant no longer on the usage_until day — the same boundary + // `validityOf` uses before adding its grace term — and opens `notice` days before the licensed + // day ITSELF, not before that end. Counting back from the end would shorten the window by a day: + // the date-semantics fixtures pin 2027-06-13T00:00:00Z for usage_until 2027-08-12 with notice 60, + // and a trial whose notice equals its whole term must warn from the day it is issued. + const usageAxisDeadline = terms.expiryTimestamp + MILLISECONDS_PER_DAY + const noticeWindowStart = terms.expiryTimestamp - (terms.expiry.noticeDays * MILLISECONDS_PER_DAY) + const now = Date.now() + + return now >= noticeWindowStart && now < usageAxisDeadline ? new Date(terms.expiryTimestamp) : null +} + +/** + * Turns the terms of an intact, unexpired entitlement key into the entitlement it grants. + * + * Per HF-307 decision D3 this is fail-closed and silent: a token this version does not recognize + * is recorded in `unrecognizedCapabilities` and grants nothing, without a warning, a message, or + * anything public to read it back from. "Silent" there means the *grant* is silent — whether the + * key's console messages are suppressed is decided solely by its `flags` (`terms.silent`), never + * by the presence of an unrecognized token; coupling the two suppressed expiry notices as a side + * effect of a vocabulary mismatch, and was confirmed an implementation error. + * + * @param {LicenseTerms} terms - the terms of the key + */ +function entitlementOf(terms: LicenseTerms): LicenseEntitlement { + const unrecognizedCapabilities = terms.capabilityTokens.filter( + (token) => !CAPABILITY_TABLE.has(normalizeCapabilityToken(token)), + ) + + return { + unrestricted: false, + capabilities: new Set(terms.capabilityTokens), + unrecognizedCapabilities, + expiry: terms.expiry, + silent: terms.silent, + isTrial: terms.isTrial, + } +} + +/** + * Resolves a license key into both gates' inputs. + * + * Routing follows the vendored {@link detectLicenseKeyFormat}, whose test order is normative + * (key spec addendum, T12): the literals, then the trailing bracketed block that marks an + * entitlement key, then the legacy 25-character shape. Everything that is not an entitlement key + * — `gpl-v3`, a legacy key, an empty string — falls through to {@link checkLicenseKeyValidity} + * completely unchanged, which is what keeps this from touching existing behaviour. A string that + * carries a bracketed block routes here even when the block is garbage: such a key is INVALID, + * not a legacy key that happens to contain brackets. + * + * **The invariant this function exists to protect.** Only a VALID entitlement key resolves to a + * restricted entitlement. Every other outcome — missing, invalid, or expired, for an entitlement + * key as much as for a legacy one — resolves to {@link unrestrictedEntitlement}. That asymmetry is + * deliberate and load-bearing: gate A already stops formula evaluation on its own (a bad key + * yields `#LIC!` in cells), while gate B additionally makes PR 2's `ensureCapability` throw from + * the CRUD API. Letting a bad key restrict the entitlement would turn today's "formulas fail, + * the API still works" into "the API throws", which is a silent breaking change for every + * existing user whose key lapsed. D3's fail-closed rule governs unrecognized tokens INSIDE an + * otherwise valid key; it is not a rule about invalid keys, and conflating the two is exactly + * the mistake this comment is here to prevent. + * + * A checksum-valid key whose payload shape cannot be read is INVALID, not a crash and not a free + * pass: every payload field is untrusted, so nothing here may assume a shape the vendored reader + * has not verified. + * + * @param {string} licenseKey - the raw `licenseKey` config value + * @param {boolean} notifyConsole - pass `false` for a resolution whose result exists only to be + * thrown away (e.g. the transient serialization-only `Config` that `rebuildWithConfig` builds + * from the OUTGOING config) — such a resolution must not print notices for a key the caller is + * in the middle of replacing. Legacy keys notify inside {@link checkLicenseKeyValidity} behind a + * once-per-page-load flag, so they cannot double-print regardless of this parameter. + */ +export function resolveLicense(licenseKey: string, notifyConsole: boolean = true): ResolvedLicense { + if (detectLicenseKeyFormat(licenseKey) !== 'entitlement') { + return { + validityState: checkLicenseKeyValidity(licenseKey), + entitlement: unrestrictedEntitlement(), + } + } + + const data = extractEntitlementKeyData(licenseKey) + + if (data === null) { + if (notifyConsole) { + notifyLicenseKeyState(LicenseKeyValidityState.INVALID) + } + + return {validityState: LicenseKeyValidityState.INVALID, entitlement: unrestrictedEntitlement()} + } + + const terms = licenseTermsOf(data) + const {state, expiredOn} = validityOf(terms) + + if (notifyConsole && !terms.silent) { + notifyLicenseKeyState(state, expiredOn, terms.comparedAgainstReleaseDate ? 'release' : 'usage') + + if (state === LicenseKeyValidityState.VALID) { + const noticeExpiryDate = expiryWithinNoticeWindow(terms) + + if (noticeExpiryDate !== null) { + notifyLicenseKeyNotice(licenseKey, noticeExpiryDate) + } + } + } + + return { + validityState: state, + entitlement: state === LicenseKeyValidityState.VALID ? entitlementOf(terms) : unrestrictedEntitlement(), + } +} From 5b8c91b03c7234a4af7582d4d5e98764c21848df Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 24 Sep 2026 19:48:48 +0800 Subject: [PATCH 06/54] HF-307: align getRegisteredFunctionNames with the license gate, deprecate its static form (#1743) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit > **Update 2026-09-22 — review round with @sequba.** The sections below are the PR as written > before that round, kept for the reasoning they record. Where a sentence no longer matches the > code it is corrected inline and marked, rather than rewritten away. ## Update 2026-09-18 — rebased onto the collapsed engine/tests PRs `hyperformula#1730` and `hyperformula-tests#32` were folded from five PRs each into one, so this PR's base moved to `#1730`. Nothing in this PR's own diff changed; the "9/9" numbering and the `#1741` base reference below are stale — the stack is now `#1728 → #1729 → #1730 → this PR`. --- 9/9 of the HF-307 stack, stacked on #1741. Pairs with `hyperformula-tests#43` — **merge the tests PR first**. Finishes decision **D2** on the one API it missed. ## The problem `getRegisteredFunctionNames()` returned the whole catalogue under a restricted key (measured: 422 names on a calculated-fields key, including functions that evaluate to `#LIC!`). A function picker built on it has exactly the problem #1724 (HF-349) and #1731's metadata filter exist to prevent. Flagged in #1731's "found, not fixed here" section; this closes it. ## What changed **Instance method** — now lists exactly what the instance can evaluate, sharing the one `licenseListsFunction` rule with the interpreter and the metadata API so the three surfaces cannot drift: - reads `getListableFunctionIds()` instead of `getRegisteredFunctionIds()` — the protected built-ins are included uniformly (`OFFSET` was missing before; `getAvailableFunctions` already listed it); - reads `config.translationPackage` — the instance's own snapshot — instead of a fresh global `getLanguage` lookup, which can report a localized name the instance refuses to evaluate, and which throws once the host unregisters that language code; - filters by the license, with the invariant intact: a missing, invalid, or expired key does **not** shorten the list. **Static method — deprecated, not removed.** See below; this is a change from the first version of this PR. ## The static: deprecated rather than removed (changed after review) The first version of this PR deleted `HyperFormula.getRegisteredFunctionNames(code)`, citing HF-349 as precedent. That was wrong, and the review caught it: ``` $ git show 3.4.0:src/HyperFormula.ts | grep -c "public static getRegisteredFunctionNames" # 1 ``` The method **is in the released 3.4.0 tag**, and HF-349's own commit message says its removal was free precisely because *"Both methods are unreleased, which is the only free moment to remove them."* So the precedent does not extend here: deleting it would be a breaking change in a minor release, against the Semantic Versioning this project states it follows, and DEV_DOCS's Definition of Done would require a migration-guide section that `docs/guide/` has no 3.x home for. So it is now `@deprecated` with the wording this repo already uses for that situation (`arraySizeMethod` / `arrayFunction` in 3.1.0: "deprecated and will be removed in one of the next major releases"), plus a `Deprecated` changelog entry. **Overturnable in one comment** if you would rather take the break now — the direction is Kuba's D2 either way; only the timing changed. The deprecation notice is explicit that the two are not interchangeable: the static translates into any registered language without an engine, so migrating means building one (`HyperFormula.buildEmpty({ language: 'plPL' }).getRegisteredFunctionNames()`). ## D2's precondition, discharged Kuba's D2 answer made the removal conditional: *"perhaps we can remove the static methods, I'll check which methods does formula-builder use"*. That check is done — searched the org, and **both consumers call the instance form, not the static one**: | Consumer | Call site | Form | |---|---|---| | `formula-builder` | `packages/core/src/engine/functionCatalog.ts:81` — `this.engine?.getRegisteredFunctionNames?.()`, in try/catch, declared optional in `engine/types.ts:66` | instance | | `aurasheet` | `src/core/FormulaEngine.ts:97` — `this.hf.getRegisteredFunctionNames()` | instance | Both use it to build a **function picker** (`functionCatalog.ts`; `FormulaAutocompletePlugin.ts`) — the surface #1724's rationale was about — so the license filter added here improves both rather than disturbing them. Under `gpl-v3` or any unrestricted key their lists are unchanged. ## Spec-to-ship review (2026-08-20): also fixed here - **The translation-snapshot change was unpinned.** Mutation-verified: reverting it to the global lookup left 309 tests green, even though the commit message and the new JSDoc both name it. Now pinned by a test that unregisters the language after the engine is built — the scenario that distinguishes the two implementations, since `getLanguage` throws for an unregistered code while the snapshot keeps working. - **The licence guide listed only two of the three narrowing methods.** It now names this one too, in both places. - **The new JSDoc over-claimed parity** with `getAvailableFunctions`: for a function whose translation is the empty string this method returns `''` while that one falls back to the canonical id. The claim is now scoped to the ids and the licence rule, with the naming difference stated. - Reverting the static removal also removed the docs-build change it required, so `docs/.vuepress/config.js` is untouched by this PR again (it no longer builds one engine per documentation page). ## Testing New suite pins the alignment in both directions (agrees with `getAvailableFunctions` name for name; narrows on a restricted key; never narrows on a bad key; aliases gate with their canonical; answers from the instance's own snapshot). Full private suite: **517 suites / 6462 passing, 3 pre-existing skips**; `tsc --noEmit` and ESLint clean. ## Note for review `functions-metadata.spec.ts` now skips listed ids with no plugin: `OFFSET` is listed (it is callable) but parse-time resolved, so it legitimately has no registry metadata. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_019pxNP45obT2LZfjitaCv9o ## The codecov/project dip, traced `codecov/project` was red at −0.02% while `codecov/patch` reported 100% of the diff hit. Rather than write that off as a threshold artifact, I measured coverage on this commit and on its base and diffed the per-file numbers: | file | base (8/9) | this PR, before the fix | |---|---|---| | `src/HyperFormula.ts` | 674 / 675 | 675 / 676 | | `src/interpreter/FunctionRegistry.ts` | 130 / 130 | **129 / 130** | | total | 12 933 / 13 268 | 12 933 / 13 269 | So the covered count did not move and one previously covered line stopped executing — a real consequence of this change, not a rounding artifact. The line was the **instance** `FunctionRegistry.prototype.getRegisteredFunctionIds()`, whose only caller in the whole repository was the method this PR rewrites. Nothing in `src/`, nothing in the private suite, and nothing outside (the class is not exported from `src/index.ts`) calls it any more. Removed, since this change is what orphaned it. The static `FunctionRegistry.getRegisteredFunctionIds()` is untouched and still used — by the deprecated static method above and by three specs. For the record, the single uncovered line left in `HyperFormula.ts` is pre-existing and not mine: `removeNamedExpression`'s unreachable `return []`, which already carries a `codecov note` comment explaining why it cannot be hit. --- > [!NOTE] > **Low Risk** > Documentation and deprecation only; no runtime behavior changes in this diff. > > **Overview** > **Deprecates** the static `HyperFormula.getRegisteredFunctionNames(code)` API (removal planned in a future major) and documents how it differs from the instance method. > > The static form is documented as reflecting the **global** function registry and any registered language without an engine; callers should migrate via `HyperFormula.buildEmpty({ language: '…' }).getRegisteredFunctionNames()`. The **instance** `getRegisteredFunctionNames()` JSDoc now states it lists everything in the instance registry (registration, not license entitlement) and points license-aware UIs to `getAvailableFunctions()`. > > `CHANGELOG.md` adds a **Deprecated** entry for the static method. > > Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit a8ffef3ea641b7332f02c9476af1cfc1fba8cf8e. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot). --- ### Open in the 2026-09-22 review round - @sequba: "`getRegisteredFunctionNames` should still list ALL functions". Agreed on the principle — this method answers for the REGISTRY, and registration is not entitlement, while `getAvailableFunctions()` and `getFunctionDetails()` answer about availability and stay filtered. That removes most of this PR's substance, leaving the deprecation note and a docs correction. **Awaiting a decision on whether to reduce this PR to that or close it with the deprecation folded into #1730.** - Fixed here meanwhile: `docs/guide/release-notes.md` now carries the same retroactive `### Removed` section for 3.4.0 that `CHANGELOG.md` gained in this PR's history. The two are mirrors and only one had it. --------- Co-authored-by: Claude Sonnet 5 Co-authored-by: Kuba Sekowski --- CHANGELOG.md | 4 ++++ src/HyperFormula.ts | 22 +++++++++++++++++++++- 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a617907e2..53715037b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Changed the parser for the new proprietary license keys to the entitlement key format, following its upstream specification. This replaces the tagged key format, which was never issued to anyone. Classic 25-character license keys and `gpl-v3` are unaffected. [#1730](https://github.com/handsontable/hyperformula/pull/1730) - Changed the license capability tokens to be matched case-insensitively, and to grant functions through the packaging group-token vocabulary only: `fun:all`, `fun:.`, and per-function `fun:` tokens. A key names the capabilities it grants, and the engine grants their union; it keeps no notion of which tokens make up a package. The callable forms of the calculation operators, such as `HF.ADD`, are granted by `fun:operator.A`, while the infix operators themselves work under any key. [#1730](https://github.com/handsontable/hyperformula/pull/1730) +### Deprecated + +- Deprecated the static `HyperFormula.getRegisteredFunctionNames()` method; it will be removed in one of the next major releases. Use the instance method of the same name instead — a static method has no engine, and therefore no configuration, in scope, so it answers for the global function registry: an engine configured with its own `functionPlugins` registers only those, and this method can list functions that engine cannot evaluate at all. The two are not interchangeable: the static one translates into any registered language without an engine, so migrating means building one, for example `HyperFormula.buildEmpty({ language: 'plPL' }).getRegisteredFunctionNames()`. [#1743](https://github.com/handsontable/hyperformula/pull/1743) + ### Fixed - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 7723687996..f83c90199e 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -596,7 +596,22 @@ export class HyperFormula implements TypedEmitter { } /** - * Returns translated names of all registered functions for a given language + * Returns translated names of all registered functions for a given language. + * + * Answers for the GLOBAL function registry, because a static method has no engine, and therefore + * no configuration, in scope. An engine configured with its own `functionPlugins` registers only + * those, so this method can list functions that engine cannot evaluate at all. Use the instance + * method [[getRegisteredFunctionNames]] instead, which answers for the engine you actually hold — + * the same reasoning that made `getAvailableFunctions()` and `getFunctionDetails()` instance-only + * from their first release. + * + * The two are not interchangeable: this one translates into any registered language without + * building an engine, while the instance method answers only under its own instance's language. + * Migrating means building an engine: + * `HyperFormula.buildEmpty({ language: 'plPL' }).getRegisteredFunctionNames()`. + * + * @deprecated Use the instance method of the same name. This static method is deprecated and + * will be removed in one of the next major releases. * * @param {string} code - language code * @@ -4544,6 +4559,11 @@ export class HyperFormula implements TypedEmitter { * Returns translated names of all functions registered in this instance of HyperFormula * according to the language set in the configuration * + * Answers for the instance's function REGISTRY — what is registered, not what the license key + * lets it evaluate — so it lists every registered function whatever the key grants. To build a + * function picker that never offers a function evaluating to `#LIC!`, use + * [[getAvailableFunctions]], which answers about availability. + * * @example * ```js * const hfInstance = HyperFormula.buildEmpty(); From dad51a42585189cce718d7163a483d394a63ad6f Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Thu, 24 Sep 2026 14:11:22 +0200 Subject: [PATCH 07/54] Apply suggestion from @sequba --- docs/guide/license-key.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index db8321b3ac..cce723db40 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -52,9 +52,7 @@ them locally, without any connection to a server. ## Feature packages and add-ons -A proprietary license key may grant the whole library, or only part of it. If your key covers -everything you buy nothing new to think about, and neither does the GPLv3 key `gpl-v3`, which -always grants everything. +A proprietary license key may grant the whole library, or only part of it. If your key grants only part of the library, then: From bfe70048e24d25984a732e06dbd6e974ec9bef39 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Thu, 24 Sep 2026 14:13:31 +0200 Subject: [PATCH 08/54] Apply suggestion from @sequba --- docs/guide/license-key.md | 24 ------------------------ 1 file changed, 24 deletions(-) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index cce723db40..ed04971c22 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -65,30 +65,6 @@ If your key grants only part of the library, then: functions your key includes, so a function picker built from them never offers a function that then fails. -Custom functions you register yourself are available whatever your key grants, as long as they use -an id of their own. The licence covers built-in ids, so a plugin registered under a built-in id your -key does not include is treated as that built-in and stays unavailable — it will not be described and -it evaluates to `#LIC!`. Pick an id the built-in catalogue does not use and this cannot happen. - -Two commercial add-ons build on top of a package: - -* **Spreadsheet Bundle** grants the CRUD API (adding, removing, and moving rows, columns, sheets, - and cell contents), undo/redo, clipboard operations, and batching (`batch()` / - `suspendEvaluation()`; `resumeEvaluation()` is deliberately never gated, so an engine can always - leave a suspended state). It does not grant named expressions, which stay outside both add-ons. -* **Import/export** is reserved for a future release. HyperFormula doesn't have an import/export - feature yet, so this add-on doesn't grant or restrict anything today. - -In this release, not having either add-on doesn't restrict anything either: a key that names no -feature token at all is granted every feature area — CRUD, undo/redo, clipboard, named expressions -and batching — regardless of whether it names these add-ons. Every key issued today is of that -shape, so the add-on tokens describe what was sold rather than changing what the engine allows. - -::: tip -To find out which package your key includes, check your order confirmation or -[contact our team](contact.md). HyperFormula deliberately reports nothing about the contents of -your key at runtime. -::: ## License key notifications From f2e590e955d34a27a8291bc7b3bef5f0c9619694 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Thu, 24 Sep 2026 14:15:00 +0200 Subject: [PATCH 09/54] Apply suggestion from @sequba --- docs/guide/license-key.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index ed04971c22..b3b596cdee 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -75,15 +75,6 @@ In that case every licence-gated function call evaluates to a `#LIC!` error — starts throwing, and `getAvailableFunctions()` still describes the full set of functions. A key problem never narrows what the library reports it can do. -Arithmetic keeps working: operators such as `=A1+B1` are not function calls, so nothing gates them. -`VERSION()` and `OFFSET()` are function calls, but they are protected built-ins that sit outside the -licence system entirely, so they keep evaluating too. A sheet with a key problem therefore does not -go blank. - -A **valid** key can print one notification too: if it expires on a set date and that date is -within the notice period your license carries, the console names the last day the key covers. It -is a heads-up only — nothing is restricted while a key is valid, and the message appears once. - ## License key support If you have any issues with your license key, [contact our team](contact.md). \ No newline at end of file From 1a1db868438abe2135a6adaa3cc76b90783c5ffe Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 24 Sep 2026 12:49:44 +0000 Subject: [PATCH 10/54] HF-307: drop the add-on tokens, the deprecation, and the gate-active flag Four things from the 24.09 review. The engine no longer knows any add-on. `spreadsheet` is out of the capability table entirely, and import/export became `feat:import_export`, one more token in the same opt-in set as the other feature areas. Which capabilities an add-on bundles is decided where keys are minted; a key may still carry the word, and this library now reads it the way it reads any word it does not know. The static getRegisteredFunctionNames is no longer marked deprecated. That decision was never taken, so the tag had no business being here. The method documentation stays, since it explains a real difference between the two forms. The changelog collapses to one entry under Added, written for someone using the library rather than reviewing it. isLicenseGateActive is removed. It short-circuited gate B for an unrestricted entitlement, which the two-axis capability shape already does in one comparison at each of the four call sites. Measured on 12000 function calls per recalculation, nine interleaved A/B pairs: median -1.3% with the flag removed, 5 ms apart on the minima of a 180 ms run. It was not paying for the fourth way to express the same condition. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 15 +---------- src/BuildEngineFactory.ts | 2 +- src/Config.ts | 13 ---------- src/HyperFormula.ts | 12 +-------- src/interpreter/Interpreter.ts | 2 +- src/license/LicenseEntitlement.ts | 6 ++--- src/license/capabilities.ts | 43 ++++++++++--------------------- 7 files changed, 20 insertions(+), 73 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53715037b8..ad3b8ae5af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,20 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Added -- Added support for proprietary license keys that grant a subset of the library ("feature packages and add-ons"). A function your key does not include evaluates to a `#LIC!` error, and the corresponding parts of the API throw a `LicenseCapabilityMissingError`. Keys that grant everything, including `gpl-v3`, are unaffected. [#1728](https://github.com/handsontable/hyperformula/pull/1728) [#1729](https://github.com/handsontable/hyperformula/pull/1729) [#1730](https://github.com/handsontable/hyperformula/pull/1730) -- Added a one-time console notice when a license key's usage-based expiry date falls within its configured notice period, naming the key's last covered day ("valid until … (UTC)"). The notice is silenced by the key's own silent flag, and never fires for a key expiring on the perpetual (`release_until`) axis. Blocking behavior at and after expiry is unchanged. [#1730](https://github.com/handsontable/hyperformula/pull/1730) -- Added grants to the two commercial add-on tokens: `spreadsheet` (the Spreadsheet Bundle) now grants the CRUD, undo/redo, clipboard, and batching feature areas, and `import_export` grants the reserved import/export feature that nothing gates on until the feature ships. A key naming neither add-on keeps every feature area it has today. [#1730](https://github.com/handsontable/hyperformula/pull/1730) - -### Changed - -- Changed `getAvailableFunctions()` and `getFunctionDetails()` to describe only the functions the instance's license key includes, so they no longer advertise a function that would evaluate to a `#LIC!` error. A missing, invalid, or expired key does not shorten the list. [#1730](https://github.com/handsontable/hyperformula/pull/1730) -- Changed the console message for an expired proprietary license key to stop naming the installed version when the key ran out on the usage axis rather than the maintenance axis. A maintenance key stops covering releases, so an older build keeps working; a usage-based key stops being valid at all, and there is no version to fall back to. Classic 25-character license keys have only the maintenance axis, so their message is unchanged. [#1730](https://github.com/handsontable/hyperformula/pull/1730) -- Changed the parser for the new proprietary license keys to the entitlement key format, following its upstream specification. This replaces the tagged key format, which was never issued to anyone. Classic 25-character license keys and `gpl-v3` are unaffected. [#1730](https://github.com/handsontable/hyperformula/pull/1730) -- Changed the license capability tokens to be matched case-insensitively, and to grant functions through the packaging group-token vocabulary only: `fun:all`, `fun:.`, and per-function `fun:` tokens. A key names the capabilities it grants, and the engine grants their union; it keeps no notion of which tokens make up a package. The callable forms of the calculation operators, such as `HF.ADD`, are granted by `fun:operator.A`, while the infix operators themselves work under any key. [#1730](https://github.com/handsontable/hyperformula/pull/1730) - -### Deprecated - -- Deprecated the static `HyperFormula.getRegisteredFunctionNames()` method; it will be removed in one of the next major releases. Use the instance method of the same name instead — a static method has no engine, and therefore no configuration, in scope, so it answers for the global function registry: an engine configured with its own `functionPlugins` registers only those, and this method can list functions that engine cannot evaluate at all. The two are not interchangeable: the static one translates into any registered language without an engine, so migrating means building one, for example `HyperFormula.buildEmpty({ language: 'plPL' }).getRegisteredFunctionNames()`. [#1743](https://github.com/handsontable/hyperformula/pull/1743) +- Added support for the new license key format. A proprietary key can now grant a subset of the library: a function your key does not include evaluates to a `#LIC!` error, and the matching parts of the API throw a `LicenseCapabilityMissingError`. Keys that grant everything, classic 25-character keys and `gpl-v3` included, work exactly as before. [#1728](https://github.com/handsontable/hyperformula/pull/1728) ### Fixed diff --git a/src/BuildEngineFactory.ts b/src/BuildEngineFactory.ts index 69b74eaea3..5c11aa7430 100644 --- a/src/BuildEngineFactory.ts +++ b/src/BuildEngineFactory.ts @@ -85,7 +85,7 @@ export class BuildEngineFactory { if (namedExpressions.length === 0) { return } - if (config.isLicenseGateActive && !allowsFeature(config.licenseCapabilities, FeatureId.NamedExpressions)) { + if (!allowsFeature(config.licenseCapabilities, FeatureId.NamedExpressions)) { throw new LicenseCapabilityMissingError(FeatureId.NamedExpressions) } } diff --git a/src/Config.ts b/src/Config.ts index 3505fb1415..d95bc1a23d 100644 --- a/src/Config.ts +++ b/src/Config.ts @@ -33,7 +33,6 @@ import {ConfigParams, ConfigParamsList} from './ConfigParams' interface LicensePrivateState { licenseKeyValidityState: LicenseKeyValidityState, licenseCapabilities: ResolvedCapabilities, - isLicenseGateActive: boolean, capabilityRegistry: CapabilityRegistry, } @@ -286,8 +285,6 @@ export class Config implements ConfigParams, ParserConfig { privatePool.set(this, { licenseKeyValidityState, licenseCapabilities, - isLicenseGateActive: licenseKeyValidityState !== LicenseKeyValidityState.VALID || - licenseCapabilities.functions !== 'all' || licenseCapabilities.features !== 'all', capabilityRegistry, }) @@ -340,16 +337,6 @@ export class Config implements ConfigParams, ParserConfig { return (privatePool.get(this) as LicensePrivateState).licenseCapabilities } - /** - * Whether gate B (the entitlement check in the interpreter) needs to run at all for this - * config. `false` — the common case, for `gpl-v3`, legacy keys, and an unrestricted entitlement - * key — is a single boolean read, cheaper than the string-enum comparison it replaces. - * - * @internal - */ - public get isLicenseGateActive(): boolean { - return (privatePool.get(this) as LicensePrivateState).isLicenseGateActive - } /** * The registry used to resolve this config's entitlement into {@link licenseCapabilities}. diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index f83c90199e..6f00b5a11d 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -610,9 +610,6 @@ export class HyperFormula implements TypedEmitter { * Migrating means building an engine: * `HyperFormula.buildEmpty({ language: 'plPL' }).getRegisteredFunctionNames()`. * - * @deprecated Use the instance method of the same name. This static method is deprecated and - * will be removed in one of the next major releases. - * * @param {string} code - language code * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type @@ -742,7 +739,7 @@ export class HyperFormula implements TypedEmitter { * @param {Config} config - the instance's config, holding its resolved entitlement */ private static licenseListsFunction(functionId: string, functionRegistry: FunctionRegistry, config: Config): boolean { - if (!config.isLicenseGateActive || FunctionRegistry.functionIsProtected(functionId)) { + if (FunctionRegistry.functionIsProtected(functionId)) { return true } const plugin = functionRegistry.getFunctionPlugin(functionId) @@ -4914,10 +4911,6 @@ export class HyperFormula implements TypedEmitter { /** * Throws an error if the current license entitlement does not grant the given feature. - * A no-op read (`isLicenseGateActive === false`) whenever this instance's entitlement is - * unrestricted, i.e. for every key this library fully understands today (HF-307 PR 1); the - * check only does work once a real license-key payload adapter (a later HF-307 PR) can - * produce a restricted entitlement. * * Where the line is drawn, so a later change does not move it by accident: * - **Gated:** methods that create value by mutating the sheet, the clipboard, the undo @@ -4943,9 +4936,6 @@ export class HyperFormula implements TypedEmitter { * @internal */ private ensureCapability(feature: FeatureId): void { - if (!this._config.isLicenseGateActive) { - return - } if (!allowsFeature(this._config.licenseCapabilities, feature)) { throw new LicenseCapabilityMissingError(feature) } diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 39ef01b6b1..5bd104737c 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -189,7 +189,7 @@ export class Interpreter { return this.unaryRangeWrapper(this.percentOp, result, state) } case AstNodeType.FUNCTION_CALL: { - if (this.config.isLicenseGateActive && !FunctionRegistry.functionIsProtected(ast.procedureName)) { + if (!FunctionRegistry.functionIsProtected(ast.procedureName)) { const validityState = this.config.licenseKeyValidityState if (validityState !== LicenseKeyValidityState.VALID) { return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(validityState)) diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index 01202acac8..8b03ccff31 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -10,9 +10,9 @@ * but HF-307 decision D1 drops function-registration gating (and the `CustomFunctions` grant) * from this release, so no capability grant maps to it. * - * `ImportExport` IS granted, by the `import_export` add-on token (2026-08-12 packages meeting) — - * but it gates no public method yet, because HF-107 hasn't shipped the import/export feature it - * would gate. The grant exists; the gate does not, yet. + * `ImportExport` IS granted, by the `feat:import_export` token — but it gates no public method + * yet, because HF-107 hasn't shipped the import/export feature it would gate. The grant exists; + * the gate does not, yet. */ export const enum FeatureId { NamedExpressions = 'named_expressions', diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts index da6d7393ad..3f2ac89870 100644 --- a/src/license/capabilities.ts +++ b/src/license/capabilities.ts @@ -20,6 +20,11 @@ export const CLIPBOARD_FEATURE_TOKEN = 'feat:clipboard' export const NAMED_EXPRESSIONS_FEATURE_TOKEN = 'feat:named_expressions' /** Grants {@link FeatureId.Batching}. */ export const BATCHING_FEATURE_TOKEN = 'feat:batching' +/** + * Grants {@link FeatureId.ImportExport} — a RESERVED grant: nothing in the public API is gated on + * it yet, because HF-107 hasn't shipped the import/export feature it would gate. + */ +export const IMPORT_EXPORT_FEATURE_TOKEN = 'feat:import_export' /** * Every feature token, in one list, for the opt-in rule in `licenseTermsOf`: a key naming no @@ -28,23 +33,11 @@ export const BATCHING_FEATURE_TOKEN = 'feat:batching' */ export const ALL_FEATURE_TOKENS = [ CRUD_FEATURE_TOKEN, UNDO_REDO_FEATURE_TOKEN, CLIPBOARD_FEATURE_TOKEN, - NAMED_EXPRESSIONS_FEATURE_TOKEN, BATCHING_FEATURE_TOKEN, + NAMED_EXPRESSIONS_FEATURE_TOKEN, BATCHING_FEATURE_TOKEN, IMPORT_EXPORT_FEATURE_TOKEN, ] /** The whole implemented catalog of built-in functions, operator callable forms included. */ export const FUN_ALL_TOKEN = 'fun:all' -/** - * Spreadsheet Bundle add-on (2026-08-12 packages meeting). Grants {@link FeatureId.Crud}, - * {@link FeatureId.UndoRedo}, {@link FeatureId.Clipboard} and {@link FeatureId.Batching} — see - * {@link CAPABILITY_TABLE}. - */ -export const SPREADSHEET_ADDON_TOKEN = 'spreadsheet' -/** - * Import/export add-on (2026-08-12 packages meeting). Grants {@link FeatureId.ImportExport}, a - * RESERVED grant: nothing in the public API is gated on it yet, because HF-107 hasn't shipped the - * import/export feature it would gate. - */ -export const IMPORT_EXPORT_ADDON_TOKEN = 'import_export' /** * The canonical spelling of a capability token for table lookups. @@ -258,15 +251,13 @@ const singleFunctionEntries: [string, CapabilityGrant][] = ALL_GATABLE_FUNCTIONS * it is added here, which the completeness invariant in `unit/license/capability-registry.spec.ts` * fails on. * - * The five `feat:*` tokens carry the gated API areas, one feature each. A key may state them - * explicitly; a key naming none is granted all five (the opt-in rule in `licenseTermsOf`); legacy - * keys resolve to the unrestricted entitlement and never consult this table. + * The `feat:*` tokens carry the gated API areas, one feature each. A key may state them + * explicitly; a key naming none is granted all of them (the opt-in rule in `licenseTermsOf`); + * legacy keys resolve to the unrestricted entitlement and never consult this table. * - * The two add-on tokens, wired per the 2026-08-12 packages meeting: `spreadsheet` backs the - * 'Spreadsheet Bundle' add-on and grants {@link FeatureId.Crud}, {@link FeatureId.UndoRedo}, - * {@link FeatureId.Clipboard} and {@link FeatureId.Batching}. `import_export` backs the - * import-export add-on and grants {@link FeatureId.ImportExport} — a RESERVED grant, since nothing - * in the public API is gated on it yet: HF-107 hasn't shipped the feature it would gate. + * There is no entry for any add-on. An add-on is a commercial wrapper, and which capabilities it + * bundles is decided where keys are minted; the engine only ever reads the capabilities the key + * actually names. That is what lets pricing rename or re-bundle an add-on without a release here. */ export const CAPABILITY_TABLE: ReadonlyMap = new Map([ [CRUD_FEATURE_TOKEN, {functions: [], features: [FeatureId.Crud]}], @@ -274,15 +265,7 @@ export const CAPABILITY_TABLE: ReadonlyMap = new Map([ [CLIPBOARD_FEATURE_TOKEN, {functions: [], features: [FeatureId.Clipboard]}], [NAMED_EXPRESSIONS_FEATURE_TOKEN, {functions: [], features: [FeatureId.NamedExpressions]}], [BATCHING_FEATURE_TOKEN, {functions: [], features: [FeatureId.Batching]}], - // NamedExpressions is absent on purpose: the Spreadsheet Bundle was scoped at the 12.08 packages - // meeting to the four areas below, and named expressions was not among them. It is recorded here - // so the omission reads as the decision it is rather than as a transcription slip, and so that - // moving it into the bundle stays a product call rather than a silent edit. - [SPREADSHEET_ADDON_TOKEN, { - functions: [], - features: [FeatureId.Crud, FeatureId.UndoRedo, FeatureId.Clipboard, FeatureId.Batching], - }], - [IMPORT_EXPORT_ADDON_TOKEN, {functions: [], features: [FeatureId.ImportExport]}], + [IMPORT_EXPORT_FEATURE_TOKEN, {functions: [], features: [FeatureId.ImportExport]}], [FUN_ALL_TOKEN, {functions: [...ALL_GATABLE_FUNCTIONS], features: []}], ...groupEntries, ...singleFunctionEntries, From 81dca2d3d60058350e663b7b83859bf3e16a5480 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 24 Sep 2026 14:25:04 +0000 Subject: [PATCH 11/54] HF-307: pin the one behaviour change the diff was not admitting to MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An adversarial line-by-line pass found it, and a mutation survived on it: `feat:import_export` is recognized, so naming it switches the opt-in fallback off like any other feature token. A key whose only feature token is this one — a token that gates nothing today — loses CRUD, undo, clipboard, named expressions and batching. Reproduced on a minted key: the same key spelling the old `import_export` word keeps all six areas, spelling `feat:import_export` keeps one. That is the ratified opt-in rule working, not a defect, but it puts a contract on the issuing side that nothing stated: once a key names this token it must name every other area the customer bought. It is now on the token's own documentation and pinned by a test that mints such a key and asserts the four guards throw. Before this the exclusion of that token from the fallback trigger could be deleted with the whole suite staying green. Also from the same pass: the capability table's vocabulary list still advertised two add-on tokens it no longer has; three comments still said "five" feature areas where there are now six; the static getRegisteredFunctionNames still deprecated by prose after its tag was removed, and now describes the difference between the two forms without telling anyone to migrate; and the changelog entry names the one existing method whose output this narrows. Co-Authored-By: Claude Opus 5 (1M context) --- CHANGELOG.md | 2 +- src/HyperFormula.ts | 14 +++++--------- src/license/capabilities.ts | 13 ++++++++++--- src/license/licenseResolution.ts | 4 ++-- 4 files changed, 18 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad3b8ae5af..e93e44d7b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Added -- Added support for the new license key format. A proprietary key can now grant a subset of the library: a function your key does not include evaluates to a `#LIC!` error, and the matching parts of the API throw a `LicenseCapabilityMissingError`. Keys that grant everything, classic 25-character keys and `gpl-v3` included, work exactly as before. [#1728](https://github.com/handsontable/hyperformula/pull/1728) +- Added support for the new license key format. A proprietary key can now grant a subset of the library: a function your key does not include evaluates to a `#LIC!` error, and the matching parts of the API throw a `LicenseCapabilityMissingError`. `getAvailableFunctions()` and `getFunctionDetails()` describe only the functions your key includes, so they no longer advertise one that would error. Keys that grant everything, classic 25-character keys and `gpl-v3` included, work exactly as before. [#1728](https://github.com/handsontable/hyperformula/pull/1728) ### Fixed diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 6f00b5a11d..0931baee04 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -600,15 +600,11 @@ export class HyperFormula implements TypedEmitter { * * Answers for the GLOBAL function registry, because a static method has no engine, and therefore * no configuration, in scope. An engine configured with its own `functionPlugins` registers only - * those, so this method can list functions that engine cannot evaluate at all. Use the instance - * method [[getRegisteredFunctionNames]] instead, which answers for the engine you actually hold — - * the same reasoning that made `getAvailableFunctions()` and `getFunctionDetails()` instance-only - * from their first release. - * - * The two are not interchangeable: this one translates into any registered language without - * building an engine, while the instance method answers only under its own instance's language. - * Migrating means building an engine: - * `HyperFormula.buildEmpty({ language: 'plPL' }).getRegisteredFunctionNames()`. + * those, so this method can list functions that engine cannot evaluate at all. + * + * The two forms answer different questions and neither replaces the other: this one translates + * into any registered language without building an engine, while the instance method of the same + * name answers for the engine you actually hold, under that instance's own language and license. * * @param {string} code - language code * diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts index 3f2ac89870..9da0a61f1e 100644 --- a/src/license/capabilities.ts +++ b/src/license/capabilities.ts @@ -23,6 +23,14 @@ export const BATCHING_FEATURE_TOKEN = 'feat:batching' /** * Grants {@link FeatureId.ImportExport} — a RESERVED grant: nothing in the public API is gated on * it yet, because HF-107 hasn't shipped the import/export feature it would gate. + * + * It is nevertheless a RECOGNIZED feature token, so naming it switches the opt-in fallback off + * like any other: a key whose only `feat:*` token is this one is granted import/export and NOTHING + * else — no CRUD, no undo, no clipboard, no named expressions, no batching. That is the opt-in rule + * working as ratified, and it is the operational contract it puts on the issuing side: once a key + * names this token it must also name every other area the customer bought. Pinned in + * `unit/license/feature-tokens.spec.ts`, because a token that gates nothing suppressing the whole + * fallback is exactly the kind of thing a later edit would undo without noticing. */ export const IMPORT_EXPORT_FEATURE_TOKEN = 'feat:import_export' @@ -47,7 +55,7 @@ export const FUN_ALL_TOKEN = 'fun:all' * under lowercasing. Surrounding whitespace is trimmed for a sharper reason than tidiness: every * rule that reads a token has to read the SAME token, and a padded one used to be read two * different ways at once — `' feat:crud'` failed the `feat:` prefix test that decides whether a key - * speaks the feature vocabulary, so the key was granted all five feature areas instead of the one + * speaks the feature vocabulary, so the key was granted every feature area instead of the one * it named, while `'feat:crud '` passed that test and then missed the table, granting none. * * Normalization happens at LOOKUP, never at storage: an entitlement carries the key's own @@ -237,8 +245,7 @@ const singleFunctionEntries: [string, CapabilityGrant][] = ALL_GATABLE_FUNCTIONS * * - function tokens, per §6 of the packaging design: `fun:all`, the group tokens * `fun:.`, and one `fun:` per canonical function; - * - one `feat:*` token per gated API area; - * - the two add-on tokens the key generator's schema mints, each naming the features it grants. + * - one `feat:*` token per gated API area. * * No token here names a package, and no grant refers to another token. Which tokens a commercial * package consists of is the generator's knowledge, expressed by the bigger licence simply diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index c8338c17eb..56d6443347 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -164,10 +164,10 @@ function licenseTermsOf(data: EntitlementKeyData): LicenseTerms { // The trigger is a feature token this version RECOGNIZES, not merely one that looks like a // feature token. An unrecognized `feat:*` token has to be inert (D3: "unrecognized token should // not grant the capability (silently ignored)"), and a purely syntactic prefix test makes it the - // opposite of inert - it suppresses the fallback, so the key ends up with ZERO of the five areas. + // opposite of inert - it suppresses the fallback, so the key ends up with ZERO gated areas. // Measured before this guard existed: a key carrying `functions_1` plus a single unknown // `feat:teleport` had CRUD, undo, clipboard, named expressions and batching all throwing, while - // the same key without that token had all five. That is the additive-safety rule inverted - an + // the same key without that token had them all. That is the additive-safety rule inverted - an // older build meeting a key minted by a newer generator, or a one-character typo at issuing time, // would revoke the whole gated API rather than ignore a word it does not know. const namesAKnownFeature = capabilityTokens.some((token) => { From d6d7786ceab6d2a7153dc0b7787c41bcfb4fd7bf Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Mon, 28 Sep 2026 14:10:56 +0200 Subject: [PATCH 12/54] Apply suggestion from @sequba --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e93e44d7b7..cd87687dfe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Added -- Added support for the new license key format. A proprietary key can now grant a subset of the library: a function your key does not include evaluates to a `#LIC!` error, and the matching parts of the API throw a `LicenseCapabilityMissingError`. `getAvailableFunctions()` and `getFunctionDetails()` describe only the functions your key includes, so they no longer advertise one that would error. Keys that grant everything, classic 25-character keys and `gpl-v3` included, work exactly as before. [#1728](https://github.com/handsontable/hyperformula/pull/1728) +- Added support for the new license key format. A proprietary key can now grant a subset of the library: a function your key does not include evaluates to a `#LIC!` error, and the matching parts of the API throw a `LicenseCapabilityMissingError`. `getAvailableFunctions()` and `getFunctionDetails()` describe only the functions your key includes. [#1728](https://github.com/handsontable/hyperformula/pull/1728) ### Fixed From 86e5c6512b567fe571e28c043b639f55bdd57b9f Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Mon, 28 Sep 2026 15:39:08 +0200 Subject: [PATCH 13/54] Refactor capabilities --- src/license/LicenseEntitlement.ts | 5 - src/license/capabilities.ts | 289 +++++----------------------- src/license/featureCapabilities.ts | 41 ++++ src/license/functionCapabilities.ts | 141 ++++++++++++++ src/license/licenseResolution.ts | 41 +--- 5 files changed, 229 insertions(+), 288 deletions(-) create mode 100644 src/license/featureCapabilities.ts create mode 100644 src/license/functionCapabilities.ts diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index 8b03ccff31..84f2f198d9 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -9,10 +9,6 @@ * `CustomFunctions` is reserved vocabulary: it exists so a license payload is free to carry it, * but HF-307 decision D1 drops function-registration gating (and the `CustomFunctions` grant) * from this release, so no capability grant maps to it. - * - * `ImportExport` IS granted, by the `feat:import_export` token — but it gates no public method - * yet, because HF-107 hasn't shipped the import/export feature it would gate. The grant exists; - * the gate does not, yet. */ export const enum FeatureId { NamedExpressions = 'named_expressions', @@ -21,7 +17,6 @@ export const enum FeatureId { UndoRedo = 'undo_redo', Batching = 'batching', CustomFunctions = 'custom_functions', - ImportExport = 'import_export', } /** diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts index 9da0a61f1e..462980cfd4 100644 --- a/src/license/capabilities.ts +++ b/src/license/capabilities.ts @@ -4,68 +4,19 @@ */ import {FeatureId} from './LicenseEntitlement' +import {FEATURE_CAPABILITY_TABLE} from './featureCapabilities' +import {FUNCTION_CAPABILITY_TABLE} from './functionCapabilities' // The engine reads CAPABILITIES, never packages. A license key carries a list of capability // tokens and the engine grants the union of what those tokens name; which tokens make up which // commercial package is decided where keys are minted, not here. In the words of the packaging // design: "Nothing else about packaging exists at the technical layer." - -/** Grants {@link FeatureId.Crud} — the mutating CRUD surface of the public API. */ -export const CRUD_FEATURE_TOKEN = 'feat:crud' -/** Grants {@link FeatureId.UndoRedo}. */ -export const UNDO_REDO_FEATURE_TOKEN = 'feat:undo_redo' -/** Grants {@link FeatureId.Clipboard}. */ -export const CLIPBOARD_FEATURE_TOKEN = 'feat:clipboard' -/** Grants {@link FeatureId.NamedExpressions}. */ -export const NAMED_EXPRESSIONS_FEATURE_TOKEN = 'feat:named_expressions' -/** Grants {@link FeatureId.Batching}. */ -export const BATCHING_FEATURE_TOKEN = 'feat:batching' -/** - * Grants {@link FeatureId.ImportExport} — a RESERVED grant: nothing in the public API is gated on - * it yet, because HF-107 hasn't shipped the import/export feature it would gate. - * - * It is nevertheless a RECOGNIZED feature token, so naming it switches the opt-in fallback off - * like any other: a key whose only `feat:*` token is this one is granted import/export and NOTHING - * else — no CRUD, no undo, no clipboard, no named expressions, no batching. That is the opt-in rule - * working as ratified, and it is the operational contract it puts on the issuing side: once a key - * names this token it must also name every other area the customer bought. Pinned in - * `unit/license/feature-tokens.spec.ts`, because a token that gates nothing suppressing the whole - * fallback is exactly the kind of thing a later edit would undo without noticing. - */ -export const IMPORT_EXPORT_FEATURE_TOKEN = 'feat:import_export' - -/** - * Every feature token, in one list, for the opt-in rule in `licenseTermsOf`: a key naming no - * `feat:*` token at all is granted all of these, because no key vocabulary in circulation can - * express "no features" — see that function for the reasoning. - */ -export const ALL_FEATURE_TOKENS = [ - CRUD_FEATURE_TOKEN, UNDO_REDO_FEATURE_TOKEN, CLIPBOARD_FEATURE_TOKEN, - NAMED_EXPRESSIONS_FEATURE_TOKEN, BATCHING_FEATURE_TOKEN, IMPORT_EXPORT_FEATURE_TOKEN, -] - -/** The whole implemented catalog of built-in functions, operator callable forms included. */ -export const FUN_ALL_TOKEN = 'fun:all' - -/** - * The canonical spelling of a capability token for table lookups. - * - * Token names are case-insensitive — the packaging doc states it outright for its `fun:*` - * vocabulary, and tolerating case on the other tokens costs nothing since none of them collide - * under lowercasing. Surrounding whitespace is trimmed for a sharper reason than tidiness: every - * rule that reads a token has to read the SAME token, and a padded one used to be read two - * different ways at once — `' feat:crud'` failed the `feat:` prefix test that decides whether a key - * speaks the feature vocabulary, so the key was granted every feature area instead of the one - * it named, while `'feat:crud '` passed that test and then missed the table, granting none. - * - * Normalization happens at LOOKUP, never at storage: an entitlement carries the key's own - * spellings (they are diagnostics), and {@link CAPABILITY_TABLE} is keyed by the normalized form. - * - * @param {string} token - a capability token as the key spells it - */ -export function normalizeCapabilityToken(token: string): string { - return token.trim().toLowerCase() -} +// +// The vocabulary itself lives in two halves — `./featureCapabilities` and +// `./functionCapabilities` — and this module is where they meet: it owns the grant shape both +// halves are read through, and joins them into the single table the engine reads. That table is +// what consumers want; neither half is worth importing directly unless you need one vocabulary +// without the other. /** * Describes what a capability token grants: a set of function ids and a set of {@link FeatureId} @@ -78,202 +29,54 @@ export interface CapabilityGrant { } /** - * The `HF.*` callable forms of the calculation operators — the members of `fun:operator.a`. - * - * They are gated like every other function: a key reaches them through `fun:operator.a`, a - * single-function token, or `fun:all`. Only the callable forms are affected. The infix operators - * themselves (`=A1+B1`) are not function calls, never reach gate B, and work under any key. - */ -const OPERATOR_FUNCTIONS = [ - 'HF.ADD', 'HF.CONCAT', 'HF.DIVIDE', 'HF.EQ', 'HF.GT', 'HF.GTE', 'HF.LT', 'HF.LTE', 'HF.MINUS', - 'HF.MULTIPLY', 'HF.NE', 'HF.POW', 'HF.UMINUS', 'HF.UNARY_PERCENT', 'HF.UPLUS', -] - -/** - * The two protected built-ins. Both are named by the packaging doc (`fun:lookup.A`, `fun:info.A`) - * but sit OUTSIDE the token system today — the interpreter never gate-checks a protected - * function, so granting them would be dead weight that implies a restriction that does not exist. - * The doc calls this a "technical limitation" on both; their tokens below are recognized but - * grant nothing. - */ -const PROTECTED_BUILT_INS = ['OFFSET', 'VERSION'] - -/** - * The 21 function groups of the packaging doc, keyed by their group tokens in normalized - * (lowercase) spelling — the doc writes them `fun:.` and declares all token names - * case-insensitive. + * The production capability table the engine reads: {@link FEATURE_CAPABILITY_TABLE} and + * {@link FUNCTION_CAPABILITY_TABLE} under one key space, keyed by NORMALIZED token spelling — + * look up through {@link normalizeCapabilityToken}, never with a raw key string. * - * Transcribed 1:1 from section 6 of the internal packaging design document ("HF function groups - * and packages"), INCLUDING the members that resolve to no grant here: the protected built-ins, - * which sit outside the token system (see {@link PROTECTED_BUILT_INS}). Keeping the doc's own - * membership verbatim is what lets `capability-table.spec.ts` pin each group's size against the - * doc's published counts, so a re-transcription is a reviewable diff. + * The two halves share no token (one vocabulary is prefixed `feat:`, the other `fun:`), so the + * merge cannot lose an entry to a collision. Features come first so that the function half keeps + * its own iteration order, which is what decides the winner in + * `CapabilityRegistry`'s reverse index: `fun:all` covers every gatable function and therefore + * names every one of them there. * - * The doc freezes group names as API surface: once shipped inside license keys, a rename is a - * breaking change. - */ -export const FUNCTION_GROUPS: ReadonlyMap = new Map([ - ['fun:math.a', ['ABS', 'LOG', 'MOD', 'POWER', 'PRODUCT', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'SQRT', 'SUM']], - ['fun:stat.a', ['AVERAGE', 'COUNT', 'MAX', 'MIN']], - ['fun:logic.a', ['IF']], - ['fun:operator.a', [...OPERATOR_FUNCTIONS]], - ['fun:info.a', ['VERSION']], - ['fun:lookup.a', ['OFFSET']], - ['fun:time.b', [ - 'DATE', 'DATEDIF', 'DATEVALUE', 'DAY', 'DAYS', 'EOMONTH', 'HOUR', 'ISOWEEKNUM', 'MINUTE', 'MONTH', - 'NETWORKDAYS', 'SECOND', 'TODAY', 'WEEKDAY', 'WEEKNUM', 'WORKDAY', 'YEAR', - ]], - ['fun:text.b', [ - 'CONCATENATE', 'EXACT', 'LEFT', 'LEN', 'LOWER', 'MID', 'REPLACE', 'REPT', 'RIGHT', 'SEARCH', - 'SUBSTITUTE', 'TEXT', 'TRIM', 'UPPER', 'VALUE', - ]], - ['fun:logic.b', ['AND', 'FALSE', 'IFS', 'NOT', 'OR', 'SWITCH', 'TRUE', 'XOR']], - ['fun:math.b', ['RAND', 'RANDBETWEEN', 'SUMIF', 'SUMIFS']], - ['fun:stat.b', ['AVERAGEIF', 'COUNTIF', 'STDEV.S']], - ['fun:lookup.c', [ - 'ADDRESS', 'CHOOSE', 'COLUMN', 'COLUMNS', 'FILTER', 'HLOOKUP', 'HSTACK', 'HYPERLINK', 'INDEX', 'MATCH', - 'ROW', 'ROWS', 'SORT', 'TRANSPOSE', 'UNIQUE', 'VLOOKUP', 'VSTACK', 'XLOOKUP', - ]], - ['fun:math.c', [ - 'ACOS', 'ASIN', 'ATAN', 'ATAN2', 'CEILING', 'COS', 'EVEN', 'EXP', 'FLOOR', 'INT', 'LN', 'MROUND', 'ODD', - 'PI', 'QUOTIENT', 'SEQUENCE', 'SIGN', 'SIN', 'SUBTOTAL', 'SUMPRODUCT', 'SUMSQ', 'SUMXMY2', 'TAN', - ]], - ['fun:stat.c', [ - 'AVERAGEA', 'COUNTA', 'COUNTBLANK', 'COUNTIFS', 'LARGE', 'MAXIFS', 'MEDIAN', 'MINIFS', 'PERCENTILE.INC', - 'SMALL', 'STDEV.P', 'STDEVA', 'STDEVPA', 'VAR.P', 'VAR.S', - ]], - ['fun:time.c', ['DAYS360', 'EDATE', 'NOW', 'TIME', 'YEARFRAC']], - ['fun:text.c', ['CHAR', 'CLEAN', 'CODE', 'FIND', 'PROPER', 'T', 'TEXTJOIN', 'UNICHAR']], - ['fun:info.c', [ - 'ISBLANK', 'ISERR', 'ISERROR', 'ISEVEN', 'ISLOGICAL', 'ISNA', 'ISNUMBER', 'ISODD', 'ISTEXT', 'N', 'NA', - ]], - ['fun:logic.c', ['IFERROR', 'IFNA']], - ['fun:finance.c', ['FV', 'IPMT', 'IRR', 'NPV', 'PMT', 'PPMT', 'PV', 'RATE', 'SLN', 'XIRR', 'XNPV']], - ['fun:engineer.c', ['DEC2HEX', 'HEX2DEC']], - ['fun:array.c', ['ARRAYFORMULA', 'ARRAY_CONSTRAIN']], -]) - -/** - * The members of a group that a grant can carry: the group verbatim, minus the protected - * built-ins, which are always available and must never become table-covered (a covered function - * is gated for every key not granting it). - * - * @param {string} groupToken - a group token, in normalized spelling - */ -function gatableMembersOf(groupToken: string): string[] { - return (FUNCTION_GROUPS.get(groupToken) ?? []).filter((name) => PROTECTED_BUILT_INS.indexOf(name) === -1) -} - -/** Every function some group names, the operator callable forms included. The groups are disjoint. */ -const GROUPED_FUNCTIONS = Array.from(FUNCTION_GROUPS.keys()).reduce( - (members, groupToken) => members.concat(gatableMembersOf(groupToken)), - [], -) - -/** - * The implemented functions no group names — the packaging design's niche tail, reachable only - * through {@link FUN_ALL_TOKEN} or their own single-function token. - * - * Enumerated rather than taken from the function registry at run time, even though "everything - * not in a group" would be the shorter way to say it. Reading the registry would sweep in - * functions registered through `HyperFormula.registerFunctionPlugin`, putting a user's OWN custom - * function under a licence token and returning `#LIC!` for it — the opposite of HF-307 decision - * D1, which drops custom-function gating entirely. A function this table does not list is not - * gated at all, which is exactly the treatment a custom function should get. - */ -const UNGROUPED_FUNCTIONS = [ - 'ACOSH', 'ACOT', 'ACOTH', 'ARABIC', 'ASINH', 'ATANH', 'AVEDEV', 'BASE', 'BESSELI', 'BESSELJ', 'BESSELK', - 'BESSELY', 'BETA.DIST', 'BETA.INV', 'BIN2DEC', 'BIN2HEX', 'BIN2OCT', 'BINOM.DIST', 'BINOM.INV', 'BITAND', - 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'CEILING.MATH', 'CEILING.PRECISE', 'CHISQ.DIST', - 'CHISQ.DIST.RT', 'CHISQ.INV', 'CHISQ.INV.RT', 'CHISQ.TEST', 'COMBIN', 'COMBINA', 'COMPLEX', - 'CONFIDENCE.NORM', 'CONFIDENCE.T', 'CORREL', 'COSH', 'COT', 'COTH', 'COUNTUNIQUE', 'COVARIANCE.P', - 'COVARIANCE.S', 'CSC', 'CSCH', 'CUMIPMT', 'CUMPRINC', 'DAVERAGE', 'DB', 'DCOUNT', 'DCOUNTA', 'DDB', - 'DEC2BIN', 'DEC2OCT', 'DECIMAL', 'DEGREES', 'DELTA', 'DEVSQ', 'DGET', 'DMAX', 'DMIN', 'DOLLARDE', - 'DOLLARFR', 'DPRODUCT', 'DSTDEV', 'DSTDEVP', 'DSUM', 'DVAR', 'DVARP', 'EFFECT', 'ERF', 'ERFC', - 'EXPON.DIST', 'F.DIST', 'F.DIST.RT', 'F.INV', 'F.INV.RT', 'F.TEST', 'FACT', 'FACTDOUBLE', 'FISHER', - 'FISHERINV', 'FLOOR.MATH', 'FLOOR.PRECISE', 'FORMULATEXT', 'FVSCHEDULE', 'GAMMA', 'GAMMA.DIST', - 'GAMMA.INV', 'GAMMALN', 'GAUSS', 'GCD', 'GEOMEAN', 'HARMEAN', 'HEX2BIN', 'HEX2OCT', 'HYPGEOM.DIST', - 'IMABS', 'IMAGINARY', 'IMARGUMENT', 'IMCONJUGATE', 'IMCOS', 'IMCOSH', 'IMCOT', 'IMCSC', 'IMCSCH', 'IMDIV', - 'IMEXP', 'IMLN', 'IMLOG10', 'IMLOG2', 'IMPOWER', 'IMPRODUCT', 'IMREAL', 'IMSEC', 'IMSECH', 'IMSIN', - 'IMSINH', 'IMSQRT', 'IMSUB', 'IMSUM', 'IMTAN', 'INTERVAL', 'ISBINARY', 'ISFORMULA', 'ISNONTEXT', 'ISPMT', - 'ISREF', 'LCM', 'LOG10', 'LOGNORM.DIST', 'LOGNORM.INV', 'MAXA', 'MAXPOOL', 'MEDIANPOOL', 'MINA', 'MIRR', - 'MMULT', 'MULTINOMIAL', 'NEGBINOM.DIST', 'NETWORKDAYS.INTL', 'NOMINAL', 'NORM.DIST', 'NORM.INV', - 'NORM.S.DIST', 'NORM.S.INV', 'NPER', 'OCT2BIN', 'OCT2DEC', 'OCT2HEX', 'PDURATION', 'PERCENTILE.EXC', - 'PHI', 'POISSON.DIST', 'QUARTILE.EXC', 'QUARTILE.INC', 'RADIANS', 'ROMAN', 'RRI', 'RSQ', 'SEC', 'SECH', - 'SERIESSUM', 'SHEET', 'SHEETS', 'SINH', 'SKEW', 'SKEW.P', 'SLOPE', 'SPLIT', 'SQRTPI', 'STANDARDIZE', - 'STEYX', 'SUMX2MY2', 'SUMX2PY2', 'SYD', 'T.DIST', 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'T.TEST', - 'TANH', 'TBILLEQ', 'TBILLPRICE', 'TBILLYIELD', 'TDIST', 'TIMEVALUE', 'UNICODE', 'VARA', 'VARPA', - 'WEIBULL.DIST', 'WORKDAY.INTL', 'Z.TEST', -] - -/** The whole gatable catalog: what {@link FUN_ALL_TOKEN} grants. */ -const ALL_GATABLE_FUNCTIONS = GROUPED_FUNCTIONS.concat(UNGROUPED_FUNCTIONS) - -/** - * One table entry per group token, granting the group's gatable members. `fun:info.a` and - * `fun:lookup.a` resolve to - * EMPTY grants on purpose — their members are the protected built-ins, which are always available - * and must never become table-covered (a covered function is gated for every key not granting - * it). The tokens stay recognized either way, so a key carrying them is never reported as - * unrecognized: they are the doc's bookkeeping identifiers for functionality every key gets. - */ -const groupEntries: [string, CapabilityGrant][] = Array.from(FUNCTION_GROUPS.keys()).map((groupToken) => [ - groupToken, - {functions: gatableMembersOf(groupToken), features: []}, -]) - -/** - * One table entry per canonical function name: the packaging doc's single-function tokens - * (`fun:`), "for surgical grants: custom deals, previews, per-function - * exceptions". One exists for EVERY canonical name — including the operator callable forms and - * the protected built-ins (empty grants, as above). Alias names get no - * token of their own: tokens reference canonical names, and an alias travels with its canonical - * function because the gates canonicalize before consulting the table. - */ -const singleFunctionEntries: [string, CapabilityGrant][] = ALL_GATABLE_FUNCTIONS - .concat(PROTECTED_BUILT_INS) - .map((name) => [ - `fun:${normalizeCapabilityToken(name)}`, - {functions: PROTECTED_BUILT_INS.indexOf(name) === -1 ? [name] : [], features: []}, - ]) - -/** - * The production capability table, keyed by NORMALIZED token spelling — look up through - * {@link normalizeCapabilityToken}, never with a raw key string. - * - * The vocabulary, and nothing else: - * - * - function tokens, per §6 of the packaging design: `fun:all`, the group tokens - * `fun:.`, and one `fun:` per canonical function; - * - one `feat:*` token per gated API area. + * Both halves are copied into fresh {@link CapabilityGrant} objects rather than referenced, so + * that a consumer holding a grant cannot reach back into a sub-table's arrays. * * No token here names a package, and no grant refers to another token. Which tokens a commercial * package consists of is the generator's knowledge, expressed by the bigger licence simply * listing more tokens — so a key's function set is the union of everything it names that this * table recognizes, and an unrecognized token is inert (strict-shape/lenient-vocabulary, T7). - * - * Every grant is STATIC. Nothing here is derived from the function registry at run time, so a - * function registered by a user through `HyperFormula.registerFunctionPlugin` can never be gated - * — see {@link UNGROUPED_FUNCTIONS}. The cost is that a newly implemented built-in is ungated until - * it is added here, which the completeness invariant in `unit/license/capability-registry.spec.ts` - * fails on. - * - * The `feat:*` tokens carry the gated API areas, one feature each. A key may state them - * explicitly; a key naming none is granted all of them (the opt-in rule in `licenseTermsOf`); - * legacy keys resolve to the unrestricted entitlement and never consult this table. + * Legacy keys resolve to the unrestricted entitlement and never consult this table at all. * * There is no entry for any add-on. An add-on is a commercial wrapper, and which capabilities it * bundles is decided where keys are minted; the engine only ever reads the capabilities the key * actually names. That is what lets pricing rename or re-bundle an add-on without a release here. */ -export const CAPABILITY_TABLE: ReadonlyMap = new Map([ - [CRUD_FEATURE_TOKEN, {functions: [], features: [FeatureId.Crud]}], - [UNDO_REDO_FEATURE_TOKEN, {functions: [], features: [FeatureId.UndoRedo]}], - [CLIPBOARD_FEATURE_TOKEN, {functions: [], features: [FeatureId.Clipboard]}], - [NAMED_EXPRESSIONS_FEATURE_TOKEN, {functions: [], features: [FeatureId.NamedExpressions]}], - [BATCHING_FEATURE_TOKEN, {functions: [], features: [FeatureId.Batching]}], - [IMPORT_EXPORT_FEATURE_TOKEN, {functions: [], features: [FeatureId.ImportExport]}], - [FUN_ALL_TOKEN, {functions: [...ALL_GATABLE_FUNCTIONS], features: []}], - ...groupEntries, - ...singleFunctionEntries, +export const CAPABILITY_TABLE: ReadonlyMap = new Map([ + ...Array.from(FEATURE_CAPABILITY_TABLE, ([token, features]): [string, CapabilityGrant] => [ + token, + {functions: [], features: [...features]}, + ]), + ...Array.from(FUNCTION_CAPABILITY_TABLE, ([token, functions]): [string, CapabilityGrant] => [ + token, + {functions: [...functions], features: []}, + ]), ]) + +/** + * The canonical spelling of a capability token for table lookups. + * + * Token names are case-insensitive — the packaging doc states it outright for its `fun:*` + * vocabulary, and tolerating case on the other tokens costs nothing since none of them collide + * under lowercasing. Surrounding whitespace is trimmed because a key's token list is text a human + * edited somewhere upstream: `'feat:crud '` is the token its author meant, and a padded spelling + * that silently grants nothing is a support ticket, not a licence restriction. + * + * Normalization happens at LOOKUP, never at storage: an entitlement carries the key's own + * spellings (they are diagnostics), and {@link CAPABILITY_TABLE} is keyed by the normalized form. + * + * @param {string} token - a capability token as the key spells it + */ +export function normalizeCapabilityToken(token: string): string { + return token.trim().toLowerCase() +} diff --git a/src/license/featureCapabilities.ts b/src/license/featureCapabilities.ts new file mode 100644 index 0000000000..d66aa2a0cd --- /dev/null +++ b/src/license/featureCapabilities.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +import {FeatureId} from './LicenseEntitlement' + +/** + * One entry per single-area feature token. `feat:all` is derived from this list rather than + * spelled out beside it, so a new gated area reaches it by being added here and nowhere else. + * + * {@link FeatureId.CustomFunctions} deliberately has no token: HF-307 decision D1 drops + * function-registration gating, so nothing may grant it. + */ +const singleFeatureEntries: [string, readonly FeatureId[]][] = [ + ['feat:crud', [FeatureId.Crud]], + ['feat:undo_redo', [FeatureId.UndoRedo]], + ['feat:clipboard', [FeatureId.Clipboard]], + ['feat:named_expressions', [FeatureId.NamedExpressions]], + ['feat:batching', [FeatureId.Batching]], +] + +/** Every gated API area: what `feat:all` grants. */ +const ALL_FEATURES = singleFeatureEntries.reduce( + (features, [, granted]) => features.concat(granted), + [], +) + +/** + * The `feat:*` half of the vocabulary, keyed by NORMALIZED token spelling: one token per gated + * area of the public API, plus `feat:all` for all of them at once. + * + * Kept apart from `FUNCTION_CAPABILITY_TABLE` because the two halves are maintained by different + * forces. This one grows when a public API area becomes gated — an engine decision, one entry + * hand-written per area — while the function half is a transcription of the packaging document's + * group membership. `CAPABILITY_TABLE` in `./capabilities` merges them for the consumers. + */ +export const FEATURE_CAPABILITY_TABLE: ReadonlyMap = new Map([ + ...singleFeatureEntries, + ['feat:all', ALL_FEATURES] as [string, readonly FeatureId[]], +]) diff --git a/src/license/functionCapabilities.ts b/src/license/functionCapabilities.ts new file mode 100644 index 0000000000..eeef1dbdcd --- /dev/null +++ b/src/license/functionCapabilities.ts @@ -0,0 +1,141 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * The 21 function groups of the packaging doc, keyed by their group tokens in normalized + * (lowercase) spelling — the doc writes them `fun:.` and declares all token names + * case-insensitive. + * + * Transcribed 1:1 from section 6 of the internal packaging design document ("HF function groups + * and packages"), so that a re-transcription is a reviewable diff against the doc's published + * counts. Module-private: the groups reach the outside only as entries of + * {@link FUNCTION_CAPABILITY_TABLE}, which is where a test has to read them from. + * + * `fun:info.a` and `fun:lookup.a` name nothing but the two protected built-ins, `VERSION` and + * `OFFSET` (see `FunctionRegistry._protectedPlugins`). The doc calls that a "technical + * limitation" on both: the interpreter never gate-checks a protected function, so those two + * evaluate under every key no matter which tokens name them, and the groups that carry them are + * bookkeeping identifiers for functionality every key already has. + * + * The doc freezes group names as API surface: once shipped inside license keys, a rename is a + * breaking change. + */ +const FUNCTION_GROUPS: ReadonlyMap = new Map([ + ['fun:math.a', ['ABS', 'LOG', 'MOD', 'POWER', 'PRODUCT', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'SQRT', 'SUM']], + ['fun:stat.a', ['AVERAGE', 'COUNT', 'MAX', 'MIN']], + ['fun:logic.a', ['IF']], + ['fun:operator.a', ['HF.ADD', 'HF.CONCAT', 'HF.DIVIDE', 'HF.EQ', 'HF.GT', 'HF.GTE', 'HF.LT', 'HF.LTE', 'HF.MINUS', + 'HF.MULTIPLY', 'HF.NE', 'HF.POW', 'HF.UMINUS', 'HF.UNARY_PERCENT', 'HF.UPLUS']], + ['fun:info.a', ['VERSION']], + ['fun:lookup.a', ['OFFSET']], + ['fun:time.b', [ + 'DATE', 'DATEDIF', 'DATEVALUE', 'DAY', 'DAYS', 'EOMONTH', 'HOUR', 'ISOWEEKNUM', 'MINUTE', 'MONTH', + 'NETWORKDAYS', 'SECOND', 'TODAY', 'WEEKDAY', 'WEEKNUM', 'WORKDAY', 'YEAR', + ]], + ['fun:text.b', [ + 'CONCATENATE', 'EXACT', 'LEFT', 'LEN', 'LOWER', 'MID', 'REPLACE', 'REPT', 'RIGHT', 'SEARCH', + 'SUBSTITUTE', 'TEXT', 'TRIM', 'UPPER', 'VALUE', + ]], + ['fun:logic.b', ['AND', 'FALSE', 'IFS', 'NOT', 'OR', 'SWITCH', 'TRUE', 'XOR']], + ['fun:math.b', ['RAND', 'RANDBETWEEN', 'SUMIF', 'SUMIFS']], + ['fun:stat.b', ['AVERAGEIF', 'COUNTIF', 'STDEV.S']], + ['fun:lookup.c', [ + 'ADDRESS', 'CHOOSE', 'COLUMN', 'COLUMNS', 'FILTER', 'HLOOKUP', 'HSTACK', 'HYPERLINK', 'INDEX', 'MATCH', + 'ROW', 'ROWS', 'SORT', 'TRANSPOSE', 'UNIQUE', 'VLOOKUP', 'VSTACK', 'XLOOKUP', + ]], + ['fun:math.c', [ + 'ACOS', 'ASIN', 'ATAN', 'ATAN2', 'CEILING', 'COS', 'EVEN', 'EXP', 'FLOOR', 'INT', 'LN', 'MROUND', 'ODD', + 'PI', 'QUOTIENT', 'SEQUENCE', 'SIGN', 'SIN', 'SUBTOTAL', 'SUMPRODUCT', 'SUMSQ', 'SUMXMY2', 'TAN', + ]], + ['fun:stat.c', [ + 'AVERAGEA', 'COUNTA', 'COUNTBLANK', 'COUNTIFS', 'LARGE', 'MAXIFS', 'MEDIAN', 'MINIFS', 'PERCENTILE.INC', + 'SMALL', 'STDEV.P', 'STDEVA', 'STDEVPA', 'VAR.P', 'VAR.S', + ]], + ['fun:time.c', ['DAYS360', 'EDATE', 'NOW', 'TIME', 'YEARFRAC']], + ['fun:text.c', ['CHAR', 'CLEAN', 'CODE', 'FIND', 'PROPER', 'T', 'TEXTJOIN', 'UNICHAR']], + ['fun:info.c', [ + 'ISBLANK', 'ISERR', 'ISERROR', 'ISEVEN', 'ISLOGICAL', 'ISNA', 'ISNUMBER', 'ISODD', 'ISTEXT', 'N', 'NA', + ]], + ['fun:logic.c', ['IFERROR', 'IFNA']], + ['fun:finance.c', ['FV', 'IPMT', 'IRR', 'NPV', 'PMT', 'PPMT', 'PV', 'RATE', 'SLN', 'XIRR', 'XNPV']], + ['fun:engineer.c', ['DEC2HEX', 'HEX2DEC']], + ['fun:array.c', ['ARRAYFORMULA', 'ARRAY_CONSTRAIN']], +]) + +/** + * The implemented functions no group names — the packaging design's niche tail, reachable only + * through `fun:all` or their own single-function token. + * + * Enumerated rather than taken from the function registry at run time, even though "everything + * not in a group" would be the shorter way to say it. Reading the registry would sweep in + * functions registered through `HyperFormula.registerFunctionPlugin`, putting a user's OWN custom + * function under a licence token and returning `#LIC!` for it — the opposite of HF-307 decision + * D1, which drops custom-function gating entirely. A function this table does not list is not + * gated at all, which is exactly the treatment a custom function should get. + */ +const UNGROUPED_FUNCTIONS = [ + 'ACOSH', 'ACOT', 'ACOTH', 'ARABIC', 'ASINH', 'ATANH', 'AVEDEV', 'BASE', 'BESSELI', 'BESSELJ', 'BESSELK', + 'BESSELY', 'BETA.DIST', 'BETA.INV', 'BIN2DEC', 'BIN2HEX', 'BIN2OCT', 'BINOM.DIST', 'BINOM.INV', 'BITAND', + 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'CEILING.MATH', 'CEILING.PRECISE', 'CHISQ.DIST', + 'CHISQ.DIST.RT', 'CHISQ.INV', 'CHISQ.INV.RT', 'CHISQ.TEST', 'COMBIN', 'COMBINA', 'COMPLEX', + 'CONFIDENCE.NORM', 'CONFIDENCE.T', 'CORREL', 'COSH', 'COT', 'COTH', 'COUNTUNIQUE', 'COVARIANCE.P', + 'COVARIANCE.S', 'CSC', 'CSCH', 'CUMIPMT', 'CUMPRINC', 'DAVERAGE', 'DB', 'DCOUNT', 'DCOUNTA', 'DDB', + 'DEC2BIN', 'DEC2OCT', 'DECIMAL', 'DEGREES', 'DELTA', 'DEVSQ', 'DGET', 'DMAX', 'DMIN', 'DOLLARDE', + 'DOLLARFR', 'DPRODUCT', 'DSTDEV', 'DSTDEVP', 'DSUM', 'DVAR', 'DVARP', 'EFFECT', 'ERF', 'ERFC', + 'EXPON.DIST', 'F.DIST', 'F.DIST.RT', 'F.INV', 'F.INV.RT', 'F.TEST', 'FACT', 'FACTDOUBLE', 'FISHER', + 'FISHERINV', 'FLOOR.MATH', 'FLOOR.PRECISE', 'FORMULATEXT', 'FVSCHEDULE', 'GAMMA', 'GAMMA.DIST', + 'GAMMA.INV', 'GAMMALN', 'GAUSS', 'GCD', 'GEOMEAN', 'HARMEAN', 'HEX2BIN', 'HEX2OCT', 'HYPGEOM.DIST', + 'IMABS', 'IMAGINARY', 'IMARGUMENT', 'IMCONJUGATE', 'IMCOS', 'IMCOSH', 'IMCOT', 'IMCSC', 'IMCSCH', 'IMDIV', + 'IMEXP', 'IMLN', 'IMLOG10', 'IMLOG2', 'IMPOWER', 'IMPRODUCT', 'IMREAL', 'IMSEC', 'IMSECH', 'IMSIN', + 'IMSINH', 'IMSQRT', 'IMSUB', 'IMSUM', 'IMTAN', 'INTERVAL', 'ISBINARY', 'ISFORMULA', 'ISNONTEXT', 'ISPMT', + 'ISREF', 'LCM', 'LOG10', 'LOGNORM.DIST', 'LOGNORM.INV', 'MAXA', 'MAXPOOL', 'MEDIANPOOL', 'MINA', 'MIRR', + 'MMULT', 'MULTINOMIAL', 'NEGBINOM.DIST', 'NETWORKDAYS.INTL', 'NOMINAL', 'NORM.DIST', 'NORM.INV', + 'NORM.S.DIST', 'NORM.S.INV', 'NPER', 'OCT2BIN', 'OCT2DEC', 'OCT2HEX', 'PDURATION', 'PERCENTILE.EXC', + 'PHI', 'POISSON.DIST', 'QUARTILE.EXC', 'QUARTILE.INC', 'RADIANS', 'ROMAN', 'RRI', 'RSQ', 'SEC', 'SECH', + 'SERIESSUM', 'SHEET', 'SHEETS', 'SINH', 'SKEW', 'SKEW.P', 'SLOPE', 'SPLIT', 'SQRTPI', 'STANDARDIZE', + 'STEYX', 'SUMX2MY2', 'SUMX2PY2', 'SYD', 'T.DIST', 'T.DIST.2T', 'T.DIST.RT', 'T.INV', 'T.INV.2T', 'T.TEST', + 'TANH', 'TBILLEQ', 'TBILLPRICE', 'TBILLYIELD', 'TDIST', 'TIMEVALUE', 'UNICODE', 'VARA', 'VARPA', + 'WEIBULL.DIST', 'WORKDAY.INTL', 'Z.TEST', +] + +/** + * The whole catalog: what `fun:all` grants. + * + * Flattened by `reduce` rather than `Array.prototype.flat`, which is ES2019 and so sits above the + * `lib` ceiling this package compiles against. + */ +const ALL_FUNCTIONS = Array.from(FUNCTION_GROUPS.values()) + .reduce((functions, members) => functions.concat(members), []) + .concat(UNGROUPED_FUNCTIONS) + +/** + * One table entry per canonical function name: the packaging doc's single-function tokens + * (`fun:`), "for surgical grants: custom deals, previews, per-function + * exceptions". One exists for EVERY canonical name — the operator callable forms and the + * protected built-ins included. Alias names get no token of their own: tokens reference canonical + * names, and an alias travels with its canonical function because the gates canonicalize before + * consulting the table. + */ +const singleFunctionEntries: [string, readonly string[]][] = ALL_FUNCTIONS.map((name) => [ + `fun:${name.trim().toLowerCase()}`, + [name], +]) + +/** + * The `fun:*` half of the vocabulary, keyed by NORMALIZED token spelling, per §6 of the packaging + * design: `fun:all`, the group tokens `fun:.`, and one + * `fun:` per canonical function. + * + * Every grant is STATIC. Nothing here is derived from the function registry at run time, so a + * function registered by a user through `HyperFormula.registerFunctionPlugin` can never be gated + * — see the note on `UNGROUPED_FUNCTIONS`. The cost is that a newly implemented built-in is + * ungated until it is added here, which the completeness invariant in + * `unit/license/capability-registry.spec.ts` fails on. + */ +export const FUNCTION_CAPABILITY_TABLE: ReadonlyMap = new Map([ + ['fun:all', ALL_FUNCTIONS] as [string, readonly string[]], + ...FUNCTION_GROUPS, + ...singleFunctionEntries, +]) diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index 56d6443347..a923391f28 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -9,7 +9,7 @@ import { notifyLicenseKeyNotice, notifyLicenseKeyState, } from '../helpers/licenseKeyValidator' -import {ALL_FEATURE_TOKENS, CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' +import {CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' import {LicenseEntitlement, LicenseExpiry, unrestrictedEntitlement} from './LicenseEntitlement' import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detectFormat' import {EntitlementKeyData, EntitlementProductGrant, extractEntitlementKeyData} from './handsontable-license-key-parser/extractKeyData' @@ -26,14 +26,6 @@ const MILLISECONDS_PER_DAY = 86400000 */ export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' -/** - * The prefix marking a capability token as granting a public-API feature area. - * - * Used to tell "this key names its feature grants" from "this key's vocabulary cannot express - * one" — see the opt-in rule in {@link licenseTermsOf}. - */ -const FEATURE_TOKEN_PREFIX = 'feat:' - /** * Flag spellings that suppress console output. * @@ -149,37 +141,6 @@ function licenseTermsOf(data: EntitlementKeyData): LicenseTerms { grant.capabilities.forEach((token) => capabilityTokens.push(token)) } - // Feature tokens are OPT-IN, never opt-out. A key carrying at least one `feat:*` token demonstrably - // speaks the feature vocabulary, so it gets exactly the areas it names - that is what makes feature - // gating real (the ratified decision: "Feature gating should work"). A key carrying NONE cannot - // be saying "no features", because no vocabulary in circulation can express one: the key spec's - // current HyperFormula token list (rev 6 §2.2 - `functions_1..4`, `spreadsheet`, - // `import_export`) contains no `feat:*` entry at all. So absence means "this key does not talk - // about features", and the task's additive-safety rule - a grant may grow between versions, - // never shrink - makes the whole gated API the only safe reading. - // - // Reading absence as denial instead would hand a dead public API to every key myHOT can mint - // today, HyperFormula-only and Handsontable-only alike; both were verified doing exactly that - // before this rule existed. - // The trigger is a feature token this version RECOGNIZES, not merely one that looks like a - // feature token. An unrecognized `feat:*` token has to be inert (D3: "unrecognized token should - // not grant the capability (silently ignored)"), and a purely syntactic prefix test makes it the - // opposite of inert - it suppresses the fallback, so the key ends up with ZERO gated areas. - // Measured before this guard existed: a key carrying `functions_1` plus a single unknown - // `feat:teleport` had CRUD, undo, clipboard, named expressions and batching all throwing, while - // the same key without that token had them all. That is the additive-safety rule inverted - an - // older build meeting a key minted by a newer generator, or a one-character typo at issuing time, - // would revoke the whole gated API rather than ignore a word it does not know. - const namesAKnownFeature = capabilityTokens.some((token) => { - const normalized = normalizeCapabilityToken(token) - - return normalized.indexOf(FEATURE_TOKEN_PREFIX) === 0 && CAPABILITY_TABLE.has(normalized) - }) - - if (!namesAKnownFeature) { - capabilityTokens.push(...ALL_FEATURE_TOKENS) - } - // Exactly one of the two date fields is present on an intact entry (the reader enforces it), // and the date used and the axis it is compared against come from that same field. The date is // carried as the payload's own `YYYY-MM-DD` string, never routed through `Date` formatting - From 2ea4fb534c6291922860da815e395cce8c2492cb Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 29 Sep 2026 02:18:54 +0000 Subject: [PATCH 14/54] =?UTF-8?q?HF-307:=20option=201=20=E2=80=94=20the=20?= =?UTF-8?q?vendored=20reader=20stops=20diverging=20from=20upstream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What @sequba asked for on 28.09. `isIsoDate` no longer type-checks the date; it stringifies exactly as upstream does, so this file is a verbatim port again and a drift review can compare it byte for byte instead of reasoning about a patch. The check moved into the code this repository owns: `hyperformulaDateFieldIsWellTyped` in licenseResolution.ts, applied where a malformed payload already takes the invalid-key path. Measured, the verdicts a customer can observe are unchanged — a string date resolves valid, an array date resolves invalid either way; a number or an object never reached the type check because the reader rejects their shape anyway. One behaviour DID change and it is deliberate: only HyperFormula's own entry is type-checked now. A malformed date in another product's entry used to invalidate the whole key and no longer does. Another product's fields are not ours to validate, and failing closed there would take down a customer whose HyperFormula grant is intact. Also restores the exports the capabilities refactor made module-private. FUNCTION_GROUPS and UNGROUPED_FUNCTIONS are what the paired suite's drift checks read to compare this transcription against the packaging document group by group; they had stopped running silently, throwing on `undefined` rather than failing an assertion. Co-Authored-By: Claude Opus 5 (1M context) --- src/license/functionCapabilities.ts | 7 +++- .../PROVENANCE.md | 26 +++++++------ .../extractKeyData.ts | 18 ++++----- src/license/licenseResolution.ts | 39 ++++++++++++++++++- 4 files changed, 64 insertions(+), 26 deletions(-) diff --git a/src/license/functionCapabilities.ts b/src/license/functionCapabilities.ts index eeef1dbdcd..d2ba0bc69c 100644 --- a/src/license/functionCapabilities.ts +++ b/src/license/functionCapabilities.ts @@ -22,7 +22,10 @@ * The doc freezes group names as API surface: once shipped inside license keys, a rename is a * breaking change. */ -const FUNCTION_GROUPS: ReadonlyMap = new Map([ +// Exported for the paired test suite's drift checks, which compare this transcription against the +// packaging document group by group and member by member, and which silently stopped running when +// these became module-private. +export const FUNCTION_GROUPS: ReadonlyMap = new Map([ ['fun:math.a', ['ABS', 'LOG', 'MOD', 'POWER', 'PRODUCT', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'SQRT', 'SUM']], ['fun:stat.a', ['AVERAGE', 'COUNT', 'MAX', 'MIN']], ['fun:logic.a', ['IF']], @@ -75,7 +78,7 @@ const FUNCTION_GROUPS: ReadonlyMap = new Map([ * D1, which drops custom-function gating entirely. A function this table does not list is not * gated at all, which is exactly the treatment a custom function should get. */ -const UNGROUPED_FUNCTIONS = [ +export const UNGROUPED_FUNCTIONS = [ 'ACOSH', 'ACOT', 'ACOTH', 'ARABIC', 'ASINH', 'ATANH', 'AVEDEV', 'BASE', 'BESSELI', 'BESSELJ', 'BESSELK', 'BESSELY', 'BETA.DIST', 'BETA.INV', 'BIN2DEC', 'BIN2HEX', 'BIN2OCT', 'BINOM.DIST', 'BINOM.INV', 'BITAND', 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'CEILING.MATH', 'CEILING.PRECISE', 'CHISQ.DIST', diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 52e866ca46..8cf4a97894 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -61,8 +61,8 @@ also left out. Everything else in that file is ported. ## Deliberate divergences from upstream `allowJs` is off in HyperFormula's `tsconfig.json` and `strict` is on, so these files are a port -rather than a copy. Beyond adding types, the semantics were kept identical except for the -following, which a drift review should expect to see: +rather than a copy. Beyond adding types, the semantics are identical to upstream's; the notes below are the shape of +the port, not changes to what it accepts, and a drift review should expect to see them: 1. **`detectFormat.ts` keeps its literals in a `Map`,** where upstream uses an object literal behind a `hasOwnProperty` guard. Same behaviour for every input (including `constructor` and @@ -74,16 +74,18 @@ following, which a drift review should expect to see: `capabilities` and `flags` are verified element by element, and `notice` and `grace` are verified as non-negative integers. Everything the reader does not verify — unknown fields are preserved on purpose — sits behind an `unknown`-valued index signature, so consumers must narrow before use. -4. **The date field is checked for type, not only for shape** (`isIsoDate` in `extractKeyData.ts`). - Upstream matches `String(value)` against `YYYY-MM-DD`, so a `usage_until` that is a single-element - array of the right string passes its shape check and the declared `string` type ends up wider than - the value. Here a non-string is rejected outright. This is the one divergence that CHANGES which - keys are accepted, so it is called out separately: a malformed key that upstream would carry into - a RESTRICTED entitlement takes the invalid-key path instead. The key spec's addendum (T7) makes - the field a real calendar date, so the stricter reading is the specified one and it is upstream - that deviates — but upstream has not adopted it (checked at `c50ef40a`, `develop` and `master`; - no pull request or issue proposes it), so this is a live fork of behaviour, not a re-port waiting - to happen. Re-check it at every drift review. +4. **`isIsoDate` takes `String(value)`, as upstream does, and the type check lives outside.** + Upstream matches `String(value)` against `YYYY-MM-DD`, so a `usage_until` that is a + single-element array of the right string passes its shape check and the declared `string` type + ends up wider than the value. The key spec's addendum (T7) makes the field a real calendar date, + so the stricter reading is the specified one — but upstream has not adopted it (checked at + `c50ef40a`, `develop` and `master`; no pull request or issue proposes it). + + Rather than fork upstream's source over it, HyperFormula checks the TYPE of its own entry's date + field in `licenseResolution.ts` (`hyperformulaDateFieldIsWellTyped`), before the payload is read + for terms, and a non-string there takes the invalid-key path. The behaviour a customer sees is + the same as when the check lived here; what changed is that this file no longer diverges, so a + drift review compares it to upstream byte for byte instead of reasoning about a patch. Upstream's `/* eslint-disable */` pragmas were dropped where HyperFormula's own ESLint config does not need them. diff --git a/src/license/handsontable-license-key-parser/extractKeyData.ts b/src/license/handsontable-license-key-parser/extractKeyData.ts index 6a71b3f310..c0b4979cf4 100644 --- a/src/license/handsontable-license-key-parser/extractKeyData.ts +++ b/src/license/handsontable-license-key-parser/extractKeyData.ts @@ -81,25 +81,21 @@ function isStringArray(value: unknown): value is string[] { } /** - * Returns `true` when the value is a real calendar date in the `YYYY-MM-DD` format. A time + * Returns `true` when the value SPELLS a real calendar date in the `YYYY-MM-DD` format. A time * component, an offset, a numeric timestamp and a date that does not exist are all rejected — * the format is the whole contract, and a validator that accepted two spellings would hide a * timezone bug at generation instead of surfacing it. * + * Shape only, and deliberately so: the value is stringified first, exactly as upstream does, so a + * non-string that spells a date once stringified passes here. HyperFormula's own type check for + * that lives in `licenseResolution.ts`, outside this vendored copy — see + * `hyperformulaDateFieldIsWellTyped` there, and the divergence table in `PROVENANCE.md`. + * * @param {unknown} value - the value to check */ function isIsoDate(value: unknown): boolean { - // `parseIsoDate` stringifies its argument before matching the `YYYY-MM-DD` shape, so a value - // that is not a string but spells a date once stringified — a single-element array is the - // realistic case — would pass a shape check the format makes fatal, and a malformed key would - // end up granting a RESTRICTED entitlement instead of taking the invalid-key path. The type is - // part of the shape, so it is rejected here rather than left to the stringifying matcher. - if (typeof value !== 'string') { - return false - } - try { - parseIsoDate(value, 'license') + parseIsoDate(String(value), 'license') return true } catch (error) { diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index a923391f28..a078ab8537 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -26,6 +26,12 @@ const MILLISECONDS_PER_DAY = 86400000 */ export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' +/** + * The two date fields a product entry may carry, exactly one of which is present on an intact + * entry. Named here because {@link hyperformulaDateFieldIsWellTyped} has to reach them by name. + */ +const DATE_FIELD_NAMES = ['usage_until', 'release_until'] as const + /** * Flag spellings that suppress console output. * @@ -108,6 +114,37 @@ function releaseDateTimestamp(): number | null { return isNaN(timestamp) ? null : timestamp } +/** + * Whether this product's entry spells its date field as a STRING, as the format requires. + * + * The vendored reader is a verbatim copy of upstream, and upstream checks the date's SHAPE + * without checking its type: `parseIsoDate` stringifies before matching `YYYY-MM-DD`, so + * `usage_until: ["2099-12-31"]` passes there and the declared `string` type ends up wider than + * the value. Left at that, a malformed key would resolve to a RESTRICTED entitlement instead of + * taking the invalid-key path. + * + * The key spec's addendum (T7) makes the field a real calendar date, so the stricter reading is + * the specified one — but upstream has not adopted it (checked at `c50ef40a`, `develop` and + * `master`), and diverging inside the vendored copy would mean carrying a patched fork of + * someone else's source through every drift review. So the check lives here instead, in the code + * this repository owns, and the copy next door stays byte-identical to upstream. + * + * Only HyperFormula's own entry is checked: another product's fields are not ours to validate, + * and rejecting a whole key over a malformed entry we never read would fail closed for a + * customer whose HyperFormula grant is intact. + * + * @param {EntitlementKeyData} data - the extracted key data + */ +function hyperformulaDateFieldIsWellTyped(data: EntitlementKeyData): boolean { + const grant = data.products[HYPERFORMULA_PRODUCT_NAME] + + if (grant === undefined) { + return true + } + + return DATE_FIELD_NAMES.every((field) => grant[field] === undefined || typeof grant[field] === 'string') +} + /** * Reads HyperFormula's terms out of an intact entitlement key payload. * @@ -322,7 +359,7 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true const data = extractEntitlementKeyData(licenseKey) - if (data === null) { + if (data === null || !hyperformulaDateFieldIsWellTyped(data)) { if (notifyConsole) { notifyLicenseKeyState(LicenseKeyValidityState.INVALID) } From 56e3e49b703d8af677dc9a1ca3a678a4698101ce Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 02:01:16 +0000 Subject: [PATCH 15/54] HF-307: correct two comments that a reproduction showed to be false MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An adversarial review of this branch reproduced both claims and neither holds. RETRACTION: "which silently stopped running when these became module-private". Measured on a cold compile, removing both exports gives TS2459 and the paired suite reports ZERO tests — a hard red, not a silence. The original observation behind that wording, `Cannot read properties of undefined`, was a stale ts-jest cache artefact. The same word went into the review comment that asked for these exports, so the premise there was overstated too; the ruling it produced stands either way, and the comment now says what a reproduction actually shows. The JSDoc fifteen lines above the export still opened with "Module-private: the groups reach the outside only as entries of FUNCTION_CAPABILITY_TABLE, which is where a test has to read them from" — the exact sentence the export overturned, shipped in a public file and contradicting the line below it. UNGROUPED_FUNCTIONS goes back to module-private. The ruling was conditional — "if they are needed for tests, you can export them" — and nothing imports this one; only FUNCTION_GROUPS is read by the drift checks. Widening a module's surface for no caller is the kind of thing that later reads as intent. tsc clean; full suite 517/517, 6551 passed, 3 skipped, 0 failed. Co-Authored-By: Claude Opus 5 (1M context) --- src/license/functionCapabilities.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/license/functionCapabilities.ts b/src/license/functionCapabilities.ts index d2ba0bc69c..a13045bd6c 100644 --- a/src/license/functionCapabilities.ts +++ b/src/license/functionCapabilities.ts @@ -10,8 +10,8 @@ * * Transcribed 1:1 from section 6 of the internal packaging design document ("HF function groups * and packages"), so that a re-transcription is a reviewable diff against the doc's published - * counts. Module-private: the groups reach the outside only as entries of - * {@link FUNCTION_CAPABILITY_TABLE}, which is where a test has to read them from. + * counts. Exported so the paired suite can compare it group by group; the table below is the + * only thing production code reads it through. * * `fun:info.a` and `fun:lookup.a` name nothing but the two protected built-ins, `VERSION` and * `OFFSET` (see `FunctionRegistry._protectedPlugins`). The doc calls that a "technical @@ -22,9 +22,9 @@ * The doc freezes group names as API surface: once shipped inside license keys, a rename is a * breaking change. */ -// Exported for the paired test suite's drift checks, which compare this transcription against the -// packaging document group by group and member by member, and which silently stopped running when -// these became module-private. +// Exported for the paired suite's drift checks, which compare this transcription against the +// packaging document group by group and member by member. Without the export those specs fail to +// compile (TS2459) and report zero tests, so the checks are lost rather than merely failing. export const FUNCTION_GROUPS: ReadonlyMap = new Map([ ['fun:math.a', ['ABS', 'LOG', 'MOD', 'POWER', 'PRODUCT', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'SQRT', 'SUM']], ['fun:stat.a', ['AVERAGE', 'COUNT', 'MAX', 'MIN']], @@ -78,7 +78,7 @@ export const FUNCTION_GROUPS: ReadonlyMap = new Map([ * D1, which drops custom-function gating entirely. A function this table does not list is not * gated at all, which is exactly the treatment a custom function should get. */ -export const UNGROUPED_FUNCTIONS = [ +const UNGROUPED_FUNCTIONS = [ 'ACOSH', 'ACOT', 'ACOTH', 'ARABIC', 'ASINH', 'ATANH', 'AVEDEV', 'BASE', 'BESSELI', 'BESSELJ', 'BESSELK', 'BESSELY', 'BETA.DIST', 'BETA.INV', 'BIN2DEC', 'BIN2HEX', 'BIN2OCT', 'BINOM.DIST', 'BINOM.INV', 'BITAND', 'BITLSHIFT', 'BITOR', 'BITRSHIFT', 'BITXOR', 'CEILING.MATH', 'CEILING.PRECISE', 'CHISQ.DIST', From adc39bd7000f767ad8e71cf53952648ff7d1e9e9 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 07:34:14 +0000 Subject: [PATCH 16/54] HF-307: make the vendored-parser drift check a real check, and it immediately found drift MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What @sequba asked for on the PR, and what we agreed at the 18.09 review call: a machine-readable pin beside the prose, and a CI guard that fails when upstream moves. "Oprócz tego zrobiłbym tu jakiś taki plik automatyczny... w formacie json, żeby potem CI to mogło łatwo czytać." upstream.lock.json is the pin: repository, tracked branch, commit, and a sha256 per upstream file. PROVENANCE.md keeps the prose and loses the hash table, which is what the call asked for - a markdown that says what this is, and a separate file for the machine. The first version of the script fetched each file AT THE PINNED COMMIT. That is close to tautological: a commit is immutable, so it would have passed forever. It now fetches from the tracked branch - `master`, the released code, since `develop` there is work in progress - and compares against the pin. First run: DRIFT utils.js: master is 8fba0566…, the pin says 135a8396… Upstream `6862da557` (2026-09-28, DEV-3031) changed `parseIsoDate` to test `typeof isoDate === 'string'` before the pattern. That is the divergence this directory used to carry and that we removed on 28.09 when moving to the verbatim port; upstream adopted the same fix the same day. PROVENANCE.md said "upstream has not adopted it (checked at c50ef40a, develop and master; no pull request or issue proposes it)" - true when written, false within forty-eight hours, and nothing would have told us. That is the whole case for the guard. Not re-ported here, because it is a behaviour decision rather than a mechanical one: upstream's check invalidates the whole key when ANY product's date is mistyped, while hyperformulaDateFieldIsWellTyped deliberately only does so for HyperFormula's own entry. Raised on the PR. Without credentials the check FAILS rather than skipping. "Could not verify" is not "verified", and a guard that reports success when it could not look is worse than no guard. Verified by breaking it five ways: a wrong hash, no credentials, an unpinned file in the directory, a pinned file missing, and the live drift above. tsc clean. Co-Authored-By: Claude Opus 5 (1M context) --- package.json | 1 + script/check-vendored-parser.js | 154 ++++++++++++++++++ .../PROVENANCE.md | 65 +++++--- .../upstream.lock.json | 48 ++++++ 4 files changed, 245 insertions(+), 23 deletions(-) create mode 100755 script/check-vendored-parser.js create mode 100644 src/license/handsontable-license-key-parser/upstream.lock.json diff --git a/package.json b/package.json index ca901db20b..645784fec8 100644 --- a/package.json +++ b/package.json @@ -101,6 +101,7 @@ "audit": "npm audit --omit=dev", "clean": "rimraf coverage/ commonjs/ dist/ es/ languages/ lib/ typings/ test-jasmine/", "compile": "tsc", + "check:vendored-parser": "node script/check-vendored-parser.js", "check:licenses": "license-checker --production --excludePackages=\"hyperformula@3.1.1\" --onlyAllow=\"MIT; Apache-2.0; BSD-3-Clause; BSD-2-Clause; ISC; BSD; Unlicense\"", "tsnode": "ts-node --transpile-only -O {\\\"module\\\":\\\"commonjs\\\"}", "release": "bash script/release/release.sh" diff --git a/script/check-vendored-parser.js b/script/check-vendored-parser.js new file mode 100755 index 0000000000..66c76ac4f1 --- /dev/null +++ b/script/check-vendored-parser.js @@ -0,0 +1,154 @@ +#!/usr/bin/env node +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/* + * Checks the vendored entitlement-key reader against the upstream sources it was ported from. + * + * `src/license/handsontable-license-key-parser/` mirrors `handsontable/license-key`. A local-only + * fix there silently forks the two copies, and a forked checksum or parser rejects genuine + * customer keys - so the pin has to be verified by measurement, not by someone remembering to look. + * + * What it does: reads `upstream.lock.json`, fetches each upstream file from the branch it tracks + * (`master` - the released code, not the work in progress on `develop`), and compares its sha256 + * against the recorded one. A mismatch means upstream moved on while this port stayed behind. + * + * It deliberately does NOT fetch at the pinned commit. A commit is immutable, so that check would + * pass forever and catch nothing - which is how a real change to `utils.js` sat unnoticed for two + * days. The pin is what we compare against; the branch is what we compare. + * + * What it deliberately does NOT do: compare our files to upstream byte for byte. They are + * TypeScript ports of JavaScript sources - `allowJs` is off and `strict` is on - so their bytes + * cannot match, and a check that pretended otherwise would fail for a reason that is never drift. + * PROVENANCE.md lists the shape differences a reviewer should expect. + * + * Usage: + * npm run check:vendored-parser + * + * Needs read access to a private repository. Provide a token through any of + * LICENSE_KEY_REPO_TOKEN, GH_TOKEN or GITHUB_TOKEN, or be logged in to the `gh` CLI. Without one + * the check FAILS rather than passing quietly: "could not verify" is not "verified". + */ + +'use strict' + +const fs = require('fs') +const path = require('path') +const crypto = require('crypto') +const https = require('https') +const {execFileSync} = require('child_process') + +const LOCK = path.resolve(__dirname, '../src/license/handsontable-license-key-parser/upstream.lock.json') + +function token() { + const fromEnv = process.env.LICENSE_KEY_REPO_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN + + if (fromEnv) { + return fromEnv + } + + try { + return execFileSync('gh', ['auth', 'token'], {encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore']}).trim() + } catch (error) { + return null + } +} + +function fetchFile(repo, filePath, ref, auth) { + return new Promise((resolve, reject) => { + const options = { + hostname: 'api.github.com', + path: `/repos/${repo}/contents/${filePath}?ref=${encodeURIComponent(ref)}`, + headers: { + 'Accept': 'application/vnd.github.raw', + 'User-Agent': 'hyperformula-vendored-parser-check', + 'Authorization': `Bearer ${auth}`, + }, + } + + https.get(options, (response) => { + const chunks = [] + + response.on('data', (chunk) => chunks.push(chunk)) + response.on('end', () => { + if (response.statusCode !== 200) { + // The body of a failed call can echo the request back. Report the status and the path only. + reject(new Error(`GET ${filePath}@${ref} answered ${response.statusCode}`)) + + return + } + resolve(Buffer.concat(chunks)) + }) + }).on('error', reject) + }) +} + +async function main() { + const lock = JSON.parse(fs.readFileSync(LOCK, 'utf8')) + const auth = token() + + console.log(`vendored parser: pinned to ${lock.repository}@${lock.commit}, checked against ${lock.track}`) + + if (auth === null) { + console.error('\nFAIL no credentials for a private repository.') + console.error(' Set LICENSE_KEY_REPO_TOKEN (or GH_TOKEN / GITHUB_TOKEN), or run `gh auth login`.') + console.error(' Failing rather than skipping: an unverified pin is not a verified one.') + process.exit(1) + } + + const problems = [] + + for (const entry of lock.files) { + const upstreamPath = `${lock.directory}/${entry.upstream}` + let actual + + try { + const body = await fetchFile(lock.repository, upstreamPath, lock.track, auth) + + actual = crypto.createHash('sha256').update(body).digest('hex') + } catch (error) { + problems.push(`${entry.upstream}: could not be read (${error.message})`) + console.log(` ???? ${entry.upstream}`) + continue + } + + if (actual === entry.sha256) { + console.log(` ok ${entry.upstream}`) + } else { + problems.push(`${entry.upstream}: ${lock.track} is ${actual}, the pin says ${entry.sha256}`) + console.log(` DRIFT ${entry.upstream}`) + } + + const vendored = path.resolve(path.dirname(LOCK), entry.vendored) + + if (!fs.existsSync(vendored)) { + problems.push(`${entry.vendored}: named in the lock file and missing from the directory`) + } + } + + const vendoredFiles = fs.readdirSync(path.dirname(LOCK)).filter((name) => name.endsWith('.ts')) + const pinned = lock.files.map((entry) => entry.vendored) + + vendoredFiles.filter((name) => pinned.indexOf(name) === -1).forEach((name) => { + problems.push(`${name}: present in the directory and named nowhere in the lock file, so nothing pins it`) + }) + + if (problems.length === 0) { + console.log(`\nOK - ${lock.track} still matches the pin`) + + return + } + + console.error(`\n${problems.length} problem(s):`) + problems.forEach((problem) => console.error(` ${problem}`)) + console.error(`\nUpstream ${lock.track} has moved on, or the directory and the pin disagree.`) + console.error('Re-port the changed file and update upstream.lock.json in the same commit.') + process.exit(1) +} + +main().catch((error) => { + console.error(`check failed: ${error.message}`) + process.exit(1) +}) diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 8cf4a97894..6981dd4625 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -13,34 +13,42 @@ parser rejects genuine customer keys. | Tag | `4.0.0` | | Commit | `c50ef40a6` (the `4.0.0` release commit; on `develop` as `1acddafa8`) | | Ported on | 2026-08-20 | -| Reference docs | the format and design notes kept alongside the upstream sources; the byte-level rules are also specified in the key spec's "Technical implementation" addendum (T1–T14) | +| Reference docs | the format and design notes kept alongside the upstream sources; the byte-level rules are also specified in the key spec's "Technical implementation" addendum (T1-T14) | -## Files +## Port, not copy — and what that means for drift -Hashes are of the **upstream** `.js` sources at the tag above, so drift is detectable without -storing a copy of them here. +These files are **TypeScript ports of upstream's JavaScript**, not byte-identical copies, and they +cannot be copies while `allowJs` is off and `strict` is on in `tsconfig.json`. A `.ts` file and the +`.js` it was ported from never share a hash, so "compare our bytes to upstream's" is not a check +that can exist in this shape. What differs is listed under *Deliberate divergences* below; none of +it changes which keys are accepted. -| This directory | Upstream `src/entitlement-key/` | Upstream sha256 | -|---|---|---| -| `constants.ts` | `constants.js` | `6e2ad68d1a316abdec3f89bf04260a2cc4098f76525427d919f22cb25fb077d6` | -| `detectFormat.ts` | `detect-format.js` | `7dc037fd70e7c64078a0fe29b42cb33ecf25e8f4d8963ae9bfb16b69479d267f` | -| `extractKeyData.ts` | `extract-key-data.js` | `afd0858768879764ea016d2bc4fca692a0cd12214c1dfda6932d7ed9e4f32e45` | -| `utils.ts` | `utils.js` | `135a8396bb22f424160fc651e899931d4be807df9b94c6dd24bb1cf6526e0541` | -| `sha512.ts` | `sha512.js` | `668dd1109160b92965a1f9a9c5fb78dfdc1e5b7e93f635a147ae8a6bb2a5d837` | - -### Checking for drift - -The check is manual and needs read access to the private repository — HyperFormula's own CI -cannot do it, which is exactly why the hashes are written down here. +What IS checked, by measurement rather than by someone remembering to look: ```bash -git clone git@github.com:handsontable/license-key.git -cd license-key/src/entitlement-key -sha256sum constants.js detect-format.js extract-key-data.js utils.js sha512.js +npm run check:vendored-parser ``` -Any hash that differs from the table means upstream moved. Re-read the changed file and re-port -it, then update this table together with the code in the same commit. +It reads `upstream.lock.json` — the pin: the commit, and a sha256 per upstream file — fetches each +file at that commit and compares. A mismatch means **upstream moved**, which is the event that +matters: it is the moment this port stops mirroring the code it is supposed to mirror. The script +also fails if a file is in the directory without being pinned, or pinned without being present. + +It needs read access to the private repository, through `LICENSE_KEY_REPO_TOKEN`, `GH_TOKEN`, +`GITHUB_TOKEN` or a logged-in `gh`. Without credentials it **fails** rather than passing quietly: +an unverified pin is not a verified one, and a check that reports success when it could not look is +worse than no check. + +When upstream moves: re-port the changed file and update its hash in `upstream.lock.json` in the +same commit, so the diff shows the two together. + +### If byte-identity is wanted + +It is reachable, and it is the remaining half of option 1: vendor upstream's `.js` verbatim, turn +`allowJs` on, and hand-write a `.d.ts` per file. The check then becomes a direct hash of our own +files, with no lock table at all. Measured as compatible with this repository's TypeScript +(4.0.8 accepts `allowJs` together with `declaration`). It is a build-configuration change, so it +is not made here without a decision. ## Not vendored, on purpose @@ -78,8 +86,19 @@ the port, not changes to what it accepts, and a drift review should expect to se Upstream matches `String(value)` against `YYYY-MM-DD`, so a `usage_until` that is a single-element array of the right string passes its shape check and the declared `string` type ends up wider than the value. The key spec's addendum (T7) makes the field a real calendar date, - so the stricter reading is the specified one — but upstream has not adopted it (checked at - `c50ef40a`, `develop` and `master`; no pull request or issue proposes it). + so the stricter reading is the specified one. + + **Upstream has since adopted it.** Commit `6862da557` on `master` (2026-09-28, DEV-3031) changed + `parseIsoDate` to `typeof isoDate === 'string' ? … : null`, with the same reasoning. An earlier + revision of this file said upstream had not adopted it and that no pull request proposed it; + that was true when written and is not true now — `npm run check:vendored-parser` is what found + it, on its first run against `master`. + + So this divergence is on its way out, and re-porting `utils.js` closes it. One thing to decide + with the re-port rather than sleepwalk into: upstream's check rejects the WHOLE key when any + product's date is mistyped, while `hyperformulaDateFieldIsWellTyped` deliberately only takes the + invalid-key path for HyperFormula's own entry, on the grounds that another product's fields are + not ours to validate. Re-porting reverses that choice. Rather than fork upstream's source over it, HyperFormula checks the TYPE of its own entry's date field in `licenseResolution.ts` (`hyperformulaDateFieldIsWellTyped`), before the payload is read diff --git a/src/license/handsontable-license-key-parser/upstream.lock.json b/src/license/handsontable-license-key-parser/upstream.lock.json new file mode 100644 index 0000000000..8d3faf3b97 --- /dev/null +++ b/src/license/handsontable-license-key-parser/upstream.lock.json @@ -0,0 +1,48 @@ +{ + "_comment": [ + "The upstream sources this directory is ported from, pinned by commit and by content hash.", + "Machine-readable on purpose: `npm run check:vendored-parser` reads it, fetches the same files", + "from the tracked branch, and fails when they no longer hash as pinned. That is the event worth", + "catching - upstream moving on while this port stays behind. PROVENANCE.md explains the port;", + "this file is the pin.", + "", + "`track` is the branch the check compares against. It is `master` because that is the released", + "code; `develop` there is work in progress.", + "", + "Updating: re-port the changed file, then update its hash and `commit` here in the SAME commit,", + "so the diff shows the port and the pin moving together." + ], + "repository": "handsontable/license-key", + "tag": "4.0.0", + "commit": "c50ef40a6", + "directory": "src/entitlement-key", + "ported_on": "2026-08-20", + "files": [ + { + "vendored": "constants.ts", + "upstream": "constants.js", + "sha256": "6e2ad68d1a316abdec3f89bf04260a2cc4098f76525427d919f22cb25fb077d6" + }, + { + "vendored": "detectFormat.ts", + "upstream": "detect-format.js", + "sha256": "7dc037fd70e7c64078a0fe29b42cb33ecf25e8f4d8963ae9bfb16b69479d267f" + }, + { + "vendored": "extractKeyData.ts", + "upstream": "extract-key-data.js", + "sha256": "afd0858768879764ea016d2bc4fca692a0cd12214c1dfda6932d7ed9e4f32e45" + }, + { + "vendored": "utils.ts", + "upstream": "utils.js", + "sha256": "135a8396bb22f424160fc651e899931d4be807df9b94c6dd24bb1cf6526e0541" + }, + { + "vendored": "sha512.ts", + "upstream": "sha512.js", + "sha256": "668dd1109160b92965a1f9a9c5fb78dfdc1e5b7e93f635a147ae8a6bb2a5d837" + } + ], + "track": "master" +} From 568b4a1add57f643dd81815c80969b76fe82bb5d Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 09:09:40 +0000 Subject: [PATCH 17/54] =?UTF-8?q?HF-307:=20finish=20option=201=20=E2=80=94?= =?UTF-8?q?=20the=20vendored=20reader=20is=20now=20byte-identical=20to=20u?= =?UTF-8?q?pstream?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit @sequba asked three times for this and I had delivered half of it. 22.09: "Can we add exceptions to tsconfig so these files could be the byte-identical copies of the upstream?" 23.09: "The goal is (b)" — literally no local edits. 28.09: "let's implement option 1." What landed on 29.09 was only the guard move; the files stayed TypeScript ports. This morning's question — "so, now all the files inside handsontable-license-key-parser/ are byte-identical copies of upstream?" — had the answer "no", and the drift check I wrote first was a workaround for that. Now the answer is yes, and `npm run check:vendored-parser` says so by measurement: vendored parser: handsontable/license-key/src/entitlement-key @ master, 5 files ok constants.js detect-format.js extract-key-data.js utils.js sha512.js OK - every file is byte-identical to master The five `.ts` ports are replaced by upstream's `.js`, copied without a character changed, at `03810fd3c` on `master`. A hand-written `.d.ts` sits beside each one. `allowJs` is on, which is what he proposed on 22.09. The check now does what he asked for literally: it hashes OUR files, fetches the same files from the tracked branch, and compares. `upstream.lock.json` is gone. It stored a hash table, and he said we do not need to store hashes — true the moment the files are copies, because then there is nothing to store a hash of that is not already the file. `upstream.json` keeps only where the copy came from. PROVENANCE.md loses the section explaining why byte-identity was impossible and drops from 118 lines to 71. One behaviour change, deliberate, because verbatim does not get to pick. Upstream adopted the date type guard on 2026-09-28 (`6862da557`), the day before we removed ours on his instruction. Taking the file whole brings it back, which makes `hyperformulaDateFieldIsWellTyped` dead code — measured, not assumed: the same four tests fail with it and without it. Removed. Ours checked HyperFormula's own product entry only, on the grounds that another product's fields were not ours to reject. Upstream's lives in the parser and applies to every entry, so a mistyped date in a DataGrid entry now invalidates the whole key, our grant included. That is upstream's rule and the key spec's (T7). Four tests are rewritten to it, with the reversal named in a comment so the next reader meets it in the suite rather than in a support ticket. Two mechanical consequences of shipping JavaScript from `src/`: - Jest transformed only `.ts`, so the ES modules went to Node raw and every licence suite died on the first `export`. The transform now covers `.js`. - ESLint produced 216 errors, all of them upstream's semicolons. `--fix` would edit the files, which is the one thing they must not have, so the directory joins `3rdparty` in `.eslintignore`. The `.d.ts` beside them are ours and stay linted. Verified: full suite 517/517 · 6551 passed · 3 skipped · 0 failed; `tsc --noEmit` clean; `npm run lint` on `src` 0 errors; `npm run bundle-all` green — four UMD bundles, commonjs and the publish-package check. The drift check was broken three ways on purpose and caught each: a local edit, an unaccounted `.js`, a missing file. Co-Authored-By: Claude Opus 5 (1M context) --- .eslintignore | 5 + jest.config.js | 5 +- script/check-vendored-parser.js | 88 +++--- .../PROVENANCE.md | 114 +++---- .../constants.d.ts | 15 + .../constants.js | 22 ++ .../constants.ts | 28 -- .../detect-format.d.ts | 25 ++ .../detect-format.js | 57 ++++ .../detectFormat.ts | 70 ----- .../extract-key-data.d.ts | 40 +++ .../extract-key-data.js | 242 +++++++++++++++ .../extractKeyData.ts | 280 ------------------ .../sha512.d.ts | 17 ++ .../{sha512.ts => sha512.js} | 231 +++++++-------- .../upstream.json | 18 ++ .../upstream.lock.json | 48 --- .../utils.d.ts | 53 ++++ .../handsontable-license-key-parser/utils.js | 250 ++++++++++++++++ .../handsontable-license-key-parser/utils.ts | 218 -------------- src/license/licenseResolution.ts | 43 +-- tsconfig.json | 2 +- 22 files changed, 941 insertions(+), 930 deletions(-) create mode 100644 src/license/handsontable-license-key-parser/constants.d.ts create mode 100644 src/license/handsontable-license-key-parser/constants.js delete mode 100644 src/license/handsontable-license-key-parser/constants.ts create mode 100644 src/license/handsontable-license-key-parser/detect-format.d.ts create mode 100644 src/license/handsontable-license-key-parser/detect-format.js delete mode 100644 src/license/handsontable-license-key-parser/detectFormat.ts create mode 100644 src/license/handsontable-license-key-parser/extract-key-data.d.ts create mode 100644 src/license/handsontable-license-key-parser/extract-key-data.js delete mode 100644 src/license/handsontable-license-key-parser/extractKeyData.ts create mode 100644 src/license/handsontable-license-key-parser/sha512.d.ts rename src/license/handsontable-license-key-parser/{sha512.ts => sha512.js} (56%) create mode 100644 src/license/handsontable-license-key-parser/upstream.json delete mode 100644 src/license/handsontable-license-key-parser/upstream.lock.json create mode 100644 src/license/handsontable-license-key-parser/utils.d.ts create mode 100644 src/license/handsontable-license-key-parser/utils.js delete mode 100644 src/license/handsontable-license-key-parser/utils.ts diff --git a/.eslintignore b/.eslintignore index 03546876e2..feedf112c3 100644 --- a/.eslintignore +++ b/.eslintignore @@ -7,6 +7,11 @@ docs/examples/ # 3rd party src/interpreter/plugin/3rdparty +# Byte-identical copies of handsontable/license-key - see PROVENANCE.md in that directory. +# Linting them would mean editing them, and editing them is the one thing they must not have. +# The hand-written .d.ts beside them are ours and ARE linted. +src/license/handsontable-license-key-parser/*.js + # Configurations *.config.js karma.* diff --git a/jest.config.js b/jest.config.js index 4b667a3960..7315e870b7 100644 --- a/jest.config.js +++ b/jest.config.js @@ -48,7 +48,10 @@ module.exports = { // A map from regular expressions to paths to transformers transform: { - "^.+\\.(ts|tsx)$": "ts-jest" + // `.js` is here for the vendored entitlement-key reader, which is upstream JavaScript copied + // verbatim (see src/license/handsontable-license-key-parser/PROVENANCE.md). It is ES modules, + // so without a transform Jest hands it to Node and fails on the first `export`. + "^.+\\.(ts|tsx|js)$": "ts-jest" }, watchPathIgnorePatterns: [ diff --git a/script/check-vendored-parser.js b/script/check-vendored-parser.js index 66c76ac4f1..68ce98daa1 100755 --- a/script/check-vendored-parser.js +++ b/script/check-vendored-parser.js @@ -5,24 +5,20 @@ */ /* - * Checks the vendored entitlement-key reader against the upstream sources it was ported from. + * Checks the vendored entitlement-key reader against the upstream it was copied from. * - * `src/license/handsontable-license-key-parser/` mirrors `handsontable/license-key`. A local-only - * fix there silently forks the two copies, and a forked checksum or parser rejects genuine - * customer keys - so the pin has to be verified by measurement, not by someone remembering to look. + * `src/license/handsontable-license-key-parser/*.js` are byte-identical copies of + * `handsontable/license-key`. A local edit silently forks the two, and a forked checksum or parser + * rejects genuine customer keys - so the copies are verified by measurement, not by trust. * - * What it does: reads `upstream.lock.json`, fetches each upstream file from the branch it tracks - * (`master` - the released code, not the work in progress on `develop`), and compares its sha256 - * against the recorded one. A mismatch means upstream moved on while this port stayed behind. + * What it does: hashes each file in that directory, fetches the same file from the branch + * `upstream.json` tracks (`master` - the released code, not the work in progress on `develop`), + * hashes that, and compares. Any difference is reported, in either direction: a local edit and an + * upstream change look the same here, and both mean the copy has to be retaken. * - * It deliberately does NOT fetch at the pinned commit. A commit is immutable, so that check would - * pass forever and catch nothing - which is how a real change to `utils.js` sat unnoticed for two - * days. The pin is what we compare against; the branch is what we compare. - * - * What it deliberately does NOT do: compare our files to upstream byte for byte. They are - * TypeScript ports of JavaScript sources - `allowJs` is off and `strict` is on - so their bytes - * cannot match, and a check that pretended otherwise would fail for a reason that is never drift. - * PROVENANCE.md lists the shape differences a reviewer should expect. + * It compares against the BRANCH, not the recorded commit. A commit is immutable, so comparing + * against it would pass forever and catch nothing - which is how a real change to `utils.js` sat + * unnoticed for two days. * * Usage: * npm run check:vendored-parser @@ -40,7 +36,8 @@ const crypto = require('crypto') const https = require('https') const {execFileSync} = require('child_process') -const LOCK = path.resolve(__dirname, '../src/license/handsontable-license-key-parser/upstream.lock.json') +const DIR = path.resolve(__dirname, '../src/license/handsontable-license-key-parser') +const PIN = path.join(DIR, 'upstream.json') function token() { const fromEnv = process.env.LICENSE_KEY_REPO_TOKEN || process.env.GH_TOKEN || process.env.GITHUB_TOKEN @@ -86,65 +83,64 @@ function fetchFile(repo, filePath, ref, auth) { } async function main() { - const lock = JSON.parse(fs.readFileSync(LOCK, 'utf8')) + const pin = JSON.parse(fs.readFileSync(PIN, 'utf8')) const auth = token() - console.log(`vendored parser: pinned to ${lock.repository}@${lock.commit}, checked against ${lock.track}`) + console.log(`vendored parser: ${pin.repository}/${pin.directory} @ ${pin.track}, ${pin.files.length} files`) if (auth === null) { console.error('\nFAIL no credentials for a private repository.') console.error(' Set LICENSE_KEY_REPO_TOKEN (or GH_TOKEN / GITHUB_TOKEN), or run `gh auth login`.') - console.error(' Failing rather than skipping: an unverified pin is not a verified one.') + console.error(' Failing rather than skipping: an unverified copy is not a verified one.') process.exit(1) } const problems = [] + const hash = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex') - for (const entry of lock.files) { - const upstreamPath = `${lock.directory}/${entry.upstream}` - let actual - - try { - const body = await fetchFile(lock.repository, upstreamPath, lock.track, auth) + for (const name of pin.files) { + const local = path.join(DIR, name) - actual = crypto.createHash('sha256').update(body).digest('hex') - } catch (error) { - problems.push(`${entry.upstream}: could not be read (${error.message})`) - console.log(` ???? ${entry.upstream}`) + if (!fs.existsSync(local)) { + problems.push(`${name}: named in upstream.json and missing from the directory`) + console.log(` GONE ${name}`) continue } - if (actual === entry.sha256) { - console.log(` ok ${entry.upstream}`) - } else { - problems.push(`${entry.upstream}: ${lock.track} is ${actual}, the pin says ${entry.sha256}`) - console.log(` DRIFT ${entry.upstream}`) + let theirs + + try { + theirs = hash(await fetchFile(pin.repository, `${pin.directory}/${name}`, pin.track, auth)) + } catch (error) { + problems.push(`${name}: upstream could not be read (${error.message})`) + console.log(` ???? ${name}`) + continue } - const vendored = path.resolve(path.dirname(LOCK), entry.vendored) + const ours = hash(fs.readFileSync(local)) - if (!fs.existsSync(vendored)) { - problems.push(`${entry.vendored}: named in the lock file and missing from the directory`) + if (ours === theirs) { + console.log(` ok ${name}`) + } else { + problems.push(`${name}: this copy is ${ours}, ${pin.track} is ${theirs}`) + console.log(` DIFF ${name}`) } } - const vendoredFiles = fs.readdirSync(path.dirname(LOCK)).filter((name) => name.endsWith('.ts')) - const pinned = lock.files.map((entry) => entry.vendored) - - vendoredFiles.filter((name) => pinned.indexOf(name) === -1).forEach((name) => { - problems.push(`${name}: present in the directory and named nowhere in the lock file, so nothing pins it`) - }) + fs.readdirSync(DIR) + .filter((name) => name.endsWith('.js') && pin.files.indexOf(name) === -1) + .forEach((name) => problems.push(`${name}: a JavaScript file nothing in upstream.json accounts for`)) if (problems.length === 0) { - console.log(`\nOK - ${lock.track} still matches the pin`) + console.log(`\nOK - every file is byte-identical to ${pin.track}`) return } console.error(`\n${problems.length} problem(s):`) problems.forEach((problem) => console.error(` ${problem}`)) - console.error(`\nUpstream ${lock.track} has moved on, or the directory and the pin disagree.`) - console.error('Re-port the changed file and update upstream.lock.json in the same commit.') + console.error('\nThe copies and upstream have diverged - either upstream moved, or something was') + console.error('edited here. Re-take the files and update upstream.json in the same commit.') process.exit(1) } diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 6981dd4625..ef022616a2 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -1,54 +1,50 @@ -# Vendored entitlement-key reader — provenance and drift control +# Vendored entitlement-key reader -The files in this directory are a **TypeScript port of code owned by another Handsoncode -repository**, not original HyperFormula code. Treat them as a mirror: fix bugs upstream first, -then re-port. A local-only fix here silently forks the two copies, and a forked checksum or -parser rejects genuine customer keys. +The `.js` files in this directory are **byte-identical copies** of code owned by another +Handsoncode repository. They are not edited here, ever: fix a bug upstream, then re-take the copy. +A local-only fix forks the two, and a forked checksum or parser rejects genuine customer keys. -## Upstream +The `.d.ts` beside each one is HyperFormula's, hand-written, because `allowJs` is on and the +JavaScript carries no types of its own. | | | |---|---| | Repository | `handsontable/license-key` (private) | -| Tag | `4.0.0` | -| Commit | `c50ef40a6` (the `4.0.0` release commit; on `develop` as `1acddafa8`) | -| Ported on | 2026-08-20 | -| Reference docs | the format and design notes kept alongside the upstream sources; the byte-level rules are also specified in the key spec's "Technical implementation" addendum (T1-T14) | +| Directory | `src/entitlement-key` | +| Tracked branch | `master` - the released code; `develop` there is work in progress | +| Copy taken from | `03810fd3c` (2026-09-28) | -## Port, not copy — and what that means for drift - -These files are **TypeScript ports of upstream's JavaScript**, not byte-identical copies, and they -cannot be copies while `allowJs` is off and `strict` is on in `tsconfig.json`. A `.ts` file and the -`.js` it was ported from never share a hash, so "compare our bytes to upstream's" is not a check -that can exist in this shape. What differs is listed under *Deliberate divergences* below; none of -it changes which keys are accepted. - -What IS checked, by measurement rather than by someone remembering to look: +## Checking it ```bash npm run check:vendored-parser ``` -It reads `upstream.lock.json` — the pin: the commit, and a sha256 per upstream file — fetches each -file at that commit and compares. A mismatch means **upstream moved**, which is the event that -matters: it is the moment this port stops mirroring the code it is supposed to mirror. The script -also fails if a file is in the directory without being pinned, or pinned without being present. +Hashes every file here and the same file on `master`, and fails on any difference. A local edit +and an upstream change look identical to it, which is the point: either means the copy is stale. +It also fails on a `.js` that `upstream.json` does not account for, and on one it names that is +missing. + +It needs read access to the private repository (`LICENSE_KEY_REPO_TOKEN`, `GH_TOKEN`, +`GITHUB_TOKEN`, or a logged-in `gh`). Without credentials it **fails** rather than skipping: a +check that reports success when it could not look is worse than no check. + +When upstream moves, re-take the changed file and update `upstream.json` in the same commit. -It needs read access to the private repository, through `LICENSE_KEY_REPO_TOKEN`, `GH_TOKEN`, -`GITHUB_TOKEN` or a logged-in `gh`. Without credentials it **fails** rather than passing quietly: -an unverified pin is not a verified one, and a check that reports success when it could not look is -worse than no check. +## What the last re-take changed -When upstream moves: re-port the changed file and update its hash in `upstream.lock.json` in the -same commit, so the diff shows the two together. +`6862da557` (2026-09-28) made `parseIsoDate` test `typeof isoDate === 'string'` before matching the +pattern, so a `usage_until` of `['2099-12-31']` - which stringifies to a valid date - is now +rejected by the reader instead of accepted. -### If byte-identity is wanted +HyperFormula used to carry that check itself, next door in `licenseResolution.ts`, because upstream +did not have it. That local check is gone: it became dead code the moment this copy was taken. -It is reachable, and it is the remaining half of option 1: vendor upstream's `.js` verbatim, turn -`allowJs` on, and hand-write a `.d.ts` per file. The check then becomes a direct hash of our own -files, with no lock table at all. Measured as compatible with this repository's TypeScript -(4.0.8 accepts `allowJs` together with `declaration`). It is a build-configuration change, so it -is not made here without a decision. +One behaviour changed with it, deliberately. The local check looked at HyperFormula's own product +entry only, on the grounds that another product's fields were not ours to reject. Upstream's check +is in the parser, so it applies to every entry: a mistyped date in a DataGrid entry now invalidates +the whole key, our grant included. That is upstream's rule and the key specification's (T7), and it +is pinned in `entitlement-key-resolution.spec.ts`. ## Not vendored, on purpose @@ -63,51 +59,9 @@ vendored surface small: everything schema- and generation-side stays out. | `create-engine.js`, `resolve-schema.js`, `validate-schema.js`, `validate-record.js` | Bind and verify a caller's schema/record at generation time — generator-side. | | `validate-key.js` | A two-line boolean wrapper over `extractEntitlementKeyData`; the extractor is called directly. | -From `utils.js`, the two generation-side helpers `bytesToBase64` and `stringToBase64Url` are -also left out. Everything else in that file is ported. - -## Deliberate divergences from upstream - -`allowJs` is off in HyperFormula's `tsconfig.json` and `strict` is on, so these files are a port -rather than a copy. Beyond adding types, the semantics are identical to upstream's; the notes below are the shape of -the port, not changes to what it accepts, and a drift review should expect to see them: - -1. **`detectFormat.ts` keeps its literals in a `Map`,** where upstream uses an object literal - behind a `hasOwnProperty` guard. Same behaviour for every input (including `constructor` and - `__proto__`); the `Map` is this repository's idiom for lookups keyed by untrusted strings. -2. **`stringToUtf8Bytes`'s parameter is named `text`, not `string`,** which is a type keyword in - TypeScript. -3. **The normalized product entry is typed** (`EntitlementProductGrant`), which upstream's plain - JavaScript does not do. The types state what the reader CHECKS, and the checks are upstream's: - `capabilities` and `flags` are verified element by element, and `notice` and `grace` are verified - as non-negative integers. Everything the reader does not verify — unknown fields are preserved on - purpose — sits behind an `unknown`-valued index signature, so consumers must narrow before use. -4. **`isIsoDate` takes `String(value)`, as upstream does, and the type check lives outside.** - Upstream matches `String(value)` against `YYYY-MM-DD`, so a `usage_until` that is a - single-element array of the right string passes its shape check and the declared `string` type - ends up wider than the value. The key spec's addendum (T7) makes the field a real calendar date, - so the stricter reading is the specified one. - - **Upstream has since adopted it.** Commit `6862da557` on `master` (2026-09-28, DEV-3031) changed - `parseIsoDate` to `typeof isoDate === 'string' ? … : null`, with the same reasoning. An earlier - revision of this file said upstream had not adopted it and that no pull request proposed it; - that was true when written and is not true now — `npm run check:vendored-parser` is what found - it, on its first run against `master`. - - So this divergence is on its way out, and re-porting `utils.js` closes it. One thing to decide - with the re-port rather than sleepwalk into: upstream's check rejects the WHOLE key when any - product's date is mistyped, while `hyperformulaDateFieldIsWellTyped` deliberately only takes the - invalid-key path for HyperFormula's own entry, on the grounds that another product's fields are - not ours to validate. Re-porting reverses that choice. - - Rather than fork upstream's source over it, HyperFormula checks the TYPE of its own entry's date - field in `licenseResolution.ts` (`hyperformulaDateFieldIsWellTyped`), before the payload is read - for terms, and a non-string there takes the invalid-key path. The behaviour a customer sees is - the same as when the check lived here; what changed is that this file no longer diverges, so a - drift review compares it to upstream byte for byte instead of reasoning about a patch. - -Upstream's `/* eslint-disable */` pragmas were dropped where HyperFormula's own ESLint config -does not need them. +`utils.js` is taken whole, so its two generation-side helpers `bytesToBase64` and +`stringToBase64Url` come with it. Nothing in HyperFormula calls them; a verbatim copy does not get +to pick which exports it keeps. ## Related diff --git a/src/license/handsontable-license-key-parser/constants.d.ts b/src/license/handsontable-license-key-parser/constants.d.ts new file mode 100644 index 0000000000..bac6b3813e --- /dev/null +++ b/src/license/handsontable-license-key-parser/constants.d.ts @@ -0,0 +1,15 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Hand-written declarations for `constants.js`, which is a verbatim copy of upstream. + * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. + */ + +/** The length in characters of the checksum segment that closes an entitlement key's block. */ +export const ENTITLEMENT_KEY_CHECKSUM_LENGTH: 128 + +/** The two mutually exclusive date fields a product entry may carry. */ +export const DATE_FIELDS: readonly string[] diff --git a/src/license/handsontable-license-key-parser/constants.js b/src/license/handsontable-license-key-parser/constants.js new file mode 100644 index 0000000000..99a1152a90 --- /dev/null +++ b/src/license/handsontable-license-key-parser/constants.js @@ -0,0 +1,22 @@ +/** + * The length of the checksum (SHA-512 as hex) which postfixes the payload + * inside the machine-readable block of every entitlement license key. + * + * @type {number} + */ +export const ENTITLEMENT_KEY_CHECKSUM_LENGTH = 128; +/** + * The two mutually exclusive date fields of a product entry. Exactly one of + * them has to be present: + * + * - "usage_until" the last licensed day (inclusive, compared in UTC), + * - "release_until" builds released on or before that day may be used + * forever (compared against the build release date as + * text, no clock involved). + * + * The pair replaces the contract type - nothing in the payload says + * "subscription" or "perpetual". + * + * @type {string[]} + */ +export const DATE_FIELDS = ['usage_until', 'release_until']; diff --git a/src/license/handsontable-license-key-parser/constants.ts b/src/license/handsontable-license-key-parser/constants.ts deleted file mode 100644 index 270be27fe1..0000000000 --- a/src/license/handsontable-license-key-parser/constants.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Vendored from `handsontable/license-key`, `src/entitlement-key/constants.js`. - * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. - */ - -/** - * The length of the checksum (SHA-512 as hex) which postfixes the payload inside the - * machine-readable block of every entitlement license key. - */ -export const ENTITLEMENT_KEY_CHECKSUM_LENGTH = 128 - -/** - * The two mutually exclusive date fields of a product entry. Exactly one of them has to be - * present: - * - * - `usage_until` — the last licensed day (inclusive, compared in UTC), - * - `release_until` — builds released on or before that day may be used forever (compared - * against the build release date as text, no clock involved). - * - * The pair replaces the contract type — nothing in the payload says "subscription" or - * "perpetual". - */ -export const DATE_FIELDS: readonly string[] = ['usage_until', 'release_until'] diff --git a/src/license/handsontable-license-key-parser/detect-format.d.ts b/src/license/handsontable-license-key-parser/detect-format.d.ts new file mode 100644 index 0000000000..993247c7d1 --- /dev/null +++ b/src/license/handsontable-license-key-parser/detect-format.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Hand-written declarations for `detect-format.js`, which is a verbatim copy of upstream. + * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. + */ + +/** Which of the licence-key shapes a string is, before anything is decoded. */ +export type LicenseKeyFormat = + | 'entitlement' + | 'legacy' + | 'non-commercial-and-evaluation' + | 'gpl-v3' + | 'unknown' + +/** + * Classifies a licence key by shape alone. A garbage bracketed block still answers + * `'entitlement'`, so the caller routes it to the entitlement validator and gets INVALID there. + * + * @param {unknown} licenseKey - the value to classify; anything at all, including a non-string + */ +export function detectLicenseKeyFormat(licenseKey: unknown): LicenseKeyFormat diff --git a/src/license/handsontable-license-key-parser/detect-format.js b/src/license/handsontable-license-key-parser/detect-format.js new file mode 100644 index 0000000000..3ea5ce4682 --- /dev/null +++ b/src/license/handsontable-license-key-parser/detect-format.js @@ -0,0 +1,57 @@ +/** + * The literal keys that stand for a licence rather than encode one. + * + * @type {object} + */ +const LITERAL_KEYS = { + 'non-commercial-and-evaluation': 'non-commercial-and-evaluation', + 'gpl-v3': 'gpl-v3', +}; +/** + * The classic 25-character key, once its dashes are stripped. + * + * @type {RegExp} + */ +const LEGACY_KEY = /^[0-9a-fA-F]{25}$/; + +/** + * Tells which license key format a string is in, without validating it. + * + * The entitlement key format removed the leading type tag, so a key no longer + * announces itself in its first characters - it now ends with the bracketed + * machine-readable block instead. Products that accept several formats need + * one place that makes the distinction, and this is it. + * + * The answer is about SHAPE only. A returned "entitlement" means "route this + * to the entitlement validator", not "this key is valid". + * + * @param {string} licenseKey The license key to inspect. + * @returns {string} One of: "entitlement", "legacy", + * "non-commercial-and-evaluation", "gpl-v3", "unknown". + */ +/* eslint-disable import/prefer-default-export */ +export function detectLicenseKeyFormat(licenseKey) { + if (typeof licenseKey !== 'string') { + return 'unknown'; + } + + const key = licenseKey.trim(); + + if (Object.prototype.hasOwnProperty.call(LITERAL_KEYS, key.toLowerCase())) { + return LITERAL_KEYS[key.toLowerCase()]; + } + + // The bracketed block closes an entitlement key. Its presence is what + // separates the new format from everything else, so it is checked before + // the shape-based ones. + const blockStart = key.lastIndexOf('['); + + if (blockStart !== -1 && key.indexOf(']', blockStart) !== -1) { + return 'entitlement'; + } + if (LEGACY_KEY.test(key.replace(/-/g, ''))) { + return 'legacy'; + } + + return 'unknown'; +} diff --git a/src/license/handsontable-license-key-parser/detectFormat.ts b/src/license/handsontable-license-key-parser/detectFormat.ts deleted file mode 100644 index 183afc66e1..0000000000 --- a/src/license/handsontable-license-key-parser/detectFormat.ts +++ /dev/null @@ -1,70 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Vendored from `handsontable/license-key`, `src/entitlement-key/detect-format.js`. - * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. - */ - -/** - * The name of each license key format {@link detectLicenseKeyFormat} can answer with. - */ -export type LicenseKeyFormat = - | 'entitlement' - | 'legacy' - | 'non-commercial-and-evaluation' - | 'gpl-v3' - | 'unknown' - -/** - * The literal keys that stand for a licence rather than encode one. - */ -const LITERAL_KEYS: ReadonlyMap = new Map([ - ['non-commercial-and-evaluation', 'non-commercial-and-evaluation'], - ['gpl-v3', 'gpl-v3'], -]) - -/** - * The classic 25-character key, once its dashes are stripped. - */ -const LEGACY_KEY = /^[0-9a-fA-F]{25}$/ - -/** - * Tells which license key format a string is in, without validating it. - * - * The entitlement key format removed the leading type tag, so a key no longer announces itself - * in its first characters — it now ends with the bracketed machine-readable block instead. - * Products that accept several formats need one place that makes the distinction, and this is it. - * - * The answer is about SHAPE only. A returned `'entitlement'` means "route this to the - * entitlement validator", not "this key is valid". - * - * @param {unknown} licenseKey - the license key to inspect - */ -export function detectLicenseKeyFormat(licenseKey: unknown): LicenseKeyFormat { - if (typeof licenseKey !== 'string') { - return 'unknown' - } - - const key = licenseKey.trim() - const literal = LITERAL_KEYS.get(key.toLowerCase()) - - if (literal !== undefined) { - return literal - } - - // The bracketed block closes an entitlement key. Its presence is what separates the new format - // from everything else, so it is checked before the shape-based ones. - const blockStart = key.lastIndexOf('[') - - if (blockStart !== -1 && key.indexOf(']', blockStart) !== -1) { - return 'entitlement' - } - if (LEGACY_KEY.test(key.replace(/-/g, ''))) { - return 'legacy' - } - - return 'unknown' -} diff --git a/src/license/handsontable-license-key-parser/extract-key-data.d.ts b/src/license/handsontable-license-key-parser/extract-key-data.d.ts new file mode 100644 index 0000000000..86613c9186 --- /dev/null +++ b/src/license/handsontable-license-key-parser/extract-key-data.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Hand-written declarations for `extract-key-data.js`, which is a verbatim copy of upstream. + * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. + */ + +/** + * One product's terms, as the reader normalizes them. + * + * The declared members are the ones the reader VERIFIES: `capabilities` and `flags` element by + * element, `notice` and `grace` as non-negative integers, and exactly one of the two date fields. + * Everything it does not verify - unknown fields are preserved on purpose - sits behind the index + * signature, so a consumer has to narrow before using it. + */ +export interface EntitlementProductGrant { + readonly capabilities: readonly string[], + readonly usage_until?: string, + readonly release_until?: string, + readonly notice: number, + readonly grace: number, + readonly flags: readonly string[], + readonly [field: string]: unknown, +} + +/** The machine-readable content of an intact entitlement key: the granted products and their terms. */ +export interface EntitlementKeyData { + readonly products: Readonly>, +} + +/** + * Reads an entitlement key: finds the bracketed block, verifies the checksum before decoding + * anything, then normalizes the payload. `null` when the envelope or the payload is not intact. + * + * @param {string} licenseKey - the whole licence artifact or the bare block + */ +export function extractEntitlementKeyData(licenseKey: string): EntitlementKeyData | null diff --git a/src/license/handsontable-license-key-parser/extract-key-data.js b/src/license/handsontable-license-key-parser/extract-key-data.js new file mode 100644 index 0000000000..1dcf5d765d --- /dev/null +++ b/src/license/handsontable-license-key-parser/extract-key-data.js @@ -0,0 +1,242 @@ +import { ENTITLEMENT_KEY_CHECKSUM_LENGTH, DATE_FIELDS } from './constants'; +import { sha512 } from './sha512'; +import { base64ToString, parseIsoDate, stringToUtf8Bytes } from './utils'; + +/** + * The alphabet of the encoded payload - URL-safe base64 without padding. + * The checksum (lowercase hex) is a subset of it, which is what lets the two + * be split by a fixed length from the right. + * + * @type {RegExp} + */ +const ENCODED_PAYLOAD = /^[A-Za-z0-9\-_]+$/; +const CHECKSUM = /^[0-9a-f]+$/; + +/** + * Returns `true` when the value is a plain object. + * + * @param {*} value The value to check. + * @returns {boolean} + */ +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * Returns `true` when the value is a non-negative integer. + * + * @param {*} value The value to check. + * @returns {boolean} + */ +function isNonNegativeInteger(value) { + return typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value && value >= 0; +} + +/** + * Returns `true` when the value is an array of strings. + * + * @param {*} value The value to check. + * @returns {boolean} + */ +function isStringArray(value) { + return Array.isArray(value) && value.every((item) => typeof item === 'string'); +} + +/** + * Returns `true` when the value is a real calendar date in the "YYYY-MM-DD" + * format. A time component, an offset, a numeric timestamp and a date that + * does not exist are all rejected - the format is the whole contract, and a + * validator that accepted two spellings would hide a timezone bug at + * generation instead of surfacing it. + * + * @param {*} value The value to check. + * @returns {boolean} + */ +function isIsoDate(value) { + try { + parseIsoDate(value, 'license'); + + return true; + } catch (error) { + return false; + } +} + +/** + * Adds an own, ordinary property. + * + * Both the product names and the field names of a product entry come from + * JSON, so "__proto__" is a name an attacker can put in a key. A plain + * assignment would go through the Object.prototype setter: the value would + * vanish from Object.keys while still resolving through the chain. + * + * @param {object} target The object to add the property to. + * @param {string} key The property name. + * @param {*} value The property value. + */ +function defineOwn(target, key, value) { + Object.defineProperty(target, key, { + value, enumerable: true, writable: true, configurable: true, + }); +} + +/** + * Verifies and normalizes one product entry. + * + * Strict about SHAPE: exactly one of the two dates, a real date, and the two + * window sizes. A key that gets this wrong is malformed, not merely unknown, + * and reading it would mean guessing what was licensed. + * + * Lenient about VOCABULARY: an unrecognised capability token, an unrecognised + * flag and an unrecognised extra field are all kept and ignored. Without that + * leniency every token added on the issuing side would break every library + * version already deployed in the field. + * + * Returns `null` when the entry is malformed. + * + * @param {*} entry The product entry of the payload. + * @returns {object|null} + */ +function normalizeProductEntry(entry) { + if (!isPlainObject(entry)) { + return null; + } + if (!isStringArray(entry.capabilities)) { + return null; + } + + const presentDateFields = DATE_FIELDS.filter((field) => entry[field] !== undefined); + + // Exactly one date per product. "Both" and "neither" are each a different + // commercial shape that the format cannot express, so neither may be + // silently resolved by whichever field the parser happens to read first. + if (presentDateFields.length !== 1) { + return null; + } + if (!isIsoDate(entry[presentDateFields[0]])) { + return null; + } + if (!isNonNegativeInteger(entry.notice) || !isNonNegativeInteger(entry.grace)) { + return null; + } + if (entry.flags !== undefined && !isStringArray(entry.flags)) { + return null; + } + + // Start from everything the entry carries, so a field this version does not + // know survives into the result instead of being silently dropped. A field + // added to the format later is exactly the case an already-vendored parser + // has to survive, and a reader that quietly discards it makes the field + // invisible to the application on top. + const normalized = {}; + + Object.keys(entry).forEach((field) => defineOwn(normalized, field, entry[field])); + + defineOwn(normalized, 'capabilities', entry.capabilities.slice()); + defineOwn(normalized, 'notice', entry.notice); + defineOwn(normalized, 'grace', entry.grace); + // An absent array and an empty one mean the same thing. Normalizing here + // keeps `flags.indexOf('trial')` safe at every call site. + defineOwn(normalized, 'flags', entry.flags === undefined ? [] : entry.flags.slice()); + defineOwn(normalized, presentDateFields[0], entry[presentDateFields[0]]); + + return normalized; +} + +/** + * Extracts the machine-readable data from an entitlement license key. + * + * The checksum is verified first, so the returned data is guaranteed to + * belong to an intact block. For a malformed or tampered key `null` is + * returned - reporting an invalid key is the caller's job, not this + * function's. + * + * Only the bracketed block matters. The prose in front of it is neither + * parsed nor covered by the checksum, so the caller may pass the whole + * artifact or just the `[...]` block, and rewrapped or re-pasted text still + * validates. + * + * No schema is needed. Unknown products, capabilities and flags are all + * tolerated, so nothing about reading a key depends on the vocabulary - which + * is what lets a product vendor this parser on its own. + * + * @param {string} licenseKey The license key to extract the data from. + * @returns {{ products: object }|null} The granted products, each with its + * capabilities, its single date (`usage_until` or `release_until`), + * its `notice` and `grace` windows in days, and its `flags`. + */ +/* eslint-disable import/prefer-default-export */ +export function extractEntitlementKeyData(licenseKey) { + if (typeof licenseKey !== 'string') { + return null; + } + + // The machine-readable block closes the key. Searching backwards means a + // bracket inside the prose cannot shadow it. + const blockStart = licenseKey.lastIndexOf('['); + + if (blockStart === -1) { + return null; + } + + const blockEnd = licenseKey.indexOf(']', blockStart); + + if (blockEnd === -1) { + return null; + } + + const content = licenseKey.slice(blockStart + 1, blockEnd); + + if (content.length <= ENTITLEMENT_KEY_CHECKSUM_LENGTH) { + return null; + } + + const encodedPayload = content.slice(0, -ENTITLEMENT_KEY_CHECKSUM_LENGTH); + const checksum = content.slice(-ENTITLEMENT_KEY_CHECKSUM_LENGTH); + + if (!ENCODED_PAYLOAD.test(encodedPayload) || !CHECKSUM.test(checksum)) { + return null; + } + if (sha512(stringToUtf8Bytes(encodedPayload)) !== checksum) { + return null; + } + + const payloadJson = base64ToString(encodedPayload); + + if (payloadJson === null) { + return null; + } + + let payload; + + try { + payload = JSON.parse(payloadJson); + } catch (error) { + return null; + } + + if (!isPlainObject(payload) || !isPlainObject(payload.products)) { + return null; + } + + const products = {}; + let malformed = false; + + Object.keys(payload.products).forEach((name) => { + const entry = normalizeProductEntry(payload.products[name]); + + if (entry === null) { + malformed = true; + + return; + } + + defineOwn(products, name, entry); + }); + + if (malformed) { + return null; + } + + return { products }; +} diff --git a/src/license/handsontable-license-key-parser/extractKeyData.ts b/src/license/handsontable-license-key-parser/extractKeyData.ts deleted file mode 100644 index c0b4979cf4..0000000000 --- a/src/license/handsontable-license-key-parser/extractKeyData.ts +++ /dev/null @@ -1,280 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Vendored from `handsontable/license-key`, `src/entitlement-key/extract-key-data.js`. - * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. - * - * Unlike the typed-key reader this file replaces, the entitlement reader is deliberately - * SCHEMA-FREE upstream: unknown products, capabilities and flags are all tolerated, so nothing - * about reading a key depends on the vocabulary — which is what lets a product vendor this - * parser on its own. - */ - -import {DATE_FIELDS, ENTITLEMENT_KEY_CHECKSUM_LENGTH} from './constants' -import {sha512} from './sha512' -import {base64ToString, parseIsoDate, stringToUtf8Bytes} from './utils' - -/** - * The alphabet of the encoded payload — URL-safe base64 without padding. The checksum (lowercase - * hex) is a subset of it, which is what lets the two be split by a fixed length from the right. - */ -const ENCODED_PAYLOAD = /^[A-Za-z0-9\-_]+$/ -const CHECKSUM = /^[0-9a-f]+$/ - -/** - * One normalized product entry of an entitlement key payload. - * - * The named fields are guaranteed by {@link normalizeProductEntry}: `capabilities` and `flags` - * are arrays of strings (`flags` normalized to `[]` when absent), `notice` and `grace` are - * non-negative integers, and exactly one of `usage_until` / `release_until` is present and is a - * real `YYYY-MM-DD` calendar date. Any OTHER field the entry carries is preserved verbatim under - * its own name — a field added to the format later must reach an application running an older - * vendored parser — which is what the index signature is for. - */ -export interface EntitlementProductGrant { - readonly capabilities: readonly string[], - readonly usage_until?: string, - readonly release_until?: string, - readonly notice: number, - readonly grace: number, - readonly flags: readonly string[], - readonly [field: string]: unknown, -} - -/** - * The machine-readable content of an intact entitlement license key: the granted products, each - * with its capabilities, its single date (`usage_until` or `release_until`), its `notice` and - * `grace` windows in days, and its `flags`. - */ -export interface EntitlementKeyData { - readonly products: Readonly>, -} - -/** - * Returns `true` when the value is a plain object. - * - * @param {unknown} value - the value to check - */ -function isPlainObject(value: unknown): value is Record { - return value !== null && typeof value === 'object' && !Array.isArray(value) -} - -/** - * Returns `true` when the value is a non-negative integer. - * - * @param {unknown} value - the value to check - */ -function isNonNegativeInteger(value: unknown): value is number { - return typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value && value >= 0 -} - -/** - * Returns `true` when the value is an array of strings. - * - * @param {unknown} value - the value to check - */ -function isStringArray(value: unknown): value is string[] { - return Array.isArray(value) && value.every((item) => typeof item === 'string') -} - -/** - * Returns `true` when the value SPELLS a real calendar date in the `YYYY-MM-DD` format. A time - * component, an offset, a numeric timestamp and a date that does not exist are all rejected — - * the format is the whole contract, and a validator that accepted two spellings would hide a - * timezone bug at generation instead of surfacing it. - * - * Shape only, and deliberately so: the value is stringified first, exactly as upstream does, so a - * non-string that spells a date once stringified passes here. HyperFormula's own type check for - * that lives in `licenseResolution.ts`, outside this vendored copy — see - * `hyperformulaDateFieldIsWellTyped` there, and the divergence table in `PROVENANCE.md`. - * - * @param {unknown} value - the value to check - */ -function isIsoDate(value: unknown): boolean { - try { - parseIsoDate(String(value), 'license') - - return true - } catch (error) { - return false - } -} - -/** - * Adds an own, ordinary property. - * - * Both the product names and the field names of a product entry come from JSON, so `__proto__` - * is a name an attacker can put in a key. A plain assignment would go through the - * `Object.prototype` setter: the value would vanish from `Object.keys` while still resolving - * through the chain. - * - * @param {object} target - the object to add the property to - * @param {string} key - the property name - * @param {unknown} value - the property value - */ -function defineOwn(target: object, key: string, value: unknown): void { - Object.defineProperty(target, key, { - value, enumerable: true, writable: true, configurable: true, - }) -} - -/** - * Verifies and normalizes one product entry. - * - * Strict about SHAPE: exactly one of the two dates, a real date, and the two window sizes. A key - * that gets this wrong is malformed, not merely unknown, and reading it would mean guessing what - * was licensed. - * - * Lenient about VOCABULARY: an unrecognised capability token, an unrecognised flag and an - * unrecognised extra field are all kept and ignored. Without that leniency every token added on - * the issuing side would break every library version already deployed in the field. - * - * Returns `null` when the entry is malformed. - * - * @param {unknown} entry - the product entry of the payload - */ -function normalizeProductEntry(entry: unknown): EntitlementProductGrant | null { - if (!isPlainObject(entry)) { - return null - } - if (!isStringArray(entry.capabilities)) { - return null - } - - const presentDateFields = DATE_FIELDS.filter((field) => entry[field] !== undefined) - - // Exactly one date per product. "Both" and "neither" are each a different commercial shape - // that the format cannot express, so neither may be silently resolved by whichever field the - // parser happens to read first. - if (presentDateFields.length !== 1) { - return null - } - if (!isIsoDate(entry[presentDateFields[0]])) { - return null - } - if (!isNonNegativeInteger(entry.notice) || !isNonNegativeInteger(entry.grace)) { - return null - } - if (entry.flags !== undefined && !isStringArray(entry.flags)) { - return null - } - - // Start from everything the entry carries, so a field this version does not know survives - // into the result instead of being silently dropped. A field added to the format later is - // exactly the case an already-vendored parser has to survive, and a reader that quietly - // discards it makes the field invisible to the application on top. - const normalized = {} - - Object.keys(entry).forEach((field) => defineOwn(normalized, field, entry[field])) - - defineOwn(normalized, 'capabilities', entry.capabilities.slice()) - defineOwn(normalized, 'notice', entry.notice) - defineOwn(normalized, 'grace', entry.grace) - // An absent array and an empty one mean the same thing. Normalizing here keeps - // `flags.indexOf('trial')` safe at every call site. - defineOwn(normalized, 'flags', entry.flags === undefined ? [] : entry.flags.slice()) - defineOwn(normalized, presentDateFields[0], entry[presentDateFields[0]]) - - return normalized as EntitlementProductGrant -} - -/** - * Extracts the machine-readable data from an entitlement license key. - * - * The checksum is verified first, so the returned data is guaranteed to belong to an intact - * block. For a malformed or tampered key `null` is returned — reporting an invalid key is the - * caller's job, not this function's. - * - * Only the bracketed block matters. The prose in front of it is neither parsed nor covered by - * the checksum, so the caller may pass the whole artifact or just the `[...]` block, and - * rewrapped or re-pasted text still validates. - * - * No schema is needed. Unknown products, capabilities and flags are all tolerated, so nothing - * about reading a key depends on the vocabulary — which is what lets a product vendor this - * parser on its own. - * - * @param {string} licenseKey - the license key to extract the data from - */ -export function extractEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { - if (typeof licenseKey !== 'string') { - return null - } - - // The machine-readable block closes the key. Searching backwards means a bracket inside the - // prose cannot shadow it. - const blockStart = licenseKey.lastIndexOf('[') - - if (blockStart === -1) { - return null - } - - const blockEnd = licenseKey.indexOf(']', blockStart) - - if (blockEnd === -1) { - return null - } - - const content = licenseKey.slice(blockStart + 1, blockEnd) - - if (content.length <= ENTITLEMENT_KEY_CHECKSUM_LENGTH) { - return null - } - - const encodedPayload = content.slice(0, -ENTITLEMENT_KEY_CHECKSUM_LENGTH) - const checksum = content.slice(-ENTITLEMENT_KEY_CHECKSUM_LENGTH) - - if (!ENCODED_PAYLOAD.test(encodedPayload) || !CHECKSUM.test(checksum)) { - return null - } - if (sha512(stringToUtf8Bytes(encodedPayload)) !== checksum) { - return null - } - - const payloadJson = base64ToString(encodedPayload) - - if (payloadJson === null) { - return null - } - - let payload: unknown - - try { - payload = JSON.parse(payloadJson) - } catch (error) { - return null - } - - if (!isPlainObject(payload)) { - return null - } - - const rawProducts = payload.products - - if (!isPlainObject(rawProducts)) { - return null - } - - const products = {} - let malformed = false - - Object.keys(rawProducts).forEach((name) => { - const entry = normalizeProductEntry(rawProducts[name]) - - if (entry === null) { - malformed = true - - return - } - - defineOwn(products, name, entry) - }) - - if (malformed) { - return null - } - - return {products} -} diff --git a/src/license/handsontable-license-key-parser/sha512.d.ts b/src/license/handsontable-license-key-parser/sha512.d.ts new file mode 100644 index 0000000000..084e765db8 --- /dev/null +++ b/src/license/handsontable-license-key-parser/sha512.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Hand-written declarations for `sha512.js`, which is a verbatim copy of upstream. + * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. + */ + +/** + * SHA-512 of the given bytes, as lower-case hexadecimal. Self-contained so the module needs no + * dependency and works on a plain `http://` page, where `crypto.subtle` is unavailable. + * + * @param {number[]|Uint8Array} bytes - the message, as byte values + */ +export function sha512(bytes: number[] | Uint8Array): string diff --git a/src/license/handsontable-license-key-parser/sha512.ts b/src/license/handsontable-license-key-parser/sha512.js similarity index 56% rename from src/license/handsontable-license-key-parser/sha512.ts rename to src/license/handsontable-license-key-parser/sha512.js index e65aee16ea..1c8cf17643 100644 --- a/src/license/handsontable-license-key-parser/sha512.ts +++ b/src/license/handsontable-license-key-parser/sha512.js @@ -1,18 +1,12 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ +/* eslint-disable no-bitwise */ /** - * Vendored from `handsontable/license-key`, `src/entitlement-key/sha512.js`. - * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. - */ - -/** - * The SHA-512 round constants. Each 64-bit constant is stored as a pair of 32-bit integers - * (high word first, low word second). + * The SHA-512 round constants. Each 64-bit constant is stored as a pair + * of 32-bit integers (high word first, low word second). + * + * @type {number[]} */ -const K: number[] = [ +const K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, @@ -53,165 +47,166 @@ const K: number[] = [ 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817, -] +]; /** * Converts a 32-bit integer to a zero-padded 8-character hex string. * - * @param {number} value - the 32-bit integer value + * @param {number} value The 32-bit integer value. + * @returns {string} */ -function toHex32(value: number): string { - return `00000000${(value >>> 0).toString(16)}`.slice(-8) +function toHex32(value) { + return `00000000${(value >>> 0).toString(16)}`.slice(-8); } /** - * Calculates the SHA-512 checksum of the passed bytes. The implementation is a plain (pure JS) - * one on purpose. It does not depend on the Web Crypto API (`crypto.subtle`), which browsers - * expose only on secure origins (https). Thanks to that, the checksum can be verified on plain - * http:// pages, for example, intranets of big companies. - * - * A second reason applies on HyperFormula's side: `crypto.subtle.digest` is asynchronous, and - * the license key is read from `Config`'s constructor, which is not. + * Calculates the SHA-512 checksum of the passed bytes. The implementation is + * a plain (pure JS) one on purpose. It does not depend on the Web Crypto API + * (`crypto.subtle`), which browsers expose only on secure origins (https). + * Thanks to that, the checksum can be verified on plain http:// pages, + * for example, intranets of big companies. * - * @param {number[] | Uint8Array} bytes - the bytes to calculate the checksum from + * @param {number[]|Uint8Array} bytes The bytes to calculate the checksum from. + * @returns {string} The checksum as a 128-character hex string. */ -export function sha512(bytes: number[] | Uint8Array): string { - const byteLength = bytes.length - // The message is padded with the 0x80 byte, zeros, and the 128-bit big-endian bit length so - // the total length is a multiple of 128 bytes. - const blockCount = Math.ceil((byteLength + 17) / 128) - const buffer = new Uint8Array(blockCount * 128) - - buffer.set(bytes) - buffer[byteLength] = 0x80 - - const bitLength = byteLength * 8 - const bufferLength = buffer.length - - // The supported message sizes fit well within 2^53 bits, so only the two lowest 32-bit words - // of the 128-bit length field are ever non-zero. - buffer[bufferLength - 7] = Math.floor(bitLength / 0x1000000000000) & 0xff // bits 48-55 - buffer[bufferLength - 6] = Math.floor(bitLength / 0x10000000000) & 0xff // bits 40-47 - buffer[bufferLength - 5] = Math.floor(bitLength / 0x100000000) & 0xff // bits 32-39 - buffer[bufferLength - 4] = (bitLength >>> 24) & 0xff // bits 24-31 - buffer[bufferLength - 3] = (bitLength >>> 16) & 0xff // bits 16-23 - buffer[bufferLength - 2] = (bitLength >>> 8) & 0xff // bits 8-15 - buffer[bufferLength - 1] = bitLength & 0xff // bits 0-7 +/* eslint-disable import/prefer-default-export */ +export function sha512(bytes) { + const byteLength = bytes.length; + // The message is padded with the 0x80 byte, zeros, and the 128-bit big-endian + // bit length so the total length is a multiple of 128 bytes. + const blockCount = Math.ceil((byteLength + 17) / 128); + const buffer = new Uint8Array(blockCount * 128); + + buffer.set(bytes); + buffer[byteLength] = 0x80; + + const bitLength = byteLength * 8; + const bufferLength = buffer.length; + + // The supported message sizes fit well within 2^53 bits, so only the two + // lowest 32-bit words of the 128-bit length field are ever non-zero. + buffer[bufferLength - 7] = Math.floor(bitLength / 0x1000000000000) & 0xff; // bits 48-55 + buffer[bufferLength - 6] = Math.floor(bitLength / 0x10000000000) & 0xff; // bits 40-47 + buffer[bufferLength - 5] = Math.floor(bitLength / 0x100000000) & 0xff; // bits 32-39 + buffer[bufferLength - 4] = (bitLength >>> 24) & 0xff; // bits 24-31 + buffer[bufferLength - 3] = (bitLength >>> 16) & 0xff; // bits 16-23 + buffer[bufferLength - 2] = (bitLength >>> 8) & 0xff; // bits 8-15 + buffer[bufferLength - 1] = bitLength & 0xff; // bits 0-7 // The initial hash values, stored as [high, low] 32-bit pairs. - const H: number[] = [ + const H = [ 0x6a09e667, 0xf3bcc908, 0xbb67ae85, 0x84caa73b, 0x3c6ef372, 0xfe94f82b, 0xa54ff53a, 0x5f1d36f1, 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, - ] - const wh = new Array(80) - const wl = new Array(80) + ]; + const wh = new Array(80); + const wl = new Array(80); for (let block = 0; block < blockCount; block += 1) { - const offset = block * 128 + const offset = block * 128; // Prepare the message schedule. for (let i = 0; i < 16; i += 1) { - const o = offset + i * 8 + const o = offset + i * 8; - wh[i] = ((buffer[o] << 24) | (buffer[o + 1] << 16) | (buffer[o + 2] << 8) | buffer[o + 3]) >>> 0 - wl[i] = ((buffer[o + 4] << 24) | (buffer[o + 5] << 16) | (buffer[o + 6] << 8) | buffer[o + 7]) >>> 0 + wh[i] = ((buffer[o] << 24) | (buffer[o + 1] << 16) | (buffer[o + 2] << 8) | buffer[o + 3]) >>> 0; + wl[i] = ((buffer[o + 4] << 24) | (buffer[o + 5] << 16) | (buffer[o + 6] << 8) | buffer[o + 7]) >>> 0; } for (let i = 16; i < 80; i += 1) { - const x2h = wh[i - 2] - const x2l = wl[i - 2] - const x15h = wh[i - 15] - const x15l = wl[i - 15] + const x2h = wh[i - 2]; + const x2l = wl[i - 2]; + const x15h = wh[i - 15]; + const x15l = wl[i - 15]; // smallSigma1 = ROTR^19(x) XOR ROTR^61(x) XOR SHR^6(x) - const s1h = ((x2h >>> 19) | (x2l << 13)) ^ ((x2l >>> 29) | (x2h << 3)) ^ (x2h >>> 6) - const s1l = ((x2l >>> 19) | (x2h << 13)) ^ ((x2h >>> 29) | (x2l << 3)) ^ ((x2l >>> 6) | (x2h << 26)) + const s1h = ((x2h >>> 19) | (x2l << 13)) ^ ((x2l >>> 29) | (x2h << 3)) ^ (x2h >>> 6); + const s1l = ((x2l >>> 19) | (x2h << 13)) ^ ((x2h >>> 29) | (x2l << 3)) ^ ((x2l >>> 6) | (x2h << 26)); // smallSigma0 = ROTR^1(x) XOR ROTR^8(x) XOR SHR^7(x) - const s0h = ((x15h >>> 1) | (x15l << 31)) ^ ((x15h >>> 8) | (x15l << 24)) ^ (x15h >>> 7) - const s0l = ((x15l >>> 1) | (x15h << 31)) ^ ((x15l >>> 8) | (x15h << 24)) ^ ((x15l >>> 7) | (x15h << 25)) + const s0h = ((x15h >>> 1) | (x15l << 31)) ^ ((x15h >>> 8) | (x15l << 24)) ^ (x15h >>> 7); + const s0l = ((x15l >>> 1) | (x15h << 31)) ^ ((x15l >>> 8) | (x15h << 24)) ^ ((x15l >>> 7) | (x15h << 25)); - const lowSum = (s1l >>> 0) + (wl[i - 7] >>> 0) + (s0l >>> 0) + (wl[i - 16] >>> 0) + const lowSum = (s1l >>> 0) + (wl[i - 7] >>> 0) + (s0l >>> 0) + (wl[i - 16] >>> 0); - wl[i] = lowSum >>> 0 + wl[i] = lowSum >>> 0; wh[i] = ((s1h >>> 0) + (wh[i - 7] >>> 0) + (s0h >>> 0) + (wh[i - 16] >>> 0) - + Math.floor(lowSum / 0x100000000)) >>> 0 + + Math.floor(lowSum / 0x100000000)) >>> 0; } - let ah = H[0] - let al = H[1] - let bh = H[2] - let bl = H[3] - let ch = H[4] - let cl = H[5] - let dh = H[6] - let dl = H[7] - let eh = H[8] - let el = H[9] - let fh = H[10] - let fl = H[11] - let gh = H[12] - let gl = H[13] - let hh = H[14] - let hl = H[15] + let ah = H[0]; + let al = H[1]; + let bh = H[2]; + let bl = H[3]; + let ch = H[4]; + let cl = H[5]; + let dh = H[6]; + let dl = H[7]; + let eh = H[8]; + let el = H[9]; + let fh = H[10]; + let fl = H[11]; + let gh = H[12]; + let gl = H[13]; + let hh = H[14]; + let hl = H[15]; for (let i = 0; i < 80; i += 1) { // bigSigma1 = ROTR^14(e) XOR ROTR^18(e) XOR ROTR^41(e) - const bs1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((el >>> 9) | (eh << 23)) - const bs1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((eh >>> 9) | (el << 23)) + const bs1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((el >>> 9) | (eh << 23)); + const bs1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((eh >>> 9) | (el << 23)); // bigSigma0 = ROTR^28(a) XOR ROTR^34(a) XOR ROTR^39(a) - const bs0h = ((ah >>> 28) | (al << 4)) ^ ((al >>> 2) | (ah << 30)) ^ ((al >>> 7) | (ah << 25)) - const bs0l = ((al >>> 28) | (ah << 4)) ^ ((ah >>> 2) | (al << 30)) ^ ((ah >>> 7) | (al << 25)) + const bs0h = ((ah >>> 28) | (al << 4)) ^ ((al >>> 2) | (ah << 30)) ^ ((al >>> 7) | (ah << 25)); + const bs0l = ((al >>> 28) | (ah << 4)) ^ ((ah >>> 2) | (al << 30)) ^ ((ah >>> 7) | (al << 25)); // ch = (e AND f) XOR (NOT e AND g) - const chh = (eh & fh) ^ (~eh & gh) - const chl = (el & fl) ^ (~el & gl) + const chh = (eh & fh) ^ (~eh & gh); + const chl = (el & fl) ^ (~el & gl); // maj = (a AND b) XOR (a AND c) XOR (b AND c) - const majh = (ah & bh) ^ (ah & ch) ^ (bh & ch) - const majl = (al & bl) ^ (al & cl) ^ (bl & cl) + const majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); + const majl = (al & bl) ^ (al & cl) ^ (bl & cl); - const t1LowSum = (hl >>> 0) + (bs1l >>> 0) + (chl >>> 0) + (K[i * 2 + 1] >>> 0) + (wl[i] >>> 0) - const t1l = t1LowSum >>> 0 + const t1LowSum = (hl >>> 0) + (bs1l >>> 0) + (chl >>> 0) + (K[i * 2 + 1] >>> 0) + (wl[i] >>> 0); + const t1l = t1LowSum >>> 0; const t1h = ((hh >>> 0) + (bs1h >>> 0) + (chh >>> 0) + (K[i * 2] >>> 0) - + (wh[i] >>> 0) + Math.floor(t1LowSum / 0x100000000)) >>> 0 + + (wh[i] >>> 0) + Math.floor(t1LowSum / 0x100000000)) >>> 0; - const t2LowSum = (bs0l >>> 0) + (majl >>> 0) - const t2l = t2LowSum >>> 0 - const t2h = ((bs0h >>> 0) + (majh >>> 0) + Math.floor(t2LowSum / 0x100000000)) >>> 0 + const t2LowSum = (bs0l >>> 0) + (majl >>> 0); + const t2l = t2LowSum >>> 0; + const t2h = ((bs0h >>> 0) + (majh >>> 0) + Math.floor(t2LowSum / 0x100000000)) >>> 0; - hh = gh - hl = gl - gh = fh - gl = fl - fh = eh - fl = el + hh = gh; + hl = gl; + gh = fh; + gl = fl; + fh = eh; + fl = el; - const eLowSum = (dl >>> 0) + t1l + const eLowSum = (dl >>> 0) + t1l; - el = eLowSum >>> 0 - eh = ((dh >>> 0) + t1h + Math.floor(eLowSum / 0x100000000)) >>> 0 + el = eLowSum >>> 0; + eh = ((dh >>> 0) + t1h + Math.floor(eLowSum / 0x100000000)) >>> 0; - dh = ch - dl = cl - ch = bh - cl = bl - bh = ah - bl = al + dh = ch; + dl = cl; + ch = bh; + cl = bl; + bh = ah; + bl = al; - const aLowSum = t1l + t2l + const aLowSum = t1l + t2l; - al = aLowSum >>> 0 - ah = (t1h + t2h + Math.floor(aLowSum / 0x100000000)) >>> 0 + al = aLowSum >>> 0; + ah = (t1h + t2h + Math.floor(aLowSum / 0x100000000)) >>> 0; } - const stateWords = [ah, al, bh, bl, ch, cl, dh, dl, eh, el, fh, fl, gh, gl, hh, hl] + const stateWords = [ah, al, bh, bl, ch, cl, dh, dl, eh, el, fh, fl, gh, gl, hh, hl]; for (let i = 0; i < 16; i += 2) { - const stateLowSum = (H[i + 1] >>> 0) + (stateWords[i + 1] >>> 0) + const stateLowSum = (H[i + 1] >>> 0) + (stateWords[i + 1] >>> 0); - H[i + 1] = stateLowSum >>> 0 - H[i] = ((H[i] >>> 0) + (stateWords[i] >>> 0) + Math.floor(stateLowSum / 0x100000000)) >>> 0 + H[i + 1] = stateLowSum >>> 0; + H[i] = ((H[i] >>> 0) + (stateWords[i] >>> 0) + Math.floor(stateLowSum / 0x100000000)) >>> 0; } } - return H.map(toHex32).join('') + return H.map(toHex32).join(''); } diff --git a/src/license/handsontable-license-key-parser/upstream.json b/src/license/handsontable-license-key-parser/upstream.json new file mode 100644 index 0000000000..de522f6dfc --- /dev/null +++ b/src/license/handsontable-license-key-parser/upstream.json @@ -0,0 +1,18 @@ +{ + "_comment": [ + "Where the JavaScript in this directory comes from. Machine-readable so CI can check it:", + "`npm run check:vendored-parser` hashes these files and the upstream ones and compares.", + "", + "No hashes are stored. The files ARE the copies, so a stored table would be a third thing", + "to keep in step. `track` is the branch to compare against - master, the released code;", + "`develop` there is work in progress. `commit` records which revision was taken.", + "", + "PROVENANCE.md says what this directory is and why. This file says where it came from." + ], + "repository": "handsontable/license-key", + "directory": "src/entitlement-key", + "track": "master", + "commit": "03810fd3c93160580e1b9665de6b38fca340e382", + "taken_on": "2026-09-30", + "files": ["constants.js", "detect-format.js", "extract-key-data.js", "utils.js", "sha512.js"] +} diff --git a/src/license/handsontable-license-key-parser/upstream.lock.json b/src/license/handsontable-license-key-parser/upstream.lock.json deleted file mode 100644 index 8d3faf3b97..0000000000 --- a/src/license/handsontable-license-key-parser/upstream.lock.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "_comment": [ - "The upstream sources this directory is ported from, pinned by commit and by content hash.", - "Machine-readable on purpose: `npm run check:vendored-parser` reads it, fetches the same files", - "from the tracked branch, and fails when they no longer hash as pinned. That is the event worth", - "catching - upstream moving on while this port stays behind. PROVENANCE.md explains the port;", - "this file is the pin.", - "", - "`track` is the branch the check compares against. It is `master` because that is the released", - "code; `develop` there is work in progress.", - "", - "Updating: re-port the changed file, then update its hash and `commit` here in the SAME commit,", - "so the diff shows the port and the pin moving together." - ], - "repository": "handsontable/license-key", - "tag": "4.0.0", - "commit": "c50ef40a6", - "directory": "src/entitlement-key", - "ported_on": "2026-08-20", - "files": [ - { - "vendored": "constants.ts", - "upstream": "constants.js", - "sha256": "6e2ad68d1a316abdec3f89bf04260a2cc4098f76525427d919f22cb25fb077d6" - }, - { - "vendored": "detectFormat.ts", - "upstream": "detect-format.js", - "sha256": "7dc037fd70e7c64078a0fe29b42cb33ecf25e8f4d8963ae9bfb16b69479d267f" - }, - { - "vendored": "extractKeyData.ts", - "upstream": "extract-key-data.js", - "sha256": "afd0858768879764ea016d2bc4fca692a0cd12214c1dfda6932d7ed9e4f32e45" - }, - { - "vendored": "utils.ts", - "upstream": "utils.js", - "sha256": "135a8396bb22f424160fc651e899931d4be807df9b94c6dd24bb1cf6526e0541" - }, - { - "vendored": "sha512.ts", - "upstream": "sha512.js", - "sha256": "668dd1109160b92965a1f9a9c5fb78dfdc1e5b7e93f635a147ae8a6bb2a5d837" - } - ], - "track": "master" -} diff --git a/src/license/handsontable-license-key-parser/utils.d.ts b/src/license/handsontable-license-key-parser/utils.d.ts new file mode 100644 index 0000000000..d4fee105bb --- /dev/null +++ b/src/license/handsontable-license-key-parser/utils.d.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +/** + * Hand-written declarations for `utils.js`, which is a verbatim copy of upstream. + * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. + * + * `bytesToBase64` and `stringToBase64Url` are upstream's generation-side helpers. They are + * declared because the file exports them, and nothing in HyperFormula calls them. + */ + +/** A date in `YYYY-MM-DD`, split into its parts plus the epoch milliseconds of its UTC midnight. */ +export interface ParsedIsoDate { + year: number, + month: number, + day: number, + timestamp: number, +} + +/** Freezes the value and everything reachable from it, in place, and returns it. */ +export function deepFreeze(value: T): T + +/** + * Parses a `YYYY-MM-DD` date. Throws when the value is not a string, is malformed, or names a day + * that does not exist in the calendar. + * + * The parameter is `unknown` rather than `string` because upstream checks the type itself, and + * these declarations state what the code does rather than what a caller ought to pass. + * + * @param {unknown} isoDate - the value to parse + * @param {string} dateLabel - the field name used in the error message + */ +export function parseIsoDate(isoDate: unknown, dateLabel: string): ParsedIsoDate + +/** UTF-8 encodes the text. */ +export function stringToUtf8Bytes(text: string): number[] + +/** Decodes UTF-8 bytes back to text. */ +export function utf8BytesToString(bytes: number[]): string + +/** Base64-encodes the bytes. Generation-side; unused in HyperFormula. */ +export function bytesToBase64(bytes: number[]): string + +/** Decodes base64 or base64url, tolerating missing padding. `null` when the input is not base64. */ +export function base64ToBytes(base64: string): number[] | null + +/** Base64url-encodes the text. Generation-side; unused in HyperFormula. */ +export function stringToBase64Url(text: string): string + +/** Decodes base64 to text. `null` when the input is not base64. */ +export function base64ToString(base64: string): string | null diff --git a/src/license/handsontable-license-key-parser/utils.js b/src/license/handsontable-license-key-parser/utils.js new file mode 100644 index 0000000000..9fd27d034c --- /dev/null +++ b/src/license/handsontable-license-key-parser/utils.js @@ -0,0 +1,250 @@ +/** + * The base64 alphabet. + * + * @type {string} + */ +const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + +/** + * Recursively freezes the value (and every nested object). Used to make a + * verified schema immutable so it cannot drift from what was validated. + * + * @param {*} value The value to freeze. + * @returns {*} + */ +export function deepFreeze(value) { + if (value !== null && typeof value === 'object') { + Object.keys(value).forEach((key) => deepFreeze(value[key])); + Object.freeze(value); + } + + return value; +} + +/** + * Parses the date in the "YYYY-MM-DD" format into its numeric parts and the + * epoch milliseconds of its UTC midnight. Throws when the date is malformed + * or does not exist in the calendar. + * + * @param {string} isoDate The date to parse. + * @param {string} dateLabel The date name used in the error message. + * @returns {{ year: number, month: number, day: number, timestamp: number }} + */ +export function parseIsoDate(isoDate, dateLabel) { + // Only a string is a date. Checked before the text test on purpose: an array + // like `['2027-08-12']` stringifies to a valid date, would pass, and would + // then be written into the payload as an array. + const match = typeof isoDate === 'string' ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(isoDate) : null; + + if (match === null) { + throw new Error(`The ${dateLabel} date (${isoDate}) has to be passed in the "YYYY-MM-DD" format.`); + } + + const year = parseInt(match[1], 10); + const month = parseInt(match[2], 10); + const day = parseInt(match[3], 10); + + // Date.UTC maps years 0-99 to 1900-1999, which would make the round-trip + // check below report a "not a valid calendar date" lie. + if (year < 100) { + throw new Error(`The ${dateLabel} date (${isoDate}) has to use a four-digit year of 100 or later.`); + } + + const timestamp = Date.UTC(year, month - 1, day); + const date = new Date(timestamp); + + // An impossible date (e.g. "2027-02-30") makes `Date.UTC` roll over to + // the next month, so a round-trip comparison catches it. + if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) { + throw new Error(`The ${dateLabel} date (${isoDate}) is not a valid calendar date.`); + } + + return { + year, month, day, timestamp, + }; +} + +/** + * Encodes the string as UTF-8 bytes. The plain implementation is used on purpose. + * It does not depend on `TextEncoder` or `Buffer`, so the same code works in + * Node.js and in every browser, including plain http:// pages. + * + * @param {string} string The string to encode. + * @returns {number[]} + */ +export function stringToUtf8Bytes(string) { + const bytes = []; + + for (let i = 0; i < string.length; i += 1) { + let codePoint = string.charCodeAt(i); + + // Combine a surrogate pair into a single code point. + if (codePoint >= 0xd800 && codePoint <= 0xdbff && i + 1 < string.length) { + const lowSurrogate = string.charCodeAt(i + 1); + + if (lowSurrogate >= 0xdc00 && lowSurrogate <= 0xdfff) { + codePoint = ((codePoint - 0xd800) * 0x400) + (lowSurrogate - 0xdc00) + 0x10000; + i += 1; // eslint-disable-line no-plusplus + } + } + + if (codePoint < 0x80) { + bytes.push(codePoint); + } else if (codePoint < 0x800) { + bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f)); // eslint-disable-line no-bitwise + } else if (codePoint < 0x10000) { + /* eslint-disable no-bitwise */ + bytes.push( + 0xe0 | (codePoint >> 12), + 0x80 | ((codePoint >> 6) & 0x3f), + 0x80 | (codePoint & 0x3f), + ); + } else { + bytes.push( + 0xf0 | (codePoint >> 18), + 0x80 | ((codePoint >> 12) & 0x3f), + 0x80 | ((codePoint >> 6) & 0x3f), + 0x80 | (codePoint & 0x3f), + ); + /* eslint-enable no-bitwise */ + } + } + + return bytes; +} + +/** + * Decodes UTF-8 bytes back into a string. + * + * @param {number[]} bytes The bytes to decode. + * @returns {string} + */ +export function utf8BytesToString(bytes) { + /* eslint-disable no-bitwise */ + let string = ''; + let i = 0; + + while (i < bytes.length) { + const byte = bytes[i]; + let codePoint; + + if (byte < 0x80) { + codePoint = byte; + i += 1; + } else if (byte < 0xe0) { + codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f); + i += 2; + } else if (byte < 0xf0) { + codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f); + i += 3; + } else { + codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) + | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f); + i += 4; + } + + if (codePoint >= 0x10000) { + // Split the code point back into a surrogate pair. + codePoint -= 0x10000; + string += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)); + } else { + string += String.fromCharCode(codePoint); + } + } + /* eslint-enable no-bitwise */ + + return string; +} + +/** + * Encodes the bytes as a base64 string (standard alphabet, with padding). + * + * @param {number[]} bytes The bytes to encode. + * @returns {string} + */ +export function bytesToBase64(bytes) { + /* eslint-disable no-bitwise */ + let base64 = ''; + + for (let i = 0; i < bytes.length; i += 3) { + const byte1 = bytes[i]; + const byte2 = bytes[i + 1]; + const byte3 = bytes[i + 2]; + + base64 += BASE64_ALPHABET.charAt(byte1 >> 2); + base64 += BASE64_ALPHABET.charAt(((byte1 & 0x03) << 4) | (byte2 === undefined ? 0 : byte2 >> 4)); + base64 += byte2 === undefined + ? '=' : BASE64_ALPHABET.charAt(((byte2 & 0x0f) << 2) | (byte3 === undefined ? 0 : byte3 >> 6)); + base64 += byte3 === undefined ? '=' : BASE64_ALPHABET.charAt(byte3 & 0x3f); + } + /* eslint-enable no-bitwise */ + + return base64; +} + +/** + * Decodes a base64 string (standard or URL-safe alphabet, padding optional) + * back into bytes. Returns `null` when the string is not valid base64. + * + * @param {string} base64 The base64 string to decode. + * @returns {number[]|null} + */ +export function base64ToBytes(base64) { + const normalized = `${base64}`.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, ''); + + if (!/^[A-Za-z0-9+/]*$/.test(normalized) || normalized.length % 4 === 1) { + return null; + } + + /* eslint-disable no-bitwise */ + const bytes = []; + + for (let i = 0; i < normalized.length; i += 4) { + const chunk = [0, 1, 2, 3].map((offset) => { + const char = normalized.charAt(i + offset); + + // `indexOf('')` would return 0, so the missing characters of the last + // chunk have to be mapped to -1 explicitly. + return char === '' ? -1 : BASE64_ALPHABET.indexOf(char); + }); + + bytes.push((chunk[0] << 2) | (chunk[1] >> 4)); + + if (chunk[2] !== -1) { + bytes.push(((chunk[1] & 0x0f) << 4) | (chunk[2] >> 2)); + } + if (chunk[3] !== -1) { + bytes.push(((chunk[2] & 0x03) << 6) | chunk[3]); + } + } + /* eslint-enable no-bitwise */ + + return bytes; +} + +/** + * Encodes the string as a URL-safe base64 string without padding (the same + * format as the JWT payload segment). + * + * @param {string} string The string to encode. + * @returns {string} + */ +export function stringToBase64Url(string) { + return bytesToBase64(stringToUtf8Bytes(string)) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, ''); +} + +/** + * Decodes a base64 (standard or URL-safe) string back into a string. + * Returns `null` when the input is not valid base64. + * + * @param {string} base64 The base64 string to decode. + * @returns {string|null} + */ +export function base64ToString(base64) { + const bytes = base64ToBytes(base64); + + return bytes === null ? null : utf8BytesToString(bytes); +} diff --git a/src/license/handsontable-license-key-parser/utils.ts b/src/license/handsontable-license-key-parser/utils.ts deleted file mode 100644 index 1a1a46d99b..0000000000 --- a/src/license/handsontable-license-key-parser/utils.ts +++ /dev/null @@ -1,218 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Vendored from `handsontable/license-key`, `src/entitlement-key/utils.js`. - * See `src/license/handsontable-license-key-parser/PROVENANCE.md` before editing — this file is a port, not original code. - * - * The two generation-side helpers of the upstream file (`bytesToBase64`, `stringToBase64Url`) are - * deliberately not ported: HyperFormula reads keys, it never mints them. - */ - -/** - * The base64 alphabet. - */ -const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' - -/** - * Recursively freezes the value (and every nested object). Used to make a verified schema - * immutable so it cannot drift from what was validated. - * - * @param {*} value - the value to freeze - */ -export function deepFreeze(value: T): T { - if (value !== null && typeof value === 'object') { - Object.keys(value as unknown as Record).forEach( - (key) => deepFreeze((value as unknown as Record)[key]) - ) - Object.freeze(value) - } - - return value -} - -/** - * A calendar date decomposed into its numeric parts plus the epoch milliseconds of its UTC - * midnight. - */ -export interface ParsedIsoDate { - year: number, - month: number, - day: number, - timestamp: number, -} - -/** - * Parses the date in the `YYYY-MM-DD` format into its numeric parts and the epoch milliseconds - * of its UTC midnight. Throws when the date is malformed or does not exist in the calendar. - * - * @param {string} isoDate - the date to parse - * @param {string} dateLabel - the date name used in the error message - */ -export function parseIsoDate(isoDate: string, dateLabel: string): ParsedIsoDate { - const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(`${isoDate}`) - - if (match === null) { - throw new Error(`The ${dateLabel} date (${isoDate}) has to be passed in the "YYYY-MM-DD" format.`) - } - - const year = parseInt(match[1], 10) - const month = parseInt(match[2], 10) - const day = parseInt(match[3], 10) - - // Date.UTC maps years 0-99 to 1900-1999, which would make the round-trip check below report a - // "not a valid calendar date" lie. - if (year < 100) { - throw new Error(`The ${dateLabel} date (${isoDate}) has to use a four-digit year of 100 or later.`) - } - - const timestamp = Date.UTC(year, month - 1, day) - const date = new Date(timestamp) - - // An impossible date (e.g. "2027-02-30") makes `Date.UTC` roll over to the next month, so a - // round-trip comparison catches it. - if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) { - throw new Error(`The ${dateLabel} date (${isoDate}) is not a valid calendar date.`) - } - - return { - year, month, day, timestamp, - } -} - -/** - * Encodes the string as UTF-8 bytes. The plain implementation is used on purpose. It does not - * depend on `TextEncoder` or `Buffer`, so the same code works in Node.js and in every browser, - * including plain http:// pages. - * - * @param {string} text - the string to encode - */ -export function stringToUtf8Bytes(text: string): number[] { - const bytes: number[] = [] - - for (let i = 0; i < text.length; i += 1) { - let codePoint = text.charCodeAt(i) - - // Combine a surrogate pair into a single code point. - if (codePoint >= 0xd800 && codePoint <= 0xdbff && i + 1 < text.length) { - const lowSurrogate = text.charCodeAt(i + 1) - - if (lowSurrogate >= 0xdc00 && lowSurrogate <= 0xdfff) { - codePoint = ((codePoint - 0xd800) * 0x400) + (lowSurrogate - 0xdc00) + 0x10000 - i += 1 - } - } - - if (codePoint < 0x80) { - bytes.push(codePoint) - } else if (codePoint < 0x800) { - bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f)) - } else if (codePoint < 0x10000) { - bytes.push( - 0xe0 | (codePoint >> 12), - 0x80 | ((codePoint >> 6) & 0x3f), - 0x80 | (codePoint & 0x3f), - ) - } else { - bytes.push( - 0xf0 | (codePoint >> 18), - 0x80 | ((codePoint >> 12) & 0x3f), - 0x80 | ((codePoint >> 6) & 0x3f), - 0x80 | (codePoint & 0x3f), - ) - } - } - - return bytes -} - -/** - * Decodes UTF-8 bytes back into a string. - * - * @param {number[]} bytes - the bytes to decode - */ -export function utf8BytesToString(bytes: number[]): string { - let text = '' - let i = 0 - - while (i < bytes.length) { - const byte = bytes[i] - let codePoint - - if (byte < 0x80) { - codePoint = byte - i += 1 - } else if (byte < 0xe0) { - codePoint = ((byte & 0x1f) << 6) | (bytes[i + 1] & 0x3f) - i += 2 - } else if (byte < 0xf0) { - codePoint = ((byte & 0x0f) << 12) | ((bytes[i + 1] & 0x3f) << 6) | (bytes[i + 2] & 0x3f) - i += 3 - } else { - codePoint = ((byte & 0x07) << 18) | ((bytes[i + 1] & 0x3f) << 12) - | ((bytes[i + 2] & 0x3f) << 6) | (bytes[i + 3] & 0x3f) - i += 4 - } - - if (codePoint >= 0x10000) { - // Split the code point back into a surrogate pair. - codePoint -= 0x10000 - text += String.fromCharCode(0xd800 + (codePoint >> 10), 0xdc00 + (codePoint & 0x3ff)) - } else { - text += String.fromCharCode(codePoint) - } - } - - return text -} - -/** - * Decodes a base64 string (standard or URL-safe alphabet, padding optional) back into bytes. - * Returns `null` when the string is not valid base64. - * - * @param {string} base64 - the base64 string to decode - */ -export function base64ToBytes(base64: string): number[] | null { - const normalized = `${base64}`.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, '') - - if (!/^[A-Za-z0-9+/]*$/.test(normalized) || normalized.length % 4 === 1) { - return null - } - - const bytes: number[] = [] - - for (let i = 0; i < normalized.length; i += 4) { - const chunk = [0, 1, 2, 3].map((offset) => { - const char = normalized.charAt(i + offset) - - // `indexOf('')` would return 0, so the missing characters of the last chunk have to be - // mapped to -1 explicitly. - return char === '' ? -1 : BASE64_ALPHABET.indexOf(char) - }) - - bytes.push((chunk[0] << 2) | (chunk[1] >> 4)) - - if (chunk[2] !== -1) { - bytes.push(((chunk[1] & 0x0f) << 4) | (chunk[2] >> 2)) - } - if (chunk[3] !== -1) { - bytes.push(((chunk[2] & 0x03) << 6) | chunk[3]) - } - } - - return bytes -} - -/** - * Decodes a base64 (standard or URL-safe) string back into a string. Returns `null` when the - * input is not valid base64. - * - * @param {string} base64 - the base64 string to decode - */ -export function base64ToString(base64: string): string | null { - const bytes = base64ToBytes(base64) - - return bytes === null ? null : utf8BytesToString(bytes) -} diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index a078ab8537..4e61181d30 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -11,8 +11,8 @@ import { } from '../helpers/licenseKeyValidator' import {CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' import {LicenseEntitlement, LicenseExpiry, unrestrictedEntitlement} from './LicenseEntitlement' -import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detectFormat' -import {EntitlementKeyData, EntitlementProductGrant, extractEntitlementKeyData} from './handsontable-license-key-parser/extractKeyData' +import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detect-format' +import {EntitlementKeyData, EntitlementProductGrant, extractEntitlementKeyData} from './handsontable-license-key-parser/extract-key-data' import {parseIsoDate} from './handsontable-license-key-parser/utils' /** Milliseconds in a day, used to turn a grace period in days into a deadline. */ @@ -26,12 +26,6 @@ const MILLISECONDS_PER_DAY = 86400000 */ export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' -/** - * The two date fields a product entry may carry, exactly one of which is present on an intact - * entry. Named here because {@link hyperformulaDateFieldIsWellTyped} has to reach them by name. - */ -const DATE_FIELD_NAMES = ['usage_until', 'release_until'] as const - /** * Flag spellings that suppress console output. * @@ -114,37 +108,6 @@ function releaseDateTimestamp(): number | null { return isNaN(timestamp) ? null : timestamp } -/** - * Whether this product's entry spells its date field as a STRING, as the format requires. - * - * The vendored reader is a verbatim copy of upstream, and upstream checks the date's SHAPE - * without checking its type: `parseIsoDate` stringifies before matching `YYYY-MM-DD`, so - * `usage_until: ["2099-12-31"]` passes there and the declared `string` type ends up wider than - * the value. Left at that, a malformed key would resolve to a RESTRICTED entitlement instead of - * taking the invalid-key path. - * - * The key spec's addendum (T7) makes the field a real calendar date, so the stricter reading is - * the specified one — but upstream has not adopted it (checked at `c50ef40a`, `develop` and - * `master`), and diverging inside the vendored copy would mean carrying a patched fork of - * someone else's source through every drift review. So the check lives here instead, in the code - * this repository owns, and the copy next door stays byte-identical to upstream. - * - * Only HyperFormula's own entry is checked: another product's fields are not ours to validate, - * and rejecting a whole key over a malformed entry we never read would fail closed for a - * customer whose HyperFormula grant is intact. - * - * @param {EntitlementKeyData} data - the extracted key data - */ -function hyperformulaDateFieldIsWellTyped(data: EntitlementKeyData): boolean { - const grant = data.products[HYPERFORMULA_PRODUCT_NAME] - - if (grant === undefined) { - return true - } - - return DATE_FIELD_NAMES.every((field) => grant[field] === undefined || typeof grant[field] === 'string') -} - /** * Reads HyperFormula's terms out of an intact entitlement key payload. * @@ -359,7 +322,7 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true const data = extractEntitlementKeyData(licenseKey) - if (data === null || !hyperformulaDateFieldIsWellTyped(data)) { + if (data === null) { if (notifyConsole) { notifyLicenseKeyState(LicenseKeyValidityState.INVALID) } diff --git a/tsconfig.json b/tsconfig.json index 812d955676..b0d3741bd8 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,7 +17,7 @@ "es2017" ], /* Specify library files to be included in the compilation. */ - // "allowJs": true, /* Allow javascript files to be compiled. */ + "allowJs": true, /* The vendored entitlement-key reader is upstream JavaScript, copied verbatim; see src/license/handsontable-license-key-parser/PROVENANCE.md. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ From 04673be769189272096a304e1f65595aeeacc8da Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 10:27:14 +0000 Subject: [PATCH 18/54] HF-307: vendor the reader upstream publishes for products, not the package's own parser The 22.09 / 23.09 / 28.09 rulings asked for byte-identical copies of upstream with no local edits. The previous commit delivered that against the wrong directory: `src/entitlement-key/*.js` is license-key's internal parser. Its own CLAUDE.md says what products copy - "They copy vendor/entitlement-key-reader/ - a general, dependency-free TypeScript reader" - and that directory appeared upstream on 2026-09-28 13:22Z, two hours after the ruling, so neither side could have pointed at it at the time. This commit copies that directory whole, at tag 4.0.1, as its README prescribes. Everything the .js detour needed goes with it: allowJs, five hand-written .d.ts, the Jest transform for .js, the lint exemption for .js, the stored-hash pin. Two independent reviews had measured that the .js route shipped typings generated from upstream's JSDoc - EntitlementKeyData and LicenseKeyFormat gone from the published contract, parseIsoDate declared as (string) while the change was about accepting non-strings, and the Handsoncode licence header missing from five shipped files. With TypeScript sources the published typings come from the code: `extractEntitlementKeyData(licenseKey: string): EntitlementKeyData | null`, `parseIsoDateToTimestamp(isoDate: unknown): number | null`. One declared divergence, and only one - so "no local edits" is one line short. HyperFormula compiles with TypeScript 4.0.8; upstream targets ^5.9.3, and 4.0.8 does not narrow `unknown` through `!== null && typeof === 'object'`. One cast on one line of extractKeyData.ts makes the directory compile here (measured: the same files type-check clean under 5.9.3, and the un-cast line starts compiling at 4.5 - 4.4.4 fails, 4.5.5 passes). The cast is recorded in upstream.json with its reason and its expiry; the drift check substitutes it before comparing. Tags are immutable, so the check cannot see upstream fix the line on a branch; it fails on the next tag, and re-taking the copy there makes the entry stop matching, so the shim comes out rather than riding along. The alternatives - wait for a license-key release carrying the cast, or move HyperFormula to TypeScript >= 4.5 - are put to the reviewer; HyperFormula has no push access to license-key, so the upstream fix has to be requested, not made. The drift check is now upstream's own `diff -r`, done through the API: every file of the upstream directory at the pinned tag, byte for byte, plus a check that the tag still points at the pinned commit, plus what a `diff -r` would not tell you - a local file upstream does not have fails the check, because a `foo.ts` beside a copied `foo.ts` wins module resolution silently (an earlier version printed "byte-identical" while exactly that shadow flipped a key from INVALID to VALID). A newer upstream tag fails it too. A 401/403/404 is reported as an access problem, not as drift. Broken eight ways on purpose, caught eight times. It also runs in CI now, which an earlier commit message claimed and no workflow did: vendored-parser.yml, on pull requests that touch the directory and on pushes to master and develop, plus a weekday cron - which GitHub runs on the default branch only, so it watches releases, not open PRs. It needs LICENSE_KEY_REPO_TOKEN as a repository secret and is red until that exists - deliberately, and visibly on this PR from the first push. Engine-side consumers change by name only: detectFormat, extractKeyData, encoding (parseIsoDateToTimestamp for parseIsoDate), types (ProductEntitlement for EntitlementProductGrant), CHECKSUM_LENGTH. detectLicenseKeyFormat now takes the literal keys from the caller and answers 'literal'; HyperFormula never passed any and only asks "is this an entitlement key", so its routing is unchanged. The reader's own date-type check made hyperformulaDateFieldIsWellTyped dead code, so it is removed - which reverses the 28.09 instruction to move the guard into licenseTermsOf and the HF-entry-only narrowing described on 29.09: a mistyped date in another product's entry now invalidates the whole key. A verbatim copy does not get to pick; that is upstream's rule and the key spec's (T7), and it is pinned. The reader also carries window evaluation and grant picking (readEntitlementLicense, classifyEntitlement, getLicenseGrants). HyperFormula keeps evaluating windows in licenseResolution.ts and does not use those yet; consolidating onto them is a separate decision, not taken here. tsc clean; full suite 517/517, 6549 passed, 3 skipped, 0 failed; lint on src 0 errors; bundle-all green with the reader present in every bundle; drift check OK. Co-Authored-By: Claude Fable 5.1 --- .eslintignore | 8 +- .github/workflows/vendored-parser.yml | 38 ++ jest.config.js | 5 +- script/check-vendored-parser.js | 204 +++++++--- src/helpers/licenseKeyValidator.ts | 4 +- src/license/functionCapabilities.ts | 7 +- .../handsontable-license-key-parser/AGENTS.md | 19 + .../PROVENANCE.md | 83 ++-- .../handsontable-license-key-parser/README.md | 359 ++++++++++++++++++ .../buildDate.ts | 69 ++++ .../classify.ts | 157 ++++++++ .../constants.d.ts | 15 - .../constants.js | 22 -- .../constants.ts | 71 ++++ .../detect-format.d.ts | 25 -- .../detect-format.js | 57 --- .../detectFormat.ts | 77 ++++ .../{utils.js => encoding.ts} | 126 +++--- .../extract-key-data.d.ts | 40 -- .../extract-key-data.js | 242 ------------ .../extractKeyData.ts | 332 ++++++++++++++++ .../handsontable-license-key-parser/grants.ts | 101 +++++ .../handsontable-license-key-parser/index.ts | 70 ++++ .../readLicense.ts | 123 ++++++ .../sha512.d.ts | 17 - .../{sha512.js => sha512.ts} | 13 +- .../handsontable-license-key-parser/types.ts | 181 +++++++++ .../upstream.json | 30 +- .../utils.d.ts | 53 --- src/license/licenseResolution.ts | 13 +- tsconfig.json | 2 +- 31 files changed, 1876 insertions(+), 687 deletions(-) create mode 100644 .github/workflows/vendored-parser.yml create mode 100644 src/license/handsontable-license-key-parser/AGENTS.md create mode 100644 src/license/handsontable-license-key-parser/README.md create mode 100644 src/license/handsontable-license-key-parser/buildDate.ts create mode 100644 src/license/handsontable-license-key-parser/classify.ts delete mode 100644 src/license/handsontable-license-key-parser/constants.d.ts delete mode 100644 src/license/handsontable-license-key-parser/constants.js create mode 100644 src/license/handsontable-license-key-parser/constants.ts delete mode 100644 src/license/handsontable-license-key-parser/detect-format.d.ts delete mode 100644 src/license/handsontable-license-key-parser/detect-format.js create mode 100644 src/license/handsontable-license-key-parser/detectFormat.ts rename src/license/handsontable-license-key-parser/{utils.js => encoding.ts} (74%) delete mode 100644 src/license/handsontable-license-key-parser/extract-key-data.d.ts delete mode 100644 src/license/handsontable-license-key-parser/extract-key-data.js create mode 100644 src/license/handsontable-license-key-parser/extractKeyData.ts create mode 100644 src/license/handsontable-license-key-parser/grants.ts create mode 100644 src/license/handsontable-license-key-parser/index.ts create mode 100644 src/license/handsontable-license-key-parser/readLicense.ts delete mode 100644 src/license/handsontable-license-key-parser/sha512.d.ts rename src/license/handsontable-license-key-parser/{sha512.js => sha512.ts} (96%) create mode 100644 src/license/handsontable-license-key-parser/types.ts delete mode 100644 src/license/handsontable-license-key-parser/utils.d.ts diff --git a/.eslintignore b/.eslintignore index feedf112c3..7b1522852f 100644 --- a/.eslintignore +++ b/.eslintignore @@ -7,10 +7,10 @@ docs/examples/ # 3rd party src/interpreter/plugin/3rdparty -# Byte-identical copies of handsontable/license-key - see PROVENANCE.md in that directory. -# Linting them would mean editing them, and editing them is the one thing they must not have. -# The hand-written .d.ts beside them are ours and ARE linted. -src/license/handsontable-license-key-parser/*.js +# A byte-identical copy of handsontable/license-key's vendor/entitlement-key-reader - see +# PROVENANCE.md in that directory. Linting it would mean editing it, and editing it is the one +# thing it must not have; upstream runs strict tsc on it instead. +src/license/handsontable-license-key-parser/*.ts # Configurations *.config.js diff --git a/.github/workflows/vendored-parser.yml b/.github/workflows/vendored-parser.yml new file mode 100644 index 0000000000..5f223e1f98 --- /dev/null +++ b/.github/workflows/vendored-parser.yml @@ -0,0 +1,38 @@ +name: Vendored parser + +# The entitlement-key reader under src/license/handsontable-license-key-parser/ is a verbatim +# copy of a private upstream directory. This job is the drift check that copy's integration guide +# asks for: it fails when any byte differs from the pinned tag, when a file shadows the copy, or +# when upstream has released a newer tag. See PROVENANCE.md in that directory. +# +# It needs LICENSE_KEY_REPO_TOKEN - a read-only token for handsontable/license-key - as a repository +# secret. Without it the check fails on purpose ("could not verify" is not "verified"), so this job +# stays red until the secret is set. Pull requests from forks never receive secrets and are skipped. + +on: + pull_request: + types: [ opened, reopened, synchronize ] + paths: + - 'src/license/handsontable-license-key-parser/**' + - 'script/check-vendored-parser.js' + - '.github/workflows/vendored-parser.yml' + push: + branches: [ master, develop ] + schedule: + - cron: '17 6 * * 1-5' # weekday mornings: a newer upstream tag is news even when nothing here changed + +jobs: + drift: + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@722adc63f1aa60a57ec37892e133b1d319cae598 # https://github.com/actions/checkout/releases/tag/v2.0.0 + - name: Setup Node.js 22 + uses: actions/setup-node@56899e050abffc08c2b3b61f3ec6a79a9dc3223d # https://github.com/actions/setup-node/releases/tag/v1.4.4 + with: + node-version: '22' + - name: Compare the vendored reader with upstream + run: node script/check-vendored-parser.js + env: + LICENSE_KEY_REPO_TOKEN: ${{ secrets.LICENSE_KEY_REPO_TOKEN }} diff --git a/jest.config.js b/jest.config.js index 7315e870b7..4b667a3960 100644 --- a/jest.config.js +++ b/jest.config.js @@ -48,10 +48,7 @@ module.exports = { // A map from regular expressions to paths to transformers transform: { - // `.js` is here for the vendored entitlement-key reader, which is upstream JavaScript copied - // verbatim (see src/license/handsontable-license-key-parser/PROVENANCE.md). It is ES modules, - // so without a transform Jest hands it to Node and fails on the first `export`. - "^.+\\.(ts|tsx|js)$": "ts-jest" + "^.+\\.(ts|tsx)$": "ts-jest" }, watchPathIgnorePatterns: [ diff --git a/script/check-vendored-parser.js b/script/check-vendored-parser.js index 68ce98daa1..56d612ee45 100755 --- a/script/check-vendored-parser.js +++ b/script/check-vendored-parser.js @@ -5,27 +5,29 @@ */ /* - * Checks the vendored entitlement-key reader against the upstream it was copied from. + * Holds `src/license/handsontable-license-key-parser/` to the upstream directory it is a copy of. * - * `src/license/handsontable-license-key-parser/*.js` are byte-identical copies of - * `handsontable/license-key`. A local edit silently forks the two, and a forked checksum or parser - * rejects genuine customer keys - so the copies are verified by measurement, not by trust. + * The directory is `handsontable/license-key`'s `vendor/entitlement-key-reader/`, taken whole from + * a tagged release, as upstream's own integration guide prescribes ("copy the whole directory, + * from a tagged release, and do not edit the copy ... add a drift check to CI"). This is that check. * - * What it does: hashes each file in that directory, fetches the same file from the branch - * `upstream.json` tracks (`master` - the released code, not the work in progress on `develop`), - * hashes that, and compares. Any difference is reported, in either direction: a local edit and an - * upstream change look the same here, and both mean the copy has to be retaken. + * What it does, per `upstream.json`: + * - lists the upstream directory at the pinned `tag` and compares EVERY file byte for byte + * against the local one - upstream's `diff -r`, without needing a clone; + * - fails on a local file upstream does not have (other than `own_files`) - a shadowing + * `foo.ts` beside a copied `foo.ts` would otherwise win module resolution silently; + * - fails on an upstream file that is missing locally; + * - applies `allowed_divergences` - each a single exact line swap with a stated reason and expiry - + * to the fetched text before comparing. If upstream changes that line, the swap no longer + * matches and the check fails, so a shim cannot outlive the bug it works around; + * - fails when upstream has a NEWER tag than the pin: the copy is taken from releases, and a + * release nobody has looked at is exactly what the reviewer asked to be told about. * - * It compares against the BRANCH, not the recorded commit. A commit is immutable, so comparing - * against it would pass forever and catch nothing - which is how a real change to `utils.js` sat - * unnoticed for two days. + * Usage: npm run check:vendored-parser * - * Usage: - * npm run check:vendored-parser - * - * Needs read access to a private repository. Provide a token through any of - * LICENSE_KEY_REPO_TOKEN, GH_TOKEN or GITHUB_TOKEN, or be logged in to the `gh` CLI. Without one - * the check FAILS rather than passing quietly: "could not verify" is not "verified". + * Needs read access to a private repository: LICENSE_KEY_REPO_TOKEN, GH_TOKEN, GITHUB_TOKEN, or + * a logged-in `gh`. Without one it FAILS - "could not verify" is not "verified" - and a 401/403/404 + * is reported as an access problem, not as drift. */ 'use strict' @@ -45,7 +47,6 @@ function token() { if (fromEnv) { return fromEnv } - try { return execFileSync('gh', ['auth', 'token'], {encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore']}).trim() } catch (error) { @@ -53,40 +54,94 @@ function token() { } } -function fetchFile(repo, filePath, ref, auth) { +function get(apiPath, accept, auth) { return new Promise((resolve, reject) => { - const options = { + https.get({ hostname: 'api.github.com', - path: `/repos/${repo}/contents/${filePath}?ref=${encodeURIComponent(ref)}`, - headers: { - 'Accept': 'application/vnd.github.raw', - 'User-Agent': 'hyperformula-vendored-parser-check', - 'Authorization': `Bearer ${auth}`, - }, - } - - https.get(options, (response) => { + path: apiPath, + headers: {'Accept': accept, 'User-Agent': 'hyperformula-vendored-parser-check', 'Authorization': `Bearer ${auth}`}, + }, (response) => { const chunks = [] response.on('data', (chunk) => chunks.push(chunk)) response.on('end', () => { - if (response.statusCode !== 200) { - // The body of a failed call can echo the request back. Report the status and the path only. - reject(new Error(`GET ${filePath}@${ref} answered ${response.statusCode}`)) + const body = Buffer.concat(chunks) + + if (response.statusCode === 200) { + resolve(body) + } else { + const error = new Error(`${response.statusCode}`) - return + error.statusCode = response.statusCode + reject(error) } - resolve(Buffer.concat(chunks)) }) }).on('error', reject) }) } +const sha256 = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex') + +function semverGreater(a, b) { + const pa = a.split('.').map(Number) + const pb = b.split('.').map(Number) + + for (let i = 0; i < 3; i++) { + if ((pa[i] || 0) !== (pb[i] || 0)) { + return (pa[i] || 0) > (pb[i] || 0) + } + } + + return false +} + +/** Every file under an upstream directory at a ref, recursively, as `relative path -> api path`. */ +async function listUpstream(repo, dir, ref, auth) { + const out = new Map() + const walk = async(sub) => { + const listing = JSON.parse((await get(`/repos/${repo}/contents/${sub}?ref=${encodeURIComponent(ref)}`, 'application/vnd.github+json', auth)).toString('utf8')) + + for (const entry of listing) { + const rel = entry.path.slice(dir.length + 1) + + if (entry.type === 'dir') { + await walk(entry.path) + } else { + out.set(rel, entry.path) + } + } + } + + await walk(dir) + + return out +} + +/** Every file under the local directory, recursively, relative. */ +function listLocal(root) { + const out = [] + const walk = (sub) => { + fs.readdirSync(path.join(root, sub), {withFileTypes: true}).forEach((entry) => { + const rel = sub ? `${sub}/${entry.name}` : entry.name + + if (entry.isDirectory()) { + walk(rel) + } else { + out.push(rel) + } + }) + } + + walk('') + + return out +} + async function main() { const pin = JSON.parse(fs.readFileSync(PIN, 'utf8')) const auth = token() - console.log(`vendored parser: ${pin.repository}/${pin.directory} @ ${pin.track}, ${pin.files.length} files`) + console.log(`vendored reader: ${pin.repository}/${pin.directory} @ ${pin.tag}`) if (auth === null) { console.error('\nFAIL no credentials for a private repository.') @@ -96,51 +151,88 @@ async function main() { } const problems = [] - const hash = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex') + let upstream - for (const name of pin.files) { - const local = path.join(DIR, name) + try { + upstream = await listUpstream(pin.repository, pin.directory, pin.tag, auth) + } catch (error) { + console.error(`\nFAIL could not list ${pin.repository}/${pin.directory} at ${pin.tag}: HTTP ${error.message}.`) + console.error(error.statusCode === 404 + ? ' 404 from a private repository means the token has no access to it, or the tag does not exist. This is not drift.' + : ' This is an access or network problem, not drift.') + process.exit(1) + } + + const divergences = new Map((pin.allowed_divergences || []).map((d) => [d.file, d])) + const own = new Set(pin.own_files || []) + const local = listLocal(DIR).filter((rel) => !own.has(rel)) - if (!fs.existsSync(local)) { - problems.push(`${name}: named in upstream.json and missing from the directory`) - console.log(` GONE ${name}`) + for (const [rel, apiPath] of upstream) { + const localPath = path.join(DIR, rel) + + if (!fs.existsSync(localPath)) { + problems.push(`${rel}: in upstream at ${pin.tag}, missing here`) + console.log(` GONE ${rel}`) continue } let theirs try { - theirs = hash(await fetchFile(pin.repository, `${pin.directory}/${name}`, pin.track, auth)) + theirs = (await get(`/repos/${pin.repository}/contents/${apiPath}?ref=${encodeURIComponent(pin.tag)}`, 'application/vnd.github.raw', auth)).toString('utf8') } catch (error) { - problems.push(`${name}: upstream could not be read (${error.message})`) - console.log(` ???? ${name}`) + problems.push(`${rel}: upstream could not be read (HTTP ${error.message}) - access, not drift`) + console.log(` ???? ${rel}`) continue } - const ours = hash(fs.readFileSync(local)) + const shim = divergences.get(rel) + + if (shim) { + const occurrences = theirs.split(shim.upstream).length - 1 - if (ours === theirs) { - console.log(` ok ${name}`) + if (occurrences !== 1) { + problems.push(`${rel}: the allowed divergence no longer matches upstream (line found ${occurrences} times). Upstream moved - drop the shim and re-take the file.`) + console.log(` SHIM? ${rel}`) + continue + } + theirs = theirs.replace(shim.upstream, shim.local) + } + + const ours = fs.readFileSync(localPath, 'utf8') + + if (sha256(Buffer.from(ours)) === sha256(Buffer.from(theirs))) { + console.log(` ok ${rel}${shim ? ' (1 allowed divergence applied)' : ''}`) } else { - problems.push(`${name}: this copy is ${ours}, ${pin.track} is ${theirs}`) - console.log(` DIFF ${name}`) + problems.push(`${rel}: differs from upstream at ${pin.tag}`) + console.log(` DIFF ${rel}`) } } - fs.readdirSync(DIR) - .filter((name) => name.endsWith('.js') && pin.files.indexOf(name) === -1) - .forEach((name) => problems.push(`${name}: a JavaScript file nothing in upstream.json accounts for`)) + local.filter((rel) => !upstream.has(rel)).forEach((rel) => { + problems.push(`${rel}: exists here and not in upstream - a local file in this directory shadows or extends the copy; move it out`) + console.log(` EXTRA ${rel}`) + }) + + try { + const tags = JSON.parse((await get(`/repos/${pin.repository}/tags?per_page=20`, 'application/vnd.github+json', auth)).toString('utf8')) + const newer = tags.map((t) => t.name).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && semverGreater(name, pin.tag)) + + if (newer.length > 0) { + problems.push(`upstream has released ${newer.join(', ')} after ${pin.tag}. Review the change and re-take the copy from the newest tag.`) + } + } catch (error) { + problems.push(`could not list upstream tags (HTTP ${error.message}) - access, not drift`) + } if (problems.length === 0) { - console.log(`\nOK - every file is byte-identical to ${pin.track}`) + console.log(`\nOK - the directory is upstream's ${pin.directory} at ${pin.tag}, byte for byte${divergences.size ? `, with ${divergences.size} declared divergence(s)` : ''}`) return } console.error(`\n${problems.length} problem(s):`) - problems.forEach((problem) => console.error(` ${problem}`)) - console.error('\nThe copies and upstream have diverged - either upstream moved, or something was') - console.error('edited here. Re-take the files and update upstream.json in the same commit.') + problems.forEach((p) => console.error(` ${p}`)) process.exit(1) } diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 76f9c0a65a..7f94d1811a 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -3,7 +3,7 @@ * Copyright (c) 2025 Handsoncode. All rights reserved. */ -import {ENTITLEMENT_KEY_CHECKSUM_LENGTH} from '../license/handsontable-license-key-parser/constants' +import {CHECKSUM_LENGTH} from '../license/handsontable-license-key-parser/constants' import {checkKeySchema, extractTime} from './licenseKeyHelper' /** @@ -161,7 +161,7 @@ export function notifyLicenseKeyNotice(licenseKey: string, expiryDate: Date): vo * it has ever warned about; 129 characters per entry bounds that to the checksum alone. */ function noticeIdentityOf(licenseKey: string): string { - return licenseKey.trim().slice(-(ENTITLEMENT_KEY_CHECKSUM_LENGTH + 1)) + return licenseKey.trim().slice(-(CHECKSUM_LENGTH + 1)) } /** diff --git a/src/license/functionCapabilities.ts b/src/license/functionCapabilities.ts index a13045bd6c..294035b284 100644 --- a/src/license/functionCapabilities.ts +++ b/src/license/functionCapabilities.ts @@ -23,8 +23,11 @@ * breaking change. */ // Exported for the paired suite's drift checks, which compare this transcription against the -// packaging document group by group and member by member. Without the export those specs fail to -// compile (TS2459) and report zero tests, so the checks are lost rather than merely failing. +// packaging document group by group and member by member. Without the export the specs still run +// and still go red, but they die on `Cannot read properties of undefined` instead of comparing +// anything - so the comparison is lost while the suite looks merely broken. Measured on all three +// paths: `tsc --noEmit` says nothing (tsconfig includes `src` only, so the specs are not in its +// program), and Jest - which is what CI runs - throws at run time. export const FUNCTION_GROUPS: ReadonlyMap = new Map([ ['fun:math.a', ['ABS', 'LOG', 'MOD', 'POWER', 'PRODUCT', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'SQRT', 'SUM']], ['fun:stat.a', ['AVERAGE', 'COUNT', 'MAX', 'MIN']], diff --git a/src/license/handsontable-license-key-parser/AGENTS.md b/src/license/handsontable-license-key-parser/AGENTS.md new file mode 100644 index 0000000000..309a01c2c4 --- /dev/null +++ b/src/license/handsontable-license-key-parser/AGENTS.md @@ -0,0 +1,19 @@ +# Entitlement key reader - rules for coding agents + +`README.md` here is the full integration guide; read it before changing anything that calls this code. Which repository you are in decides the first rule: + +- **In `handsontable/license-key`** (this directory is `vendor/entitlement-key-reader/` next to `src/`), this is the **original**. Edit it together with `src/entitlement-key/` - a change to the key format is a change to both, in the same PR (see the root `CLAUDE.md`). Keep the tests in `test/entitlement-key-reader/` passing and extend them for anything new. +- **Anywhere else** (a product such as Handsontable or HyperFormula), this directory is a **copy**. **Do not edit files in it.** Fix the original in `license-key` and copy the directory again. A local change makes two products disagree about the same key, and CI drift checks will fail. + +In both places: + +- **Every import stays inside this directory.** No npm dependencies, and no `crypto`, `Buffer`, `TextEncoder`, `crypto.subtle` or DOM APIs - the reader must run on plain `http://` pages and in any bundler. +- **Product-specific code lives outside this directory**: the product name, the build date, the literal keys, the messages and the capability-token gates. +- **Call `readEntitlementLicense(key, { product, buildDate })`** for a key that `detectLicenseKeyFormat` reports as `'entitlement'`. Legacy and literal keys are the product's own path. +- **Never convert a license date through `Date`.** Print `lifecycle.licensedUntil` as it is. Pass the build date as bare `YYYY-MM-DD` text (`toIsoBuildDate` converts `DD/MM/YYYY`). +- **Do not "repair" a key** by removing whitespace inside the `[...]` block. Trimming the whole key is fine. +- **An unlicensed key unlocks everything** (`UNRESTRICTED_GRANTS`). Never gate features away from a key that failed to read. +- **`no-ui-warns` silences UI warnings, not the trial hard-stop block.** +- **Everything the reader returns is frozen** and typed read-only. Copy an array before sorting or changing it. +- **A build date in the wrong format throws**; only a missing one fails open. +- **Tests pin the clock.** Pass `now`, or mock `Date.now`. Fixture keys come from the `license-key` generator CLI; forged keys come from a test-only helper that is never imported from product source. diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index ef022616a2..30ab7a6cbb 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -1,18 +1,24 @@ # Vendored entitlement-key reader -The `.js` files in this directory are **byte-identical copies** of code owned by another -Handsoncode repository. They are not edited here, ever: fix a bug upstream, then re-take the copy. -A local-only fix forks the two, and a forked checksum or parser rejects genuine customer keys. - -The `.d.ts` beside each one is HyperFormula's, hand-written, because `allowJs` is on and the -JavaScript carries no types of its own. +This directory is a copy of `handsontable/license-key`'s **`vendor/entitlement-key-reader/`**, +the TypeScript reader that repository publishes for products to copy. It is taken whole, from a +tagged release, and not edited here: fix upstream, then re-take. A local fix makes two products +disagree about the same key. | | | |---|---| | Repository | `handsontable/license-key` (private) | -| Directory | `src/entitlement-key` | -| Tracked branch | `master` - the released code; `develop` there is work in progress | -| Copy taken from | `03810fd3c` (2026-09-28) | +| Directory | `vendor/entitlement-key-reader` | +| Tag | `4.0.1` (`03810fd3c`, 2026-09-28) | +| Pin | `upstream.json` | + +## One declared divergence + +`extractKeyData.ts`, one line: `Object.keys(current)` → `Object.keys(current as object)`. HyperFormula +compiles with TypeScript 4.0.8, which does not narrow `unknown` through `!== null && typeof === +'object'`; upstream compiles under 5.9. The cast changes no behaviour. It is recorded in +`upstream.json` with its reason, and the check below applies it before comparing - so the day +upstream changes that line, the entry stops matching, the check fails, and the shim comes out. ## Checking it @@ -20,53 +26,30 @@ JavaScript carries no types of its own. npm run check:vendored-parser ``` -Hashes every file here and the same file on `master`, and fails on any difference. A local edit -and an upstream change look identical to it, which is the point: either means the copy is stale. -It also fails on a `.js` that `upstream.json` does not account for, and on one it names that is -missing. - -It needs read access to the private repository (`LICENSE_KEY_REPO_TOKEN`, `GH_TOKEN`, -`GITHUB_TOKEN`, or a logged-in `gh`). Without credentials it **fails** rather than skipping: a -check that reports success when it could not look is worse than no check. - -When upstream moves, re-take the changed file and update `upstream.json` in the same commit. +Lists the upstream directory at the pinned tag and compares every file byte for byte. Fails on any +difference, on a file here that upstream does not have (a shadowing `.ts` would win module +resolution silently), on an upstream file missing here, and on a **newer upstream tag** than the +pin. Without credentials to the private repository it fails rather than skips. -## What the last re-take changed +## What HyperFormula uses from it -`6862da557` (2026-09-28) made `parseIsoDate` test `typeof isoDate === 'string'` before matching the -pattern, so a `usage_until` of `['2099-12-31']` - which stringifies to a valid date - is now -rejected by the reader instead of accepted. +`extractEntitlementKeyData`, `detectLicenseKeyFormat`, `parseIsoDateToTimestamp`, `CHECKSUM_LENGTH`, +and the types - from `src/license/licenseResolution.ts` and `src/helpers/licenseKeyValidator.ts`, +which sit beside the copy, as upstream's guide prescribes. The reader also offers +`readEntitlementLicense` / `classifyEntitlement` / `getLicenseGrants` (window evaluation and grant +picking); HyperFormula evaluates windows in `licenseResolution.ts` and does not use those yet. +Consolidating onto them is a separate decision. -HyperFormula used to carry that check itself, next door in `licenseResolution.ts`, because upstream -did not have it. That local check is gone: it became dead code the moment this copy was taken. +Upstream's `README.md` in this directory is the integration guide; `AGENTS.md` is theirs too. -One behaviour changed with it, deliberately. The local check looked at HyperFormula's own product -entry only, on the grounds that another product's fields were not ours to reject. Upstream's check -is in the parser, so it applies to every entry: a mistyped date in a DataGrid entry now invalidates -the whole key, our grant included. That is upstream's rule and the key specification's (T7), and it -is pinned in `entitlement-key-resolution.spec.ts`. - -## Not vendored, on purpose - -The entitlement reader is deliberately schema-free upstream (unknown products, tokens and flags -are tolerated, so nothing about *reading* a key depends on the vocabulary), which keeps the -vendored surface small: everything schema- and generation-side stays out. - -| Upstream file | Why not | -|---|---| -| `generate-key.js`, `build-payload.js`, `build-prose.js` | Mint keys. HyperFormula only ever reads them. | -| `default-schema.js` | The generator's vocabulary (packages, add-ons, wordings, templates). The reader needs no schema; the only name this library reads is its own product entry, kept as `HYPERFORMULA_PRODUCT_NAME` in `src/license/licenseResolution.ts`. | -| `create-engine.js`, `resolve-schema.js`, `validate-schema.js`, `validate-record.js` | Bind and verify a caller's schema/record at generation time — generator-side. | -| `validate-key.js` | A two-line boolean wrapper over `extractEntitlementKeyData`; the extractor is called directly. | +## Lint and types -`utils.js` is taken whole, so its two generation-side helpers `bytesToBase64` and -`stringToBase64Url` come with it. Nothing in HyperFormula calls them; a verbatim copy does not get -to pick which exports it keeps. +The directory is excluded from ESLint (upstream style; the same treatment as +`src/interpreter/plugin/3rdparty`) and type-checked with the rest of `src`. Published typings are +emitted from these sources by `tsc`, as for any other `.ts` here. ## Related -- `src/helpers/licenseKeyHelper.ts` — the validator for the legacy 25-character key format, - untouched here (upstream 4.0.0 still exports it too). -- `src/license/licenseResolution.ts` — the consumer: routes on `detectLicenseKeyFormat` and turns +- `src/license/licenseResolution.ts` - the consumer: routes on `detectLicenseKeyFormat` and turns the extracted payload into an entitlement. -- `src/license/capabilities.ts` — the capability table the payload's tokens are resolved against. +- `src/license/capabilities.ts` - the capability table the payload's tokens are resolved against. diff --git a/src/license/handsontable-license-key-parser/README.md b/src/license/handsontable-license-key-parser/README.md new file mode 100644 index 0000000000..a91a89b492 --- /dev/null +++ b/src/license/handsontable-license-key-parser/README.md @@ -0,0 +1,359 @@ +# Entitlement key reader + +The part of [`handsontable/license-key`](https://github.com/handsontable/license-key) that a product copies into its own source tree to read **entitlement license keys**. It verifies a key, picks the entry for your product, tells you which lifecycle window the license is in, which warning channels the key keeps open, and which capabilities it unlocks. + +It is plain TypeScript with **no dependencies**. It does not use `crypto`, `Buffer`, `TextEncoder`, the Web Crypto API or the DOM, so it runs in any browser (including plain `http://` intranet pages), in Node, and in a worker. It type-checks under `strict` against the ES2015 library only. + +It is **general**. Nothing in it names Handsontable, HyperFormula or any other product. Your product passes in what is specific to it: its product name, its build date and the literal keys it accepts. + +What it does **not** do: + +- generate keys (that is the `license-key` package, used by my.handsontable.com), +- read the legacy 25-character keys (each product keeps its own legacy validator), +- print messages or render UI (the wording and the surfaces are the product's; the table in [What to do in each state](#what-to-do-in-each-state) gives the specification's text). + +## Contents + +- [Copy it into a product](#copy-it-into-a-product) +- [The key in 60 seconds](#the-key-in-60-seconds) +- [Integrate it in five steps](#integrate-it-in-five-steps) +- [What to do in each state](#what-to-do-in-each-state) +- [Rules you must not break](#rules-you-must-not-break) +- [What each product supplies](#what-each-product-supplies) +- [Test it in your product](#test-it-in-your-product) +- [API reference](#api-reference) +- [Files](#files) + +## Copy it into a product + +Copy the **whole directory**, from a tagged release of `license-key`, and do not edit the copy: + +```bash +# from the product repository +LICENSE_KEY_TAG=4.1.0 # the license-key release you copy from - an example, use a real tag +git clone --depth 1 --branch "$LICENSE_KEY_TAG" git@github.com:handsontable/license-key.git /tmp/license-key +rm -rf src/utils/entitlementKeyReader +cp -R /tmp/license-key/vendor/entitlement-key-reader src/utils/entitlementKeyReader +``` + +The target path is yours to choose. Keep the files together: every import inside the directory is relative to it, and nothing imports from outside it. + +Treat the copy as read-only: + +- **Fix bugs in `license-key`, then copy again.** A local fix makes the products disagree about the same key, and a customer sees one product accept a key another rejects. +- **Add a drift check to CI.** Record the tag you copied from, and fail the build when the copy no longer matches it: + + ```bash + git clone --depth 1 --branch "$LICENSE_KEY_TAG" git@github.com:handsontable/license-key.git /tmp/license-key + diff -r /tmp/license-key/vendor/entitlement-key-reader src/utils/entitlementKeyReader + ``` + +- **Put your own code next to the copy, not inside it.** A `license.ts` beside it that calls `readEntitlementLicense` and holds your messages is the usual shape. + +A TypeScript product imports it directly. A JavaScript product needs a build step that strips types (Babel's `@babel/preset-typescript`, `esbuild`, `swc` or `tsc`) - the files use nothing beyond type annotations. + +**Do not install `license-key` as a dependency instead.** The package carries the generator, which products must not ship, and a product with a GPL distribution (HyperFormula) cannot depend on a private package without breaking `npm install` for its open-source users. Copying the reader is the chosen delivery form (specification §7.1). + +## The key in 60 seconds + +A key is plain-English text for humans, then a block for the library: + +``` +This is a Handsontable license key for Acme Corp, issued on 2026-08-12. It includes 1 license: + +> 1. Subscription license under Handsontable Subscription License Agreement 2.0 of 2022-05-21, for Handsontable on the Enterprise package, for internal use, valid until 2027-08-12 (UTC). Use after that date is not permitted. To renew, contact sales@handsontable.com. + +[eyJwcm9kdWN0cyI6eyJoYW5k......<128 hex characters of SHA-512>] +``` + +- **The prose is never read.** It is not covered by the checksum either, so a key still works after a mail client rewraps it. A user may paste the whole text or the `[...]` block alone - both read the same. +- **The block** is `[`, a base64url (URL-safe, unpadded) JSON payload, the SHA-512 hex of that encoded payload (128 lowercase characters), and `]`. The block is the **last** `[` in the string and the first `]` after it. +- **The payload** lists what is licensed, per product: + + ```json + { + "products": { + "hyperformula": { + "capabilities": ["functions_1", "functions_2", "spreadsheet"], + "release_until": "2027-03-31", + "notice": 0, + "grace": 0, + "flags": ["no-console-warns", "no-ui-warns"] + } + } + } + ``` + +| Field | Meaning | +| --- | --- | +| `products` | Keyed by product name. **Presence means licensed.** A key may grant several products; each has its own dates and flags. | +| `capabilities` | Opaque tokens. The key says *what is granted*; your product decides *what each token unlocks*. | +| `usage_until` | The last licensed day, inclusive, in UTC. Measured against the clock. A subscription or a trial. | +| `release_until` | Builds released on or before this day may run forever. Measured against your build date, never the clock. A perpetual license. | +| `notice` | Days of advance warning before `usage_until`. `0` means no warning. | +| `grace` | Days of soft stop after `usage_until` before the hard stop. | +| `flags` | `trial`, `no-console-warns`, `no-ui-warns`, `custom`. Present or absent - there is no `false`. | + +Exactly **one** of `usage_until` / `release_until` is present. There is no contract type, tier, package name or holder in the payload - "subscription" or "perpetual" is only visible as which date is present. + +## Integrate it in five steps + +```ts +import { + detectLicenseKeyFormat, + readEntitlementLicense, + toIsoBuildDate, + hasCapability, + UNRESTRICTED_GRANTS, +} from './entitlementKeyReader'; +import type { LicenseGrants } from './entitlementKeyReader'; + +const PRODUCT = 'hyperformula'; // 1. your product name, as it appears in the payload +const LITERAL_KEYS = ['gpl-v3', 'internal-use-in-handsontable', 'hftrial-0168e-1f2b7-47158-70b05-0842f']; +const BUILD_DATE = toIsoBuildDate(process.env.HT_RELEASE_DATE); // "DD/MM/YYYY" -> "YYYY-MM-DD" + +// Returns what the key unlocks. Every path returns grants - never a report's +// result - because the feature gates read them. +export function checkLicense(rawKey: unknown): LicenseGrants { + const key = typeof rawKey === 'string' ? rawKey.trim() : ''; + + // 2. Route the key. Only "entitlement" goes to this reader. + switch (detectLicenseKeyFormat(key, LITERAL_KEYS)) { + case 'literal': + handleLiteralKey(key); // your existing behaviour + return UNRESTRICTED_GRANTS; + case 'legacy': + handleLegacyKey(key); // your existing legacy validator + return UNRESTRICTED_GRANTS; + case 'unknown': + if (key === '') { + reportMissingKey(); + } else { + reportInvalidKey(); + } + return UNRESTRICTED_GRANTS; + case 'entitlement': + break; + } + + // 3. Read it for your product. + const license = readEntitlementLicense(key, { product: PRODUCT, buildDate: BUILD_DATE }); + + if (!license.licensed) { + // The block is broken, or the key licenses other products only. + // license.reason is 'unreadable' or 'product_missing' - both are an invalid key to the user. + reportInvalidKey(); + + return license.grants; // UNRESTRICTED_GRANTS - an invalid key nags, it never strips features + } + + // 4. Act on the lifecycle state, through the channels the key leaves open. + notify(license.lifecycle, license.channels); + + // 5. Gate features by capability token. + return license.grants; +} + +// Anywhere a feature is gated: +const grants = checkLicense(settings.licenseKey); + +if (!hasCapability(grants, PRODUCT, 'spreadsheet')) { + // not unlocked by this key +} +``` + +Notes on each step: + +1. **The product name** is the key of `products` in the payload. Names are append-only and never renamed, so a constant is right. +2. **Literal keys** are the plain words your product accepts as a key. They are your decision, so the reader knows none unless you pass them. Check them before anything else, as the example does. Trim the key once, at the start, and pass the trimmed value everywhere - an untrimmed legacy key fails its checksum. A blank entry in the list is ignored. +3. **The build date** is the release date of the installed build as a bare `YYYY-MM-DD`. `toIsoBuildDate` converts the `DD/MM/YYYY` the Handsoncode build pipelines inject, by reordering the text - never through a `Date`. A **missing** build date (`undefined`, `null`, `''`) fails open; a date in **any other format** - the raw `DD/MM/YYYY` included - throws a `TypeError`, whatever the key, so the mistake shows in your first test instead of silently switching off every `release_until` check. `now` is optional and defaults to `Date.now()`; pass it in tests. +4. **Read the key once per start-up** and share the result between your console message and your UI. The reader caches the last key it read, so a second read is cheap, but one result is what keeps two surfaces from disagreeing. +5. **An unlicensed key unlocks everything.** When `licensed` is `false`, `grants` is `UNRESTRICTED_GRANTS` and `hasCapability` answers `true` for every token. An invalid key nags; it never takes features away. Do the same for legacy, literal, missing and unknown keys - return `UNRESTRICTED_GRANTS` to your gates, as the example does - so adding capability gating can never break an existing customer. +6. **Everything the reader returns is frozen**, and typed read-only. Copy an array (`capabilities.slice()`) before sorting or changing it; `getProductCapabilities` already returns a copy. + +## What to do in each state + +`license.lifecycle.state` is one of ten values. The windows are measured the same way for a trial and a subscription; the `trial` flag changes only the wording and whether the hard stop blocks. + +| State | When | Console (if `channels.console`) | UI (if `channels.ui`) | +| --- | --- | --- | --- | +| `usage_valid` | before the notice window | nothing | nothing | +| `usage_notice` | the last `notice` days, up to and including `usage_until` | warning | nothing | +| `usage_soft_stop` | after `usage_until`, through `grace` days | error | nothing | +| `usage_hard_stop` | after the grace period | error - the soft-stop message persists (18.1 never blocks a paying customer) | nothing | +| `trial_valid` | as `usage_valid`, on a trial | nothing | optional trial badge | +| `trial_notice` | as `usage_notice`, on a trial | warning | optional trial badge | +| `trial_soft_stop` | as `usage_soft_stop`, on a trial | error | a banner or a modal | +| `trial_hard_stop` | as `usage_hard_stop`, on a trial | error | **block the product** - applied even when `channels.ui` is `false` | +| `release_valid` | the build is covered by `release_until` | nothing | nothing | +| `release_expired` | the build was released after `release_until` | error | a banner | + +`lifecycle.daysRemaining` is the whole UTC days until `usage_until` (`0` on the last licensed day, negative after it, `null` for `release_until`). `lifecycle.licensedUntil` is the date exactly as the key carries it - print that string, never a date rebuilt from a timestamp. + +The two flags close channels, per product: + +- `no-console-warns` - nothing reaches the console. +- `no-ui-warns` - no **warning** is rendered in the UI. It does **not** lift the trial hard-stop block: the block is enforcement, not a warning (Handsontable decision DEV-2709; the specification's §4.1 table header does not record the split yet). + +Both are set on keys issued for external, end-user-facing use, so your license messages never reach your customer's own users. + +The specification's message text (§4.1, §4.2). Replace `{PRODUCT}` with your product's display name. Print `usage_until` dates with the ` (UTC)` marker and `release_until` dates without it: + +| State | Message | +| --- | --- | +| `trial_notice` | `Your {PRODUCT} license key expires in {N} days. To continue using {PRODUCT}, you need to purchase a license.` | +| `trial_soft_stop` | `Your {PRODUCT} trial license key expired on {DATE} (UTC). To continue using {PRODUCT}, you need to purchase a license.` | +| `trial_hard_stop` | `Your {PRODUCT} trial license key expired on {DATE} (UTC). You may no longer use {PRODUCT} under the trial license. To continue using the software, contact sales@handsontable.com to purchase a valid license.` | +| `usage_notice` | `Your {PRODUCT} subscription license expires on {DATE} (UTC). To renew your license, contact sales@handsontable.com.` | +| `usage_soft_stop`, `usage_hard_stop` | `Your {PRODUCT} subscription license expired on {DATE} (UTC). To continue using the software, contact sales@handsontable.com to purchase a valid license key.` | +| `release_expired` | `The license key for {PRODUCT} expired on {DATE}, and is not valid for the installed version {VERSION}. Renew your license key or downgrade to a version released on or before {DATE}. If you need any help, contact us at sales@handsontable.com.` | + +Two edges the specification leaves open, as Handsontable words them: `{N}` of `1` reads "expires in 1 day", and `0` reads "expires today" (the last licensed day is licensed in full). Show each distinct message once per key per page, not once per instance. + +The message for an **invalid or missing** key is not in the specification yet (§4.5). Handsontable reuses its legacy messages and points at support rather than sales, because both are install faults. + +## Rules you must not break + +Each of these has broken a real implementation, or a specification fixture exists for it. + +1. **Never convert a date through `Date`.** Compare `usage_until` in UTC, and `release_until` against the build date **as text** (`'2027-08-12' >= '2027-08-11'` is exact for `YYYY-MM-DD`). `new Date('07/14/2025')` parses in local time; a `toISOString()` round trip moves a date by a day east of UTC. +2. **`usage_until` is inclusive.** The license is valid until the UTC midnight that *follows* it. The hard stop starts at `usage_until + 1 + grace` days, `00:00:00Z`. Day counts are calendar days (UTC midnight to UTC midnight), never milliseconds divided and floored. `notice: 0` means no warning window at all. +3. **A `release_until` license never reads the clock.** A perpetual key must read the same with the clock set to 1999 or 2035, or on an offline machine. +4. **Fail open on a missing build date, and only on a missing one.** If the build date is missing (`undefined`, `null`, empty), a `release_until` license reads as `release_valid` - a broken build must never tell a paying customer their license lapsed. A build date in the wrong format is your bug and throws; convert with `toIsoBuildDate`. Read the build constant exactly as your bundler inlines it - do not wrap `process.env.X` in a `typeof process` guard, which the bundler does not inline and which then blanks the date. +5. **Do not repair a key.** Surrounding whitespace is fine to trim. Whitespace, line breaks or anything else *inside* the brackets makes the key invalid - stripping it would accept keys the generator never issued. +6. **Be strict about shape, lenient about vocabulary.** Unknown products, capability tokens, flags and extra fields are kept and ignored. A key your build does not fully understand must still read. Only a malformed shape (both dates, no date, a bad date, a negative window) makes a key invalid. +7. **Never branch on a contract type or a package name.** The payload has neither. Decide by which date is present and by the `trial` flag - which is what the state names already encode. +8. **The capability-token meaning lives in your product.** Keep the list of tokens your build understands next to your feature gates. Tokens are only ever added to a product, never removed, so a gate on an existing token stays valid. +9. **Keep the copy identical to `license-key`.** See [Copy it into a product](#copy-it-into-a-product). + +## What each product supplies + +| | Handsontable | HyperFormula | +| --- | --- | --- | +| `product` | `'handsontable'` | `'hyperformula'` | +| Build date | `process.env.HOT_RELEASE_DATE` (`DD/MM/YYYY`) | `process.env.HT_RELEASE_DATE` (`DD/MM/YYYY`) | +| Literal keys | `non-commercial-and-evaluation`, `ht68e-1f2b7-47158-70b05-0842f` | `gpl-v3`, `internal-use-in-handsontable`, `hftrial-0168e-1f2b7-47158-70b05-0842f` | +| Capability tokens | `core` | `functions_1` ... `functions_4`, `spreadsheet`, `import_export` | +| Legacy keys | own obfuscated validator | own obfuscated validator | + +Pass **every** literal key the product accepts today, including the ones shaped like a legacy key: checked first, they never reach the legacy validator. The lists above are what each product accepted when this reader was written - check the product's own validator before copying them. + +A new product needs the same five things: a product name agreed with my.handsontable.com, a build date, its literal keys (maybe none), its capability tokens, and a decision about its legacy keys (maybe none). + +Handsontable already ships an earlier port of this reader in `handsontable/src/utils/entitlementLicenseKey/` (DEV-2562). This directory is that port made general, with the same state names and window rules. The differences, when switching Handsontable over: + +- the product name is passed in (`readEntitlementLicense(key, { product })`) instead of being built in, +- `detectLicenseKeyFormat(key, literalKeys)` takes the literal keys and returns `'literal'` for them, where the port returns `'non-commercial-and-evaluation'` (Handsontable only calls `isEntitlementKey`, which is unchanged), +- a date that is not a string, such as `["2027-08-12"]`, makes the key invalid - the port still accepts it, +- `extractEntitlementKeyData` returns `null` for a value that is not a string, +- every result is frozen and typed read-only - code that sorts or pushes into one must copy it first, +- a build date in the wrong format throws; the port fails open on it, +- `classifyEntitlement` throws for an entry without exactly one valid date, +- the clock is read once per `readEntitlementLicense` call, and never for a `release_until` entry. + +## Test it in your product + +The windows are evaluated in this directory and are already covered by `license-key`'s own tests (the specification's Date semantics fixtures J1-J10). Your product still needs to test **its own wiring**: + +- each literal key, a legacy key, a missing key and an unreadable key reach the right path, +- each of the ten states produces the right message on the right surface, and nothing when the matching channel is closed, +- the trial hard stop blocks even with `no-ui-warns`, +- a key for another product only reports an invalid key, +- the build date constant reaches `readEntitlementLicense` in your real bundle, not only in tests, +- pin `now` (or mock `Date.now`) in every test - never rely on the real clock. + +For fixture keys, generate real ones with the `license-key` CLI, so a misunderstanding shared by your test and your code cannot pass: + +```bash +# in a checkout of license-key +npm install && npm run build +npm run generate-entitlement-key --record='{"holder":"Test Fixture","issued":"2026-08-12","licenses":[{"product":"hyperformula","contractType":"perpetual","agreement":"perpetual-2.0","package":"Pro","mode":"internal","date":"2027-03-31","notice":0,"grace":0}]}' +``` + +For the shapes the generator refuses (both dates, a bad date, an unknown token), build the block yourself in a test-only helper - kept in a `__tests__/` directory beside the copy, and never imported from your source: + +```ts +import { sha512 } from '../entitlementKeyReader/sha512'; +import { stringToUtf8Bytes, stringToBase64Url } from '../entitlementKeyReader/encoding'; + +export function buildTestKey(payload: object): string { + const encoded = stringToBase64Url(JSON.stringify(payload)); + + return `[${encoded}${sha512(stringToUtf8Bytes(encoded))}]`; +} +``` + +This is not a secret: the checksum recipe ships in every product bundle by design. The key protects integrity (a typo or a broken paste cannot pass), not authenticity. + +## API reference + +### `readEntitlementLicense(licenseKey, { product, buildDate, now? })` -> `EntitlementLicense` + +The one call a product needs. Verifies the block, picks the product's entry, classifies it, reads its flags and resolves its grants. + +```text +licensed: { licensed: true, reason: null, entitlement, lifecycle, channels, grants } +not licensed: { licensed: false, reason: 'unreadable' | 'product_missing', entitlement: null, + lifecycle: null, channels: { console: true, ui: true }, grants: UNRESTRICTED_GRANTS } +``` + +The result is frozen all the way down, in both cases. + +Throws a `TypeError` - a wrong argument is your bug, and a silent "invalid" would hide it - when: + +- the options object is missing, +- `product` is not a non-empty string, +- `now` is given and is not a finite number of milliseconds, +- `buildDate` is present but not a real `YYYY-MM-DD` (a missing one - `undefined`, `null`, `''` - fails open instead). + +The argument checks run before the key is read, so they fail whatever key a test uses. + +### `toIsoBuildDate(releaseDate)` -> `string` + +`'14/07/2025'` -> `'2025-07-14'`. Also accepts an already-bare `YYYY-MM-DD`. Returns `''` for anything that is not a real date, so its output is always safe to pass on: a real date, or a missing one (fails open). + +### `detectLicenseKeyFormat(licenseKey, literalKeys?)` -> `'entitlement' | 'legacy' | 'literal' | 'unknown'` + +Tells the shape of a key without validating it. `'entitlement'` means "a `[...]` block is present", not "valid". `literalKeys` are compared trimmed and case-insensitively; a blank entry, and a missing or non-array list, are ignored. `isEntitlementKey(licenseKey)` is the one-line form of the entitlement check. + +### `extractEntitlementKeyData(licenseKey)` -> `{ products } | null` + +The verified, frozen payload, or `null` for any unreadable key. `validateEntitlementKey(licenseKey)` returns the same as a boolean. `getProductEntitlement(data, product)` returns one product's entry or `null`, reading own properties only. + +### `classifyEntitlement(entitlement, { now, buildDate })` -> `LicenseLifecycle` + +`{ state, isTrial, daysRemaining, licensedUntil }` for one verified entry. It checks `buildDate` as `readEntitlementLicense` does, and throws for an entry that does not carry exactly one valid date - pass an entry read by `extractEntitlementKeyData`, not one you built. + +### `resolveChannels(entitlement)` -> `{ console, ui }` + +Which channels the entry's flags leave open. + +### Grants + +- `getLicenseGrants(data)` -> `{ unrestricted: false, products: { [name]: { capabilities } } }` +- `UNRESTRICTED_GRANTS` - frozen; every query answers "granted". +- `hasProductGrant(grants, product)` -> `boolean` +- `hasCapability(grants, product, token)` -> `boolean` +- `getProductCapabilities(grants, product)` -> `string[] | null` (a copy; `null` when unrestricted or not granted) + +### Constants + +`TRIAL_FLAG`, `NO_CONSOLE_WARNS_FLAG`, `NO_UI_WARNS_FLAG`, `CUSTOM_FLAG`. + +## Files + +| File | What it holds | +| --- | --- | +| `index.ts` | the public exports | +| `readLicense.ts` | `readEntitlementLicense` | +| `detectFormat.ts` | `detectLicenseKeyFormat`, `isEntitlementKey` | +| `extractKeyData.ts` | the block reader: checksum, decode, shape checks, the one-entry cache | +| `classify.ts` | the lifecycle windows and the channels | +| `grants.ts` | capability queries | +| `buildDate.ts` | `toIsoBuildDate` | +| `encoding.ts` | UTF-8, base64 and `YYYY-MM-DD` parsing, without `TextEncoder` or `Buffer` | +| `sha512.ts` | a pure-JS SHA-512 - the Web Crypto API is unavailable on plain `http://` pages | +| `constants.ts`, `types.ts` | names and shapes | +| `AGENTS.md` | the rules above, for AI coding agents working near the copy | + +The full format, and the reasons behind it, are in `license-key`: `.ai/ENTITLEMENT-KEY-FORMAT.md` and `.ai/DESIGN-DECISIONS.md`. The specification is [License Keys - part 1 (18.1) rev 6](https://app.clickup.com/9015210959/v/dc/8cnjcyf-31675/8cnjcyf-46715), with its [Date semantics fixtures](https://app.clickup.com/9015210959/v/dc/8cnjcyf-31675/8cnjcyf-48255) and [Examples](https://app.clickup.com/9015210959/v/dc/8cnjcyf-31675/8cnjcyf-48235). diff --git a/src/license/handsontable-license-key-parser/buildDate.ts b/src/license/handsontable-license-key-parser/buildDate.ts new file mode 100644 index 0000000000..a2b9ceb3f6 --- /dev/null +++ b/src/license/handsontable-license-key-parser/buildDate.ts @@ -0,0 +1,69 @@ +import { parseIsoDateToTimestamp } from './encoding'; + +/** + * Turns a build release date into the bare "YYYY-MM-DD" text that + * `release_until` is compared against. + * + * Accepts the "DD/MM/YYYY" form the Handsoncode build pipelines inject (for + * example `process.env.HOT_RELEASE_DATE` or `process.env.HT_RELEASE_DATE`) and + * an already-bare "YYYY-MM-DD". The parts are REORDERED as text and never + * routed through a `Date`: `new Date('07/14/2025')` parses in the machine's + * local timezone, which is exactly the kind of shift the date rules exist to + * prevent. + * + * Returns an empty string when the value is missing or not a real date. Passed + * on to `readEntitlementLicense`, an empty build date fails OPEN - a broken + * build must never tell a paying customer that their license lapsed. + * + * @param {*} releaseDate The build release date, "DD/MM/YYYY" or "YYYY-MM-DD". + * @returns {string} The date as "YYYY-MM-DD", or "" when it cannot be read. + */ +export function toIsoBuildDate(releaseDate: unknown): string { + if (typeof releaseDate !== 'string') { + return ''; + } + + const value = releaseDate.trim(); + const dayMonthYear = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(value); + const isoDate = dayMonthYear === null + ? value + : `${dayMonthYear[3]}-${`0${dayMonthYear[2]}`.slice(-2)}-${`0${dayMonthYear[1]}`.slice(-2)}`; + + return parseIsoDateToTimestamp(isoDate) === null ? '' : isoDate; +} + +/** + * Checks the build date a caller passed in, and returns it ready to compare. + * + * Two different failures, two different answers: + * + * - MISSING (`undefined`, `null`, an empty or blank string) fails OPEN and + * returns "". That is a broken build - a bundler that did not inline the + * release date constant - and a paying customer must never be told their + * license lapsed because of it. + * - PRESENT BUT WRONG (anything else that is not a bare, real "YYYY-MM-DD", + * such as the raw "DD/MM/YYYY" a build pipeline injects) throws. That is + * the product's bug, it is the same on every run, and failing open on it + * would silently turn off every `release_until` check. The product's own + * tests see the error on the first key they read. + * + * @param {*} buildDate The build date the caller passed. + * @param {string} caller The public function name, for the error message. + * @returns {string} The build date, or "" when it is missing. + */ +export function resolveBuildDate(buildDate: unknown, caller: string): string { + if (buildDate === undefined || buildDate === null) { + return ''; + } + if (typeof buildDate === 'string' && buildDate.trim() === '') { + return ''; + } + if (parseIsoDateToTimestamp(buildDate) === null) { + const got = typeof buildDate === 'string' ? `"${buildDate}"` : `a ${typeof buildDate}`; + + throw new TypeError(`${caller}: "buildDate" has to be a "YYYY-MM-DD" date, got ${got}. ` + + 'Convert a "DD/MM/YYYY" release date with toIsoBuildDate().'); + } + + return buildDate as string; +} diff --git a/src/license/handsontable-license-key-parser/classify.ts b/src/license/handsontable-license-key-parser/classify.ts new file mode 100644 index 0000000000..ce158e2295 --- /dev/null +++ b/src/license/handsontable-license-key-parser/classify.ts @@ -0,0 +1,157 @@ +import type { + ProductEntitlement, + LicenseLifecycle, + LicenseState, + LicenseChannels, + LicenseTimeReference, +} from './types'; +import { parseIsoDateToTimestamp } from './encoding'; +import { resolveBuildDate } from './buildDate'; +import { + TRIAL_FLAG, + NO_CONSOLE_WARNS_FLAG, + NO_UI_WARNS_FLAG, + MILLISECONDS_PER_DAY, +} from './constants'; + +/** + * The window a `usage_until` license is in, before the trial flag decides how + * it is worded. + */ +type UsageWindow = 'valid' | 'notice' | 'soft_stop' | 'hard_stop'; + +/** + * The UTC midnight of the day an instant falls on. Every window boundary is a + * UTC midnight, so both sides of every comparison are snapped to one - the + * local calendar, the locale and DST are inputs the classification must not + * read at all. + * + * @param {number} timestamp The instant, in epoch milliseconds. + * @returns {number} + */ +function utcMidnightOf(timestamp: number): number { + return Math.floor(timestamp / MILLISECONDS_PER_DAY) * MILLISECONDS_PER_DAY; +} + +/** + * Whole UTC days from today until the last licensed day. `0` on the last + * licensed day (which is still licensed in full) and negative once it has + * passed. Both sides are UTC midnights, so the count is a whole number of + * calendar days and never a rounded fraction. + * + * @param {number} expiryTimestamp The UTC midnight of the last licensed day. + * @param {number} now The current instant, in epoch milliseconds. + * @returns {number} + */ +function daysUntil(expiryTimestamp: number, now: number): number { + return (expiryTimestamp - utcMidnightOf(now)) / MILLISECONDS_PER_DAY; +} + +/** + * Places a `usage_until` license in its window. + * + * The named day is licensed in full: the license runs until the UTC midnight + * that FOLLOWS it, and the grace period is measured from there. A `notice` of + * `0` means no advance warning at all, so the notice window is empty rather + * than one day long. + * + * @param {number} expiryTimestamp The UTC midnight of the last licensed day. + * @param {ProductEntitlement} entitlement The product entry the windows come from. + * @param {number} now The current instant, in epoch milliseconds. + * @returns {UsageWindow} + */ +function resolveUsageWindow( + expiryTimestamp: number, + entitlement: ProductEntitlement, + now: number, +): UsageWindow { + const expiryBoundary = expiryTimestamp + MILLISECONDS_PER_DAY; + + if (now >= expiryBoundary) { + return now < expiryBoundary + (entitlement.grace * MILLISECONDS_PER_DAY) ? 'soft_stop' : 'hard_stop'; + } + + const daysRemaining = daysUntil(expiryTimestamp, now); + + return entitlement.notice > 0 && daysRemaining <= entitlement.notice ? 'notice' : 'valid'; +} + +/** + * Classifies one product entitlement into its lifecycle facet. + * + * Which of the two dates the entry carries decides how it is measured; the + * `trial` flag decides only what the user is told. Nothing here branches on a + * contract type, because the payload does not carry one. + * + * A `release_until` entry never reads `time.now`, and a `usage_until` entry + * never compares against `time.buildDate`. The build date is checked either + * way, so a wrong one fails on the first key a product's tests read, whatever + * its kind - see `resolveBuildDate`. + * + * Pass an entry from `extractEntitlementKeyData` / `getProductEntitlement`. An + * entry that is not a verified one - no date, both dates, a date that is not a + * real "YYYY-MM-DD" string - throws rather than being guessed at. + * + * @param {ProductEntitlement} entitlement The verified product entry. + * @param {LicenseTimeReference} time The time references to measure against. + * @returns {LicenseLifecycle} + */ +export function classifyEntitlement( + entitlement: ProductEntitlement, + time: LicenseTimeReference, +): LicenseLifecycle { + const buildDate = resolveBuildDate(time.buildDate, 'classifyEntitlement'); + const isTrial = entitlement.flags.indexOf(TRIAL_FLAG) !== -1; + const releaseUntil = entitlement.release_until; + const usageUntil = entitlement.usage_until; + // Read without turning the value into text first: `['2027-08-12']` would + // stringify to a valid date. + const releaseTimestamp = parseIsoDateToTimestamp(releaseUntil); + const usageTimestamp = parseIsoDateToTimestamp(usageUntil); + + if ((releaseTimestamp === null) === (usageTimestamp === null)) { + throw new TypeError('classifyEntitlement: the entry has to carry exactly one valid date. ' + + 'Pass an entry read by extractEntitlementKeyData().'); + } + + if (releaseTimestamp !== null) { + // Fail OPEN when the build release date is missing (a bundler consuming + // the source without the build-time define step, a broken build): a paying + // customer must never be told their license lapsed because of a build + // defect. The comparison as text is exact because both sides are + // "YYYY-MM-DD". + const covered = buildDate === '' || (releaseUntil as string) >= buildDate; + + return Object.freeze({ + state: covered ? 'release_valid' : 'release_expired', + isTrial, + daysRemaining: null, + licensedUntil: releaseUntil as string, + }); + } + + const expiryTimestamp = usageTimestamp as number; + const window = resolveUsageWindow(expiryTimestamp, entitlement, time.now); + + return Object.freeze({ + state: `${isTrial ? 'trial' : 'usage'}_${window}` as LicenseState, + isTrial, + daysRemaining: daysUntil(expiryTimestamp, time.now), + licensedUntil: usageUntil as string, + }); +} + +/** + * Reads which notification channels a product entitlement leaves open. Both + * flags are per product and default to open; a key issued for external, + * end-user-facing use carries both. + * + * @param {ProductEntitlement} entitlement The verified product entry. + * @returns {LicenseChannels} + */ +export function resolveChannels(entitlement: ProductEntitlement): LicenseChannels { + return Object.freeze({ + console: entitlement.flags.indexOf(NO_CONSOLE_WARNS_FLAG) === -1, + ui: entitlement.flags.indexOf(NO_UI_WARNS_FLAG) === -1, + }); +} diff --git a/src/license/handsontable-license-key-parser/constants.d.ts b/src/license/handsontable-license-key-parser/constants.d.ts deleted file mode 100644 index bac6b3813e..0000000000 --- a/src/license/handsontable-license-key-parser/constants.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Hand-written declarations for `constants.js`, which is a verbatim copy of upstream. - * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. - */ - -/** The length in characters of the checksum segment that closes an entitlement key's block. */ -export const ENTITLEMENT_KEY_CHECKSUM_LENGTH: 128 - -/** The two mutually exclusive date fields a product entry may carry. */ -export const DATE_FIELDS: readonly string[] diff --git a/src/license/handsontable-license-key-parser/constants.js b/src/license/handsontable-license-key-parser/constants.js deleted file mode 100644 index 99a1152a90..0000000000 --- a/src/license/handsontable-license-key-parser/constants.js +++ /dev/null @@ -1,22 +0,0 @@ -/** - * The length of the checksum (SHA-512 as hex) which postfixes the payload - * inside the machine-readable block of every entitlement license key. - * - * @type {number} - */ -export const ENTITLEMENT_KEY_CHECKSUM_LENGTH = 128; -/** - * The two mutually exclusive date fields of a product entry. Exactly one of - * them has to be present: - * - * - "usage_until" the last licensed day (inclusive, compared in UTC), - * - "release_until" builds released on or before that day may be used - * forever (compared against the build release date as - * text, no clock involved). - * - * The pair replaces the contract type - nothing in the payload says - * "subscription" or "perpetual". - * - * @type {string[]} - */ -export const DATE_FIELDS = ['usage_until', 'release_until']; diff --git a/src/license/handsontable-license-key-parser/constants.ts b/src/license/handsontable-license-key-parser/constants.ts new file mode 100644 index 0000000000..438e0e3dd3 --- /dev/null +++ b/src/license/handsontable-license-key-parser/constants.ts @@ -0,0 +1,71 @@ +/** + * The length of the checksum (SHA-512 as hex) that closes the machine-readable + * block of every entitlement license key. + * + * @type {number} + */ +export const CHECKSUM_LENGTH = 128; + +/** + * The two mutually exclusive date fields of a product entry. Exactly one of + * them is present: + * + * - "usage_until" the last licensed day (inclusive, compared in UTC), + * - "release_until" builds released on or before that day may be used + * forever (compared against the build release date as + * text, no clock involved). + * + * The pair replaces the contract type - nothing in the payload says + * "subscription" or "perpetual". + * + * @type {string[]} + */ +export const DATE_FIELDS = ['usage_until', 'release_until']; + +/** + * Marks a license as an evaluation one. It changes how a license is WORDED and + * whether the hard stop blocks the product - never how its dates are measured. + * A flag is present or absent - there is no `false` value - and an + * unrecognized flag is ignored, for the same reason an unrecognized capability + * token is. + * + * @type {string} + */ +export const TRIAL_FLAG = 'trial'; + +/** + * Closes the console channel: nothing the license has to say reaches it. + * + * @type {string} + */ +export const NO_CONSOLE_WARNS_FLAG = 'no-console-warns'; + +/** + * Closes the UI WARNING surfaces (a banner, a badge, a popover). Both this flag + * and the one above are the default for a key issued for external, + * end-user-facing use. + * + * It does NOT close the trial hard-stop block. The block is enforcement rather + * than a warning. This is a product decision (DEV-2709, Handsontable); the + * specification's S4.1 table header does not yet record the split, so do not + * "restore" the other reading from the spec alone. + * + * @type {string} + */ +export const NO_UI_WARNS_FLAG = 'no-ui-warns'; + +/** + * Marks an individually negotiated key. Reserved - it changes nothing a reader + * does today, and is listed only so a reader knows the name is taken. + * + * @type {string} + */ +export const CUSTOM_FLAG = 'custom'; + +/** + * The number of milliseconds in a day, used to walk from one UTC midnight to + * the next. + * + * @type {number} + */ +export const MILLISECONDS_PER_DAY = 86400000; diff --git a/src/license/handsontable-license-key-parser/detect-format.d.ts b/src/license/handsontable-license-key-parser/detect-format.d.ts deleted file mode 100644 index 993247c7d1..0000000000 --- a/src/license/handsontable-license-key-parser/detect-format.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Hand-written declarations for `detect-format.js`, which is a verbatim copy of upstream. - * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. - */ - -/** Which of the licence-key shapes a string is, before anything is decoded. */ -export type LicenseKeyFormat = - | 'entitlement' - | 'legacy' - | 'non-commercial-and-evaluation' - | 'gpl-v3' - | 'unknown' - -/** - * Classifies a licence key by shape alone. A garbage bracketed block still answers - * `'entitlement'`, so the caller routes it to the entitlement validator and gets INVALID there. - * - * @param {unknown} licenseKey - the value to classify; anything at all, including a non-string - */ -export function detectLicenseKeyFormat(licenseKey: unknown): LicenseKeyFormat diff --git a/src/license/handsontable-license-key-parser/detect-format.js b/src/license/handsontable-license-key-parser/detect-format.js deleted file mode 100644 index 3ea5ce4682..0000000000 --- a/src/license/handsontable-license-key-parser/detect-format.js +++ /dev/null @@ -1,57 +0,0 @@ -/** - * The literal keys that stand for a licence rather than encode one. - * - * @type {object} - */ -const LITERAL_KEYS = { - 'non-commercial-and-evaluation': 'non-commercial-and-evaluation', - 'gpl-v3': 'gpl-v3', -}; -/** - * The classic 25-character key, once its dashes are stripped. - * - * @type {RegExp} - */ -const LEGACY_KEY = /^[0-9a-fA-F]{25}$/; - -/** - * Tells which license key format a string is in, without validating it. - * - * The entitlement key format removed the leading type tag, so a key no longer - * announces itself in its first characters - it now ends with the bracketed - * machine-readable block instead. Products that accept several formats need - * one place that makes the distinction, and this is it. - * - * The answer is about SHAPE only. A returned "entitlement" means "route this - * to the entitlement validator", not "this key is valid". - * - * @param {string} licenseKey The license key to inspect. - * @returns {string} One of: "entitlement", "legacy", - * "non-commercial-and-evaluation", "gpl-v3", "unknown". - */ -/* eslint-disable import/prefer-default-export */ -export function detectLicenseKeyFormat(licenseKey) { - if (typeof licenseKey !== 'string') { - return 'unknown'; - } - - const key = licenseKey.trim(); - - if (Object.prototype.hasOwnProperty.call(LITERAL_KEYS, key.toLowerCase())) { - return LITERAL_KEYS[key.toLowerCase()]; - } - - // The bracketed block closes an entitlement key. Its presence is what - // separates the new format from everything else, so it is checked before - // the shape-based ones. - const blockStart = key.lastIndexOf('['); - - if (blockStart !== -1 && key.indexOf(']', blockStart) !== -1) { - return 'entitlement'; - } - if (LEGACY_KEY.test(key.replace(/-/g, ''))) { - return 'legacy'; - } - - return 'unknown'; -} diff --git a/src/license/handsontable-license-key-parser/detectFormat.ts b/src/license/handsontable-license-key-parser/detectFormat.ts new file mode 100644 index 0000000000..ffa1c55beb --- /dev/null +++ b/src/license/handsontable-license-key-parser/detectFormat.ts @@ -0,0 +1,77 @@ +import type { LicenseKeyFormat } from './types'; + +/** + * The classic 25-character key, once its dashes are stripped. + * + * @type {RegExp} + */ +const LEGACY_KEY = /^[0-9a-fA-F]{25}$/; + +/** + * Tells which license key format a string is in, without validating it. + * + * The entitlement key format has no leading type tag, so a key no longer + * announces itself in its first characters - it ends with the bracketed + * machine-readable block instead. A product that accepts several formats needs + * one place that makes the distinction, and this is it. + * + * The answer is about SHAPE only. A returned "entitlement" means "route this to + * `readEntitlementLicense`", not "this key is valid". A returned "legacy" means + * "route this to the product's own legacy validator" - this module does not + * read the legacy format. + * + * Surrounding whitespace is ignored: a key pasted out of an email or a chat + * window commonly carries a trailing space or newline. Whitespace INSIDE the + * brackets is not - see `extractEntitlementKeyData`. + * + * @param {*} licenseKey The license key to inspect. + * @param {string[]} [literalKeys] The plain words this product accepts as a key + * (for example "non-commercial-and-evaluation"). Compared trimmed and + * case-insensitively. Which words are accepted is the product's decision, so + * none is built in. A blank entry is ignored - it would otherwise turn a + * missing key into a literal one. + * @returns {LicenseKeyFormat} + */ +export function detectLicenseKeyFormat( + licenseKey: unknown, + literalKeys?: readonly string[] | null, +): LicenseKeyFormat { + if (typeof licenseKey !== 'string') { + return 'unknown'; + } + + const key = licenseKey.trim(); + const lowerCaseKey = key.toLowerCase(); + const isLiteral = Array.isArray(literalKeys) && literalKeys.some((literalKey: unknown) => ( + typeof literalKey === 'string' && literalKey.trim() !== '' && literalKey.trim().toLowerCase() === lowerCaseKey + )); + + if (isLiteral) { + return 'literal'; + } + + // The bracketed block closes an entitlement key. Its presence is what + // separates the new format from everything else, so it is checked before the + // shape-based ones. + const blockStart = key.lastIndexOf('['); + + if (blockStart !== -1 && key.indexOf(']', blockStart) !== -1) { + return 'entitlement'; + } + if (LEGACY_KEY.test(key.replace(/-/g, ''))) { + return 'legacy'; + } + + return 'unknown'; +} + +/** + * Tells whether a license key has the shape of an entitlement key - the one + * check a product needs to route a key away from its legacy path. + * + * @param {*} licenseKey The license key to inspect. + * @returns {boolean} + */ +export function isEntitlementKey(licenseKey: unknown): boolean { + return detectLicenseKeyFormat(licenseKey) === 'entitlement'; +} diff --git a/src/license/handsontable-license-key-parser/utils.js b/src/license/handsontable-license-key-parser/encoding.ts similarity index 74% rename from src/license/handsontable-license-key-parser/utils.js rename to src/license/handsontable-license-key-parser/encoding.ts index 9fd27d034c..d29fa6cf0d 100644 --- a/src/license/handsontable-license-key-parser/utils.js +++ b/src/license/handsontable-license-key-parser/encoding.ts @@ -1,3 +1,5 @@ +/* eslint-disable no-bitwise */ + /** * The base64 alphabet. * @@ -5,65 +7,6 @@ */ const BASE64_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; -/** - * Recursively freezes the value (and every nested object). Used to make a - * verified schema immutable so it cannot drift from what was validated. - * - * @param {*} value The value to freeze. - * @returns {*} - */ -export function deepFreeze(value) { - if (value !== null && typeof value === 'object') { - Object.keys(value).forEach((key) => deepFreeze(value[key])); - Object.freeze(value); - } - - return value; -} - -/** - * Parses the date in the "YYYY-MM-DD" format into its numeric parts and the - * epoch milliseconds of its UTC midnight. Throws when the date is malformed - * or does not exist in the calendar. - * - * @param {string} isoDate The date to parse. - * @param {string} dateLabel The date name used in the error message. - * @returns {{ year: number, month: number, day: number, timestamp: number }} - */ -export function parseIsoDate(isoDate, dateLabel) { - // Only a string is a date. Checked before the text test on purpose: an array - // like `['2027-08-12']` stringifies to a valid date, would pass, and would - // then be written into the payload as an array. - const match = typeof isoDate === 'string' ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(isoDate) : null; - - if (match === null) { - throw new Error(`The ${dateLabel} date (${isoDate}) has to be passed in the "YYYY-MM-DD" format.`); - } - - const year = parseInt(match[1], 10); - const month = parseInt(match[2], 10); - const day = parseInt(match[3], 10); - - // Date.UTC maps years 0-99 to 1900-1999, which would make the round-trip - // check below report a "not a valid calendar date" lie. - if (year < 100) { - throw new Error(`The ${dateLabel} date (${isoDate}) has to use a four-digit year of 100 or later.`); - } - - const timestamp = Date.UTC(year, month - 1, day); - const date = new Date(timestamp); - - // An impossible date (e.g. "2027-02-30") makes `Date.UTC` roll over to - // the next month, so a round-trip comparison catches it. - if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) { - throw new Error(`The ${dateLabel} date (${isoDate}) is not a valid calendar date.`); - } - - return { - year, month, day, timestamp, - }; -} - /** * Encodes the string as UTF-8 bytes. The plain implementation is used on purpose. * It does not depend on `TextEncoder` or `Buffer`, so the same code works in @@ -72,7 +15,7 @@ export function parseIsoDate(isoDate, dateLabel) { * @param {string} string The string to encode. * @returns {number[]} */ -export function stringToUtf8Bytes(string) { +export function stringToUtf8Bytes(string: string): number[] { const bytes = []; for (let i = 0; i < string.length; i += 1) { @@ -84,16 +27,15 @@ export function stringToUtf8Bytes(string) { if (lowSurrogate >= 0xdc00 && lowSurrogate <= 0xdfff) { codePoint = ((codePoint - 0xd800) * 0x400) + (lowSurrogate - 0xdc00) + 0x10000; - i += 1; // eslint-disable-line no-plusplus + i += 1; } } if (codePoint < 0x80) { bytes.push(codePoint); } else if (codePoint < 0x800) { - bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f)); // eslint-disable-line no-bitwise + bytes.push(0xc0 | (codePoint >> 6), 0x80 | (codePoint & 0x3f)); } else if (codePoint < 0x10000) { - /* eslint-disable no-bitwise */ bytes.push( 0xe0 | (codePoint >> 12), 0x80 | ((codePoint >> 6) & 0x3f), @@ -106,7 +48,6 @@ export function stringToUtf8Bytes(string) { 0x80 | ((codePoint >> 6) & 0x3f), 0x80 | (codePoint & 0x3f), ); - /* eslint-enable no-bitwise */ } } @@ -119,8 +60,7 @@ export function stringToUtf8Bytes(string) { * @param {number[]} bytes The bytes to decode. * @returns {string} */ -export function utf8BytesToString(bytes) { - /* eslint-disable no-bitwise */ +export function utf8BytesToString(bytes: number[]): string { let string = ''; let i = 0; @@ -151,7 +91,6 @@ export function utf8BytesToString(bytes) { string += String.fromCharCode(codePoint); } } - /* eslint-enable no-bitwise */ return string; } @@ -162,8 +101,7 @@ export function utf8BytesToString(bytes) { * @param {number[]} bytes The bytes to encode. * @returns {string} */ -export function bytesToBase64(bytes) { - /* eslint-disable no-bitwise */ +export function bytesToBase64(bytes: number[]): string { let base64 = ''; for (let i = 0; i < bytes.length; i += 3) { @@ -177,7 +115,6 @@ export function bytesToBase64(bytes) { ? '=' : BASE64_ALPHABET.charAt(((byte2 & 0x0f) << 2) | (byte3 === undefined ? 0 : byte3 >> 6)); base64 += byte3 === undefined ? '=' : BASE64_ALPHABET.charAt(byte3 & 0x3f); } - /* eslint-enable no-bitwise */ return base64; } @@ -189,14 +126,13 @@ export function bytesToBase64(bytes) { * @param {string} base64 The base64 string to decode. * @returns {number[]|null} */ -export function base64ToBytes(base64) { +export function base64ToBytes(base64: string): number[] | null { const normalized = `${base64}`.replace(/-/g, '+').replace(/_/g, '/').replace(/=+$/, ''); if (!/^[A-Za-z0-9+/]*$/.test(normalized) || normalized.length % 4 === 1) { return null; } - /* eslint-disable no-bitwise */ const bytes = []; for (let i = 0; i < normalized.length; i += 4) { @@ -217,7 +153,6 @@ export function base64ToBytes(base64) { bytes.push(((chunk[2] & 0x03) << 6) | chunk[3]); } } - /* eslint-enable no-bitwise */ return bytes; } @@ -229,7 +164,7 @@ export function base64ToBytes(base64) { * @param {string} string The string to encode. * @returns {string} */ -export function stringToBase64Url(string) { +export function stringToBase64Url(string: string): string { return bytesToBase64(stringToUtf8Bytes(string)) .replace(/\+/g, '-') .replace(/\//g, '_') @@ -243,8 +178,49 @@ export function stringToBase64Url(string) { * @param {string} base64 The base64 string to decode. * @returns {string|null} */ -export function base64ToString(base64) { +export function base64ToString(base64: string): string | null { const bytes = base64ToBytes(base64); return bytes === null ? null : utf8BytesToString(bytes); } + +/** + * Parses a date in the "YYYY-MM-DD" format into the epoch milliseconds of its + * UTC midnight. Returns `null` when the date is malformed or does not exist in + * the calendar (for example "2027-02-30"). Unlike the generator side, the + * reader never throws on a bad date - a broken payload simply makes the key + * unreadable. + * + * @param {*} isoDate The date to parse. Anything but a string is not a date. + * @returns {number|null} + */ +export function parseIsoDateToTimestamp(isoDate: unknown): number | null { + // Only a string is a date. Checked before the text test on purpose: an array + // like `['2027-08-12']` stringifies to a valid date and would otherwise pass. + const match = typeof isoDate === 'string' ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(isoDate) : null; + + if (match === null) { + return null; + } + + const year = parseInt(match[1], 10); + const month = parseInt(match[2], 10); + const day = parseInt(match[3], 10); + + // Date.UTC maps years 0-99 to 1900-1999, which would make the round-trip + // check below report a "not a valid calendar date" lie. + if (year < 100) { + return null; + } + + const timestamp = Date.UTC(year, month - 1, day); + const date = new Date(timestamp); + + // An impossible date (e.g. "2027-02-30") makes `Date.UTC` roll over to + // the next month, so a round-trip comparison catches it. + if (date.getUTCFullYear() !== year || date.getUTCMonth() !== month - 1 || date.getUTCDate() !== day) { + return null; + } + + return timestamp; +} diff --git a/src/license/handsontable-license-key-parser/extract-key-data.d.ts b/src/license/handsontable-license-key-parser/extract-key-data.d.ts deleted file mode 100644 index 86613c9186..0000000000 --- a/src/license/handsontable-license-key-parser/extract-key-data.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Hand-written declarations for `extract-key-data.js`, which is a verbatim copy of upstream. - * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. - */ - -/** - * One product's terms, as the reader normalizes them. - * - * The declared members are the ones the reader VERIFIES: `capabilities` and `flags` element by - * element, `notice` and `grace` as non-negative integers, and exactly one of the two date fields. - * Everything it does not verify - unknown fields are preserved on purpose - sits behind the index - * signature, so a consumer has to narrow before using it. - */ -export interface EntitlementProductGrant { - readonly capabilities: readonly string[], - readonly usage_until?: string, - readonly release_until?: string, - readonly notice: number, - readonly grace: number, - readonly flags: readonly string[], - readonly [field: string]: unknown, -} - -/** The machine-readable content of an intact entitlement key: the granted products and their terms. */ -export interface EntitlementKeyData { - readonly products: Readonly>, -} - -/** - * Reads an entitlement key: finds the bracketed block, verifies the checksum before decoding - * anything, then normalizes the payload. `null` when the envelope or the payload is not intact. - * - * @param {string} licenseKey - the whole licence artifact or the bare block - */ -export function extractEntitlementKeyData(licenseKey: string): EntitlementKeyData | null diff --git a/src/license/handsontable-license-key-parser/extract-key-data.js b/src/license/handsontable-license-key-parser/extract-key-data.js deleted file mode 100644 index 1dcf5d765d..0000000000 --- a/src/license/handsontable-license-key-parser/extract-key-data.js +++ /dev/null @@ -1,242 +0,0 @@ -import { ENTITLEMENT_KEY_CHECKSUM_LENGTH, DATE_FIELDS } from './constants'; -import { sha512 } from './sha512'; -import { base64ToString, parseIsoDate, stringToUtf8Bytes } from './utils'; - -/** - * The alphabet of the encoded payload - URL-safe base64 without padding. - * The checksum (lowercase hex) is a subset of it, which is what lets the two - * be split by a fixed length from the right. - * - * @type {RegExp} - */ -const ENCODED_PAYLOAD = /^[A-Za-z0-9\-_]+$/; -const CHECKSUM = /^[0-9a-f]+$/; - -/** - * Returns `true` when the value is a plain object. - * - * @param {*} value The value to check. - * @returns {boolean} - */ -function isPlainObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} - -/** - * Returns `true` when the value is a non-negative integer. - * - * @param {*} value The value to check. - * @returns {boolean} - */ -function isNonNegativeInteger(value) { - return typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value && value >= 0; -} - -/** - * Returns `true` when the value is an array of strings. - * - * @param {*} value The value to check. - * @returns {boolean} - */ -function isStringArray(value) { - return Array.isArray(value) && value.every((item) => typeof item === 'string'); -} - -/** - * Returns `true` when the value is a real calendar date in the "YYYY-MM-DD" - * format. A time component, an offset, a numeric timestamp and a date that - * does not exist are all rejected - the format is the whole contract, and a - * validator that accepted two spellings would hide a timezone bug at - * generation instead of surfacing it. - * - * @param {*} value The value to check. - * @returns {boolean} - */ -function isIsoDate(value) { - try { - parseIsoDate(value, 'license'); - - return true; - } catch (error) { - return false; - } -} - -/** - * Adds an own, ordinary property. - * - * Both the product names and the field names of a product entry come from - * JSON, so "__proto__" is a name an attacker can put in a key. A plain - * assignment would go through the Object.prototype setter: the value would - * vanish from Object.keys while still resolving through the chain. - * - * @param {object} target The object to add the property to. - * @param {string} key The property name. - * @param {*} value The property value. - */ -function defineOwn(target, key, value) { - Object.defineProperty(target, key, { - value, enumerable: true, writable: true, configurable: true, - }); -} - -/** - * Verifies and normalizes one product entry. - * - * Strict about SHAPE: exactly one of the two dates, a real date, and the two - * window sizes. A key that gets this wrong is malformed, not merely unknown, - * and reading it would mean guessing what was licensed. - * - * Lenient about VOCABULARY: an unrecognised capability token, an unrecognised - * flag and an unrecognised extra field are all kept and ignored. Without that - * leniency every token added on the issuing side would break every library - * version already deployed in the field. - * - * Returns `null` when the entry is malformed. - * - * @param {*} entry The product entry of the payload. - * @returns {object|null} - */ -function normalizeProductEntry(entry) { - if (!isPlainObject(entry)) { - return null; - } - if (!isStringArray(entry.capabilities)) { - return null; - } - - const presentDateFields = DATE_FIELDS.filter((field) => entry[field] !== undefined); - - // Exactly one date per product. "Both" and "neither" are each a different - // commercial shape that the format cannot express, so neither may be - // silently resolved by whichever field the parser happens to read first. - if (presentDateFields.length !== 1) { - return null; - } - if (!isIsoDate(entry[presentDateFields[0]])) { - return null; - } - if (!isNonNegativeInteger(entry.notice) || !isNonNegativeInteger(entry.grace)) { - return null; - } - if (entry.flags !== undefined && !isStringArray(entry.flags)) { - return null; - } - - // Start from everything the entry carries, so a field this version does not - // know survives into the result instead of being silently dropped. A field - // added to the format later is exactly the case an already-vendored parser - // has to survive, and a reader that quietly discards it makes the field - // invisible to the application on top. - const normalized = {}; - - Object.keys(entry).forEach((field) => defineOwn(normalized, field, entry[field])); - - defineOwn(normalized, 'capabilities', entry.capabilities.slice()); - defineOwn(normalized, 'notice', entry.notice); - defineOwn(normalized, 'grace', entry.grace); - // An absent array and an empty one mean the same thing. Normalizing here - // keeps `flags.indexOf('trial')` safe at every call site. - defineOwn(normalized, 'flags', entry.flags === undefined ? [] : entry.flags.slice()); - defineOwn(normalized, presentDateFields[0], entry[presentDateFields[0]]); - - return normalized; -} - -/** - * Extracts the machine-readable data from an entitlement license key. - * - * The checksum is verified first, so the returned data is guaranteed to - * belong to an intact block. For a malformed or tampered key `null` is - * returned - reporting an invalid key is the caller's job, not this - * function's. - * - * Only the bracketed block matters. The prose in front of it is neither - * parsed nor covered by the checksum, so the caller may pass the whole - * artifact or just the `[...]` block, and rewrapped or re-pasted text still - * validates. - * - * No schema is needed. Unknown products, capabilities and flags are all - * tolerated, so nothing about reading a key depends on the vocabulary - which - * is what lets a product vendor this parser on its own. - * - * @param {string} licenseKey The license key to extract the data from. - * @returns {{ products: object }|null} The granted products, each with its - * capabilities, its single date (`usage_until` or `release_until`), - * its `notice` and `grace` windows in days, and its `flags`. - */ -/* eslint-disable import/prefer-default-export */ -export function extractEntitlementKeyData(licenseKey) { - if (typeof licenseKey !== 'string') { - return null; - } - - // The machine-readable block closes the key. Searching backwards means a - // bracket inside the prose cannot shadow it. - const blockStart = licenseKey.lastIndexOf('['); - - if (blockStart === -1) { - return null; - } - - const blockEnd = licenseKey.indexOf(']', blockStart); - - if (blockEnd === -1) { - return null; - } - - const content = licenseKey.slice(blockStart + 1, blockEnd); - - if (content.length <= ENTITLEMENT_KEY_CHECKSUM_LENGTH) { - return null; - } - - const encodedPayload = content.slice(0, -ENTITLEMENT_KEY_CHECKSUM_LENGTH); - const checksum = content.slice(-ENTITLEMENT_KEY_CHECKSUM_LENGTH); - - if (!ENCODED_PAYLOAD.test(encodedPayload) || !CHECKSUM.test(checksum)) { - return null; - } - if (sha512(stringToUtf8Bytes(encodedPayload)) !== checksum) { - return null; - } - - const payloadJson = base64ToString(encodedPayload); - - if (payloadJson === null) { - return null; - } - - let payload; - - try { - payload = JSON.parse(payloadJson); - } catch (error) { - return null; - } - - if (!isPlainObject(payload) || !isPlainObject(payload.products)) { - return null; - } - - const products = {}; - let malformed = false; - - Object.keys(payload.products).forEach((name) => { - const entry = normalizeProductEntry(payload.products[name]); - - if (entry === null) { - malformed = true; - - return; - } - - defineOwn(products, name, entry); - }); - - if (malformed) { - return null; - } - - return { products }; -} diff --git a/src/license/handsontable-license-key-parser/extractKeyData.ts b/src/license/handsontable-license-key-parser/extractKeyData.ts new file mode 100644 index 0000000000..6343ff6def --- /dev/null +++ b/src/license/handsontable-license-key-parser/extractKeyData.ts @@ -0,0 +1,332 @@ +import type { EntitlementKeyData, ProductEntitlement } from './types'; +import { CHECKSUM_LENGTH, DATE_FIELDS } from './constants'; +import { sha512 } from './sha512'; +import { base64ToString, stringToUtf8Bytes, parseIsoDateToTimestamp } from './encoding'; + +/** + * The alphabet of the encoded payload - URL-safe base64 without padding. The + * checksum (lowercase hex) is a subset of it, which is what lets the two be + * split by a fixed length from the right. + * + * @type {RegExp} + */ +const ENCODED_PAYLOAD = /^[A-Za-z0-9\-_]+$/; +const CHECKSUM = /^[0-9a-f]+$/; + +/** + * Reports own-property presence without trusting a payload's inherited or + * overridden `hasOwnProperty`. + * + * @param {object} object The object to inspect. + * @param {string} key The property name to look up. + * @returns {boolean} + */ +function hasOwn(object: object, key: string): boolean { + return Object.prototype.hasOwnProperty.call(object, key); +} + +/** + * Narrows an unknown value to a plain (non-null, non-array) object. + * + * @param {*} value The value to check. + * @returns {boolean} + */ +function isPlainObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * Returns `true` when the value is a non-negative integer. `Number.isFinite` + * also rejects `Infinity` (JSON `1e999` parses to it), which would otherwise + * turn a window size into a non-finite date later on. + * + * @param {*} value The value to check. + * @returns {boolean} + */ +function isNonNegativeInteger(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value) && Math.floor(value) === value && value >= 0; +} + +/** + * Returns `true` when the value is an array of strings. + * + * @param {*} value The value to check. + * @returns {boolean} + */ +function isStringArray(value: unknown): value is string[] { + return Array.isArray(value) && value.every(item => typeof item === 'string'); +} + +/** + * Freezes the value and everything nested in it. The read result is shared + * between callers (see the memo below), so a caller that sorted or pushed into + * it would silently rewrite what the next caller reads. + * + * It walks with an explicit stack, not by recursion. An unknown extra field is + * kept as it is, and a key can nest one thousands of levels deep - recursion + * would then overflow the call stack and throw out of the reader, where a + * key is only ever allowed to read as data or as `null`. + * + * @param {*} value The value to freeze. + * @returns {*} + */ +function deepFreeze(value: T): T { + const pending: unknown[] = [value]; + + while (pending.length > 0) { + const current = pending.pop(); + + if (current !== null && typeof current === 'object' && !Object.isFrozen(current)) { + Object.freeze(current); + Object.keys(current as object).forEach(key => pending.push((current as Record)[key])); + } + } + + return value; +} + +/** + * Adds an own, ordinary property. + * + * Both the product names and the field names of a product entry come from + * JSON, so "__proto__" is a name an attacker can put in a key. A plain + * assignment would go through the `Object.prototype` setter: the value would + * vanish from `Object.keys` while still resolving through the chain. Exported + * because every payload-keyed write in this module must use it - `grants.ts` + * re-keys the same product names. + * + * @param {object} target The object to add the property to. + * @param {string} key The property name. + * @param {*} value The property value. + * @returns {void} + */ +export function defineOwn(target: object, key: string, value: unknown): void { + Object.defineProperty(target, key, { + value, enumerable: true, writable: true, configurable: true, + }); +} + +/** + * Verifies and normalizes one product entry. + * + * Strict about SHAPE: exactly one of the two dates, a real calendar date, and + * the two window sizes. A key that gets this wrong is malformed, not merely + * unknown, and reading it would mean guessing what was licensed. + * + * Lenient about VOCABULARY: an unrecognized capability token, an unrecognized + * flag and an unrecognized extra field are all kept and ignored. Without that + * leniency every token added on the issuing side would break every build + * already deployed in the field. + * + * Returns `null` when the entry is malformed. + * + * @param {*} entry The product entry of the payload. + * @returns {ProductEntitlement|null} + */ +function normalizeProductEntry(entry: unknown): ProductEntitlement | null { + if (!isPlainObject(entry)) { + return null; + } + if (!isStringArray(entry.capabilities)) { + return null; + } + + const presentDateFields = DATE_FIELDS.filter(field => entry[field] !== undefined); + + // Exactly one date per product. "Both" and "neither" are each a different + // commercial shape that the format cannot express, so neither may be silently + // resolved by whichever field the reader happens to look at first. + if (presentDateFields.length !== 1) { + return null; + } + if (parseIsoDateToTimestamp(entry[presentDateFields[0]]) === null) { + return null; + } + if (!isNonNegativeInteger(entry.notice) || !isNonNegativeInteger(entry.grace)) { + return null; + } + if (entry.flags !== undefined && !isStringArray(entry.flags)) { + return null; + } + + // Start from everything the entry carries, so a field this version does not + // know survives into the result instead of being silently dropped. A field + // added to the format later is exactly the case a vendored reader has to + // survive, and one that quietly discards it makes the field invisible to the + // layers above. + const normalized = {} as ProductEntitlement; + + Object.keys(entry).forEach(field => defineOwn(normalized, field, entry[field])); + + defineOwn(normalized, 'capabilities', entry.capabilities.slice()); + defineOwn(normalized, 'notice', entry.notice); + defineOwn(normalized, 'grace', entry.grace); + // An absent array and an empty one mean the same thing. Normalizing here + // keeps `flags.indexOf('trial')` safe at every call site. + defineOwn(normalized, 'flags', entry.flags === undefined ? [] : entry.flags.slice()); + defineOwn(normalized, presentDateFields[0], entry[presentDateFields[0]]); + + return normalized; +} + +/** + * Reads and verifies one key. Split out from the memoized public entry point so + * the memo can wrap every exit path uniformly. + * + * @param {string} licenseKey The license key to read. + * @returns {EntitlementKeyData|null} + */ +function readEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { + // The machine-readable block closes the key. Searching backwards means a + // bracket inside the prose cannot shadow it. + const blockStart = licenseKey.lastIndexOf('['); + + if (blockStart === -1) { + return null; + } + + const blockEnd = licenseKey.indexOf(']', blockStart); + + if (blockEnd === -1) { + return null; + } + + const content = licenseKey.slice(blockStart + 1, blockEnd); + + if (content.length <= CHECKSUM_LENGTH) { + return null; + } + + const encodedPayload = content.slice(0, -CHECKSUM_LENGTH); + const checksum = content.slice(-CHECKSUM_LENGTH); + + if (!ENCODED_PAYLOAD.test(encodedPayload) || !CHECKSUM.test(checksum)) { + return null; + } + if (sha512(stringToUtf8Bytes(encodedPayload)) !== checksum) { + return null; + } + + const payloadJson = base64ToString(encodedPayload); + + if (payloadJson === null) { + return null; + } + + let payload: unknown; + + try { + payload = JSON.parse(payloadJson); + } catch (error) { + return null; + } + + if (!isPlainObject(payload) || !isPlainObject(payload.products)) { + return null; + } + + const products = {} as EntitlementKeyData['products']; + const entries = payload.products; + let malformed = false; + + Object.keys(entries).forEach((name) => { + const entry = normalizeProductEntry(entries[name]); + + if (entry === null) { + malformed = true; + + return; + } + + defineOwn(products, name, entry); + }); + + if (malformed) { + return null; + } + + return deepFreeze({ products }); +} + +// A product typically reads its key more than once per start-up (a console +// message and a UI surface each resolve the license state), and reading runs +// the full SHA-512 + base64 + JSON parse. A one-entry memo on the key makes the +// second read free. The returned data is frozen, so sharing one object is safe. +let memoizedKey: string | null = null; +let memoizedData: EntitlementKeyData | null = null; + +/** + * Extracts the machine-readable data from an entitlement license key. + * + * The checksum is verified first, so the returned data is guaranteed to belong + * to an intact block. A malformed or tampered key reads as `null` - reporting + * an invalid key is the caller's job, not this function's. + * + * Only the bracketed block matters. The prose in front of it is neither parsed + * nor covered by the checksum, so the caller may pass the whole key or just the + * `[...]` block, and rewrapped or re-pasted prose still validates. The block + * itself has to be intact: its alphabet has no whitespace, so a newline inside + * it makes the key unreadable, exactly as it does for the key generator. Do not + * "repair" such a key by stripping whitespace inside the brackets - that would + * accept keys the generator rejects. + * + * Unknown products, capability tokens and flags are all tolerated, so nothing + * about reading a key depends on the commercial vocabulary. + * + * The result is frozen. Copy an array before sorting or changing it. + * + * @param {string} licenseKey The license key to extract the data from. + * @returns {EntitlementKeyData|null} + */ +export function extractEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { + if (typeof licenseKey !== 'string') { + return null; + } + if (licenseKey !== memoizedKey) { + // Read first, remember second. Were the key remembered before the read, + // a read that throws would leave the new key paired with the previous + // key's data, and the next read of the new key would return it. + const data = readEntitlementKeyData(licenseKey); + + memoizedKey = licenseKey; + memoizedData = data; + } + + return memoizedData; +} + +/** + * Tells whether a license key is a well-formed, untampered entitlement key. + * + * The check is about integrity, not about entitlement: a key that is valid + * here may still be past its `usage_until` date, or may grant a product the + * caller does not care about. `readEntitlementLicense` answers those. + * + * @param {string} licenseKey The license key to check. + * @returns {boolean} + */ +export function validateEntitlementKey(licenseKey: string): boolean { + return extractEntitlementKeyData(licenseKey) !== null; +} + +/** + * Returns the entitlement of one product, but only when it is present as an own + * property. Used by the lifecycle and grants layers to read one product without + * trusting the prototype chain. + * + * @param {EntitlementKeyData} keyData The verified key data. + * @param {string} productName The product to read. + * @returns {ProductEntitlement|null} + */ +export function getProductEntitlement( + keyData: EntitlementKeyData, + productName: string, +): ProductEntitlement | null { + if (!hasOwn(keyData.products, productName)) { + return null; + } + + const product = keyData.products[productName]; + + return isPlainObject(product) ? product as ProductEntitlement : null; +} diff --git a/src/license/handsontable-license-key-parser/grants.ts b/src/license/handsontable-license-key-parser/grants.ts new file mode 100644 index 0000000000..7af5dfd39c --- /dev/null +++ b/src/license/handsontable-license-key-parser/grants.ts @@ -0,0 +1,101 @@ +import type { EntitlementKeyData, LicenseGrants } from './types'; +import { getProductEntitlement, defineOwn } from './extractKeyData'; + +/** + * The grants shared by every non-entitlement license state: a valid legacy + * commercial key, a legacy expired key, a literal key, a missing key, + * an invalid key, or an unreadable entitlement key. Every query short-circuits + * on `unrestricted`, so these keys unlock everything - introducing capability + * gating can never take a feature away from an existing customer. Frozen so it + * cannot be mutated by a consumer. + * + * @type {LicenseGrants} + */ +export const UNRESTRICTED_GRANTS: LicenseGrants = Object.freeze({ + unrestricted: true, + products: Object.freeze({}), +}); + +/** + * Builds the grants facet from a verified entitlement key: exactly the + * capability tokens the payload lists, per product. Entitlement keys are never + * unrestricted - they unlock only what they name. Frozen, like every result of + * this module, so the grants a product resolved once cannot be rewritten later. + * + * @param {EntitlementKeyData} keyData The verified key data. + * @returns {LicenseGrants} + */ +export function getLicenseGrants(keyData: EntitlementKeyData): LicenseGrants { + const products: LicenseGrants['products'] = {}; + + Object.keys(keyData.products).forEach((productName) => { + const entitlement = getProductEntitlement(keyData, productName); + + if (entitlement !== null) { + // Defined, not assigned: the product name comes from the key's JSON, and a plain assignment + // of "__proto__" would hit the `Object.prototype` setter - replacing the prototype of + // `products` instead of adding the grant, which then reads back as not granted. + defineOwn(products, productName, Object.freeze({ + capabilities: Object.freeze(entitlement.capabilities.slice()), + })); + } + }); + + return Object.freeze({ + unrestricted: false, + products: Object.freeze(products), + }); +} + +/** + * Tells whether the license grants a product. An unrestricted license grants + * every product; an entitlement license grants a product only when its payload + * lists it. + * + * @param {LicenseGrants} grants The resolved grants. + * @param {string} productName The product to check. + * @returns {boolean} + */ +export function hasProductGrant(grants: LicenseGrants, productName: string): boolean { + return grants.unrestricted || Object.prototype.hasOwnProperty.call(grants.products, productName); +} + +/** + * Returns the capability tokens a license grants for a product, or `null` when + * the product is not granted. An unrestricted license reports no token list - + * it answers "granted" to every capability query instead, so a caller that + * needs a yes/no answer asks `hasCapability`. + * + * @param {LicenseGrants} grants The resolved grants. + * @param {string} productName The product to read. + * @returns {string[]|null} + */ +export function getProductCapabilities(grants: LicenseGrants, productName: string): string[] | null { + if (grants.unrestricted || !hasProductGrant(grants, productName)) { + return null; + } + + // A copy: the grants are frozen, and a caller asking for a plain token list + // usually wants one it can sort or extend. + return grants.products[productName].capabilities.slice(); +} + +/** + * Tells whether the license unlocks a capability for a product. An unrestricted + * license unlocks every capability - even tokens that do not exist yet. An + * entitlement license unlocks a capability only when its payload lists the + * token for that product. + * + * @param {LicenseGrants} grants The resolved grants. + * @param {string} productName The product the capability belongs to. + * @param {string} capability The capability token to check. + * @returns {boolean} + */ +export function hasCapability(grants: LicenseGrants, productName: string, capability: string): boolean { + if (grants.unrestricted) { + return true; + } + + return hasProductGrant(grants, productName) && + grants.products[productName].capabilities.indexOf(capability) !== -1; +} diff --git a/src/license/handsontable-license-key-parser/index.ts b/src/license/handsontable-license-key-parser/index.ts new file mode 100644 index 0000000000..e1f4129690 --- /dev/null +++ b/src/license/handsontable-license-key-parser/index.ts @@ -0,0 +1,70 @@ +/** + * The entitlement license key reader - the part of `handsontable/license-key` + * that products copy into their own source tree. + * + * Copy this whole directory. Do not edit the copy: change the original in + * `handsontable/license-key` (`vendor/entitlement-key-reader/`) and copy it + * again. See `README.md` in this directory. + */ +import { detectLicenseKeyFormat, isEntitlementKey } from './detectFormat'; +import { + extractEntitlementKeyData, + validateEntitlementKey, + getProductEntitlement, +} from './extractKeyData'; +import { classifyEntitlement, resolveChannels } from './classify'; +import { + UNRESTRICTED_GRANTS, + getLicenseGrants, + hasProductGrant, + getProductCapabilities, + hasCapability, +} from './grants'; +import { readEntitlementLicense } from './readLicense'; +import { toIsoBuildDate } from './buildDate'; +import { + TRIAL_FLAG, + NO_CONSOLE_WARNS_FLAG, + NO_UI_WARNS_FLAG, + CUSTOM_FLAG, +} from './constants'; + +export type { + LicenseKeyFormat, + ProductEntitlement, + EntitlementKeyData, + LicenseState, + LicenseLifecycle, + LicenseChannels, + LicenseGrants, + LicenseTimeReference, + UnlicensedReason, + EntitlementLicense, + ReadEntitlementLicenseOptions, +} from './types'; + +export { + // The one call a product needs. + readEntitlementLicense, + toIsoBuildDate, + // Routing a key to the right validator. + detectLicenseKeyFormat, + isEntitlementKey, + // The building blocks `readEntitlementLicense` is made of. + extractEntitlementKeyData, + validateEntitlementKey, + getProductEntitlement, + classifyEntitlement, + resolveChannels, + // Capability gating. + UNRESTRICTED_GRANTS, + getLicenseGrants, + hasProductGrant, + getProductCapabilities, + hasCapability, + // The flag names, for a product that reads one directly. + TRIAL_FLAG, + NO_CONSOLE_WARNS_FLAG, + NO_UI_WARNS_FLAG, + CUSTOM_FLAG, +}; diff --git a/src/license/handsontable-license-key-parser/readLicense.ts b/src/license/handsontable-license-key-parser/readLicense.ts new file mode 100644 index 0000000000..896126de9c --- /dev/null +++ b/src/license/handsontable-license-key-parser/readLicense.ts @@ -0,0 +1,123 @@ +import type { + EntitlementLicense, + LicenseChannels, + ReadEntitlementLicenseOptions, + UnlicensedReason, +} from './types'; +import { extractEntitlementKeyData, getProductEntitlement } from './extractKeyData'; +import { classifyEntitlement, resolveChannels } from './classify'; +import { UNRESTRICTED_GRANTS, getLicenseGrants } from './grants'; +import { resolveBuildDate } from './buildDate'; + +/** + * Both notification channels open - what a key gets when its flags could not + * be read. + * + * @type {LicenseChannels} + */ +const OPEN_CHANNELS: LicenseChannels = Object.freeze({ console: true, ui: true }); + +/** + * Builds the result for a key that does not license the product. + * + * @param {UnlicensedReason} reason Why the key does not license the product. + * @returns {EntitlementLicense} + */ +function unlicensed(reason: UnlicensedReason): EntitlementLicense { + return Object.freeze({ + licensed: false, + reason, + entitlement: null, + lifecycle: null, + channels: OPEN_CHANNELS, + grants: UNRESTRICTED_GRANTS, + }); +} + +/** + * Reads an entitlement license key for one product, in one call: verifies the + * block, picks the product's entry, places it in its lifecycle window, reads + * its silencing flags and resolves what it unlocks. + * + * This is the single entry point a product needs. Route a key here only when + * `detectLicenseKeyFormat` says "entitlement" - legacy and literal keys are + * the product's own path. + * + * A key that grants other products but not this one is NOT a license for this + * product, however many others it grants. It reads as `licensed: false` with + * the reason `product_missing`, and the product reports it as an invalid key. + * Another product's entry never invalidates the key on its own: one install + * can be licensed for one product and not for another. + * + * The grants of an unlicensed key stay UNRESTRICTED on purpose. An invalid key + * nags - it does not strip features - so introducing capability gating can + * never take a feature away from a customer whose key failed to read. + * + * The clock is read only for a `usage_until` entry, and only when `now` is not + * passed. A `release_until` entry never reads it. + * + * A missing build date fails OPEN; a build date that is present but not a + * bare "YYYY-MM-DD" throws - see `resolveBuildDate`. Both are checked before + * the key is read, so the error shows whatever key a product's tests use. + * + * The result is frozen, whichever way it goes. + * + * @param {string} licenseKey The license key, as the user supplied it. + * @param {ReadEntitlementLicenseOptions} options What the product tells the reader. + * @param {string} options.product The product name this build reads its license from. + * @param {string} options.buildDate The build release date, "YYYY-MM-DD". + * @param {number} [options.now] The current instant, in epoch milliseconds. + * @returns {EntitlementLicense} + */ +export function readEntitlementLicense( + licenseKey: string, + options: ReadEntitlementLicenseOptions, +): EntitlementLicense { + // A wrong argument is the product's bug, not the customer's, so it throws - + // a silent "invalid" would make every key look broken with no clue why. + if (options === null || typeof options !== 'object') { + throw new TypeError('readEntitlementLicense: pass the options - { product, buildDate, now? }.'); + } + + const { product, now } = options; + const buildDate = resolveBuildDate(options.buildDate, 'readEntitlementLicense'); + + if (typeof product !== 'string' || product === '') { + throw new TypeError('readEntitlementLicense: "product" has to be a non-empty product name.'); + } + if (now !== undefined && (typeof now !== 'number' || !Number.isFinite(now))) { + throw new TypeError('readEntitlementLicense: "now" has to be epoch milliseconds.'); + } + + const keyData = extractEntitlementKeyData(licenseKey); + + if (keyData === null) { + return unlicensed('unreadable'); + } + + const entitlement = getProductEntitlement(keyData, product); + + if (entitlement === null) { + return unlicensed('product_missing'); + } + + // The clock is read once, so every window boundary is measured against the + // same instant, and only for a `usage_until` entry - a `release_until` one + // never reads it (fixture J9), so it gets a value nothing looks at. + let currentTime = NaN; + + if (entitlement.usage_until !== undefined) { + currentTime = now === undefined ? Date.now() : now; + } + + const lifecycle = classifyEntitlement(entitlement, { now: currentTime, buildDate }); + + return Object.freeze({ + licensed: true, + reason: null, + entitlement, + lifecycle, + channels: resolveChannels(entitlement), + grants: getLicenseGrants(keyData), + }); +} diff --git a/src/license/handsontable-license-key-parser/sha512.d.ts b/src/license/handsontable-license-key-parser/sha512.d.ts deleted file mode 100644 index 084e765db8..0000000000 --- a/src/license/handsontable-license-key-parser/sha512.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Hand-written declarations for `sha512.js`, which is a verbatim copy of upstream. - * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. - */ - -/** - * SHA-512 of the given bytes, as lower-case hexadecimal. Self-contained so the module needs no - * dependency and works on a plain `http://` page, where `crypto.subtle` is unavailable. - * - * @param {number[]|Uint8Array} bytes - the message, as byte values - */ -export function sha512(bytes: number[] | Uint8Array): string diff --git a/src/license/handsontable-license-key-parser/sha512.js b/src/license/handsontable-license-key-parser/sha512.ts similarity index 96% rename from src/license/handsontable-license-key-parser/sha512.js rename to src/license/handsontable-license-key-parser/sha512.ts index 1c8cf17643..3e479d7790 100644 --- a/src/license/handsontable-license-key-parser/sha512.js +++ b/src/license/handsontable-license-key-parser/sha512.ts @@ -55,7 +55,7 @@ const K = [ * @param {number} value The 32-bit integer value. * @returns {string} */ -function toHex32(value) { +function toHex32(value: number): string { return `00000000${(value >>> 0).toString(16)}`.slice(-8); } @@ -69,8 +69,7 @@ function toHex32(value) { * @param {number[]|Uint8Array} bytes The bytes to calculate the checksum from. * @returns {string} The checksum as a 128-character hex string. */ -/* eslint-disable import/prefer-default-export */ -export function sha512(bytes) { +export function sha512(bytes: number[] | Uint8Array): string { const byteLength = bytes.length; // The message is padded with the 0x80 byte, zeros, and the 128-bit big-endian // bit length so the total length is a multiple of 128 bytes. @@ -100,15 +99,15 @@ export function sha512(bytes) { 0x510e527f, 0xade682d1, 0x9b05688c, 0x2b3e6c1f, 0x1f83d9ab, 0xfb41bd6b, 0x5be0cd19, 0x137e2179, ]; - const wh = new Array(80); - const wl = new Array(80); + const wh: number[] = new Array(80); + const wl: number[] = new Array(80); for (let block = 0; block < blockCount; block += 1) { const offset = block * 128; // Prepare the message schedule. for (let i = 0; i < 16; i += 1) { - const o = offset + i * 8; + const o = offset + (i * 8); wh[i] = ((buffer[o] << 24) | (buffer[o + 1] << 16) | (buffer[o + 2] << 8) | buffer[o + 3]) >>> 0; wl[i] = ((buffer[o + 4] << 24) | (buffer[o + 5] << 16) | (buffer[o + 6] << 8) | buffer[o + 7]) >>> 0; @@ -164,7 +163,7 @@ export function sha512(bytes) { const majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); const majl = (al & bl) ^ (al & cl) ^ (bl & cl); - const t1LowSum = (hl >>> 0) + (bs1l >>> 0) + (chl >>> 0) + (K[i * 2 + 1] >>> 0) + (wl[i] >>> 0); + const t1LowSum = (hl >>> 0) + (bs1l >>> 0) + (chl >>> 0) + (K[(i * 2) + 1] >>> 0) + (wl[i] >>> 0); const t1l = t1LowSum >>> 0; const t1h = ((hh >>> 0) + (bs1h >>> 0) + (chh >>> 0) + (K[i * 2] >>> 0) + (wh[i] >>> 0) + Math.floor(t1LowSum / 0x100000000)) >>> 0; diff --git a/src/license/handsontable-license-key-parser/types.ts b/src/license/handsontable-license-key-parser/types.ts new file mode 100644 index 0000000000..8d97514f6d --- /dev/null +++ b/src/license/handsontable-license-key-parser/types.ts @@ -0,0 +1,181 @@ +/** + * The shapes a license key string can have. `literal` is one of the plain words + * the calling product accepts as a key (for example + * "non-commercial-and-evaluation" or "gpl-v3") - which words those are is the + * product's decision, so the reader only recognizes the ones it is handed. + * Only "entitlement" is read by this module; every other format is the + * product's own path. + */ +export type LicenseKeyFormat = + | 'entitlement' + | 'legacy' + | 'literal' + | 'unknown'; + +/** + * What one product entry of a verified key grants. Exactly one of + * `usage_until` / `release_until` is present - the pair replaces the contract + * type, which the payload does not carry. `notice` and `grace` are the warning + * and soft-stop windows, in days, and arrive in the key rather than living in + * the library. Unknown extra fields survive verification untouched, so a field + * added to the format later stays visible to the layers above. + * + * Read-only: the verified data is frozen and shared between callers. Copy an + * array (`capabilities.slice()`) before sorting or changing it. + */ +export interface ProductEntitlement { + readonly capabilities: readonly string[]; + readonly usage_until?: string; + readonly release_until?: string; + readonly notice: number; + readonly grace: number; + readonly flags: readonly string[]; + readonly [field: string]: unknown; +} + +/** + * The machine-readable data of a verified entitlement license key: what it + * grants, keyed by product name. Presence means licensed. A product the reader + * does not know is kept and ignored - one install can be licensed for one + * product and not for another, and the unknown one must not take down the + * known ones. + */ +export interface EntitlementKeyData { + readonly products: { readonly [productName: string]: ProductEntitlement }; +} + +/** + * The lifecycle state of a license, derived from the governing date of the + * product entry: + * + * - `usage_until` runs the notice -> soft stop -> hard stop windows against + * the current UTC instant. The `trial_*` states are the same windows on a + * key carrying the `trial` flag - they differ in what the user is told and + * shown, not in how they are measured. + * - `release_until` compares the build release date against the maintenance + * date as text. No clock takes part, so the verdict never changes. + */ +export type LicenseState = + | 'usage_valid' + | 'usage_notice' + | 'usage_soft_stop' + | 'usage_hard_stop' + | 'trial_valid' + | 'trial_notice' + | 'trial_soft_stop' + | 'trial_hard_stop' + | 'release_valid' + | 'release_expired'; + +/** + * The lifecycle facet of a license: the state, whether the key is a trial, the + * whole UTC days left until the last licensed day (`null` when no clock is + * involved), and the governing date as the bare "YYYY-MM-DD" string the + * payload carries. The date is never re-derived from a timestamp - the string + * in the key is what the messages print. + */ +export interface LicenseLifecycle { + readonly state: LicenseState; + readonly isTrial: boolean; + readonly daysRemaining: number | null; + readonly licensedUntil: string | null; +} + +/** + * Which notification channels the license leaves open. A product entry may + * carry `no-console-warns` (nothing reaches the console) and `no-ui-warns` (no + * WARNING is rendered in the UI); both are the default for a key issued for + * external, end-user-facing use. + * + * `ui` governs warnings only. A trial hard-stop block is enforcement and is + * applied regardless - see `NO_UI_WARNS_FLAG` in `./constants`. A new surface + * reading this field has to decide which of the two it is before honoring it. + */ +export interface LicenseChannels { + readonly console: boolean; + readonly ui: boolean; +} + +/** + * What a license unlocks. `unrestricted` is the fallback shortcut - every query + * answers "granted" for it, so the same API serves keys outside the + * entitlement format (unlock everything) and entitlement keys (unlock exactly + * the tokens the payload lists) without the caller branching on the key + * family. + */ +export interface LicenseGrants { + readonly unrestricted: boolean; + readonly products: { readonly [productName: string]: { readonly capabilities: readonly string[] } }; +} + +/** + * The time references a license is measured against: the current instant for a + * `usage_until` entitlement, and the build release date (as the bare + * "YYYY-MM-DD" text it is compared to) for a `release_until` one. The build + * date is text on purpose - the maintenance check is static against static, so + * it holds on a machine with no clock and cannot disagree between two + * timezones. + */ +export interface LicenseTimeReference { + now: number; + buildDate: string | null | undefined; +} + +/** + * Why an entitlement key does not license the product that reads it: + * + * - `unreadable` the block is missing, tampered with or malformed, + * - `product_missing` the key is intact but grants other products only. + * + * Both are reported to the user as an invalid key; the split exists so a + * product can log which one it was. + */ +export type UnlicensedReason = 'unreadable' | 'product_missing'; + +/** + * The result of reading an entitlement key for one product. + * + * When `licensed` is `true`, `entitlement`, `lifecycle` and `channels` describe + * that product and `grants` lists exactly what the key unlocks. + * + * When `licensed` is `false`, the product must report an invalid key. + * `entitlement` and `lifecycle` are `null`, both channels are open (the flags + * that close them could not be read), and `grants` is unrestricted - an + * invalid key nags, it never takes features away. + * + * The whole result is frozen, in both cases. + */ +export type EntitlementLicense = + | { + readonly licensed: true; + readonly reason: null; + readonly entitlement: ProductEntitlement; + readonly lifecycle: LicenseLifecycle; + readonly channels: LicenseChannels; + readonly grants: LicenseGrants; + } + | { + readonly licensed: false; + readonly reason: UnlicensedReason; + readonly entitlement: null; + readonly lifecycle: null; + readonly channels: LicenseChannels; + readonly grants: LicenseGrants; + }; + +/** + * What the calling product tells `readEntitlementLicense`. + */ +export interface ReadEntitlementLicenseOptions { + /** The product name this build reads its own license from (e.g. "hyperformula"). */ + product: string; + /** + * The build release date, as a bare "YYYY-MM-DD" (`toIsoBuildDate` converts + * "DD/MM/YYYY"). Compared against `release_until` keys only. A missing value + * (`undefined`, `null`, "") fails OPEN; any other value that is not a real + * "YYYY-MM-DD" throws - see `resolveBuildDate`. + */ + buildDate: string | null | undefined; + /** The current instant, in epoch milliseconds. Defaults to `Date.now()`. */ + now?: number; +} diff --git a/src/license/handsontable-license-key-parser/upstream.json b/src/license/handsontable-license-key-parser/upstream.json index de522f6dfc..1cfb886e10 100644 --- a/src/license/handsontable-license-key-parser/upstream.json +++ b/src/license/handsontable-license-key-parser/upstream.json @@ -1,18 +1,30 @@ { "_comment": [ - "Where the JavaScript in this directory comes from. Machine-readable so CI can check it:", - "`npm run check:vendored-parser` hashes these files and the upstream ones and compares.", + "Where this directory comes from, machine-readable so `npm run check:vendored-parser` can hold", + "it to upstream: it fetches every file of the upstream directory at `tag` and compares bytes.", + "Nothing else may live here except `own_files`; a local-only file would shadow a copied one.", "", - "No hashes are stored. The files ARE the copies, so a stored table would be a third thing", - "to keep in step. `track` is the branch to compare against - master, the released code;", - "`develop` there is work in progress. `commit` records which revision was taken.", + "`allowed_divergences` is the ONE place a local edit is permitted, and each entry has to say", + "why and when it goes away. The checker substitutes `local` for `upstream` in the fetched file", + "before comparing, so the moment upstream changes that line the entry stops matching, the", + "check fails, and the shim gets removed rather than forgotten.", "", - "PROVENANCE.md says what this directory is and why. This file says where it came from." + "A newer upstream tag also fails the check: the copy is taken from a tagged release, and a", + "release we have not looked at is the event the reviewer asked to be told about." ], "repository": "handsontable/license-key", - "directory": "src/entitlement-key", - "track": "master", + "directory": "vendor/entitlement-key-reader", + "tag": "4.0.1", "commit": "03810fd3c93160580e1b9665de6b38fca340e382", "taken_on": "2026-09-30", - "files": ["constants.js", "detect-format.js", "extract-key-data.js", "utils.js", "sha512.js"] + "own_files": ["PROVENANCE.md", "upstream.json"], + "allowed_divergences": [ + { + "file": "extractKeyData.ts", + "why": "TypeScript 4.0.8 (HyperFormula's) does not narrow `unknown` through `!== null && typeof === 'object'`; upstream compiles under ^5.9.3. One cast makes the file compile here. Semantics unchanged.", + "until": "upstream ships the cast (or HyperFormula moves to TypeScript >= 4.9) - then delete this entry and re-take the file", + "upstream": " Object.keys(current).forEach(key => pending.push((current as Record)[key]));", + "local": " Object.keys(current as object).forEach(key => pending.push((current as Record)[key]));" + } + ] } diff --git a/src/license/handsontable-license-key-parser/utils.d.ts b/src/license/handsontable-license-key-parser/utils.d.ts deleted file mode 100644 index d4fee105bb..0000000000 --- a/src/license/handsontable-license-key-parser/utils.d.ts +++ /dev/null @@ -1,53 +0,0 @@ -/** - * @license - * Copyright (c) 2025 Handsoncode. All rights reserved. - */ - -/** - * Hand-written declarations for `utils.js`, which is a verbatim copy of upstream. - * See PROVENANCE.md: the JavaScript is not edited here, so the types live beside it. - * - * `bytesToBase64` and `stringToBase64Url` are upstream's generation-side helpers. They are - * declared because the file exports them, and nothing in HyperFormula calls them. - */ - -/** A date in `YYYY-MM-DD`, split into its parts plus the epoch milliseconds of its UTC midnight. */ -export interface ParsedIsoDate { - year: number, - month: number, - day: number, - timestamp: number, -} - -/** Freezes the value and everything reachable from it, in place, and returns it. */ -export function deepFreeze(value: T): T - -/** - * Parses a `YYYY-MM-DD` date. Throws when the value is not a string, is malformed, or names a day - * that does not exist in the calendar. - * - * The parameter is `unknown` rather than `string` because upstream checks the type itself, and - * these declarations state what the code does rather than what a caller ought to pass. - * - * @param {unknown} isoDate - the value to parse - * @param {string} dateLabel - the field name used in the error message - */ -export function parseIsoDate(isoDate: unknown, dateLabel: string): ParsedIsoDate - -/** UTF-8 encodes the text. */ -export function stringToUtf8Bytes(text: string): number[] - -/** Decodes UTF-8 bytes back to text. */ -export function utf8BytesToString(bytes: number[]): string - -/** Base64-encodes the bytes. Generation-side; unused in HyperFormula. */ -export function bytesToBase64(bytes: number[]): string - -/** Decodes base64 or base64url, tolerating missing padding. `null` when the input is not base64. */ -export function base64ToBytes(base64: string): number[] | null - -/** Base64url-encodes the text. Generation-side; unused in HyperFormula. */ -export function stringToBase64Url(text: string): string - -/** Decodes base64 to text. `null` when the input is not base64. */ -export function base64ToString(base64: string): string | null diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index 4e61181d30..e3c4e0f370 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -11,9 +11,10 @@ import { } from '../helpers/licenseKeyValidator' import {CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' import {LicenseEntitlement, LicenseExpiry, unrestrictedEntitlement} from './LicenseEntitlement' -import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detect-format' -import {EntitlementKeyData, EntitlementProductGrant, extractEntitlementKeyData} from './handsontable-license-key-parser/extract-key-data' -import {parseIsoDate} from './handsontable-license-key-parser/utils' +import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detectFormat' +import {extractEntitlementKeyData} from './handsontable-license-key-parser/extractKeyData' +import {EntitlementKeyData, ProductEntitlement} from './handsontable-license-key-parser/types' +import {parseIsoDateToTimestamp} from './handsontable-license-key-parser/encoding' /** Milliseconds in a day, used to turn a grace period in days into a deadline. */ const MILLISECONDS_PER_DAY = 86400000 @@ -112,7 +113,7 @@ function releaseDateTimestamp(): number | null { * Reads HyperFormula's terms out of an intact entitlement key payload. * * Total on purpose: the vendored reader has already rejected every malformed shape, so every - * field read here is exactly what {@link EntitlementProductGrant} promises. A payload without a + * field read here is exactly what {@link ProductEntitlement} promises. A payload without a * `hyperformula` entry — including `products: {}` — is a VALID key that grants this library * nothing and never expires for it; per HF-307 decision D6-A that cliff is silent. Note this * differs from the typed-key format this replaces, where a key licensed to another product @@ -122,7 +123,7 @@ function releaseDateTimestamp(): number | null { * @param {EntitlementKeyData} data - the extracted key data */ function licenseTermsOf(data: EntitlementKeyData): LicenseTerms { - const grant: EntitlementProductGrant | undefined = data.products[HYPERFORMULA_PRODUCT_NAME] + const grant: ProductEntitlement | undefined = data.products[HYPERFORMULA_PRODUCT_NAME] // Nothing is granted implicitly: a key's functions are exactly what its own tokens name. A key // whose tokens this build does not recognize therefore still evaluates the infix operators (they @@ -148,7 +149,7 @@ function licenseTermsOf(data: EntitlementKeyData): LicenseTerms { // of UTC by a day. const expiryDate = grant === undefined ? undefined : (grant.usage_until ?? grant.release_until) const comparedAgainstReleaseDate = grant !== undefined && grant.release_until !== undefined - const expiryTimestamp = expiryDate === undefined ? null : parseIsoDate(expiryDate, 'expiration').timestamp + const expiryTimestamp = expiryDate === undefined ? null : parseIsoDateToTimestamp(expiryDate) const flags = grant === undefined ? [] : grant.flags // A release-date comparison has no grace period: it is static, so there is no window to be // inside of. diff --git a/tsconfig.json b/tsconfig.json index b0d3741bd8..812d955676 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -17,7 +17,7 @@ "es2017" ], /* Specify library files to be included in the compilation. */ - "allowJs": true, /* The vendored entitlement-key reader is upstream JavaScript, copied verbatim; see src/license/handsontable-license-key-parser/PROVENANCE.md. */ + // "allowJs": true, /* Allow javascript files to be compiled. */ // "checkJs": true, /* Report errors in .js files. */ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ // "declaration": true, /* Generates corresponding '.d.ts' file. */ From 71a0af6b90c4b4a5da147956b52afe9a75cc2790 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 11:16:53 +0000 Subject: [PATCH 19/54] HF-307: the drift check verifies the tag still points at the pinned commit A review of the previous commit found two things it said that its code did not do. "The check fails the moment upstream touches that line" - it cannot. It compares against an immutable tag, so an upstream fix on a branch never reaches it. What it sees is the next tag, and re-taking the copy there is what makes the shim entry stop matching. Reworded in the script header, the pin's comment and PROVENANCE. `pin.commit` was decorative - nothing read it, so a moved tag or an edited pin passed silently, the opposite of the commit tracking agreed on 18.09. The check now asserts that the pinned tag resolves to the pinned commit, and fails if the tag is gone or points elsewhere. Verified by editing the commit in the pin. The TypeScript floor in the divergence's expiry was wrong: measured, the un-cast line fails under 4.4.4 and compiles under 4.5.5, so it reads ">= 4.5", not 4.9. Co-Authored-By: Claude Fable 5.1 --- script/check-vendored-parser.js | 15 ++++++++-- .../PROVENANCE.md | 8 ++++-- .../upstream.json | 28 ++++++++++--------- 3 files changed, 33 insertions(+), 18 deletions(-) diff --git a/script/check-vendored-parser.js b/script/check-vendored-parser.js index 56d612ee45..fb3568bc43 100755 --- a/script/check-vendored-parser.js +++ b/script/check-vendored-parser.js @@ -17,9 +17,12 @@ * - fails on a local file upstream does not have (other than `own_files`) - a shadowing * `foo.ts` beside a copied `foo.ts` would otherwise win module resolution silently; * - fails on an upstream file that is missing locally; + * - checks that the pinned `tag` still points at the pinned `commit`, so a moved tag or an edited + * pin does not pass as the copy it is not; * - applies `allowed_divergences` - each a single exact line swap with a stated reason and expiry - - * to the fetched text before comparing. If upstream changes that line, the swap no longer - * matches and the check fails, so a shim cannot outlive the bug it works around; + * to the fetched text before comparing. Tags are immutable, so this cannot see upstream fix the + * line on a branch; on the next tag the swap stops matching and the check fails, so a shim + * cannot outlive the tag it was written against; * - fails when upstream has a NEWER tag than the pin: the copy is taken from releases, and a * release nobody has looked at is exactly what the reviewer asked to be told about. * @@ -216,6 +219,14 @@ async function main() { try { const tags = JSON.parse((await get(`/repos/${pin.repository}/tags?per_page=20`, 'application/vnd.github+json', auth)).toString('utf8')) + const pinned = tags.find((t) => t.name === pin.tag) + + if (pinned === undefined) { + problems.push(`tag ${pin.tag} is not among upstream's tags - the pin names a release that does not exist`) + } else if (pinned.commit.sha !== pin.commit) { + problems.push(`tag ${pin.tag} points at ${pinned.commit.sha.slice(0, 9)}, the pin says ${pin.commit.slice(0, 9)} - the tag moved or the pin was edited`) + } + const newer = tags.map((t) => t.name).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && semverGreater(name, pin.tag)) if (newer.length > 0) { diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 30ab7a6cbb..13d45cfa13 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -16,9 +16,11 @@ disagree about the same key. `extractKeyData.ts`, one line: `Object.keys(current)` → `Object.keys(current as object)`. HyperFormula compiles with TypeScript 4.0.8, which does not narrow `unknown` through `!== null && typeof === -'object'`; upstream compiles under 5.9. The cast changes no behaviour. It is recorded in -`upstream.json` with its reason, and the check below applies it before comparing - so the day -upstream changes that line, the entry stops matching, the check fails, and the shim comes out. +'object'`; upstream compiles under 5.9, and TypeScript 4.5 is where the line starts to compile +uncast. The cast changes no behaviour. It is recorded in `upstream.json` with its reason, and the +check below applies it before comparing. A tag is immutable, so the check does not see upstream fix +the line on a branch; it sees the next tag - a newer tag fails the check - and re-taking the copy at +that tag makes the entry stop matching, so the shim comes out instead of riding along. ## Checking it diff --git a/src/license/handsontable-license-key-parser/upstream.json b/src/license/handsontable-license-key-parser/upstream.json index 1cfb886e10..19597c3bd6 100644 --- a/src/license/handsontable-license-key-parser/upstream.json +++ b/src/license/handsontable-license-key-parser/upstream.json @@ -1,30 +1,32 @@ { "_comment": [ - "Where this directory comes from, machine-readable so `npm run check:vendored-parser` can hold", - "it to upstream: it fetches every file of the upstream directory at `tag` and compares bytes.", - "Nothing else may live here except `own_files`; a local-only file would shadow a copied one.", + "Where this directory comes from, machine-readable so `npm run check:vendored-parser` can hold it", + "to upstream: it fetches every file of the upstream directory at `tag`, checks that `tag` still", + "points at `commit`, and compares bytes. Nothing else may live here except `own_files`; a", + "local-only file would shadow a copied one.", "", - "`allowed_divergences` is the ONE place a local edit is permitted, and each entry has to say", - "why and when it goes away. The checker substitutes `local` for `upstream` in the fetched file", - "before comparing, so the moment upstream changes that line the entry stops matching, the", - "check fails, and the shim gets removed rather than forgotten.", - "", - "A newer upstream tag also fails the check: the copy is taken from a tagged release, and a", - "release we have not looked at is the event the reviewer asked to be told about." + "`allowed_divergences` is the ONE place a local edit is permitted, and each entry has to say why", + "and when it goes away. The checker substitutes `local` for `upstream` in the fetched file before", + "comparing. A tag is immutable, so this does not notice upstream fixing the line on its branches;", + "what it notices is a NEWER TAG (the check fails on one), and on re-taking the copy at that tag", + "the swap stops matching, so the shim has to come out rather than ride along." ], "repository": "handsontable/license-key", "directory": "vendor/entitlement-key-reader", "tag": "4.0.1", "commit": "03810fd3c93160580e1b9665de6b38fca340e382", "taken_on": "2026-09-30", - "own_files": ["PROVENANCE.md", "upstream.json"], + "own_files": [ + "PROVENANCE.md", + "upstream.json" + ], "allowed_divergences": [ { "file": "extractKeyData.ts", "why": "TypeScript 4.0.8 (HyperFormula's) does not narrow `unknown` through `!== null && typeof === 'object'`; upstream compiles under ^5.9.3. One cast makes the file compile here. Semantics unchanged.", - "until": "upstream ships the cast (or HyperFormula moves to TypeScript >= 4.9) - then delete this entry and re-take the file", + "until": "upstream ships the cast (or HyperFormula moves to TypeScript >= 4.5, measured: 4.4.4 fails, 4.5.5 passes) - then delete this entry and re-take the file", "upstream": " Object.keys(current).forEach(key => pending.push((current as Record)[key]));", - "local": " Object.keys(current as object).forEach(key => pending.push((current as Record)[key]));" + "local": " Object.keys(current as object).forEach(key => pending.push((current as Record)[key]));" } ] } From e0ed3e15b43e49172358230c23a97b31b94cd727 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 11:50:46 +0000 Subject: [PATCH 20/54] HF-307: codecov ignores the vendored reader; the drift workflow declares its permissions Two things CI said about 71a0af6b9. codecov/patch fell to 78%: 149 uncovered lines, all inside the vendored reader, mostly in the modules HyperFormula does not call yet (classify, readLicense, grants, buildDate, index). That directory is a byte-identical copy of upstream's vendor/entitlement-key-reader - upstream tests it, and this repository may not edit it - so its coverage measures nothing about HyperFormula. codecov now ignores it for the patch and project statuses. The local jest report is left alone on purpose, so the numbers are still there for anyone who wants them. CodeQL: "Workflow does not contain permissions". Every other workflow here sets `permissions: contents: read`; vendored-parser.yml now does too. The job only reads the repository and talks to a different one with its own token. Co-Authored-By: Claude Fable 5.1 --- .github/workflows/vendored-parser.yml | 3 +++ codecov.yml | 7 +++++++ 2 files changed, 10 insertions(+) diff --git a/.github/workflows/vendored-parser.yml b/.github/workflows/vendored-parser.yml index 5f223e1f98..39200122fa 100644 --- a/.github/workflows/vendored-parser.yml +++ b/.github/workflows/vendored-parser.yml @@ -21,6 +21,9 @@ on: schedule: - cron: '17 6 * * 1-5' # weekday mornings: a newer upstream tag is news even when nothing here changed +permissions: + contents: read + jobs: drift: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository diff --git a/codecov.yml b/codecov.yml index acc230a501..9610511d8d 100644 --- a/codecov.yml +++ b/codecov.yml @@ -6,6 +6,13 @@ coverage: round: down precision: 2 +# src/license/handsontable-license-key-parser/ is a byte-identical copy of handsontable/license-key's +# vendor/entitlement-key-reader (see PROVENANCE.md there). Upstream tests it; HyperFormula only calls +# part of it and may not edit it, so its coverage says nothing about this repository. It is left in the +# local jest report on purpose - only the codecov statuses ignore it. +ignore: + - "src/license/handsontable-license-key-parser/**" + comment: layout: "reach, diff, flags, files" behavior: new From 997e5b5726edb38ed78df01250a8fe79bec9b0db Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 12:07:18 +0000 Subject: [PATCH 21/54] HF-307: the drift check names a tag/commit mismatch as one, not as an access error Review found the realistic failure - a real tag with a commit that does not match it - blamed access: the pin pointed at 4.0.0, the reader directory does not exist at 4.0.0, the listing 404'd, and the check stopped there with "the token has no access to it, or the tag does not exist", both false. The tag-to-commit assertion ran after the listing, so it never spoke. It now runs first, the 404 message names the third cause (the directory absent at that ref), and the newer-tag rule is skipped when the pin itself is not a release tag, which used to list every tag as "newer" than `master`. The same review found one sentence, in three places, promising more than the code does: "a shim cannot outlive the tag it was written against". It can - a newer tag that leaves the line alone re-takes cleanly with the same cast. What the check does guarantee is that an upstream fix of the line cannot be missed, because the swap stops matching at that re-take. The three places now say that, and PROVENANCE's "Checking it" lists the tag-to-commit check it had left out. Co-Authored-By: Claude Fable 5.1 --- script/check-vendored-parser.js | 52 +++++++++++-------- .../PROVENANCE.md | 10 ++-- .../upstream.json | 5 +- 3 files changed, 39 insertions(+), 28 deletions(-) diff --git a/script/check-vendored-parser.js b/script/check-vendored-parser.js index fb3568bc43..7e96b5c17b 100755 --- a/script/check-vendored-parser.js +++ b/script/check-vendored-parser.js @@ -21,8 +21,9 @@ * pin does not pass as the copy it is not; * - applies `allowed_divergences` - each a single exact line swap with a stated reason and expiry - * to the fetched text before comparing. Tags are immutable, so this cannot see upstream fix the - * line on a branch; on the next tag the swap stops matching and the check fails, so a shim - * cannot outlive the tag it was written against; + * line on a branch; the next tag fails the check (newer-tag rule), and at the re-take the swap + * stops matching once upstream has changed the line, so an upstream fix cannot be missed. A tag + * that leaves the line alone carries the shim forward; `until` is a note, not a check; * - fails when upstream has a NEWER tag than the pin: the copy is taken from releases, and a * release nobody has looked at is exactly what the reviewer asked to be told about. * @@ -154,6 +155,32 @@ async function main() { } const problems = [] + + // The pin first: a tag that moved, or a pin edited by hand, is named as that - before any + // listing at the tag can fail for a different reason and blame access. + try { + const tags = JSON.parse((await get(`/repos/${pin.repository}/tags?per_page=20`, 'application/vnd.github+json', auth)).toString('utf8')) + const pinned = tags.find((t) => t.name === pin.tag) + + if (pinned === undefined) { + problems.push(`tag ${pin.tag} is not among upstream's tags - the pin names a release that does not exist`) + } else if (pinned.commit.sha !== pin.commit) { + problems.push(`tag ${pin.tag} points at ${pinned.commit.sha.slice(0, 9)}, the pin says ${pin.commit.slice(0, 9)} - the tag moved or the pin was edited`) + } + + const pinIsRelease = /^\d+\.\d+\.\d+$/.test(pin.tag) + const newer = pinIsRelease + ? tags.map((t) => t.name).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && semverGreater(name, pin.tag)) + : [] + + if (newer.length > 0) { + problems.push(`upstream has released ${newer.join(', ')} after ${pin.tag}. Review the change and re-take the copy from the newest tag.`) + } + } catch (error) { + problems.push(`could not list upstream tags (HTTP ${error.message}) - access, not drift`) + } + + let upstream try { @@ -161,7 +188,7 @@ async function main() { } catch (error) { console.error(`\nFAIL could not list ${pin.repository}/${pin.directory} at ${pin.tag}: HTTP ${error.message}.`) console.error(error.statusCode === 404 - ? ' 404 from a private repository means the token has no access to it, or the tag does not exist. This is not drift.' + ? ' 404 from a private repository means the token has no access to it, the tag does not exist, or the directory does not exist at that ref. This is not drift.' : ' This is an access or network problem, not drift.') process.exit(1) } @@ -217,25 +244,6 @@ async function main() { console.log(` EXTRA ${rel}`) }) - try { - const tags = JSON.parse((await get(`/repos/${pin.repository}/tags?per_page=20`, 'application/vnd.github+json', auth)).toString('utf8')) - const pinned = tags.find((t) => t.name === pin.tag) - - if (pinned === undefined) { - problems.push(`tag ${pin.tag} is not among upstream's tags - the pin names a release that does not exist`) - } else if (pinned.commit.sha !== pin.commit) { - problems.push(`tag ${pin.tag} points at ${pinned.commit.sha.slice(0, 9)}, the pin says ${pin.commit.slice(0, 9)} - the tag moved or the pin was edited`) - } - - const newer = tags.map((t) => t.name).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && semverGreater(name, pin.tag)) - - if (newer.length > 0) { - problems.push(`upstream has released ${newer.join(', ')} after ${pin.tag}. Review the change and re-take the copy from the newest tag.`) - } - } catch (error) { - problems.push(`could not list upstream tags (HTTP ${error.message}) - access, not drift`) - } - if (problems.length === 0) { console.log(`\nOK - the directory is upstream's ${pin.directory} at ${pin.tag}, byte for byte${divergences.size ? `, with ${divergences.size} declared divergence(s)` : ''}`) diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 13d45cfa13..3111b3ee83 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -19,8 +19,9 @@ compiles with TypeScript 4.0.8, which does not narrow `unknown` through `!== nul 'object'`; upstream compiles under 5.9, and TypeScript 4.5 is where the line starts to compile uncast. The cast changes no behaviour. It is recorded in `upstream.json` with its reason, and the check below applies it before comparing. A tag is immutable, so the check does not see upstream fix -the line on a branch; it sees the next tag - a newer tag fails the check - and re-taking the copy at -that tag makes the entry stop matching, so the shim comes out instead of riding along. +the line on a branch; it sees the next tag - a newer tag fails the check - and at the re-take the swap +stops matching once upstream has changed the line, so the fix cannot be missed. A tag that leaves the +line alone carries the shim forward; the `until` field is a note for the person re-taking, not a check. ## Checking it @@ -28,8 +29,9 @@ that tag makes the entry stop matching, so the shim comes out instead of riding npm run check:vendored-parser ``` -Lists the upstream directory at the pinned tag and compares every file byte for byte. Fails on any -difference, on a file here that upstream does not have (a shadowing `.ts` would win module +Checks that the pinned tag still resolves to the pinned commit, lists the upstream directory at that +tag and compares every file byte for byte. Fails on a moved tag or an edited pin, on any difference, +on a file here that upstream does not have (a shadowing `.ts` would win module resolution silently), on an upstream file missing here, and on a **newer upstream tag** than the pin. Without credentials to the private repository it fails rather than skips. diff --git a/src/license/handsontable-license-key-parser/upstream.json b/src/license/handsontable-license-key-parser/upstream.json index 19597c3bd6..9d114dbbe5 100644 --- a/src/license/handsontable-license-key-parser/upstream.json +++ b/src/license/handsontable-license-key-parser/upstream.json @@ -8,8 +8,9 @@ "`allowed_divergences` is the ONE place a local edit is permitted, and each entry has to say why", "and when it goes away. The checker substitutes `local` for `upstream` in the fetched file before", "comparing. A tag is immutable, so this does not notice upstream fixing the line on its branches;", - "what it notices is a NEWER TAG (the check fails on one), and on re-taking the copy at that tag", - "the swap stops matching, so the shim has to come out rather than ride along." + "what it notices is a NEWER TAG (the check fails on one), and at the re-take the swap stops matching", + "once upstream has changed the line. A tag that leaves the line alone carries the shim forward;", + "`until` is a note for whoever re-takes, not something the checker evaluates." ], "repository": "handsontable/license-key", "directory": "vendor/entitlement-key-reader", From 38500f70cbd054d361c78d86633565b5da64a9cb Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Wed, 30 Sep 2026 12:09:05 +0000 Subject: [PATCH 22/54] HF-307: when the listing fails, the drift check says what the pin check found first The previous commit moved the tag-to-commit assertion ahead of the listing and said the mismatch is now named. It was collected, not printed: the listing's failure exited before the problem list was shown, so the output still blamed access. Verified on the realistic case - pin at 4.0.0 with the 4.0.1 commit - which now prints the mismatch before the 404. Co-Authored-By: Claude Fable 5.1 --- script/check-vendored-parser.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/script/check-vendored-parser.js b/script/check-vendored-parser.js index 7e96b5c17b..6c1e07cebc 100755 --- a/script/check-vendored-parser.js +++ b/script/check-vendored-parser.js @@ -186,6 +186,8 @@ async function main() { try { upstream = await listUpstream(pin.repository, pin.directory, pin.tag, auth) } catch (error) { + // Whatever the pin check already found is the more likely cause of this failure - say it first. + problems.forEach((p) => console.error(`\nFAIL ${p}`)) console.error(`\nFAIL could not list ${pin.repository}/${pin.directory} at ${pin.tag}: HTTP ${error.message}.`) console.error(error.statusCode === 404 ? ' 404 from a private repository means the token has no access to it, the tag does not exist, or the directory does not exist at that ref. This is not drift.' From 4e876b83549194fb5c12daabeb086d98750ee728 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 30 Sep 2026 13:45:58 +0000 Subject: [PATCH 23/54] Rename vendored parser check to license-key-parser-drift Co-authored-by: Kuba Sekowski --- .github/workflows/vendored-parser.yml | 4 ++-- package.json | 2 +- ...k-vendored-parser.js => check-license-key-parser-drift.js} | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) rename script/{check-vendored-parser.js => check-license-key-parser-drift.js} (99%) diff --git a/.github/workflows/vendored-parser.yml b/.github/workflows/vendored-parser.yml index 39200122fa..306152cac2 100644 --- a/.github/workflows/vendored-parser.yml +++ b/.github/workflows/vendored-parser.yml @@ -14,7 +14,7 @@ on: types: [ opened, reopened, synchronize ] paths: - 'src/license/handsontable-license-key-parser/**' - - 'script/check-vendored-parser.js' + - 'script/check-license-key-parser-drift.js' - '.github/workflows/vendored-parser.yml' push: branches: [ master, develop ] @@ -36,6 +36,6 @@ jobs: with: node-version: '22' - name: Compare the vendored reader with upstream - run: node script/check-vendored-parser.js + run: node script/check-license-key-parser-drift.js env: LICENSE_KEY_REPO_TOKEN: ${{ secrets.LICENSE_KEY_REPO_TOKEN }} diff --git a/package.json b/package.json index 645784fec8..94c7e70223 100644 --- a/package.json +++ b/package.json @@ -101,7 +101,7 @@ "audit": "npm audit --omit=dev", "clean": "rimraf coverage/ commonjs/ dist/ es/ languages/ lib/ typings/ test-jasmine/", "compile": "tsc", - "check:vendored-parser": "node script/check-vendored-parser.js", + "check:license-key-parser-drift": "node script/check-license-key-parser-drift.js", "check:licenses": "license-checker --production --excludePackages=\"hyperformula@3.1.1\" --onlyAllow=\"MIT; Apache-2.0; BSD-3-Clause; BSD-2-Clause; ISC; BSD; Unlicense\"", "tsnode": "ts-node --transpile-only -O {\\\"module\\\":\\\"commonjs\\\"}", "release": "bash script/release/release.sh" diff --git a/script/check-vendored-parser.js b/script/check-license-key-parser-drift.js similarity index 99% rename from script/check-vendored-parser.js rename to script/check-license-key-parser-drift.js index 6c1e07cebc..b5b7e61d11 100755 --- a/script/check-vendored-parser.js +++ b/script/check-license-key-parser-drift.js @@ -27,7 +27,7 @@ * - fails when upstream has a NEWER tag than the pin: the copy is taken from releases, and a * release nobody has looked at is exactly what the reviewer asked to be told about. * - * Usage: npm run check:vendored-parser + * Usage: npm run check:license-key-parser-drift * * Needs read access to a private repository: LICENSE_KEY_REPO_TOKEN, GH_TOKEN, GITHUB_TOKEN, or * a logged-in `gh`. Without one it FAILS - "could not verify" is not "verified" - and a 401/403/404 From 8e47e2b32ea6c3c242bee19e89db02f876266768 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 1 Oct 2026 00:19:58 +0000 Subject: [PATCH 24/54] HF-307: read entitlement keys through readEntitlementLicense, as upstream prescribes The vendored reader's root README and its own guide both say a product calls `readEntitlementLicense` and keeps beside the copy only what is product-specific. HyperFormula used the reader's parsing pieces and re-implemented the lifecycle on top of them. That layer is gone: - the reader verifies the key, picks the `hyperformula` entry, places it in its lifecycle window and reads its flags; - `licenseResolution.ts` maps the ten lifecycle states onto gate A (the soft-stop states stay VALID and quiet, as decision D5-A builds only the notice and the hard stop), and keeps the capability-token meaning and the console messages. Two observable changes, both towards what every other product reading the same key does: - a key granting other products but not HyperFormula is INVALID (`product_missing`) and restricts nothing; it used to be VALID with an empty grant; - only `no-console-warns` silences the console; `silent-console` and `silent` are unknown flags now. The generator emits neither. Measured: tsc 0, lint 0, drift check OK, 517/517 suites (6543 passed, 3 skipped), bundle-all OK. Three mutations of the state mapping (soft stop as expired, notice never printed, release_expired as valid) each fail the license suite (1, 8 and 5 tests). Co-Authored-By: Claude Opus 5.5 --- src/license/LicenseEntitlement.ts | 4 +- .../PROVENANCE.md | 19 +- .../upstream.json | 2 +- src/license/licenseResolution.ts | 301 +++++------------- 4 files changed, 91 insertions(+), 235 deletions(-) diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index 84f2f198d9..c76b3dae0c 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -65,8 +65,8 @@ export interface LicenseEntitlement { /** * When `true`, resolving this entitlement must not print a console message of any kind. * - * Set from the key's own flags ONLY — the key spec spells that flag three different ways across - * revisions and even within one revision, and all are honoured. An unrecognized token does NOT + * Set from the key's own `no-console-warns` flag ONLY, as the vendored reader reads it (its + * `channels.console`). An unrecognized token does NOT * set it: HF-307 decision D3 makes the *grant* silent (an unknown token grants nothing, with no * message and no diagnostics getter), which is a different thing from muting the key's console * output. Coupling them suppressed expiry notices as a side effect of a vocabulary mismatch, and diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 3111b3ee83..a99a85bdf2 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -26,7 +26,7 @@ line alone carries the shim forward; the `until` field is a note for the person ## Checking it ```bash -npm run check:vendored-parser +npm run check:license-key-parser-drift ``` Checks that the pinned tag still resolves to the pinned commit, lists the upstream directory at that @@ -37,12 +37,13 @@ pin. Without credentials to the private repository it fails rather than skips. ## What HyperFormula uses from it -`extractEntitlementKeyData`, `detectLicenseKeyFormat`, `parseIsoDateToTimestamp`, `CHECKSUM_LENGTH`, -and the types - from `src/license/licenseResolution.ts` and `src/helpers/licenseKeyValidator.ts`, -which sit beside the copy, as upstream's guide prescribes. The reader also offers -`readEntitlementLicense` / `classifyEntitlement` / `getLicenseGrants` (window evaluation and grant -picking); HyperFormula evaluates windows in `licenseResolution.ts` and does not use those yet. -Consolidating onto them is a separate decision. +`readEntitlementLicense`, the single entry point upstream prescribes, plus `detectLicenseKeyFormat`, +`toIsoBuildDate`, `parseIsoDateToTimestamp`, `CHECKSUM_LENGTH` and the types - from +`src/license/licenseResolution.ts` and `src/helpers/licenseKeyValidator.ts`, which sit beside the +copy, as upstream's guide prescribes. The reader verifies the key, picks HyperFormula's entry, +places it in its lifecycle window and reads its flags. HyperFormula keeps what the guide leaves to +the product: the meaning of the capability tokens (`src/license/capabilities.ts`) and the console +messages. Upstream's `README.md` in this directory is the integration guide; `AGENTS.md` is theirs too. @@ -54,6 +55,6 @@ emitted from these sources by `tsc`, as for any other `.ts` here. ## Related -- `src/license/licenseResolution.ts` - the consumer: routes on `detectLicenseKeyFormat` and turns - the extracted payload into an entitlement. +- `src/license/licenseResolution.ts` - the consumer: routes on `detectLicenseKeyFormat`, reads the + key with `readEntitlementLicense` and turns the result into an entitlement. - `src/license/capabilities.ts` - the capability table the payload's tokens are resolved against. diff --git a/src/license/handsontable-license-key-parser/upstream.json b/src/license/handsontable-license-key-parser/upstream.json index 9d114dbbe5..93775f53b7 100644 --- a/src/license/handsontable-license-key-parser/upstream.json +++ b/src/license/handsontable-license-key-parser/upstream.json @@ -1,6 +1,6 @@ { "_comment": [ - "Where this directory comes from, machine-readable so `npm run check:vendored-parser` can hold it", + "Where this directory comes from, machine-readable so `npm run check:license-key-parser-drift` can hold it", "to upstream: it fetches every file of the upstream directory at `tag`, checks that `tag` still", "points at `commit`, and compares bytes. Nothing else may live here except `own_files`; a", "local-only file would shadow a copied one.", diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index e3c4e0f370..ca2796a61d 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -12,31 +12,36 @@ import { import {CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' import {LicenseEntitlement, LicenseExpiry, unrestrictedEntitlement} from './LicenseEntitlement' import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detectFormat' -import {extractEntitlementKeyData} from './handsontable-license-key-parser/extractKeyData' -import {EntitlementKeyData, ProductEntitlement} from './handsontable-license-key-parser/types' +import {readEntitlementLicense} from './handsontable-license-key-parser/readLicense' +import {toIsoBuildDate} from './handsontable-license-key-parser/buildDate' import {parseIsoDateToTimestamp} from './handsontable-license-key-parser/encoding' +import {LicenseState, ProductEntitlement} from './handsontable-license-key-parser/types' /** Milliseconds in a day, used to turn a grace period in days into a deadline. */ const MILLISECONDS_PER_DAY = 86400000 /** - * The name of HyperFormula's own product entry in an entitlement key payload. Every product - * entry carries its own capabilities, dates and windows, so this is the only entry this library - * reads — a key granting other products alongside (or instead of) HyperFormula is a valid key - * whose other entries are simply not for us. + * The name of HyperFormula's own product entry in an entitlement key payload. A key that grants + * other products but not this one is not a license for HyperFormula (the reader returns + * `product_missing`), however many other products it grants. */ export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' /** - * Flag spellings that suppress console output. + * Lifecycle states in which an entitlement key still lets this build evaluate formulas. * - * Three, because the key spec is not self-consistent: its normative flags table and its example - * payload (rev 6 §2.3 and §2) say `no-console-warns`, while the runtime-behaviour sections of the - * same revision (§4.3, §5.2) say `silent-console`, and earlier revisions said plain `silent`. A key - * minted against any of those readings must be honoured — a SaaS deployment that asked for silence - * and got console warnings is the failure this list exists to prevent. + * The soft-stop states are here on purpose: HF-307 decision D5-A builds the notice and the hard + * stop for 3.5.0, not the soft-stop message, so the grace period behaves as it did before the + * reader was adopted — valid and quiet. */ -const SILENT_CONSOLE_FLAGS = ['silent', 'silent-console', 'no-console-warns'] +const VALID_STATES: LicenseState[] = [ + 'usage_valid', 'usage_notice', 'usage_soft_stop', + 'trial_valid', 'trial_notice', 'trial_soft_stop', + 'release_valid', +] + +/** Lifecycle states in which a key that is still valid prints its expiry notice. */ +const NOTICE_STATES: LicenseState[] = ['usage_notice', 'trial_notice'] /** * Both halves of the license decision, resolved from one reading of the key. @@ -52,231 +57,70 @@ export interface ResolvedLicense { } /** - * What HyperFormula needs from an entitlement key, read from its own product entry. - * - * The entry's shape is guaranteed by the vendored reader ({@link extractEntitlementKeyData} - * returns `null` for anything malformed), so unlike the typed-key adapter this replaces, nothing - * here re-checks field types or reconciles competing payload shapes: the entitlement format is - * the only shape there is, and a key granting HyperFormula nothing is simply a key with no - * `hyperformula` entry. - */ -interface LicenseTerms { - capabilityTokens: string[], - expiry: LicenseExpiry, - /** Epoch milliseconds of the last licensed day, or `null` when the key never expires. */ - expiryTimestamp: number | null, - /** `true` compares against the build release date, `false` against the clock. */ - comparedAgainstReleaseDate: boolean, - graceDays: number, - isTrial: boolean, - silent: boolean, -} - -/** - * The build's release date as epoch milliseconds (UTC midnight), or `null` when it is unknown or - * malformed. - * - * Read from the same `HT_RELEASE_DATE` (`DD/MM/YYYY`) the legacy validator uses, but **parsed - * differently on purpose**, and the difference is observable — so do not "simplify" either one to - * match the other without reading this. - * - * This function uses `Date.UTC`. The legacy validator builds the same value with - * `new Date(month/day/year)`, which is parsed in the host's LOCAL zone. East of UTC the two land on - * different day numbers for one and the same release date: - * - * ```text - * HT_RELEASE_DATE=10/08/2026 legacy (local) this function (UTC) - * TZ=UTC, TZ=America/Los_Angeles 20675 20675 agree - * TZ=Asia/Tokyo 20674 20675 differ by a day - * TZ=Pacific/Kiritimati 20674 20675 differ by a day - * ``` - * - * UTC is the required reading for an entitlement key: key spec rev 6 §1.2 makes offline/online - * parity a hard rule — the offline check and a future online check must return the same verdict - * for the same key at the same instant — and any rule reading a local clock breaks it. The legacy - * path keeps its local parse because legacy behaviour is frozen for this release; switching it - * would move the expiry verdict of already-issued legacy keys by a day for every customer east - * of UTC. - * - * The consequence, flagged rather than hidden: two customers east of UTC, one on a legacy key and - * one on an equivalent entitlement key, can disagree by a day about whether this build is covered. - * Reconciling them is a product decision, not a refactor. - */ -function releaseDateTimestamp(): number | null { - const [day, month, year] = (process.env.HT_RELEASE_DATE ?? '').split('/') - const timestamp = Date.UTC(parseInt(year, 10), parseInt(month, 10) - 1, parseInt(day, 10)) - - return isNaN(timestamp) ? null : timestamp -} - -/** - * Reads HyperFormula's terms out of an intact entitlement key payload. + * The expiry details an entitlement records, read off HyperFormula's own entry. * - * Total on purpose: the vendored reader has already rejected every malformed shape, so every - * field read here is exactly what {@link ProductEntitlement} promises. A payload without a - * `hyperformula` entry — including `products: {}` — is a VALID key that grants this library - * nothing and never expires for it; per HF-307 decision D6-A that cliff is silent. Note this - * differs from the typed-key format this replaces, where a key licensed to another product - * carried the expiry HyperFormula was checked against: an entitlement key's product entries each - * carry their own terms, so another product's dates are not ours to read. + * A `release_until` date has no grace period: it is compared with the build date, which never + * moves, so there is no window to be inside of. * - * @param {EntitlementKeyData} data - the extracted key data + * @param {ProductEntitlement} entry - HyperFormula's entry of an intact key */ -function licenseTermsOf(data: EntitlementKeyData): LicenseTerms { - const grant: ProductEntitlement | undefined = data.products[HYPERFORMULA_PRODUCT_NAME] - - // Nothing is granted implicitly: a key's functions are exactly what its own tokens name. A key - // whose tokens this build does not recognize therefore still evaluates the infix operators (they - // are not function calls) and the protected built-ins, and returns #LIC! for every function call, - // silently, per HF-307 decision D3. That cliff is ratified as-is (D6-A): "this situation should - // never happen. There is no point in issuing a key if empty capabilities." - const capabilityTokens: string[] = [] - - if (grant !== undefined) { - // Appended one by one rather than with `push(...grant.capabilities)`. The array comes from an - // attacker-influenced payload and the format sets no size limit (the spec addendum lists - // "payload size" as an open question on its own page), and spreading an array into a call puts - // one argument per stack slot: measured, a checksum-valid key carrying 125 000 tokens threw - // `RangeError: Maximum call stack size exceeded` out of `HyperFormula.buildFromArray` instead - // of resolving to a verdict. A malformed or hostile key must produce INVALID, never a throw. - grant.capabilities.forEach((token) => capabilityTokens.push(token)) - } - - // Exactly one of the two date fields is present on an intact entry (the reader enforces it), - // and the date used and the axis it is compared against come from that same field. The date is - // carried as the payload's own `YYYY-MM-DD` string, never routed through `Date` formatting - - // the key spec's fixture J11 exists because `toISOString()` shortens every licence issued east - // of UTC by a day. - const expiryDate = grant === undefined ? undefined : (grant.usage_until ?? grant.release_until) - const comparedAgainstReleaseDate = grant !== undefined && grant.release_until !== undefined - const expiryTimestamp = expiryDate === undefined ? null : parseIsoDateToTimestamp(expiryDate) - const flags = grant === undefined ? [] : grant.flags - // A release-date comparison has no grace period: it is static, so there is no window to be - // inside of. - const graceDays = comparedAgainstReleaseDate || grant === undefined ? 0 : grant.grace +function expiryOf(entry: ProductEntitlement): LicenseExpiry { + const comparedAgainstReleaseDate = entry.release_until !== undefined return { - capabilityTokens, - expiry: expiryDate === undefined || expiryTimestamp === null - ? {kind: 'none', date: null, noticeDays: 0, graceDays: 0} - : { - kind: comparedAgainstReleaseDate ? 'release' : 'usage', - date: expiryDate, - // Read off HyperFormula's OWN entry, which is what makes the shape gate structural here: - // the tagged format took its terms from the LICENSED product's entry, so a `notice` field - // another product added for its own purposes could switch HyperFormula's console output - // on (fixed under gate in the previous PR). An entitlement key carries per-entry terms, so - // another product's `notice` is not reachable from here at all. - noticeDays: grant === undefined ? 0 : grant.notice, - graceDays, - }, - expiryTimestamp, - comparedAgainstReleaseDate, - graceDays, - isTrial: flags.indexOf('trial') !== -1, - // Every spelling the key spec uses for "suppress console output" - see SILENT_CONSOLE_FLAGS. - // The key's flags are the ONLY source of silence: an earlier revision also silenced any key - // carrying an unrecognized token, which suppressed strictly more than D3 asks for (it would - // have swallowed expiry notices too). That was confirmed an implementation error. - silent: flags.some((flag) => SILENT_CONSOLE_FLAGS.indexOf(flag) !== -1), + kind: comparedAgainstReleaseDate ? 'release' : 'usage', + date: (comparedAgainstReleaseDate ? entry.release_until : entry.usage_until) as string, + noticeDays: entry.notice, + graceDays: comparedAgainstReleaseDate ? 0 : entry.grace, } } /** - * Whether an intact entitlement key is still valid, and if not, the day it stopped being valid. - * - * A key with no expiry never expires. Otherwise the expiration date is INCLUSIVE of its last - * valid day, and a grace period extends it further. A date compared against the build's release - * date involves no clock at all, which is what keeps an air-gapped install with a wrong system - * clock working. + * The first day an expired key no longer covers, which is the convention the legacy validator + * already uses for the same message (it reports `keyValidityDays + 1`). * - * An unknown release date resolves to "not expired", matching what the legacy validator already - * does when `HT_RELEASE_DATE` is missing: a build that cannot tell its own age must not start - * rejecting keys that customers paid for. - * - * @param {LicenseTerms} terms - the terms of the key + * @param {LicenseExpiry} expiry - the expiry of the key */ -function validityOf(terms: LicenseTerms): {state: LicenseKeyValidityState, expiredOn?: Date} { - if (terms.expiryTimestamp === null) { - return {state: LicenseKeyValidityState.VALID} - } - - const now = terms.comparedAgainstReleaseDate ? releaseDateTimestamp() : Date.now() - - if (now === null) { - return {state: LicenseKeyValidityState.VALID} - } - - const deadline = terms.expiryTimestamp + MILLISECONDS_PER_DAY + (terms.graceDays * MILLISECONDS_PER_DAY) +function firstUncoveredDay(expiry: LicenseExpiry): Date { + const lastLicensedDay = parseIsoDateToTimestamp(expiry.date) as number - return now < deadline - ? {state: LicenseKeyValidityState.VALID} - // The reported day is the first day NOT covered, which is the convention the legacy validator - // already uses for the same message (it reports `keyValidityDays + 1`). - : {state: LicenseKeyValidityState.EXPIRED, expiredOn: new Date(deadline)} + return new Date(lastLicensedDay + MILLISECONDS_PER_DAY + (expiry.graceDays * MILLISECONDS_PER_DAY)) } /** - * The day a VALID key's usage-until expiry falls on, if the current UTC instant is within its - * notice window — `null` otherwise, which covers "no notice window configured" (`noticeDays` is - * `0`, which is also what a key with no HyperFormula entry resolves to) just as much as "not close - * enough yet" or "already past its usage-until day". - * - * Deliberately blind to `graceDays`: notice is about the usage_until axis itself, not about the - * grace extension past it. Key spec rev 6 §4.1 sequences notice, then a soft-stop window, then the - * hard-stop this build already enforces; only the hard stop and this notice are built for 3.5.0 - * (decision D5-A), so the window checked here ends exactly where the soft-stop phase would - * begin, rather than reaching into grace and printing a notice for a key already past its expiry. - * - * `release_until`-axis keys never reach here with a non-`null` result — `kind` is `'usage'` only - * when the date came from `usage_until` (see {@link licenseTermsOf}) — matching the spec's rule - * that notice and grace have no effect on that axis. The converse holds too now: the tagged - * format let an entry with no date of its own fall through to the key envelope's `exp`, so - * `'usage'` did not imply `usage_until`; an entitlement key has no envelope date to fall back to. - * - * @param {LicenseTerms} terms - the terms of the key - */ -function expiryWithinNoticeWindow(terms: LicenseTerms): Date | null { - if (terms.expiry.kind !== 'usage' || terms.expiry.noticeDays <= 0 || terms.expiryTimestamp === null) { - return null - } - - // The window ends at the first instant no longer on the usage_until day — the same boundary - // `validityOf` uses before adding its grace term — and opens `notice` days before the licensed - // day ITSELF, not before that end. Counting back from the end would shorten the window by a day: - // the date-semantics fixtures pin 2027-06-13T00:00:00Z for usage_until 2027-08-12 with notice 60, - // and a trial whose notice equals its whole term must warn from the day it is issued. - const usageAxisDeadline = terms.expiryTimestamp + MILLISECONDS_PER_DAY - const noticeWindowStart = terms.expiryTimestamp - (terms.expiry.noticeDays * MILLISECONDS_PER_DAY) - const now = Date.now() - - return now >= noticeWindowStart && now < usageAxisDeadline ? new Date(terms.expiryTimestamp) : null -} - -/** - * Turns the terms of an intact, unexpired entitlement key into the entitlement it grants. + * Turns HyperFormula's entry of a valid entitlement key into the entitlement it grants. * * Per HF-307 decision D3 this is fail-closed and silent: a token this version does not recognize * is recorded in `unrecognizedCapabilities` and grants nothing, without a warning, a message, or * anything public to read it back from. "Silent" there means the *grant* is silent — whether the - * key's console messages are suppressed is decided solely by its `flags` (`terms.silent`), never + * key's console messages are suppressed is decided solely by its `no-console-warns` flag, never * by the presence of an unrecognized token; coupling the two suppressed expiry notices as a side * effect of a vocabulary mismatch, and was confirmed an implementation error. * - * @param {LicenseTerms} terms - the terms of the key + * @param {ProductEntitlement} entry - HyperFormula's entry of a valid key + * @param {boolean} isTrial - whether the key carries the `trial` flag + * @param {boolean} silent - whether the key closes the console channel */ -function entitlementOf(terms: LicenseTerms): LicenseEntitlement { - const unrecognizedCapabilities = terms.capabilityTokens.filter( +function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: boolean): LicenseEntitlement { + // Appended one by one rather than with `push(...entry.capabilities)`. The array comes from an + // attacker-influenced payload and the format sets no size limit, and spreading an array into a + // call puts one argument per stack slot: measured, a checksum-valid key carrying 125 000 tokens + // threw `RangeError: Maximum call stack size exceeded` out of `HyperFormula.buildFromArray` + // instead of resolving to a verdict. + const capabilityTokens: string[] = [] + entry.capabilities.forEach((token) => capabilityTokens.push(token)) + + const unrecognizedCapabilities = capabilityTokens.filter( (token) => !CAPABILITY_TABLE.has(normalizeCapabilityToken(token)), ) return { unrestricted: false, - capabilities: new Set(terms.capabilityTokens), + capabilities: new Set(capabilityTokens), unrecognizedCapabilities, - expiry: terms.expiry, - silent: terms.silent, - isTrial: terms.isTrial, + expiry: expiryOf(entry), + silent, + isTrial, } } @@ -291,6 +135,11 @@ function entitlementOf(terms: LicenseTerms): LicenseEntitlement { * carries a bracketed block routes here even when the block is garbage: such a key is INVALID, * not a legacy key that happens to contain brackets. * + * An entitlement key is read by the vendored {@link readEntitlementLicense}, the single entry + * point upstream prescribes for products: it verifies the block, picks HyperFormula's entry, + * places it in its lifecycle window and reads its flags. Only the meaning of the capability + * tokens and the console messages live here. + * * **The invariant this function exists to protect.** Only a VALID entitlement key resolves to a * restricted entitlement. Every other outcome — missing, invalid, or expired, for an entitlement * key as much as for a legacy one — resolves to {@link unrestrictedEntitlement}. That asymmetry is @@ -321,9 +170,17 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true } } - const data = extractEntitlementKeyData(licenseKey) - - if (data === null) { + // Read exactly as the bundler inlines it - see the reader's README, rule 4. A missing or + // malformed `HT_RELEASE_DATE` becomes '', which the reader treats as "build date unknown" and + // fails open on, as the legacy validator does. + const license = readEntitlementLicense(licenseKey, { + product: HYPERFORMULA_PRODUCT_NAME, + buildDate: toIsoBuildDate(process.env.HT_RELEASE_DATE), + }) + + if (!license.licensed) { + // `unreadable` (a broken block) and `product_missing` (a key for other products only) are + // both reported as an invalid key, and neither restricts anything. if (notifyConsole) { notifyLicenseKeyState(LicenseKeyValidityState.INVALID) } @@ -331,23 +188,21 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true return {validityState: LicenseKeyValidityState.INVALID, entitlement: unrestrictedEntitlement()} } - const terms = licenseTermsOf(data) - const {state, expiredOn} = validityOf(terms) - - if (notifyConsole && !terms.silent) { - notifyLicenseKeyState(state, expiredOn, terms.comparedAgainstReleaseDate ? 'release' : 'usage') + const {entitlement: entry, lifecycle, channels} = license + const expiry = expiryOf(entry) + const isValid = VALID_STATES.indexOf(lifecycle.state) !== -1 + const state = isValid ? LicenseKeyValidityState.VALID : LicenseKeyValidityState.EXPIRED - if (state === LicenseKeyValidityState.VALID) { - const noticeExpiryDate = expiryWithinNoticeWindow(terms) + if (notifyConsole && channels.console) { + notifyLicenseKeyState(state, isValid ? undefined : firstUncoveredDay(expiry), expiry.kind === 'release' ? 'release' : 'usage') - if (noticeExpiryDate !== null) { - notifyLicenseKeyNotice(licenseKey, noticeExpiryDate) - } + if (NOTICE_STATES.indexOf(lifecycle.state) !== -1) { + notifyLicenseKeyNotice(licenseKey, new Date(parseIsoDateToTimestamp(expiry.date) as number)) } } return { validityState: state, - entitlement: state === LicenseKeyValidityState.VALID ? entitlementOf(terms) : unrestrictedEntitlement(), + entitlement: isValid ? entitlementOf(entry, lifecycle.isTrial, !channels.console) : unrestrictedEntitlement(), } } From 96a7b171dc7e518f7545681f4d0c66a79e563c94 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 1 Oct 2026 04:40:17 +0000 Subject: [PATCH 25/54] HF-307: comments say what the code does after the reader switch - LicenseEntitlement: drop "until PR 3 lands" (it landed); `unrestricted` also covers missing, invalid and expired keys. - licenseResolution: D5-A keeps hard blocking and defers the windows; the notice was built anyway. The old wording attributed the notice to D5-A. Comments only. Co-Authored-By: Claude Opus 5.5 --- src/license/LicenseEntitlement.ts | 9 +++++---- src/license/licenseResolution.ts | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index c76b3dae0c..ea99886341 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -47,11 +47,11 @@ export interface LicenseExpiry { * * This is the contract every later HF-307 task consumes: {@link CapabilityRegistry} turns it * into a `ResolvedCapabilities` set, gate B in the interpreter reads that set, and PR 2's - * `ensureCapability` reads it for the public API. Until PR 3 lands the real license-key payload - * adapter, instances of this are built by hand in tests rather than read from a real key. + * `ensureCapability` reads it for the public API. `resolveLicense` builds it from the + * configured key. */ export interface LicenseEntitlement { - /** `true` for every key this library fully understands today (`gpl-v3`, legacy keys). */ + /** `true` for every key that restricts nothing: legacy keys, `gpl-v3`, and any missing, invalid or expired key. */ unrestricted: boolean, /** Capability tokens this entitlement grants, recognized by this library version. */ capabilities: ReadonlySet, @@ -77,7 +77,8 @@ export interface LicenseEntitlement { } /** - * The unrestricted entitlement: legacy keys and `gpl-v3` resolve to this today. + * The unrestricted entitlement: legacy keys, `gpl-v3`, and every missing, invalid or expired + * entitlement key resolve to this. * * HF-307 decision D3 (fail-closed, silent) means an entitlement key whose tokens this library version * does not recognize at all no longer maps here — it resolves to an entitlement with an empty, diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index ca2796a61d..3d7e61cdc8 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -30,9 +30,9 @@ export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' /** * Lifecycle states in which an entitlement key still lets this build evaluate formulas. * - * The soft-stop states are here on purpose: HF-307 decision D5-A builds the notice and the hard - * stop for 3.5.0, not the soft-stop message, so the grace period behaves as it did before the - * reader was adopted — valid and quiet. + * The soft-stop states are here on purpose. HF-307 decision D5-A keeps hard blocking in this + * release and defers the rev 5 §4.1 windows to a follow-up; the notice was built anyway, the + * soft-stop message was not, so the grace period stays valid and quiet. */ const VALID_STATES: LicenseState[] = [ 'usage_valid', 'usage_notice', 'usage_soft_stop', From 85dc9762b60ab3d82f5bf9e901e3b13f95a69886 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 1 Oct 2026 09:46:34 +0000 Subject: [PATCH 26/54] HF-307: an expired non-trial entitlement key no longer blocks evaluation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ruling on #1728 (2026-10-01), for a non-trial hard stop and release_expired: "Don't block. It should just print an error in console." That matches the reader's guide ("18.1 never blocks a paying customer") and rev 5 §4.1. - resolveLicense now returns `blocksEvaluation` beside `validityState`. The state stays EXPIRED, so VERSION() and the message still say so; gate A in the interpreter reads the new flag instead of the state. - usage_hard_stop and release_expired: EXPIRED, not blocking, the message goes to console.error, and the key keeps its own grants (the reader reports it as licensed, so it never gains more on expiry). - trial_hard_stop, invalid, missing and every classic 25-character key block exactly as before. - docs/guide/license-key.md says which expired keys still give #LIC!. Measured: tsc 0, lint 0, 517/517 suites (6550 passed, 3 skipped), bundle-all OK. Paired tests: hyperformula-tests 107ea9d. Co-Authored-By: Claude Opus 5.5 --- docs/guide/license-key.md | 6 ++++- src/Config.ts | 14 +++++++++- src/helpers/licenseKeyValidator.ts | 10 +++++++- src/interpreter/Interpreter.ts | 5 ++-- src/license/licenseResolution.ts | 41 ++++++++++++++++++++++++------ 5 files changed, 62 insertions(+), 14 deletions(-) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index b3b596cdee..5de31f7468 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -71,10 +71,14 @@ If your key grants only part of the library, then: If your license key is missing, invalid, or expired, you see a corresponding notification in the console. -In that case every licence-gated function call evaluates to a `#LIC!` error — but no API method +A missing or invalid key, an expired trial key, and an expired key in the classic 25-character +format make every licence-gated function call evaluate to a `#LIC!` error — but no API method starts throwing, and `getAvailableFunctions()` still describes the full set of functions. A key problem never narrows what the library reports it can do. +Any other expired key in the new format keeps working with what it grants, and prints an error in +the console. + ## License key support If you have any issues with your license key, [contact our team](contact.md). \ No newline at end of file diff --git a/src/Config.ts b/src/Config.ts index d95bc1a23d..fbb48d72ec 100644 --- a/src/Config.ts +++ b/src/Config.ts @@ -32,6 +32,7 @@ import {ConfigParams, ConfigParamsList} from './ConfigParams' */ interface LicensePrivateState { licenseKeyValidityState: LicenseKeyValidityState, + licenseBlocksEvaluation: boolean, licenseCapabilities: ResolvedCapabilities, capabilityRegistry: CapabilityRegistry, } @@ -278,12 +279,13 @@ export class Config implements ConfigParams, ParserConfig { validateNumberToBeAtLeast(this.maxColumns, 'maxColumns', 1) this.context = context - const {validityState: licenseKeyValidityState, entitlement} = resolveLicense(this.licenseKey, notifyLicenseMessages) + const {validityState: licenseKeyValidityState, blocksEvaluation: licenseBlocksEvaluation, entitlement} = resolveLicense(this.licenseKey, notifyLicenseMessages) const capabilityRegistry = new CapabilityRegistry() const licenseCapabilities = capabilityRegistry.resolve(entitlement) privatePool.set(this, { licenseKeyValidityState, + licenseBlocksEvaluation, licenseCapabilities, capabilityRegistry, }) @@ -326,6 +328,16 @@ export class Config implements ConfigParams, ParserConfig { return (privatePool.get(this) as LicensePrivateState).licenseKeyValidityState } + /** + * Gate A: `true` when function calls must evaluate to `#LIC!`. Proxied to its private + * counterpart for the same reason as {@link licenseKeyValidityState}. + * + * @internal + */ + public get licenseBlocksEvaluation(): boolean { + return (privatePool.get(this) as LicensePrivateState).licenseBlocksEvaluation + } + /** * The functions and features this config's license entitles it to, already resolved from * whatever tokens the license key carries. Proxied to its private counterpart for the same diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 7f94d1811a..e346962b76 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -99,11 +99,15 @@ export function resetLicenseKeyNotificationForTests(): void { * @param {LicenseExpiryAxis} [expiryAxis] - which axis the key ran out along. Defaults to * `release`, which is the only axis the classic 25-character format has, so its message is * unchanged. + * @param {boolean} [asError] - print with `console.error` instead of `console.warn`. Used for an + * expired entitlement key that no longer blocks evaluation, where the console line is the only + * consequence left (decided on #1728, 2026-10-01). */ export function notifyLicenseKeyState( state: LicenseKeyValidityState, keyValidityDate?: Date, expiryAxis: LicenseExpiryAxis = 'release', + asError: boolean = false, ): void { if (_notified || state === LicenseKeyValidityState.VALID) { return @@ -113,7 +117,11 @@ export function notifyLicenseKeyState( ? {} : {keyValidityDate: formatDate(keyValidityDate), axis: expiryAxis} - console.warn(consoleMessages[state](vars)) + if (asError) { + console.error(consoleMessages[state](vars)) + } else { + console.warn(consoleMessages[state](vars)) + } _notified = true } diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 5bd104737c..ba7c5b6636 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -190,9 +190,8 @@ export class Interpreter { } case AstNodeType.FUNCTION_CALL: { if (!FunctionRegistry.functionIsProtected(ast.procedureName)) { - const validityState = this.config.licenseKeyValidityState - if (validityState !== LicenseKeyValidityState.VALID) { - return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(validityState)) + if (this.config.licenseBlocksEvaluation) { + return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(this.config.licenseKeyValidityState)) } const canonicalId = this.canonicalFunctionId(ast.procedureName) diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index 3d7e61cdc8..a838d41f61 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -30,9 +30,9 @@ export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' /** * Lifecycle states in which an entitlement key still lets this build evaluate formulas. * - * The soft-stop states are here on purpose. HF-307 decision D5-A keeps hard blocking in this - * release and defers the rev 5 §4.1 windows to a follow-up; the notice was built anyway, the - * soft-stop message was not, so the grace period stays valid and quiet. + * The soft-stop states are here on purpose: the grace period stays valid and quiet. HF-307 + * decision D5-A deferred the rev 5 §4.1 windows; the notice was built anyway, the soft-stop + * message was not. What happens after the grace period is {@link EXPIRED_WITHOUT_BLOCKING_STATES}. */ const VALID_STATES: LicenseState[] = [ 'usage_valid', 'usage_notice', 'usage_soft_stop', @@ -40,6 +40,17 @@ const VALID_STATES: LicenseState[] = [ 'release_valid', ] +/** + * Lifecycle states in which a non-trial key has run out but still lets this build evaluate + * formulas, printing an error to the console instead. Decided on #1728 (2026-10-01): "Don't block. + * It should just print an error in console." This matches the reader's guide (18.1 never blocks a + * paying customer) and rev 5 §4.1. A trial hard stop still blocks. + * + * The key keeps its own grants: the reader reports it as licensed, so an expired key is never + * granted more than the same key was granted while it was current. + */ +const EXPIRED_WITHOUT_BLOCKING_STATES: LicenseState[] = ['usage_hard_stop', 'release_expired'] + /** Lifecycle states in which a key that is still valid prints its expiry notice. */ const NOTICE_STATES: LicenseState[] = ['usage_notice', 'trial_notice'] @@ -50,8 +61,14 @@ const NOTICE_STATES: LicenseState[] = ['usage_notice', 'trial_notice'] * string, and parsing it twice would let them disagree about what it says. */ export interface ResolvedLicense { - /** Gate A — may this instance evaluate formulas at all. */ + /** The key's state, as reported by `VERSION()` and the console messages. */ validityState: LicenseKeyValidityState, + /** + * Gate A — `true` when function calls must return `#LIC!`. Usually `validityState !== VALID`; + * the exception is an expired non-trial entitlement key, which reports `EXPIRED` but keeps + * evaluating (see {@link EXPIRED_WITHOUT_BLOCKING_STATES}). + */ + blocksEvaluation: boolean, /** Gate B — which functions and API features the key grants. */ entitlement: LicenseEntitlement, } @@ -164,8 +181,11 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool */ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true): ResolvedLicense { if (detectLicenseKeyFormat(licenseKey) !== 'entitlement') { + const validityState = checkLicenseKeyValidity(licenseKey) + return { - validityState: checkLicenseKeyValidity(licenseKey), + validityState, + blocksEvaluation: validityState !== LicenseKeyValidityState.VALID, entitlement: unrestrictedEntitlement(), } } @@ -185,16 +205,18 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true notifyLicenseKeyState(LicenseKeyValidityState.INVALID) } - return {validityState: LicenseKeyValidityState.INVALID, entitlement: unrestrictedEntitlement()} + return {validityState: LicenseKeyValidityState.INVALID, blocksEvaluation: true, entitlement: unrestrictedEntitlement()} } const {entitlement: entry, lifecycle, channels} = license const expiry = expiryOf(entry) + const expiredWithoutBlocking = EXPIRED_WITHOUT_BLOCKING_STATES.indexOf(lifecycle.state) !== -1 const isValid = VALID_STATES.indexOf(lifecycle.state) !== -1 const state = isValid ? LicenseKeyValidityState.VALID : LicenseKeyValidityState.EXPIRED + const axis = expiry.kind === 'release' ? 'release' : 'usage' if (notifyConsole && channels.console) { - notifyLicenseKeyState(state, isValid ? undefined : firstUncoveredDay(expiry), expiry.kind === 'release' ? 'release' : 'usage') + notifyLicenseKeyState(state, isValid ? undefined : firstUncoveredDay(expiry), axis, expiredWithoutBlocking) if (NOTICE_STATES.indexOf(lifecycle.state) !== -1) { notifyLicenseKeyNotice(licenseKey, new Date(parseIsoDateToTimestamp(expiry.date) as number)) @@ -203,6 +225,9 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true return { validityState: state, - entitlement: isValid ? entitlementOf(entry, lifecycle.isTrial, !channels.console) : unrestrictedEntitlement(), + blocksEvaluation: !isValid && !expiredWithoutBlocking, + entitlement: isValid || expiredWithoutBlocking + ? entitlementOf(entry, lifecycle.isTrial, !channels.console) + : unrestrictedEntitlement(), } } From 670b46a17f0530ca2d646113492966abdeb09d49 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Thu, 1 Oct 2026 11:01:21 +0000 Subject: [PATCH 27/54] HF-307: the license guide no longer names key formats when explaining expiry Bugbot (Low) on 85dc9762b: the public guide should not describe the anatomy of proprietary key formats. The paragraph now says an expired key either behaves like an invalid one or keeps working with what it grants and prints a console error, depending on the license terms. Co-Authored-By: Claude Opus 5.5 --- docs/guide/license-key.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index 5de31f7468..a7780e2f32 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -71,13 +71,12 @@ If your key grants only part of the library, then: If your license key is missing, invalid, or expired, you see a corresponding notification in the console. -A missing or invalid key, an expired trial key, and an expired key in the classic 25-character -format make every licence-gated function call evaluate to a `#LIC!` error — but no API method -starts throwing, and `getAvailableFunctions()` still describes the full set of functions. A key -problem never narrows what the library reports it can do. +A missing or invalid key makes every licence-gated function call evaluate to a `#LIC!` error — but +no API method starts throwing, and `getAvailableFunctions()` still describes the full set of +functions. A key problem never narrows what the library reports it can do. -Any other expired key in the new format keeps working with what it grants, and prints an error in -the console. +Depending on your license terms, an expired key either behaves the same way, or keeps working with +what it grants and prints an error in the console. ## License key support From e929f23f6b59b975d96e6df2222795e10c3204fd Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Fri, 2 Oct 2026 03:38:42 +0000 Subject: [PATCH 28/54] HF-307: entitlement keys print the specification's console messages, as Handsontable does Compared with Handsontable's implementation of the same reader (handsontable/src/helpers/mixed.ts), HyperFormula disagreed about one key in two ways: it printed a day rebuilt from the grace period (usage_until + 1 + grace, "February 1, 2020") where Handsontable prints the key's own date ("2020-01-01 (UTC)"), and it said nothing during the grace period where Handsontable prints an error. - licenseKeyValidator: a per-state table (severity + text) transcribed from the specification, the same rows as Handsontable's, chosen by the reader's lifecycle state. Warnings while the key works, errors once it has run out, including the grace period. release_expired names the installed version and the downgrade clause. Once per key per page. - Classic 25-character keys keep their messages and their single once-per-page flag byte for byte. - Removed the rebuilt-date path (firstUncoveredDay), the separate notice function and the usage/release split of the classic expired message. - PROVENANCE.md records the owner's ruling on the one declared cast ("Neither. Let's keep this solution for now.", 2026-10-01). Measured: tsc 0, lint 0, drift check OK, 517/517 suites (6557 passed, 3 skipped), bundle-all OK. Paired tests: hyperformula-tests (this push). Co-Authored-By: Claude Opus 5.5 --- src/helpers/licenseKeyValidator.ts | 210 ++++++++++-------- .../PROVENANCE.md | 5 +- src/license/licenseResolution.ts | 40 +--- 3 files changed, 131 insertions(+), 124 deletions(-) diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index e346962b76..9648d9d7d7 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -4,6 +4,7 @@ */ import {CHECKSUM_LENGTH} from '../license/handsontable-license-key-parser/constants' +import {LicenseState} from '../license/handsontable-license-key-parser/types' import {checkKeySchema, extractTime} from './licenseKeyHelper' /** @@ -18,12 +19,6 @@ export const enum LicenseKeyValidityState { type LicenseKeyInvalidState = Exclude -/** - * Which deadline a key ran out against: the date of the build in use (`release`) or the wall - * clock (`usage`). - */ -export type LicenseExpiryAxis = 'release' | 'usage' - interface TemplateVars { [key: string]: string, } @@ -42,133 +37,168 @@ type MessageDescriptor = { */ const consoleMessages: ConsoleMessages = { invalid: () => 'The license key for HyperFormula is invalid.', - // Two wordings, because a key can run out along either of two axes and only one of them is - // about the build you installed. A maintenance key stops covering RELEASES after its date, so - // an older version keeps working and the fix is to install one; a usage-based key stops being - // valid at all, and telling its holder the key "is not valid for the installed version" sends - // them to downgrade, which changes nothing. - expired: ({keyValidityDate, axis}) => axis === 'usage' - ? `The license key for HyperFormula expired on ${keyValidityDate}.` - : `The license key for HyperFormula expired on ${keyValidityDate}, and is not valid for the installed version.`, + expired: ({keyValidityDate}) => 'The license key for HyperFormula expired' + + ` on ${keyValidityDate}, and is not valid for the installed version.`, missing: () => 'The license key for HyperFormula is missing.', } let _notified = false /** - * Identities (see {@link noticeIdentityOf}) of license keys that have already printed their - * expiry-approaching notice. - * - * Deliberately keyed per key rather than a single boolean like {@link _notified} - * above: that flag reports one of a handful of states that mean the same thing regardless of - * which key triggered them ("a key is invalid", "a key is missing"), so once-per-page-load is the - * right behaviour for it. Two different keys approaching their OWN expiry are two different - * events, and a page that swaps keys (or a test suite that builds one engine per key) must still - * warn for the second one even though the first already consumed a shared flag. + * What an entitlement-key console message is built from: the date exactly as the key carries it + * (never rebuilt from a timestamp) and the whole UTC days left until it. + */ +export interface EntitlementMessageParams { + licensedUntil: string | null, + daysRemaining: number | null, +} + +/** + * One console notification for an entitlement-key lifecycle state: its severity and its text. Kept + * as one record so a state cannot get a text without a severity. A warning while the license still + * works, an error once it has run out. */ -const _noticedKeys = new Set() +interface EntitlementConsoleNotification { + severity: 'warn' | 'error', + message: (params: EntitlementMessageParams) => string, +} + +const PURCHASE_LICENSE_TEXT = 'To continue using HyperFormula, you need to purchase a license.' + +/** + * A `usage_until` date is compared against the clock in UTC, so it is printed with the marker; a + * `release_until` date involves no clock and carries none. + */ +function utcDay(isoDate: string | null): string { + return `${isoDate} (UTC)` +} + +function expiryClause(days: number | null): string { + return days === 0 ? 'expires today' : `expires in ${days} ${days === 1 ? 'day' : 'days'}` +} + +function subscriptionExpiredMessage({licensedUntil}: EntitlementMessageParams): string { + return `Your HyperFormula subscription license expired on ${utcDay(licensedUntil)}. To continue using the software, contact sales@handsontable.com to purchase a valid license key.` +} + +/** + * The console message for each entitlement-key lifecycle state that talks to the developer: the + * specification's text (rev 5/6 §4.1, §4.2, as the vendored reader's README carries it), the same + * table Handsontable prints (`handsontable/src/helpers/mixed.ts`, `entitlementConsoleNotifications`), + * so one key reads the same in both products. Silent states (inside the term, a build covered by its + * maintenance date) have no entry. A non-trial key past its grace keeps the soft-stop message: it + * never blocks a paying customer (decided on #1728, 2026-10-01). + */ +const ENTITLEMENT_CONSOLE_NOTIFICATIONS: Partial> = { + trial_notice: { + severity: 'warn', + message: ({daysRemaining}) => `Your HyperFormula license key ${expiryClause(daysRemaining)}. ${PURCHASE_LICENSE_TEXT}`, + }, + trial_soft_stop: { + severity: 'error', + message: ({licensedUntil}) => `Your HyperFormula trial license key expired on ${utcDay(licensedUntil)}. ${PURCHASE_LICENSE_TEXT}`, + }, + trial_hard_stop: { + severity: 'error', + message: ({licensedUntil}) => `Your HyperFormula trial license key expired on ${utcDay(licensedUntil)}. You may no longer use HyperFormula under the trial license. To continue using the software, contact sales@handsontable.com to purchase a valid license.`, + }, + usage_notice: { + severity: 'warn', + message: ({licensedUntil}) => `Your HyperFormula subscription license expires on ${utcDay(licensedUntil)}. To renew your license, contact sales@handsontable.com.`, + }, + usage_soft_stop: {severity: 'error', message: subscriptionExpiredMessage}, + usage_hard_stop: {severity: 'error', message: subscriptionExpiredMessage}, + release_expired: { + severity: 'error', + message: ({licensedUntil}) => `The license key for HyperFormula expired on ${licensedUntil}, and is not valid for the installed version ${process.env.HT_VERSION as string}. Renew your license key or downgrade to a version released on or before ${licensedUntil}. If you need any help, contact us at sales@handsontable.com.`, + }, +} + +/** + * Identities (see {@link keyIdentityOf}) of entitlement keys that have already printed their + * message. Per key, as the specification asks ("each distinct message once per key per page") and + * as Handsontable does: two keys on one page are two licenses. Kept apart from {@link _notified}, + * which serves classic 25-character keys and stays a single flag, unchanged. + */ +const _notifiedEntitlementKeys = new Set() /** * Clears the once-per-page-load flag {@link notifyLicenseKeyState} keeps, and the per-key set - * {@link notifyLicenseKeyNotice} keeps. + * {@link notifyEntitlementKey} keeps. * * Exists for tests only. Both are module-level and never otherwise reset, so without this the - * whole console-message path is unobservable: the first spec to build any engine consumes the single - * warning and every later assertion sees silence regardless of what the code does. Making the reset - * explicit beats the alternatives — depending on spec-file order is flaky, and under Karma every - * spec shares one browser context, so order tricks do not work there at all. + * whole console-message path is unobservable: the first spec to build any engine consumes the + * message and every later assertion sees silence regardless of what the code does. Under Karma + * every spec shares one browser context, so spec-order tricks do not work there at all. * * @internal */ export function resetLicenseKeyNotificationForTests(): void { _notified = false - _noticedKeys.clear() + _notifiedEntitlementKeys.clear() } /** - * Prints the console message for a non-valid license key state, at most once per page load. - * - * Extracted so the entitlement-key path in `src/license/licenseResolution.ts` reports the same states - * with the same wording and the same once-only behaviour, without duplicating the message table - * or getting a second `_notified` flag of its own — two flags would let a page print two - * warnings for one key. + * Prints the console message for a classic 25-character key's non-valid state, at most once per + * page load. Unchanged from before HF-307. * * @param {LicenseKeyValidityState} state - the state to report; `VALID` prints nothing - * @param {Date} [keyValidityDate] - the day the key stopped being valid, used by the `expired` - * message - * @param {LicenseExpiryAxis} [expiryAxis] - which axis the key ran out along. Defaults to - * `release`, which is the only axis the classic 25-character format has, so its message is - * unchanged. - * @param {boolean} [asError] - print with `console.error` instead of `console.warn`. Used for an - * expired entitlement key that no longer blocks evaluation, where the console line is the only - * consequence left (decided on #1728, 2026-10-01). + * @param {Date} [keyValidityDate] - the day the key stopped being valid, used by the `expired` message */ -export function notifyLicenseKeyState( - state: LicenseKeyValidityState, - keyValidityDate?: Date, - expiryAxis: LicenseExpiryAxis = 'release', - asError: boolean = false, -): void { +export function notifyLicenseKeyState(state: LicenseKeyValidityState, keyValidityDate?: Date): void { if (_notified || state === LicenseKeyValidityState.VALID) { return } - const vars: TemplateVars = keyValidityDate === undefined - ? {} - : {keyValidityDate: formatDate(keyValidityDate), axis: expiryAxis} + const vars: TemplateVars = keyValidityDate === undefined ? {} : {keyValidityDate: formatDate(keyValidityDate)} - if (asError) { - console.error(consoleMessages[state](vars)) - } else { - console.warn(consoleMessages[state](vars)) - } + console.warn(consoleMessages[state](vars)) _notified = true } /** - * Prints a one-time notice that a VALID entitlement key's usage-until expiry is approaching, at - * most once per distinct license key. + * Prints the console message for an entitlement key, at most once per distinct key per page. + * `'invalid'` (a broken block, or a key for other products only) reuses the classic invalid-key + * text, as Handsontable does: the specification leaves that message open (§4.5). * - * Called from `src/license/licenseResolution.ts`'s `resolveLicense`, alongside - * {@link notifyLicenseKeyState} — see that function's doc for why the two share this module - * instead of each keeping a message table and a flag of their own. - * - * The wording is rev 5 §3.2's own subscription clause ("valid until {date} (UTC)"), naming the - * key's LAST covered day. It deliberately does not say "expires on": the pre-existing expired - * message reports the first day NOT covered (`validityOf`'s convention, +1 day), and two messages - * for the same key must not name two different days for the same boundary. "Valid until Aug 25" - * followed later by "expired on Aug 26" is consistent; "expires on Aug 25" followed by - * "expired on Aug 26" is a support ticket. - * - * @param {string} licenseKey - the raw key string; only its identity is retained, see below - * @param {Date} expiryDate - the last covered day of the key's usage-until axis, at UTC midnight + * @param {string} licenseKey - the raw key; only its identity is retained + * @param {LicenseState | 'invalid'} state - the reader's lifecycle state, or `'invalid'` + * @param {EntitlementMessageParams} params - the key's own date and days remaining */ -export function notifyLicenseKeyNotice(licenseKey: string, expiryDate: Date): void { - const identity = noticeIdentityOf(licenseKey) +export function notifyEntitlementKey(licenseKey: string, state: LicenseState | 'invalid', params: EntitlementMessageParams): void { + const identity = keyIdentityOf(licenseKey) - if (_noticedKeys.has(identity)) { + if (_notifiedEntitlementKeys.has(identity)) { return } - console.warn(`The HyperFormula license key is valid until ${formatDate(expiryDate)} (UTC). To renew the license, contact sales@handsontable.com.`) - _noticedKeys.add(identity) + const notification: EntitlementConsoleNotification | undefined = state === 'invalid' + ? {severity: 'warn', message: () => consoleMessages.invalid({})} + : ENTITLEMENT_CONSOLE_NOTIFICATIONS[state] + + if (notification === undefined) { + return + } + + if (notification.severity === 'error') { + console.error(notification.message(params)) + } else { + console.warn(notification.message(params)) + } + _notifiedEntitlementKeys.add(identity) } /** - * The warn-once identity of a key: its trailing 129 characters, after trimming — for an intact - * entitlement key, the sha512 checksum plus the closing bracket that ends the machine-readable - * block, unique per distinct key content. - * - * Trimmed because the reader ignores trailing whitespace (it looks for the block, not for the end - * of the string), so `'KEY'` and `'KEY\n'` are one license and must be one identity here too. - * Reading from the END rather than the start also makes the whole artifact and its bare `[...]` - * block — which the format says are equally valid spellings of the same license — one identity. + * The identity of a key: its trailing 129 characters, after trimming — for an intact entitlement + * key, the sha512 checksum plus the closing bracket, unique per distinct key content. * - * Truncated because the set retains its entries for the life of the process: a multi-tenant server - * building one engine per customer-supplied key would otherwise accumulate every full key string - * it has ever warned about; 129 characters per entry bounds that to the checksum alone. + * Trimmed because the reader ignores surrounding whitespace, so `'KEY'` and `'KEY\n'` are one + * license and must be one identity here too. Read from the END, so the whole artifact and its bare + * `[...]` block, which the format treats as the same license, are one identity. Truncated because + * the set lives as long as the page: a server building one engine per customer key would otherwise + * keep every full key string it has ever seen. */ -function noticeIdentityOf(licenseKey: string): string { +function keyIdentityOf(licenseKey: string): string { return licenseKey.trim().slice(-(CHECKSUM_LENGTH + 1)) } diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index a99a85bdf2..c28af97efa 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -2,8 +2,9 @@ This directory is a copy of `handsontable/license-key`'s **`vendor/entitlement-key-reader/`**, the TypeScript reader that repository publishes for products to copy. It is taken whole, from a -tagged release, and not edited here: fix upstream, then re-take. A local fix makes two products -disagree about the same key. +tagged release, and edited here in one declared line only (below), which the HyperFormula owner +accepted on 2026-10-01 ("Let's keep this solution for now", #1728). Anything else is fixed upstream +and re-taken: a local fix makes two products disagree about the same key. | | | |---|---| diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index a838d41f61..095c78c81c 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -6,20 +6,15 @@ import { checkLicenseKeyValidity, LicenseKeyValidityState, - notifyLicenseKeyNotice, - notifyLicenseKeyState, + notifyEntitlementKey, } from '../helpers/licenseKeyValidator' import {CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' import {LicenseEntitlement, LicenseExpiry, unrestrictedEntitlement} from './LicenseEntitlement' import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detectFormat' import {readEntitlementLicense} from './handsontable-license-key-parser/readLicense' import {toIsoBuildDate} from './handsontable-license-key-parser/buildDate' -import {parseIsoDateToTimestamp} from './handsontable-license-key-parser/encoding' import {LicenseState, ProductEntitlement} from './handsontable-license-key-parser/types' -/** Milliseconds in a day, used to turn a grace period in days into a deadline. */ -const MILLISECONDS_PER_DAY = 86400000 - /** * The name of HyperFormula's own product entry in an entitlement key payload. A key that grants * other products but not this one is not a license for HyperFormula (the reader returns @@ -30,9 +25,9 @@ export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' /** * Lifecycle states in which an entitlement key still lets this build evaluate formulas. * - * The soft-stop states are here on purpose: the grace period stays valid and quiet. HF-307 - * decision D5-A deferred the rev 5 §4.1 windows; the notice was built anyway, the soft-stop - * message was not. What happens after the grace period is {@link EXPIRED_WITHOUT_BLOCKING_STATES}. + * The soft-stop states are here on purpose: the grace period keeps evaluating and prints the + * specification's error (see `notifyEntitlementKey`). What happens after the grace period is + * {@link EXPIRED_WITHOUT_BLOCKING_STATES}. */ const VALID_STATES: LicenseState[] = [ 'usage_valid', 'usage_notice', 'usage_soft_stop', @@ -51,9 +46,6 @@ const VALID_STATES: LicenseState[] = [ */ const EXPIRED_WITHOUT_BLOCKING_STATES: LicenseState[] = ['usage_hard_stop', 'release_expired'] -/** Lifecycle states in which a key that is still valid prints its expiry notice. */ -const NOTICE_STATES: LicenseState[] = ['usage_notice', 'trial_notice'] - /** * Both halves of the license decision, resolved from one reading of the key. * @@ -92,18 +84,6 @@ function expiryOf(entry: ProductEntitlement): LicenseExpiry { } } -/** - * The first day an expired key no longer covers, which is the convention the legacy validator - * already uses for the same message (it reports `keyValidityDays + 1`). - * - * @param {LicenseExpiry} expiry - the expiry of the key - */ -function firstUncoveredDay(expiry: LicenseExpiry): Date { - const lastLicensedDay = parseIsoDateToTimestamp(expiry.date) as number - - return new Date(lastLicensedDay + MILLISECONDS_PER_DAY + (expiry.graceDays * MILLISECONDS_PER_DAY)) -} - /** * Turns HyperFormula's entry of a valid entitlement key into the entitlement it grants. * @@ -202,25 +182,21 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true // `unreadable` (a broken block) and `product_missing` (a key for other products only) are // both reported as an invalid key, and neither restricts anything. if (notifyConsole) { - notifyLicenseKeyState(LicenseKeyValidityState.INVALID) + notifyEntitlementKey(licenseKey, 'invalid', {licensedUntil: null, daysRemaining: null}) } return {validityState: LicenseKeyValidityState.INVALID, blocksEvaluation: true, entitlement: unrestrictedEntitlement()} } const {entitlement: entry, lifecycle, channels} = license - const expiry = expiryOf(entry) const expiredWithoutBlocking = EXPIRED_WITHOUT_BLOCKING_STATES.indexOf(lifecycle.state) !== -1 const isValid = VALID_STATES.indexOf(lifecycle.state) !== -1 const state = isValid ? LicenseKeyValidityState.VALID : LicenseKeyValidityState.EXPIRED - const axis = expiry.kind === 'release' ? 'release' : 'usage' + // The message is chosen by the reader's state and prints the key's own date (rev 5/6 §4.1, the + // same table Handsontable uses). The `no-console-warns` flag closes the channel. if (notifyConsole && channels.console) { - notifyLicenseKeyState(state, isValid ? undefined : firstUncoveredDay(expiry), axis, expiredWithoutBlocking) - - if (NOTICE_STATES.indexOf(lifecycle.state) !== -1) { - notifyLicenseKeyNotice(licenseKey, new Date(parseIsoDateToTimestamp(expiry.date) as number)) - } + notifyEntitlementKey(licenseKey, lifecycle.state, {licensedUntil: lifecycle.licensedUntil, daysRemaining: lifecycle.daysRemaining}) } return { From 153920bae129f916fa44499bfb66e0bfb193bbc7 Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Fri, 2 Oct 2026 04:56:34 +0000 Subject: [PATCH 29/54] HF-307: dedupe entitlement messages per key and message, not per key Bugbot (Medium) on e929f23f6: keying the once-per-page set by the key alone dropped a later, different message for the same key, so a page that stayed open while a key moved from its notice window into expiry never printed the expiry error. The set now holds key + message text, which is what the specification asks ("each distinct message once per key per page"). A soft stop and a hard stop share one text, so it does not repeat. Measured: tsc 0, lint 0, full suite green. Paired test in hyperformula-tests. Co-Authored-By: Claude Opus 5.5 --- src/helpers/licenseKeyValidator.ts | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 9648d9d7d7..7c4aa03f1e 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -115,9 +115,9 @@ const ENTITLEMENT_CONSOLE_NOTIFICATIONS: Partial() @@ -166,12 +166,6 @@ export function notifyLicenseKeyState(state: LicenseKeyValidityState, keyValidit * @param {EntitlementMessageParams} params - the key's own date and days remaining */ export function notifyEntitlementKey(licenseKey: string, state: LicenseState | 'invalid', params: EntitlementMessageParams): void { - const identity = keyIdentityOf(licenseKey) - - if (_notifiedEntitlementKeys.has(identity)) { - return - } - const notification: EntitlementConsoleNotification | undefined = state === 'invalid' ? {severity: 'warn', message: () => consoleMessages.invalid({})} : ENTITLEMENT_CONSOLE_NOTIFICATIONS[state] @@ -180,10 +174,20 @@ export function notifyEntitlementKey(licenseKey: string, state: LicenseState | ' return } + // Keyed by the key AND the text, not the key alone: on a page that stays open while a key moves + // from its notice window into expiry, the expiry message is a different message and must still + // print. A soft stop and a hard stop share one text, so the hard stop does not repeat it. + const text = notification.message(params) + const identity = `${keyIdentityOf(licenseKey)}\n${text}` + + if (_notifiedEntitlementKeys.has(identity)) { + return + } + if (notification.severity === 'error') { - console.error(notification.message(params)) + console.error(text) } else { - console.warn(notification.message(params)) + console.warn(text) } _notifiedEntitlementKeys.add(identity) } From fc59e57ee03d539cc87feb0352de5a89586e6b73 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Mon, 5 Oct 2026 17:39:53 +0200 Subject: [PATCH 30/54] HF-307: license comments describe behaviour, not ticket history Remove ticket, pull request, task, review-date and decision references, internal specification section numbers and a personal name from comments in the license code. The reasons they carried are kept in plain terms. Co-Authored-By: Claude Opus 5.5 --- src/BuildEngineFactory.ts | 2 +- src/errors.ts | 2 +- src/helpers/licenseKeyValidator.ts | 8 ++++---- src/license/CapabilityRegistry.ts | 9 ++++----- src/license/LicenseEntitlement.ts | 26 +++++++++++--------------- src/license/capabilities.ts | 2 +- src/license/featureCapabilities.ts | 4 ++-- src/license/functionCapabilities.ts | 11 +++++------ src/license/licenseResolution.ts | 24 ++++++++++++------------ 9 files changed, 41 insertions(+), 47 deletions(-) diff --git a/src/BuildEngineFactory.ts b/src/BuildEngineFactory.ts index 5c11aa7430..f06a7d9301 100644 --- a/src/BuildEngineFactory.ts +++ b/src/BuildEngineFactory.ts @@ -75,7 +75,7 @@ export class BuildEngineFactory { /** * Throws if `namedExpressions` is non-empty and `config`'s entitlement does not grant - * {@link FeatureId.NamedExpressions} (HF-307 PR 2, task 2.3 - the build-time counterpart of + * {@link FeatureId.NamedExpressions} (the build-time counterpart of * {@link HyperFormula.ensureCapability}). An empty list is never checked: building an engine * with no named expressions never touches the feature. Deliberately not called from * {@link rebuildWithConfig}, which re-serializes named expressions an already-built instance diff --git a/src/errors.ts b/src/errors.ts index 7c0778d71d..283ed1d8da 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -397,7 +397,7 @@ export class AliasAlreadyExisting extends Error { /** * Error thrown when a public API method is called for a {@link FeatureId} that the current * license entitlement does not grant. Mirrors gate B's `ErrorMessage.LicenseCapability`, but - * this one guards the API surface itself (HF-307 PR 2) rather than a formula evaluation, so it + * this one guards the API surface itself rather than a formula evaluation, so it * is thrown synchronously instead of surfacing as a cell error. * * This list names every method that can throw it - `resumeEvaluation` is deliberately NOT among diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 7c4aa03f1e..9e335c5613 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -83,11 +83,11 @@ function subscriptionExpiredMessage({licensedUntil}: EntitlementMessageParams): /** * The console message for each entitlement-key lifecycle state that talks to the developer: the - * specification's text (rev 5/6 §4.1, §4.2, as the vendored reader's README carries it), the same + * specification's text (as the vendored reader's README carries it), the same * table Handsontable prints (`handsontable/src/helpers/mixed.ts`, `entitlementConsoleNotifications`), * so one key reads the same in both products. Silent states (inside the term, a build covered by its * maintenance date) have no entry. A non-trial key past its grace keeps the soft-stop message: it - * never blocks a paying customer (decided on #1728, 2026-10-01). + * never blocks a paying customer. */ const ENTITLEMENT_CONSOLE_NOTIFICATIONS: Partial> = { trial_notice: { @@ -140,7 +140,7 @@ export function resetLicenseKeyNotificationForTests(): void { /** * Prints the console message for a classic 25-character key's non-valid state, at most once per - * page load. Unchanged from before HF-307. + * page load. Entitlement keys do not go through this function. * * @param {LicenseKeyValidityState} state - the state to report; `VALID` prints nothing * @param {Date} [keyValidityDate] - the day the key stopped being valid, used by the `expired` message @@ -159,7 +159,7 @@ export function notifyLicenseKeyState(state: LicenseKeyValidityState, keyValidit /** * Prints the console message for an entitlement key, at most once per distinct key per page. * `'invalid'` (a broken block, or a key for other products only) reuses the classic invalid-key - * text, as Handsontable does: the specification leaves that message open (§4.5). + * text, as Handsontable does: the specification leaves that message open. * * @param {string} licenseKey - the raw key; only its identity is retained * @param {LicenseState | 'invalid'} state - the reader's lifecycle state, or `'invalid'` diff --git a/src/license/CapabilityRegistry.ts b/src/license/CapabilityRegistry.ts index 3e95b891c1..698798adb4 100644 --- a/src/license/CapabilityRegistry.ts +++ b/src/license/CapabilityRegistry.ts @@ -8,7 +8,7 @@ import {CAPABILITY_TABLE, CapabilityGrant, normalizeCapabilityToken} from './cap /** * The capabilities a resolved {@link LicenseEntitlement} grants, ready for gate B (the - * interpreter) and PR 2's `ensureCapability` to query through {@link allowsFunction} and + * interpreter) and `ensureCapability` to query through {@link allowsFunction} and * {@link allowsFeature}. */ export interface ResolvedCapabilities { @@ -16,7 +16,7 @@ export interface ResolvedCapabilities { * `'all'` short-circuits {@link allowsFunction} to `true` for every function id, independently * of {@link features}: a key can cover every function without covering every feature, or the * other way round. A single `unrestricted: boolean` could not express that combination — it - * could only grant both axes together or neither (review of #1728, Kuba Sękowski). + * could only grant both axes together or neither. */ functions: ReadonlySet | 'all', /** `'all'` short-circuits {@link allowsFeature} to `true` for every {@link FeatureId}. */ @@ -143,12 +143,11 @@ export function allowsFeature(resolved: ResolvedCapabilities, feature: FeatureId * at all is allowed. {@link CapabilityRegistry.capabilityOf} returns `undefined` only for an id no * token lists, which the completeness invariant in `unit/license/capability-registry.spec.ts` * guarantees is not an unlisted built-in but a custom, instance-registered function — exempt from - * gate B by decision D1. Everything the table does cover has to be granted by the entitlement. + * gate B, because custom functions are never gated. Everything the table does cover has to be granted by the entitlement. * * Extracted so the interpreter and the function metadata API cannot drift apart. The metadata API * exists to describe the functions an instance can actually evaluate, so a second spelling of this - * rule would eventually let it advertise a function that then returns `#LIC!` — the exact failure - * removing the static metadata methods (HF-349) was meant to prevent. + * rule would eventually let it advertise a function that then returns `#LIC!`. * * Note this is gate B only: it says nothing about {@link LicenseKeyValidityState}. Callers that * also need gate A check it separately, because the two gates have different answers for the same diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index ea99886341..1d06e2243a 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -7,8 +7,7 @@ * Identifies a feature area of the public API that a license entitlement can gate. * * `CustomFunctions` is reserved vocabulary: it exists so a license payload is free to carry it, - * but HF-307 decision D1 drops function-registration gating (and the `CustomFunctions` grant) - * from this release, so no capability grant maps to it. + * but registering a custom function is never gated, so no capability grant maps to it. */ export const enum FeatureId { NamedExpressions = 'named_expressions', @@ -24,9 +23,8 @@ export const enum FeatureId { * * `date` is kept as a calendar string rather than an epoch, and is INCLUSIVE of its last valid * day: - * - `kind === 'usage'`: compared against the current instant in **UTC**. An earlier revision of - * the key spec called for the client's LOCAL calendar date; that was reversed, because the - * offline check and a future online check have to return the same verdict for the same key at + * - `kind === 'usage'`: compared against the current instant in **UTC**, not the client's LOCAL + * calendar date, because the offline check and a future online check have to return the same verdict for the same key at * the same instant, and any rule that reads a local clock breaks that parity. The practical * cost is that a customer far west of UTC loses the tail of their last local day. * - `kind === 'release'`: compared against the library's build date; no clock is involved, which @@ -45,9 +43,8 @@ export interface LicenseExpiry { * The resolved set of things a license grants, independent of how the underlying license key * was parsed. * - * This is the contract every later HF-307 task consumes: {@link CapabilityRegistry} turns it - * into a `ResolvedCapabilities` set, gate B in the interpreter reads that set, and PR 2's - * `ensureCapability` reads it for the public API. `resolveLicense` builds it from the + * {@link CapabilityRegistry} turns it into a `ResolvedCapabilities` set, gate B in the + * interpreter reads that set, and `ensureCapability` reads it for the public API. `resolveLicense` builds it from the * configured key. */ export interface LicenseEntitlement { @@ -57,7 +54,7 @@ export interface LicenseEntitlement { capabilities: ReadonlySet, /** * Tokens present on the license payload that this library version does not recognize. - * Kept for diagnostics and tests; per HF-307 decision D3 nothing public reads this field — an + * Kept for diagnostics and tests; nothing public reads this field — an * unrecognized token never grants a capability, and it does so silently. */ unrecognizedCapabilities: readonly string[], @@ -67,10 +64,9 @@ export interface LicenseEntitlement { * * Set from the key's own `no-console-warns` flag ONLY, as the vendored reader reads it (its * `channels.console`). An unrecognized token does NOT - * set it: HF-307 decision D3 makes the *grant* silent (an unknown token grants nothing, with no - * message and no diagnostics getter), which is a different thing from muting the key's console - * output. Coupling them suppressed expiry notices as a side effect of a vocabulary mismatch, and - * was confirmed an implementation error. + * set it: an unknown token makes the *grant* silent (it grants nothing, with no message and no + * diagnostics getter), which is a different thing from muting the key's console output. + * Coupling them would suppress expiry notices as a side effect of a vocabulary mismatch. */ silent: boolean, isTrial: boolean, @@ -80,8 +76,8 @@ export interface LicenseEntitlement { * The unrestricted entitlement: legacy keys, `gpl-v3`, and every missing, invalid or expired * entitlement key resolve to this. * - * HF-307 decision D3 (fail-closed, silent) means an entitlement key whose tokens this library version - * does not recognize at all no longer maps here — it resolves to an entitlement with an empty, + * Unrecognized tokens fail closed and silently, so an entitlement key whose tokens this library + * version does not recognize at all does not map here — it resolves to an entitlement with an empty, * silent capability set instead of falling back to unrestricted access. Do not reuse this * function for that case. */ diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts index 462980cfd4..3cb209692f 100644 --- a/src/license/capabilities.ts +++ b/src/license/capabilities.ts @@ -45,7 +45,7 @@ export interface CapabilityGrant { * No token here names a package, and no grant refers to another token. Which tokens a commercial * package consists of is the generator's knowledge, expressed by the bigger licence simply * listing more tokens — so a key's function set is the union of everything it names that this - * table recognizes, and an unrecognized token is inert (strict-shape/lenient-vocabulary, T7). + * table recognizes, and an unrecognized token is inert. * Legacy keys resolve to the unrestricted entitlement and never consult this table at all. * * There is no entry for any add-on. An add-on is a commercial wrapper, and which capabilities it diff --git a/src/license/featureCapabilities.ts b/src/license/featureCapabilities.ts index d66aa2a0cd..49d7704860 100644 --- a/src/license/featureCapabilities.ts +++ b/src/license/featureCapabilities.ts @@ -9,8 +9,8 @@ import {FeatureId} from './LicenseEntitlement' * One entry per single-area feature token. `feat:all` is derived from this list rather than * spelled out beside it, so a new gated area reaches it by being added here and nowhere else. * - * {@link FeatureId.CustomFunctions} deliberately has no token: HF-307 decision D1 drops - * function-registration gating, so nothing may grant it. + * {@link FeatureId.CustomFunctions} deliberately has no token: registering a custom function is + * never gated, so nothing may grant it. */ const singleFeatureEntries: [string, readonly FeatureId[]][] = [ ['feat:crud', [FeatureId.Crud]], diff --git a/src/license/functionCapabilities.ts b/src/license/functionCapabilities.ts index 294035b284..7e817b8895 100644 --- a/src/license/functionCapabilities.ts +++ b/src/license/functionCapabilities.ts @@ -10,8 +10,7 @@ * * Transcribed 1:1 from section 6 of the internal packaging design document ("HF function groups * and packages"), so that a re-transcription is a reviewable diff against the doc's published - * counts. Exported so the paired suite can compare it group by group; the table below is the - * only thing production code reads it through. + * counts. The table below is the only thing production code reads it through. * * `fun:info.a` and `fun:lookup.a` name nothing but the two protected built-ins, `VERSION` and * `OFFSET` (see `FunctionRegistry._protectedPlugins`). The doc calls that a "technical @@ -77,8 +76,8 @@ export const FUNCTION_GROUPS: ReadonlyMap = new Map([ * Enumerated rather than taken from the function registry at run time, even though "everything * not in a group" would be the shorter way to say it. Reading the registry would sweep in * functions registered through `HyperFormula.registerFunctionPlugin`, putting a user's OWN custom - * function under a licence token and returning `#LIC!` for it — the opposite of HF-307 decision - * D1, which drops custom-function gating entirely. A function this table does not list is not + * function under a licence token and returning `#LIC!` for it, while custom functions must never + * be gated. A function this table does not list is not * gated at all, which is exactly the treatment a custom function should get. */ const UNGROUPED_FUNCTIONS = [ @@ -130,8 +129,8 @@ const singleFunctionEntries: [string, readonly string[]][] = ALL_FUNCTIONS.map(( ]) /** - * The `fun:*` half of the vocabulary, keyed by NORMALIZED token spelling, per §6 of the packaging - * design: `fun:all`, the group tokens `fun:.`, and one + * The `fun:*` half of the vocabulary, keyed by NORMALIZED token spelling, as the packaging design + * defines it: `fun:all`, the group tokens `fun:.`, and one * `fun:` per canonical function. * * Every grant is STATIC. Nothing here is derived from the function registry at run time, so a diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index 095c78c81c..0f1f387adb 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -37,9 +37,9 @@ const VALID_STATES: LicenseState[] = [ /** * Lifecycle states in which a non-trial key has run out but still lets this build evaluate - * formulas, printing an error to the console instead. Decided on #1728 (2026-10-01): "Don't block. - * It should just print an error in console." This matches the reader's guide (18.1 never blocks a - * paying customer) and rev 5 §4.1. A trial hard stop still blocks. + * formulas, printing an error to the console instead. An expired license never blocks a paying + * customer, as the reader's guide and the key specification both say. A trial hard stop still + * blocks. * * The key keeps its own grants: the reader reports it as licensed, so an expired key is never * granted more than the same key was granted while it was current. @@ -87,12 +87,12 @@ function expiryOf(entry: ProductEntitlement): LicenseExpiry { /** * Turns HyperFormula's entry of a valid entitlement key into the entitlement it grants. * - * Per HF-307 decision D3 this is fail-closed and silent: a token this version does not recognize + * This is fail-closed and silent: a token this version does not recognize * is recorded in `unrecognizedCapabilities` and grants nothing, without a warning, a message, or * anything public to read it back from. "Silent" there means the *grant* is silent — whether the * key's console messages are suppressed is decided solely by its `no-console-warns` flag, never - * by the presence of an unrecognized token; coupling the two suppressed expiry notices as a side - * effect of a vocabulary mismatch, and was confirmed an implementation error. + * by the presence of an unrecognized token; coupling the two would suppress expiry notices as a + * side effect of a vocabulary mismatch. * * @param {ProductEntitlement} entry - HyperFormula's entry of a valid key * @param {boolean} isTrial - whether the key carries the `trial` flag @@ -124,8 +124,8 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool /** * Resolves a license key into both gates' inputs. * - * Routing follows the vendored {@link detectLicenseKeyFormat}, whose test order is normative - * (key spec addendum, T12): the literals, then the trailing bracketed block that marks an + * Routing follows the vendored {@link detectLicenseKeyFormat}, whose test order is normative: the + * literals, then the trailing bracketed block that marks an * entitlement key, then the legacy 25-character shape. Everything that is not an entitlement key * — `gpl-v3`, a legacy key, an empty string — falls through to {@link checkLicenseKeyValidity} * completely unchanged, which is what keeps this from touching existing behaviour. A string that @@ -141,10 +141,10 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool * restricted entitlement. Every other outcome — missing, invalid, or expired, for an entitlement * key as much as for a legacy one — resolves to {@link unrestrictedEntitlement}. That asymmetry is * deliberate and load-bearing: gate A already stops formula evaluation on its own (a bad key - * yields `#LIC!` in cells), while gate B additionally makes PR 2's `ensureCapability` throw from + * yields `#LIC!` in cells), while gate B additionally makes `ensureCapability` throw from * the CRUD API. Letting a bad key restrict the entitlement would turn today's "formulas fail, * the API still works" into "the API throws", which is a silent breaking change for every - * existing user whose key lapsed. D3's fail-closed rule governs unrecognized tokens INSIDE an + * existing user whose key lapsed. The fail-closed rule governs unrecognized tokens INSIDE an * otherwise valid key; it is not a rule about invalid keys, and conflating the two is exactly * the mistake this comment is here to prevent. * @@ -193,8 +193,8 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true const isValid = VALID_STATES.indexOf(lifecycle.state) !== -1 const state = isValid ? LicenseKeyValidityState.VALID : LicenseKeyValidityState.EXPIRED - // The message is chosen by the reader's state and prints the key's own date (rev 5/6 §4.1, the - // same table Handsontable uses). The `no-console-warns` flag closes the channel. + // The message is chosen by the reader's state and prints the key's own date (the key + // specification's text, the same table Handsontable uses). The `no-console-warns` flag closes the channel. if (notifyConsole && channels.console) { notifyEntitlementKey(licenseKey, lifecycle.state, {licensedUntil: lifecycle.licensedUntil, daysRemaining: lifecycle.daysRemaining}) } From b0ee8e4d742ce95f580c296f3f62a0a1c143a7ab Mon Sep 17 00:00:00 2001 From: marcin-kordas-hoc Date: Tue, 6 Oct 2026 06:51:16 +0000 Subject: [PATCH 31/54] Describe what the docs generator's license key does now that functions are gated The comment said function availability is not license-gated and pointed at a future change. Function listing is gated by the key now, so the comment stated the opposite of the behaviour and carried ticket ids. It now says why the page is generated with a fully entitled key. Comment only. Co-Authored-By: Claude Sonnet 5.5 --- script/generate-builtin-functions-doc.ts | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/script/generate-builtin-functions-doc.ts b/script/generate-builtin-functions-doc.ts index 6281a10cc5..93a6296403 100644 --- a/script/generate-builtin-functions-doc.ts +++ b/script/generate-builtin-functions-doc.ts @@ -24,15 +24,10 @@ const TEMPLATE_PATH = path.join(REPO_ROOT, 'docs/guide/built-in-functions.tmpl.m const DOC_PATH = path.join(REPO_ROOT, 'docs/guide/built-in-functions.md') const LANGUAGE = 'enGB' /** - * The GPLv3 key. Two reasons to name a key here, one current and one not yet: - * - * - Today it only keeps the build quiet. Function availability is **not** license-gated: every key, and no key at - * all, yields the same function set. But the metadata API is instance-scoped, so this page is now generated from - * an engine, and constructing one without a key logs "The license key for HyperFormula is missing." — noise the - * static path never produced, because it built no engine. - * - Once entitlement lands (HF-307), the engine's key *will* decide which functions the metadata API reports. - * Naming the fully-entitled key now means that change cannot silently narrow the published reference to one tier; - * the page must always document the complete function set (HF-349). + * The GPLv3 key, which restricts nothing. The metadata API is instance-scoped and an engine reports only the + * functions its key grants, so this page has to be generated with a fully entitled key: the published reference + * must always document the complete function set. The key also keeps the build quiet, because constructing an + * engine without one logs "The license key for HyperFormula is missing." */ const LICENSE_KEY = 'gpl-v3' From 7fcbd3ab578c799f8e12fe67c1ffcd345a2b227f Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 08:39:01 +0200 Subject: [PATCH 32/54] Fix tests --- src/BuildEngineFactory.ts | 10 ++++----- src/HyperFormula.ts | 18 +++++++--------- src/errors.ts | 13 ++++++++++-- src/helpers/licenseKeyValidator.ts | 30 +++++++++++++++++++-------- src/license/ensureFeatureAllowed.ts | 32 +++++++++++++++++++++++++++++ src/license/licenseResolution.ts | 20 ++++++++---------- 6 files changed, 85 insertions(+), 38 deletions(-) create mode 100644 src/license/ensureFeatureAllowed.ts diff --git a/src/BuildEngineFactory.ts b/src/BuildEngineFactory.ts index f06a7d9301..10336fd4d8 100644 --- a/src/BuildEngineFactory.ts +++ b/src/BuildEngineFactory.ts @@ -10,7 +10,7 @@ import {Config} from './Config' import {CrudOperations} from './CrudOperations' import {DateTimeHelper} from './DateTimeHelper' import {DependencyGraph} from './DependencyGraph' -import {LicenseCapabilityMissingError, SheetSizeLimitExceededError} from './errors' +import {SheetSizeLimitExceededError} from './errors' import {Evaluator} from './Evaluator' import {Exporter} from './Exporter' import {GraphBuilder} from './GraphBuilder' @@ -19,7 +19,7 @@ import {ArithmeticHelper} from './interpreter/ArithmeticHelper' import {FunctionRegistry} from './interpreter/FunctionRegistry' import {Interpreter} from './interpreter/Interpreter' import {LazilyTransformingAstService} from './LazilyTransformingAstService' -import {allowsFeature} from './license/CapabilityRegistry' +import {ensureFeatureAllowed} from './license/ensureFeatureAllowed' import {FeatureId} from './license/LicenseEntitlement' import {buildColumnSearchStrategy, ColumnSearchStrategy} from './Lookup/SearchStrategy' import {NamedExpressions} from './NamedExpressions' @@ -74,7 +74,7 @@ export class BuildEngineFactory { } /** - * Throws if `namedExpressions` is non-empty and `config`'s entitlement does not grant + * Throws if `namedExpressions` is non-empty and `config`'s license does not allow * {@link FeatureId.NamedExpressions} (the build-time counterpart of * {@link HyperFormula.ensureCapability}). An empty list is never checked: building an engine * with no named expressions never touches the feature. Deliberately not called from @@ -85,9 +85,7 @@ export class BuildEngineFactory { if (namedExpressions.length === 0) { return } - if (!allowsFeature(config.licenseCapabilities, FeatureId.NamedExpressions)) { - throw new LicenseCapabilityMissingError(FeatureId.NamedExpressions) - } + ensureFeatureAllowed(config, FeatureId.NamedExpressions) } private static buildEngine(config: Config, sheets: Sheets = {}, inputNamedExpressions: SerializedNamedExpression[] = [], stats: Statistics = config.useStats ? new Statistics() : new EmptyStatistics()): EngineState { diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 0931baee04..2369a68fa4 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -38,13 +38,13 @@ import { ExpectedValueOfTypeError, LanguageAlreadyRegisteredError, LanguageNotRegisteredError, - LicenseCapabilityMissingError, NotAFormulaError, } from './errors' import {Evaluator} from './Evaluator' import {ExportedChange, Exporter} from './Exporter' import {LicenseKeyValidityState} from './helpers/licenseKeyValidator' -import {allowsFeature, licenseAllowsFunction} from './license/CapabilityRegistry' +import {licenseAllowsFunction} from './license/CapabilityRegistry' +import {ensureFeatureAllowed} from './license/ensureFeatureAllowed' import {FeatureId} from './license/LicenseEntitlement' import {buildTranslationPackage, RawTranslationPackage, TranslationPackage} from './i18n' import {FunctionPluginDefinition} from './interpreter' @@ -4906,7 +4906,8 @@ export class HyperFormula implements TypedEmitter { } /** - * Throws an error if the current license entitlement does not grant the given feature. + * Throws an error if the current license does not allow the given feature: either the key's + * state blocks every gated feature (missing, invalid or expired), or the key does not grant it. * * Where the line is drawn, so a later change does not move it by accident: * - **Gated:** methods that create value by mutating the sheet, the clipboard, the undo @@ -4923,18 +4924,13 @@ export class HyperFormula implements TypedEmitter { * the instance permanently unusable. A capability check must never be reachable only on * the way out of a state it let the caller into. * - * Note this checks gate B (entitlement) only, never gate A (key validity). That asymmetry - * with the interpreter's gate B - which checks key validity first - is deliberate: it keeps - * today's behaviour for a missing or invalid key, where formulas yield `#LIC!` but the CRUD - * API keeps working. A later PR that resolves an invalid key to a *restricted* entitlement - * rather than an unrestricted one would silently turn that into a breaking API change. + * Must stay the first statement of every gated method, so a blocking key is reported before + * any argument validation. * * @internal */ private ensureCapability(feature: FeatureId): void { - if (!allowsFeature(this._config.licenseCapabilities, feature)) { - throw new LicenseCapabilityMissingError(feature) - } + ensureFeatureAllowed(this._config, feature) } /** diff --git a/src/errors.ts b/src/errors.ts index 283ed1d8da..2cdb802852 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -4,6 +4,7 @@ */ import {SimpleCellAddress} from './Cell' +import {LicenseKeyValidityState} from './helpers/licenseKeyValidator' import {FeatureId} from './license/LicenseEntitlement' /** @@ -437,7 +438,15 @@ export class AliasAlreadyExisting extends Error { * @see [[suspendEvaluation]] */ export class LicenseCapabilityMissingError extends Error { - constructor(feature: FeatureId) { - super(`Feature ${feature} is not included in your license.`) + /** + * @param {FeatureId} feature - the gated feature that was called + * @param {LicenseKeyValidityState} [blockingState] - the key's state when the key itself blocks + * every gated feature (missing, invalid or expired); omit when the key is valid but does not + * grant `feature` + */ + constructor(feature: FeatureId, blockingState?: LicenseKeyValidityState) { + super(blockingState === undefined + ? `Feature ${feature} is not included in your license.` + : `License key is ${blockingState}. Feature ${feature} is not available.`) } } diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 9e335c5613..042f3e15a5 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -4,7 +4,7 @@ */ import {CHECKSUM_LENGTH} from '../license/handsontable-license-key-parser/constants' -import {LicenseState} from '../license/handsontable-license-key-parser/types' +import {LicenseState, UnlicensedReason} from '../license/handsontable-license-key-parser/types' import {checkKeySchema, extractTime} from './licenseKeyHelper' /** @@ -114,6 +114,21 @@ const ENTITLEMENT_CONSOLE_NOTIFICATIONS: Partial = { + unreadable: { + severity: 'error', + message: () => 'The license key for HyperFormula is invalid. If you need any help, contact us at support@handsontable.com.', + }, + product_missing: { + severity: 'error', + message: () => 'The license key does not include a license for HyperFormula. To purchase one, contact sales@handsontable.com.', + }, +} + /** * Entitlement messages already printed, each as a key identity (see {@link keyIdentityOf}) plus * the message text: "each distinct message once per key per page", as the specification asks. Two @@ -158,16 +173,14 @@ export function notifyLicenseKeyState(state: LicenseKeyValidityState, keyValidit /** * Prints the console message for an entitlement key, at most once per distinct key per page. - * `'invalid'` (a broken block, or a key for other products only) reuses the classic invalid-key - * text, as Handsontable does: the specification leaves that message open. * * @param {string} licenseKey - the raw key; only its identity is retained - * @param {LicenseState | 'invalid'} state - the reader's lifecycle state, or `'invalid'` + * @param {LicenseState | UnlicensedReason} state - the reader's lifecycle state, or why the key does not license HyperFormula * @param {EntitlementMessageParams} params - the key's own date and days remaining */ -export function notifyEntitlementKey(licenseKey: string, state: LicenseState | 'invalid', params: EntitlementMessageParams): void { - const notification: EntitlementConsoleNotification | undefined = state === 'invalid' - ? {severity: 'warn', message: () => consoleMessages.invalid({})} +export function notifyEntitlementKey(licenseKey: string, state: LicenseState | UnlicensedReason, params: EntitlementMessageParams): void { + const notification: EntitlementConsoleNotification | undefined = state === 'unreadable' || state === 'product_missing' + ? UNLICENSED_CONSOLE_NOTIFICATIONS[state] : ENTITLEMENT_CONSOLE_NOTIFICATIONS[state] if (notification === undefined) { @@ -222,7 +235,8 @@ export function checkLicenseKeyValidity(licenseKey: string): LicenseKeyValidityS } else if (typeof licenseKey === 'string' && checkKeySchema(licenseKey)) { const [day, month, year] = (process.env.HT_RELEASE_DATE || '').split('/') - const releaseDays = Math.floor(new Date(`${month}/${day}/${year}`).getTime() / 8.64e7) + // UTC, not `new Date('MM/DD/YYYY')`: local parsing puts the release day one day early east of UTC. + const releaseDays = Math.floor(Date.UTC(Number(year), Number(month) - 1, Number(day)) / 8.64e7) const keyValidityDays = extractTime(licenseKey) messageDescriptor.expiryDate = new Date((keyValidityDays + 1) * 8.64e7) diff --git a/src/license/ensureFeatureAllowed.ts b/src/license/ensureFeatureAllowed.ts new file mode 100644 index 0000000000..a124af0cf3 --- /dev/null +++ b/src/license/ensureFeatureAllowed.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +import {Config} from '../Config' +import {LicenseCapabilityMissingError} from '../errors' +import {allowsFeature} from './CapabilityRegistry' +import {FeatureId} from './LicenseEntitlement' + +/** + * Throws {@link LicenseCapabilityMissingError} unless the license lets the caller use `feature`. + * + * Checks both gates, in the same order the interpreter does for functions: + * - gate A first: a key whose state blocks evaluation (missing, invalid, or expired past any + * grace period) blocks every gated feature, whatever the entitlement says; + * - then gate B: a valid key must grant `feature`. + * + * Shared by the build-time named-expressions check and `HyperFormula.ensureCapability`, so the two + * cannot disagree about the same key. + * + * @param {Config} config - the config whose resolved license is checked + * @param {FeatureId} feature - the gated feature being called + */ +export function ensureFeatureAllowed(config: Config, feature: FeatureId): void { + if (config.licenseBlocksEvaluation) { + throw new LicenseCapabilityMissingError(feature, config.licenseKeyValidityState) + } + if (!allowsFeature(config.licenseCapabilities, feature)) { + throw new LicenseCapabilityMissingError(feature) + } +} diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index 0f1f387adb..e8fcb573af 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -139,14 +139,12 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool * * **The invariant this function exists to protect.** Only a VALID entitlement key resolves to a * restricted entitlement. Every other outcome — missing, invalid, or expired, for an entitlement - * key as much as for a legacy one — resolves to {@link unrestrictedEntitlement}. That asymmetry is - * deliberate and load-bearing: gate A already stops formula evaluation on its own (a bad key - * yields `#LIC!` in cells), while gate B additionally makes `ensureCapability` throw from - * the CRUD API. Letting a bad key restrict the entitlement would turn today's "formulas fail, - * the API still works" into "the API throws", which is a silent breaking change for every - * existing user whose key lapsed. The fail-closed rule governs unrecognized tokens INSIDE an - * otherwise valid key; it is not a rule about invalid keys, and conflating the two is exactly - * the mistake this comment is here to prevent. + * key as much as for a legacy one — resolves to {@link unrestrictedEntitlement}. A bad key is + * stopped by gate A alone, through `blocksEvaluation`: formulas yield `#LIC!` and every gated API + * feature throws with the key's state (see `ensureFeatureAllowed`). Gate B never reports a bad + * key, so its "not included in your license" error is reserved for a valid key that lacks the + * grant. The fail-closed rule governs unrecognized tokens INSIDE an otherwise valid key; it is not + * a rule about invalid keys. * * A checksum-valid key whose payload shape cannot be read is INVALID, not a crash and not a free * pass: every payload field is untrusted, so nothing here may assume a shape the vendored reader @@ -179,10 +177,10 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true }) if (!license.licensed) { - // `unreadable` (a broken block) and `product_missing` (a key for other products only) are - // both reported as an invalid key, and neither restricts anything. + // `unreadable` (a broken block) and `product_missing` (a key for other products only) both + // resolve to an invalid key that restricts nothing; only their console messages differ. if (notifyConsole) { - notifyEntitlementKey(licenseKey, 'invalid', {licensedUntil: null, daysRemaining: null}) + notifyEntitlementKey(licenseKey, license.reason, {licensedUntil: null, daysRemaining: null}) } return {validityState: LicenseKeyValidityState.INVALID, blocksEvaluation: true, entitlement: unrestrictedEntitlement()} From 1919fd09fc52b37d0e7a32337e84b1791f7a4c37 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 09:20:52 +0200 Subject: [PATCH 33/54] HF-307: re-take the vendored entitlement-key reader from license-key 5.1.1 The reader in src/license/handsontable-license-key-parser/ is now upstream's vendor/entitlement-key-reader at tag 5.1.1, with the one declared TypeScript 4.0 cast re-applied. Keys in format version 2 carry a digest of their prose, so a key whose prose was edited or removed (the bare [...] block), or that has text after its block, is invalid. Whitespace and line breaks saved as text are ignored anywhere in the key, inside the block too. Following that: - the warn-once identity of a key is the hash of the key without the characters the reader ignores, so a rewrapped key is one license and two keys that share a block but differ in their prose are two keys; - VERSION() reads a valid entitlement key's status from the checksum in its block, not from the end of the string, so trailing whitespace or a line break saved as text no longer changes it; - the license key guide tells users to pass the whole key as issued. Co-Authored-By: Claude Opus 5.5 --- docs/guide/license-key.md | 5 + src/helpers/licenseKeyValidator.ts | 44 +++- src/interpreter/plugin/VersionPlugin.ts | 9 +- .../handsontable-license-key-parser/AGENTS.md | 4 +- .../PROVENANCE.md | 17 +- .../handsontable-license-key-parser/README.md | 90 ++++++-- .../constants.ts | 8 + .../detectFormat.ts | 5 +- .../extractKeyData.ts | 215 ++++++++++++++++-- .../readLicense.ts | 21 +- .../handsontable-license-key-parser/types.ts | 34 ++- .../upstream.json | 6 +- src/license/licenseResolution.ts | 8 +- 13 files changed, 399 insertions(+), 67 deletions(-) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index a7780e2f32..362dc413d5 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -40,6 +40,11 @@ const options = { } ``` +If your key is a few sentences of text followed by a block in square brackets (`[...]`), pass the +whole key, exactly as you received it. The key covers its text, so a key cut down to the bracketed +block, or with any word changed, is invalid. Whitespace and line breaks don't matter, including a +line break saved as `\n` in a `.env` file, but keeping the key on one line is the safest choice. + ### Proprietary license key validation ::: tip diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 042f3e15a5..1170446bd0 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -4,6 +4,8 @@ */ import {CHECKSUM_LENGTH} from '../license/handsontable-license-key-parser/constants' +import {stringToUtf8Bytes} from '../license/handsontable-license-key-parser/encoding' +import {sha512} from '../license/handsontable-license-key-parser/sha512' import {LicenseState, UnlicensedReason} from '../license/handsontable-license-key-parser/types' import {checkKeySchema, extractTime} from './licenseKeyHelper' @@ -206,17 +208,41 @@ export function notifyEntitlementKey(licenseKey: string, state: LicenseState | U } /** - * The identity of a key: its trailing 129 characters, after trimming — for an intact entitlement - * key, the sha512 checksum plus the closing bracket, unique per distinct key content. - * - * Trimmed because the reader ignores surrounding whitespace, so `'KEY'` and `'KEY\n'` are one - * license and must be one identity here too. Read from the END, so the whole artifact and its bare - * `[...]` block, which the format treats as the same license, are one identity. Truncated because - * the set lives as long as the page: a server building one engine per customer key would otherwise - * keep every full key string it has ever seen. + * The identity of a key: the SHA-512 of the key with every character the reader ignores removed, + * unique per distinct key content. A rewrapped key and its one-line form are one license to the + * reader, so they are one identity here too. Two keys that share a block but differ in their prose + * are two keys - the payload carries a digest of the prose - so they are two identities. Hashed + * because the set lives as long as the page: a server building one engine per customer key would + * otherwise keep every full key string it has ever seen. */ function keyIdentityOf(licenseKey: string): string { - return licenseKey.trim().slice(-(CHECKSUM_LENGTH + 1)) + return sha512(stringToUtf8Bytes(withoutIgnoredCharacters(licenseKey).normalize('NFC'))) +} + +/** + * The checksum of an entitlement key: the last 128 characters of its block. The block is found + * the way the reader finds it - the last `[` and the first `]` after it - and read without the + * characters the reader ignores, so a key wrapped inside its block, or followed by a line break, + * reports the same checksum as its one-line form. + * + * @param {string} licenseKey - an entitlement key, as the user passed it + * @returns {string} the checksum + */ +export function entitlementKeyChecksumOf(licenseKey: string): string { + const blockStart = licenseKey.lastIndexOf('[') + const blockEnd = licenseKey.indexOf(']', blockStart + 1) + + return withoutIgnoredCharacters(licenseKey.slice(blockStart + 1, blockEnd)).slice(-CHECKSUM_LENGTH) +} + +/** + * The text without the characters the reader ignores anywhere in a key: every line break or tab + * saved as text (`\n`, `\r`, `\t`, as a `.env` file stores one), then every whitespace character. + * Removed in the reader's order, escapes first; `\s` is exactly the set of characters the reader + * treats as whitespace. + */ +function withoutIgnoredCharacters(text: string): string { + return text.replace(/\\[nrt]/g, '').replace(/\s+/g, '') } /** diff --git a/src/interpreter/plugin/VersionPlugin.ts b/src/interpreter/plugin/VersionPlugin.ts index 2a9275a354..882dec373f 100644 --- a/src/interpreter/plugin/VersionPlugin.ts +++ b/src/interpreter/plugin/VersionPlugin.ts @@ -3,8 +3,9 @@ * Copyright (c) 2025 Handsoncode. All rights reserved. */ -import {LicenseKeyValidityState} from '../../helpers/licenseKeyValidator' +import {entitlementKeyChecksumOf, LicenseKeyValidityState} from '../../helpers/licenseKeyValidator' import {HyperFormula} from '../../HyperFormula' +import {detectLicenseKeyFormat} from '../../license/handsontable-license-key-parser/detectFormat' import {ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {InterpreterValue} from '../InterpreterValue' @@ -38,7 +39,11 @@ export class VersionPlugin extends FunctionPlugin implements FunctionPluginTypec } else if (LICENSE_STATUS_MAP.has(validityState)) { status = LICENSE_STATUS_MAP.get(validityState) } else if (validityState === LicenseKeyValidityState.VALID) { - status = licenseKey.slice(-5) + // An entitlement key may end in its closing bracket, whitespace or a line break saved as + // text, so its status is read from the checksum, not from the end of the string. + status = detectLicenseKeyFormat(licenseKey) === 'entitlement' + ? entitlementKeyChecksumOf(licenseKey).slice(-5) + : licenseKey.slice(-5) } return `HyperFormula v${HyperFormula.version}, ${status}` diff --git a/src/license/handsontable-license-key-parser/AGENTS.md b/src/license/handsontable-license-key-parser/AGENTS.md index 309a01c2c4..dc81b54a53 100644 --- a/src/license/handsontable-license-key-parser/AGENTS.md +++ b/src/license/handsontable-license-key-parser/AGENTS.md @@ -11,7 +11,9 @@ In both places: - **Product-specific code lives outside this directory**: the product name, the build date, the literal keys, the messages and the capability-token gates. - **Call `readEntitlementLicense(key, { product, buildDate })`** for a key that `detectLicenseKeyFormat` reports as `'entitlement'`. Legacy and literal keys are the product's own path. - **Never convert a license date through `Date`.** Print `lifecycle.licensedUntil` as it is. Pass the build date as bare `YYYY-MM-DD` text (`toIsoBuildDate` converts `DD/MM/YYYY`). -- **Do not "repair" a key** by removing whitespace inside the `[...]` block. Trimming the whole key is fine. +- **Tell users to keep the key on one line** (in `.env`, CI secrets, YAML or code). The reader ignores whitespace and a line break saved as `\n`, but a shell or `.env` value can be cut short by a quote inside the key. The README's "Where users keep the key" table lists what works. +- **Pass the whole key, and do not "repair" it.** A version 2 key covers the prose too (a digest in the payload), so never cut a key down to its `[...]` block or strip characters from it. Trimming the whole key is fine. A version 1 key (no `v`) never covered its prose - do not treat a readable key as proof its sentences are unedited; check `version`. +- **Every format version keeps the payload checksum and the prose digest.** That is what lets a product that only knows an older version read a newer key. In `license-key`, a change that bumps `v` may add fields, never change those two - a change that must is a new format, not a new version. - **An unlicensed key unlocks everything** (`UNRESTRICTED_GRANTS`). Never gate features away from a key that failed to read. - **`no-ui-warns` silences UI warnings, not the trial hard-stop block.** - **Everything the reader returns is frozen** and typed read-only. Copy an array before sorting or changing it. diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index c28af97efa..683ef71073 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -10,7 +10,7 @@ and re-taken: a local fix makes two products disagree about the same key. |---|---| | Repository | `handsontable/license-key` (private) | | Directory | `vendor/entitlement-key-reader` | -| Tag | `4.0.1` (`03810fd3c`, 2026-09-28) | +| Tag | `5.1.1` (`124660718`, 2026-10-06) | | Pin | `upstream.json` | ## One declared divergence @@ -39,12 +39,15 @@ pin. Without credentials to the private repository it fails rather than skips. ## What HyperFormula uses from it `readEntitlementLicense`, the single entry point upstream prescribes, plus `detectLicenseKeyFormat`, -`toIsoBuildDate`, `parseIsoDateToTimestamp`, `CHECKSUM_LENGTH` and the types - from -`src/license/licenseResolution.ts` and `src/helpers/licenseKeyValidator.ts`, which sit beside the -copy, as upstream's guide prescribes. The reader verifies the key, picks HyperFormula's entry, -places it in its lifecycle window and reads its flags. HyperFormula keeps what the guide leaves to -the product: the meaning of the capability tokens (`src/license/capabilities.ts`) and the console -messages. +`toIsoBuildDate`, `CHECKSUM_LENGTH`, `sha512`, `stringToUtf8Bytes` and the types - from +`src/license/licenseResolution.ts`, `src/helpers/licenseKeyValidator.ts` and +`src/interpreter/plugin/VersionPlugin.ts`, which sit outside the copy, as upstream's guide +prescribes. The reader verifies the key (the checksum and, from format version 2, the prose +digest), picks HyperFormula's entry, places it in its lifecycle window and reads its flags. +HyperFormula keeps what the guide leaves to the product: the meaning of the capability tokens +(`src/license/capabilities.ts`), the console messages, and the identity a key is printed once +under. The test suite mints keys with the test-only exports `canonicalizeProse`, +`computeProseDigest`, `computePayloadChecksum` and `stringToBase64Url`, as upstream's README shows. Upstream's `README.md` in this directory is the integration guide; `AGENTS.md` is theirs too. diff --git a/src/license/handsontable-license-key-parser/README.md b/src/license/handsontable-license-key-parser/README.md index a91a89b492..c94788a67b 100644 --- a/src/license/handsontable-license-key-parser/README.md +++ b/src/license/handsontable-license-key-parser/README.md @@ -16,6 +16,7 @@ What it does **not** do: - [Copy it into a product](#copy-it-into-a-product) - [The key in 60 seconds](#the-key-in-60-seconds) +- [Where users keep the key](#where-users-keep-the-key) - [Integrate it in five steps](#integrate-it-in-five-steps) - [What to do in each state](#what-to-do-in-each-state) - [Rules you must not break](#rules-you-must-not-break) @@ -66,8 +67,18 @@ This is a Handsontable license key for Acme Corp, issued on 2026-08-12. It inclu [eyJwcm9kdWN0cyI6eyJoYW5k......<128 hex characters of SHA-512>] ``` -- **The prose is never read.** It is not covered by the checksum either, so a key still works after a mail client rewraps it. A user may paste the whole text or the `[...]` block alone - both read the same. -- **The block** is `[`, a base64url (URL-safe, unpadded) JSON payload, the SHA-512 hex of that encoded payload (128 lowercase characters), and `]`. The block is the **last** `[` in the string and the first `]` after it. +- **The prose is never parsed, but it is covered** (version 2, every key issued now). The payload carries a digest of it, so a key whose sentences were edited or removed is invalid - the `[...]` block alone is **not** a key. A version 1 key (`license-key` 4.x, trial keys in production) never covered its prose: its bare block, an edited prose and text after its block all read, as they did when it was issued. Only the whitespace and the Unicode composition of the prose are ignored: a key still works after a mail client rewraps it (also inside a word or between two CJK characters), collapses the blank line, stores it decomposed, or after it is put on one line. +- **The block** is `[`, a base64url (URL-safe, unpadded) JSON payload, the checksum (128 lowercase hex characters), and `]`. The block is the **last** `[` in the string and the first `]` after it. Whitespace inside the block is ignored, so a block a mail client wrapped still reads. In a version 2 key only whitespace (or a line break saved as `\n`) may follow it. +- **The checksum** is the SHA-512 hex of the UTF-8 bytes of the encoded payload. +- **The prose digest** (`prose` in the payload) is the first 64 characters of the SHA-512 hex of the UTF-8 bytes of `canonical(prose)`, where `prose` is everything in front of the `[` and `canonical` is the prose with every line break or tab saved as text (`\n`, `\r`, `\t`) and every whitespace character removed, then put in Unicode NFC. The characters are listed exactly, as `PROSE_WHITESPACE` in `extractKeyData.ts`: TAB, LF, VT, FF, CR, SPACE, U+00A0, U+1680, U+2000-U+200A, U+2028, U+2029, U+202F, U+205F, U+3000 and U+FEFF. A version 2 key with an empty prose is invalid. +- **The format version** is `v` in the payload. The reader accepts two kinds of key and returns the version with the data: + + | Version | `v` | Checksum | Prose checked? | Issued by | + | --- | --- | --- | --- | --- | + | 1 | absent | SHA-512 of the payload | no | `license-key` 4.x | + | 2 | `2` | SHA-512 of the payload | yes, by the digest | `license-key` from DEV-3286 on | + + A newer `v` than the reader knows is accepted: later versions only add fields and keep the payload checksum and the digest. That is also why a version 2 key reads in a product that only knows version 1 (Handsontable 18.1.x) - such a product does not check the prose. - **The payload** lists what is licensed, per product: ```json @@ -80,13 +91,17 @@ This is a Handsontable license key for Acme Corp, issued on 2026-08-12. It inclu "grace": 0, "flags": ["no-console-warns", "no-ui-warns"] } - } + }, + "v": 2, + "prose": "<64 hex characters>" } ``` | Field | Meaning | | --- | --- | | `products` | Keyed by product name. **Presence means licensed.** A key may grant several products; each has its own dates and flags. | +| `v` | The format version. Absent in the first keys (version 1). | +| `prose` | The digest of the prose, from version 2. The reader checks it; your product never needs it. | | `capabilities` | Opaque tokens. The key says *what is granted*; your product decides *what each token unlocks*. | | `usage_until` | The last licensed day, inclusive, in UTC. Measured against the clock. A subscription or a trial. | | `release_until` | Builds released on or before this day may run forever. Measured against your build date, never the clock. A perpetual license. | @@ -96,6 +111,33 @@ This is a Handsontable license key for Acme Corp, issued on 2026-08-12. It inclu Exactly **one** of `usage_until` / `release_until` is present. There is no contract type, tier, package name or holder in the payload - "subscription" or "perpetual" is only visible as which date is present. +## Where users keep the key + +Users paste the key into code, `.env` files, CI secrets, container settings and YAML. The reader ignores every whitespace character and a line break or tab saved as text (`\n`, `\r`, `\t`), so most of these work. What breaks a key is a store that **loses part of it** or **changes a character** - most often a quote. The prose can contain `"` (around the project name) and `'` (in a company name such as `O'Brien`). + +Tell your users to keep the key **on one line**. The `license-key` generator prints that form, and it is the same key: the reader ignores the line breaks it no longer has. + +Checked by hand on 2026-10-05, with real keys pushed through the real parsers (`dotenv` 16.6.1, `js-yaml` 3.14, `bash`). This is not part of CI, so check again before relying on a row if those tools change: + +| Where the key is kept | Valid | +| --- | --- | +| Code: a string with real line breaks, or the one-line form | yes | +| A JSON config, parsed (`\n` in the JSON) | yes | +| YAML: `\|` block, `>` folded block | yes | +| YAML: a double-quoted string | only with the key's own `"` escaped - the prose contains `"` around the project name | +| `.env`, the one-line form - unquoted, `"..."` or `'...'` | yes | +| `.env`, line breaks saved as `\n` - unquoted, `"..."` or `'...'` | yes | +| `.env`, real line breaks inside `"..."` or `'...'` | only if the key has no `"` / `'` of that kind | +| `.env`, real line breaks, **unquoted** | **no** - only the first line is kept | +| Docker `--env-file`, CI secret fields that store `\n` as text | yes | +| A shell script: `KEY="$(cat key.txt)"` | yes | +| A shell script: the key pasted inside `"..."` or `'...'` | **no** if the key contains that quote - the shell ends the value there | +| JSON text used as it is, without parsing it | **no** - the quotes and the escapes stay in | +| Line breaks saved twice-escaped (`\\n`) | **no** - a stray backslash is left | +| A word processor that turned `"` into `“` `”` (curly quotes) | **no** - that is a changed character | + +Do not "fix" a key on the way in - see rule 5 below. If a user's key reads as `unreadable`, the message should ask them to paste the key exactly as it was issued, on one line. + ## Integrate it in five steps ```ts @@ -140,7 +182,7 @@ export function checkLicense(rawKey: unknown): LicenseGrants { const license = readEntitlementLicense(key, { product: PRODUCT, buildDate: BUILD_DATE }); if (!license.licensed) { - // The block is broken, or the key licenses other products only. + // The key is broken, edited (version 2), or it licenses other products only. // license.reason is 'unreadable' or 'product_missing' - both are an invalid key to the user. reportInvalidKey(); @@ -220,7 +262,7 @@ Each of these has broken a real implementation, or a specification fixture exist 2. **`usage_until` is inclusive.** The license is valid until the UTC midnight that *follows* it. The hard stop starts at `usage_until + 1 + grace` days, `00:00:00Z`. Day counts are calendar days (UTC midnight to UTC midnight), never milliseconds divided and floored. `notice: 0` means no warning window at all. 3. **A `release_until` license never reads the clock.** A perpetual key must read the same with the clock set to 1999 or 2035, or on an offline machine. 4. **Fail open on a missing build date, and only on a missing one.** If the build date is missing (`undefined`, `null`, empty), a `release_until` license reads as `release_valid` - a broken build must never tell a paying customer their license lapsed. A build date in the wrong format is your bug and throws; convert with `toIsoBuildDate`. Read the build constant exactly as your bundler inlines it - do not wrap `process.env.X` in a `typeof process` guard, which the bundler does not inline and which then blanks the date. -5. **Do not repair a key.** Surrounding whitespace is fine to trim. Whitespace, line breaks or anything else *inside* the brackets makes the key invalid - stripping it would accept keys the generator never issued. +5. **Pass the whole key, and do not repair it.** Surrounding whitespace is fine to trim, and so is nothing else - the reader already ignores whitespace and a line break saved as `\n`, in the prose and inside the block (see [Where users keep the key](#where-users-keep-the-key)). Do not cut the key down to its `[...]` block, and do not strip quotes or other characters from it: a version 2 key covers its prose, so the block alone or a changed sentence is invalid. Do not treat a readable key as proof that its sentences are unedited, either - a version 1 key never covered them (check `version`). 6. **Be strict about shape, lenient about vocabulary.** Unknown products, capability tokens, flags and extra fields are kept and ignored. A key your build does not fully understand must still read. Only a malformed shape (both dates, no date, a bad date, a negative window) makes a key invalid. 7. **Never branch on a contract type or a package name.** The payload has neither. Decide by which date is present and by the `trial` flag - which is what the state names already encode. 8. **The capability-token meaning lives in your product.** Keep the list of tokens your build understands next to your feature gates. Tokens are only ever added to a product, never removed, so a gate on an existing token stays valid. @@ -242,6 +284,9 @@ A new product needs the same five things: a product name agreed with my.handsont Handsontable already ships an earlier port of this reader in `handsontable/src/utils/entitlementLicenseKey/` (DEV-2562). This directory is that port made general, with the same state names and window rules. The differences, when switching Handsontable over: +- **the prose is covered and the key has a version** (`license-key` 5.0.0, DEV-3253; DEV-3286) - the 18.1.x port checks the payload checksum only and accepts the bare `[...]` block. It reads 4.x keys and version 2 keys, without checking their prose. A port of the unreleased 5.0.0 rule (Handsontable `develop` after DEV-3254) rejects both and has to be replaced by this reader before it ships, +- whitespace inside the block is ignored - the port rejects a wrapped block, +- the data carries `version`, - the product name is passed in (`readEntitlementLicense(key, { product })`) instead of being built in, - `detectLicenseKeyFormat(key, literalKeys)` takes the literal keys and returns `'literal'` for them, where the port returns `'non-commercial-and-evaluation'` (Handsontable only calls `isEntitlementKey`, which is unchanged), - a date that is not a string, such as `["2027-08-12"]`, makes the key invalid - the port still accepts it, @@ -270,20 +315,27 @@ npm install && npm run build npm run generate-entitlement-key --record='{"holder":"Test Fixture","issued":"2026-08-12","licenses":[{"product":"hyperformula","contractType":"perpetual","agreement":"perpetual-2.0","package":"Pro","mode":"internal","date":"2027-03-31","notice":0,"grace":0}]}' ``` -For the shapes the generator refuses (both dates, a bad date, an unknown token), build the block yourself in a test-only helper - kept in a `__tests__/` directory beside the copy, and never imported from your source: +For the shapes the generator refuses (both dates, a bad date, an unknown token), build the key yourself in a test-only helper - kept in a `__tests__/` directory beside the copy, and never imported from your source: ```ts -import { sha512 } from '../entitlementKeyReader/sha512'; -import { stringToUtf8Bytes, stringToBase64Url } from '../entitlementKeyReader/encoding'; +import { canonicalizeProse, computePayloadChecksum, computeProseDigest } from '../entitlementKeyReader/extractKeyData'; +import { stringToBase64Url } from '../entitlementKeyReader/encoding'; + +// A version 2 payload carries a digest of the prose, so a test key needs one. +const PROSE = 'This is a test license key.'; -export function buildTestKey(payload: object): string { - const encoded = stringToBase64Url(JSON.stringify(payload)); +export function buildTestKey(payload: { products: object }): string { + const encoded = stringToBase64Url(JSON.stringify({ + ...payload, + v: 2, + prose: computeProseDigest(canonicalizeProse(PROSE)), + })); - return `[${encoded}${sha512(stringToUtf8Bytes(encoded))}]`; + return `${PROSE}\n\n[${encoded}${computePayloadChecksum(encoded)}]`; } ``` -This is not a secret: the checksum recipe ships in every product bundle by design. The key protects integrity (a typo or a broken paste cannot pass), not authenticity. +This is not a secret: the checksum recipe ships in every product bundle by design. The key protects integrity (a typo, a broken paste or - in a version 2 key - an edited sentence cannot pass), not authenticity. ## API reference @@ -292,11 +344,15 @@ This is not a secret: the checksum recipe ships in every product bundle by desig The one call a product needs. Verifies the block, picks the product's entry, classifies it, reads its flags and resolves its grants. ```text -licensed: { licensed: true, reason: null, entitlement, lifecycle, channels, grants } -not licensed: { licensed: false, reason: 'unreadable' | 'product_missing', entitlement: null, +licensed: { licensed: true, reason: null, version, entitlement, lifecycle, channels, grants } +not licensed: { licensed: false, reason: 'unreadable' | 'product_missing', version, entitlement: null, lifecycle: null, channels: { console: true, ui: true }, grants: UNRESTRICTED_GRANTS } ``` +`version` is the format version of the key - `1` for a key without `v` (its prose is not checked), `2` for one issued now - so a product can treat an older key differently. It is `null` only for an unreadable key. + +What to do with `version === 1`: **accept it.** Trial keys in that format are in production. Do not treat `version` as a security signal either: anyone can turn a version 2 key into a version 1 key by dropping `v` and `prose` and recomputing the checksum - the checksum is not a signature. `version` only says what was checked, for example to log it or to word a support message. + The result is frozen all the way down, in both cases. Throws a `TypeError` - a wrong argument is your bug, and a silent "invalid" would hide it - when: @@ -316,9 +372,9 @@ The argument checks run before the key is read, so they fail whatever key a test Tells the shape of a key without validating it. `'entitlement'` means "a `[...]` block is present", not "valid". `literalKeys` are compared trimmed and case-insensitively; a blank entry, and a missing or non-array list, are ignored. `isEntitlementKey(licenseKey)` is the one-line form of the entitlement check. -### `extractEntitlementKeyData(licenseKey)` -> `{ products } | null` +### `extractEntitlementKeyData(licenseKey)` -> `{ version, products } | null` -The verified, frozen payload, or `null` for any unreadable key. `validateEntitlementKey(licenseKey)` returns the same as a boolean. `getProductEntitlement(data, product)` returns one product's entry or `null`, reading own properties only. +The verified, frozen payload, or `null` for any unreadable key. `version` is the format version (1 for a key without `v`). `validateEntitlementKey(licenseKey)` returns the same as a boolean. `getProductEntitlement(data, product)` returns one product's entry or `null`, reading own properties only. ### `classifyEntitlement(entitlement, { now, buildDate })` -> `LicenseLifecycle` @@ -347,7 +403,7 @@ Which channels the entry's flags leave open. | `index.ts` | the public exports | | `readLicense.ts` | `readEntitlementLicense` | | `detectFormat.ts` | `detectLicenseKeyFormat`, `isEntitlementKey` | -| `extractKeyData.ts` | the block reader: checksum, decode, shape checks, the one-entry cache | +| `extractKeyData.ts` | the key reader: the checksum, the format version and the prose digest, decode, shape checks, the one-entry cache | | `classify.ts` | the lifecycle windows and the channels | | `grants.ts` | capability queries | | `buildDate.ts` | `toIsoBuildDate` | diff --git a/src/license/handsontable-license-key-parser/constants.ts b/src/license/handsontable-license-key-parser/constants.ts index 438e0e3dd3..71064b1f91 100644 --- a/src/license/handsontable-license-key-parser/constants.ts +++ b/src/license/handsontable-license-key-parser/constants.ts @@ -6,6 +6,14 @@ */ export const CHECKSUM_LENGTH = 128; +/** + * The length of the prose digest (the first 64 hex characters of a SHA-512, + * 256 bits) that a version 2 payload carries as `prose`. + * + * @type {number} + */ +export const PROSE_DIGEST_LENGTH = 64; + /** * The two mutually exclusive date fields of a product entry. Exactly one of * them is present: diff --git a/src/license/handsontable-license-key-parser/detectFormat.ts b/src/license/handsontable-license-key-parser/detectFormat.ts index ffa1c55beb..2bb4230fa4 100644 --- a/src/license/handsontable-license-key-parser/detectFormat.ts +++ b/src/license/handsontable-license-key-parser/detectFormat.ts @@ -21,8 +21,9 @@ const LEGACY_KEY = /^[0-9a-fA-F]{25}$/; * read the legacy format. * * Surrounding whitespace is ignored: a key pasted out of an email or a chat - * window commonly carries a trailing space or newline. Whitespace INSIDE the - * brackets is not - see `extractEntitlementKeyData`. + * window commonly carries a trailing space or newline. `extractEntitlementKeyData` + * ignores whitespace inside the brackets too, so a block a mail client + * wrapped still reads. * * @param {*} licenseKey The license key to inspect. * @param {string[]} [literalKeys] The plain words this product accepts as a key diff --git a/src/license/handsontable-license-key-parser/extractKeyData.ts b/src/license/handsontable-license-key-parser/extractKeyData.ts index 6343ff6def..0316e3cc57 100644 --- a/src/license/handsontable-license-key-parser/extractKeyData.ts +++ b/src/license/handsontable-license-key-parser/extractKeyData.ts @@ -1,5 +1,5 @@ import type { EntitlementKeyData, ProductEntitlement } from './types'; -import { CHECKSUM_LENGTH, DATE_FIELDS } from './constants'; +import { CHECKSUM_LENGTH, DATE_FIELDS, PROSE_DIGEST_LENGTH } from './constants'; import { sha512 } from './sha512'; import { base64ToString, stringToUtf8Bytes, parseIsoDateToTimestamp } from './encoding'; @@ -13,6 +13,111 @@ import { base64ToString, stringToUtf8Bytes, parseIsoDateToTimestamp } from './en const ENCODED_PAYLOAD = /^[A-Za-z0-9\-_]+$/; const CHECKSUM = /^[0-9a-f]+$/; +/** + * The whitespace removed from the prose before its digest is taken: TAB, LF, + * VT, FF, CR, SPACE, NO-BREAK SPACE, OGHAM SPACE MARK, the U+2000-U+200A spaces, + * LINE SEPARATOR, PARAGRAPH SEPARATOR, NARROW NO-BREAK SPACE, MEDIUM + * MATHEMATICAL SPACE, IDEOGRAPHIC SPACE and the BOM. + * + * Listed explicitly instead of `\s`, whose set has changed between JavaScript + * engines (U+180E) and differs in other languages (U+0085), so a reader written + * anywhere can reproduce it exactly. + * + * @type {RegExp} + */ +const PROSE_WHITESPACE = /[\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/g; + +/** + * A line break or tab that was saved as text - a backslash followed by "n", + * "r" or "t" - also removed before the digest of the prose is taken. + * + * Several places a key is stored keep a line break that way rather than as a + * real one: a single-quoted or unquoted `.env` value, Docker's `--env-file`, + * and many CI secret fields. The block survives that intact, so without this + * a genuine key would fail only because of how it was stored. The generator + * strips backslashes from every free-text field, so a key it issues never + * carries one of its own. + * + * @type {RegExp} + */ +const ESCAPED_WHITESPACE = /\\[nrt]/g; + +/** + * Removes every escaped line break or tab (`\n`, `\r`, `\t` saved as text) + * and then every whitespace character - the first two steps of + * `canonicalizeProse`, and all that is done to the content of the block. + * + * The block is one long word, so a mail client or an editor that wraps the key + * can break it across lines - and a `.env` file can save that line break as + * the text `\n`. Neither base64url nor hex contains whitespace or a backslash, + * so removing them cannot change a genuine block. The block is not put in NFC: + * it is ASCII, and anything else in it fails the alphabet check anyway. + * + * The escapes go first, so a backslash, a space and "n" stay three characters. + * + * @param {string} text The text to strip. + * @returns {string} + */ +function removeWhitespace(text: string): string { + return text.replace(ESCAPED_WHITESPACE, '').replace(PROSE_WHITESPACE, ''); +} + +/** + * Brings the human-readable text of a key to the form the prose digest covers: + * every escaped line break or tab (`\n`, `\r`, `\t` saved as text) and every + * whitespace character removed, then Unicode NFC. + * + * Only the whitespace, its escaped forms and the Unicode composition are + * ignored. A mail client that rewraps the text - also between two CJK + * characters or inside a word - collapses a blank line, a `.env` file that + * saves a line break as `\n`, or a system that stores "u" + U+0308 for "u" + * leaves the key valid. A changed, added or removed letter, digit or symbol + * does not. + * + * Exported for test helpers; products call `extractEntitlementKeyData`. + * + * @param {string} prose The text in front of the machine-readable block. + * @returns {string} + */ +export function canonicalizeProse(prose: string): string { + // NFC runs last: a line break between a letter and its combining mark (an + // NFD copy rewrapped there) has to be gone before the two can compose. + return removeWhitespace(prose).normalize('NFC'); +} + +/** + * Computes the checksum that closes the block of every key: the SHA-512 + * (lowercase hex) of the UTF-8 bytes of the encoded payload. It is the same in + * every format version, which is what lets a reader that only knows version 1 + * read a newer key. + * + * Named apart from the 5.0.0 `computeChecksum(canonicalProse, encodedPayload)` + * on purpose: a test helper written for that one fails to import instead of + * hashing the wrong input. + * + * Exported for test helpers; products call `extractEntitlementKeyData`. + * + * @param {string} encodedPayload The base64url payload. + * @returns {string} + */ +export function computePayloadChecksum(encodedPayload: string): string { + return sha512(stringToUtf8Bytes(encodedPayload)); +} + +/** + * Computes the prose digest a version 2 payload carries as `prose`: the first + * 64 hex characters of the SHA-512 of the UTF-8 bytes of the canonical prose. + * + * Exported for test helpers; products call `extractEntitlementKeyData`. + * + * @param {string} canonicalProse The prose, already passed through + * `canonicalizeProse`. + * @returns {string} + */ +export function computeProseDigest(canonicalProse: string): string { + return sha512(stringToUtf8Bytes(canonicalProse)).slice(0, PROSE_DIGEST_LENGTH); +} + /** * Reports own-property presence without trusting a payload's inherited or * overridden `hasOwnProperty`. @@ -169,6 +274,68 @@ function normalizeProductEntry(entry: unknown): ProductEntitlement | null { return normalized; } +/** + * Reads the format version of a payload: 1 when it has no `v` (the keys issued + * before the field existed), the value of `v` otherwise. Returns `null` when + * `v` is there but is not a whole number of at least 2 - no generator ever + * wrote such a key. + * + * A version newer than this reader knows is accepted. A later version may add + * fields, but it keeps the block checksum and the prose digest, so this reader + * still verifies everything it knows about. + * + * Only an own `v` counts. Read through the prototype chain, one property + * another script set on `Object.prototype` would decide how every key reads. + * + * @param {Record} payload The decoded payload. + * @returns {number|null} + */ +function readFormatVersion(payload: Record): number | null { + if (!hasOwn(payload, 'v')) { + return 1; + } + if (!isNonNegativeInteger(payload.v) || payload.v < 2) { + return null; + } + + return payload.v; +} + +/** + * Tells whether a version 2 key covers its prose: nothing but whitespace + * follows the block, the prose is not empty, and its digest is the one the + * payload carries. + * + * Text after the block would be words nothing covers. A key always states its + * terms, so the bare block is rejected even with a digest computed over empty + * prose. + * + * @param {string} licenseKey The whole key. + * @param {number} blockStart The index of the block's "[". + * @param {number} blockEnd The index of the block's "]". + * @param {Record} payload The decoded payload. + * @returns {boolean} + */ +function coversProse( + licenseKey: string, + blockStart: number, + blockEnd: number, + payload: Record, +): boolean { + // Judged by the same rule as the prose, so a trailing line break saved as + // text ("\n") is allowed too. + if (canonicalizeProse(licenseKey.slice(blockEnd + 1)) !== '') { + return false; + } + + const canonicalProse = canonicalizeProse(licenseKey.slice(0, blockStart)); + + return canonicalProse !== '' + && hasOwn(payload, 'prose') + && typeof payload.prose === 'string' + && computeProseDigest(canonicalProse) === payload.prose; +} + /** * Reads and verifies one key. Split out from the memoized public entry point so * the memo can wrap every exit path uniformly. @@ -191,7 +358,7 @@ function readEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { return null; } - const content = licenseKey.slice(blockStart + 1, blockEnd); + const content = removeWhitespace(licenseKey.slice(blockStart + 1, blockEnd)); if (content.length <= CHECKSUM_LENGTH) { return null; @@ -203,7 +370,8 @@ function readEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { if (!ENCODED_PAYLOAD.test(encodedPayload) || !CHECKSUM.test(checksum)) { return null; } - if (sha512(stringToUtf8Bytes(encodedPayload)) !== checksum) { + + if (computePayloadChecksum(encodedPayload) !== checksum) { return null; } @@ -225,6 +393,17 @@ function readEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { return null; } + const version = readFormatVersion(payload); + + if (version === null) { + return null; + } + // The prose is canonicalized only here, after the checksum passed: a version + // 1 key and a broken one never pay for the NFC pass. + if (version >= 2 && !coversProse(licenseKey, blockStart, blockEnd, payload)) { + return null; + } + const products = {} as EntitlementKeyData['products']; const entries = payload.products; let malformed = false; @@ -245,7 +424,7 @@ function readEntitlementKeyData(licenseKey: string): EntitlementKeyData | null { return null; } - return deepFreeze({ products }); + return deepFreeze({ version, products }); } // A product typically reads its key more than once per start-up (a console @@ -259,16 +438,24 @@ let memoizedData: EntitlementKeyData | null = null; * Extracts the machine-readable data from an entitlement license key. * * The checksum is verified first, so the returned data is guaranteed to belong - * to an intact block. A malformed or tampered key reads as `null` - reporting - * an invalid key is the caller's job, not this function's. - * - * Only the bracketed block matters. The prose in front of it is neither parsed - * nor covered by the checksum, so the caller may pass the whole key or just the - * `[...]` block, and rewrapped or re-pasted prose still validates. The block - * itself has to be intact: its alphabet has no whitespace, so a newline inside - * it makes the key unreadable, exactly as it does for the key generator. Do not - * "repair" such a key by stripping whitespace inside the brackets - that would - * accept keys the generator rejects. + * to an intact key. A malformed or tampered key reads as `null` - reporting an + * invalid key is the caller's job, not this function's. + * + * The checksum is the SHA-512 of the encoded payload in every version. The + * payload's `v` decides what else is checked: + * + * - version 2 and later (`v` in the payload): the payload's `prose` digest + * has to match the text in front of the block, and only whitespace may + * follow the block. A key whose prose was edited or removed (the bare + * `[...]` block) reads as `null`. + * - version 1 (no `v`), as license-key 4.x issued it: neither is checked, + * exactly as 4.x did not - the bare block, an edited prose and text after + * the block all read. Trial keys in that format are in production. + * + * The caller passes the whole key. The prose is never parsed, and its + * whitespace and Unicode composition are ignored, so rewrapped or re-pasted + * prose still validates. Whitespace inside the block is ignored too, so a + * block wrapped by a mail client still validates. * * Unknown products, capability tokens and flags are all tolerated, so nothing * about reading a key depends on the commercial vocabulary. diff --git a/src/license/handsontable-license-key-parser/readLicense.ts b/src/license/handsontable-license-key-parser/readLicense.ts index 896126de9c..26a14dee43 100644 --- a/src/license/handsontable-license-key-parser/readLicense.ts +++ b/src/license/handsontable-license-key-parser/readLicense.ts @@ -18,25 +18,33 @@ import { resolveBuildDate } from './buildDate'; const OPEN_CHANNELS: LicenseChannels = Object.freeze({ console: true, ui: true }); /** - * Builds the result for a key that does not license the product. + * Builds the result for a key that does not license the product. The + * overloads tie the version to the reason: a key that grants other products + * was read, so it has one; an unreadable key has none. * * @param {UnlicensedReason} reason Why the key does not license the product. + * @param {number|null} version The format version of the key, or `null` when + * it could not be read. * @returns {EntitlementLicense} */ -function unlicensed(reason: UnlicensedReason): EntitlementLicense { +function unlicensed(reason: 'unreadable', version: null): EntitlementLicense; +function unlicensed(reason: 'product_missing', version: number): EntitlementLicense; +function unlicensed(reason: UnlicensedReason, version: number | null): EntitlementLicense { return Object.freeze({ licensed: false, reason, + version, entitlement: null, lifecycle: null, channels: OPEN_CHANNELS, grants: UNRESTRICTED_GRANTS, - }); + }) as EntitlementLicense; } /** * Reads an entitlement license key for one product, in one call: verifies the - * block, picks the product's entry, places it in its lifecycle window, reads + * key (the checksum, and from version 2 the prose digest), picks the product's + * entry, places it in its lifecycle window, reads * its silencing flags and resolves what it unlocks. * * This is the single entry point a product needs. Route a key here only when @@ -92,13 +100,13 @@ export function readEntitlementLicense( const keyData = extractEntitlementKeyData(licenseKey); if (keyData === null) { - return unlicensed('unreadable'); + return unlicensed('unreadable', null); } const entitlement = getProductEntitlement(keyData, product); if (entitlement === null) { - return unlicensed('product_missing'); + return unlicensed('product_missing', keyData.version); } // The clock is read once, so every window boundary is measured against the @@ -115,6 +123,7 @@ export function readEntitlementLicense( return Object.freeze({ licensed: true, reason: null, + version: keyData.version, entitlement, lifecycle, channels: resolveChannels(entitlement), diff --git a/src/license/handsontable-license-key-parser/types.ts b/src/license/handsontable-license-key-parser/types.ts index 8d97514f6d..961a12c04c 100644 --- a/src/license/handsontable-license-key-parser/types.ts +++ b/src/license/handsontable-license-key-parser/types.ts @@ -41,6 +41,15 @@ export interface ProductEntitlement { * known ones. */ export interface EntitlementKeyData { + /** + * The format version of the key: 1 for a key without `v` in its payload + * (the first keys), the value of `v` otherwise. The checksum and the shape + * are verified for every version. The prose is verified only from version + * 2: a version 1 key reads with an edited prose, as its bare block, or with + * text after the block, exactly as it did when it was issued. A product may + * use the number to decide how to treat such a key. + */ + readonly version: number; readonly products: { readonly [productName: string]: ProductEntitlement }; } @@ -124,7 +133,12 @@ export interface LicenseTimeReference { /** * Why an entitlement key does not license the product that reads it: * - * - `unreadable` the block is missing, tampered with or malformed, + * - `unreadable` the key fails verification: the block is missing, + * tampered with or malformed, or - for a version 2 + * key - the prose was edited or removed (the prose + * digest covers it) or text other than whitespace + * follows the block. A version 1 key never covered + * its prose, so neither makes it unreadable, * - `product_missing` the key is intact but grants other products only. * * Both are reported to the user as an invalid key; the split exists so a @@ -138,6 +152,11 @@ export type UnlicensedReason = 'unreadable' | 'product_missing'; * When `licensed` is `true`, `entitlement`, `lifecycle` and `channels` describe * that product and `grants` lists exactly what the key unlocks. * + * `version` is the format version of the key (1 for a key without `v`, whose + * prose is not checked) whenever the key could be read - also for + * `product_missing`. It is `null` only for an unreadable key, and the union + * narrows it: check `reason` and `version` is a `number` or `null`. + * * When `licensed` is `false`, the product must report an invalid key. * `entitlement` and `lifecycle` are `null`, both channels are open (the flags * that close them could not be read), and `grants` is unrestricted - an @@ -149,6 +168,7 @@ export type EntitlementLicense = | { readonly licensed: true; readonly reason: null; + readonly version: number; readonly entitlement: ProductEntitlement; readonly lifecycle: LicenseLifecycle; readonly channels: LicenseChannels; @@ -156,7 +176,17 @@ export type EntitlementLicense = } | { readonly licensed: false; - readonly reason: UnlicensedReason; + readonly reason: 'product_missing'; + readonly version: number; + readonly entitlement: null; + readonly lifecycle: null; + readonly channels: LicenseChannels; + readonly grants: LicenseGrants; + } + | { + readonly licensed: false; + readonly reason: 'unreadable'; + readonly version: null; readonly entitlement: null; readonly lifecycle: null; readonly channels: LicenseChannels; diff --git a/src/license/handsontable-license-key-parser/upstream.json b/src/license/handsontable-license-key-parser/upstream.json index 93775f53b7..05188fce14 100644 --- a/src/license/handsontable-license-key-parser/upstream.json +++ b/src/license/handsontable-license-key-parser/upstream.json @@ -14,9 +14,9 @@ ], "repository": "handsontable/license-key", "directory": "vendor/entitlement-key-reader", - "tag": "4.0.1", - "commit": "03810fd3c93160580e1b9665de6b38fca340e382", - "taken_on": "2026-09-30", + "tag": "5.1.1", + "commit": "12466071875bfb3b807e8321d9d5e9c9a8551b09", + "taken_on": "2026-10-07", "own_files": [ "PROVENANCE.md", "upstream.json" diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index e8fcb573af..7b18a866f3 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -133,9 +133,9 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool * not a legacy key that happens to contain brackets. * * An entitlement key is read by the vendored {@link readEntitlementLicense}, the single entry - * point upstream prescribes for products: it verifies the block, picks HyperFormula's entry, - * places it in its lifecycle window and reads its flags. Only the meaning of the capability - * tokens and the console messages live here. + * point upstream prescribes for products: it verifies the key (the checksum and the prose + * digest), picks HyperFormula's entry, places it in its lifecycle window and reads its flags. Only + * the meaning of the capability tokens and the console messages live here. * * **The invariant this function exists to protect.** Only a VALID entitlement key resolves to a * restricted entitlement. Every other outcome — missing, invalid, or expired, for an entitlement @@ -177,7 +177,7 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true }) if (!license.licensed) { - // `unreadable` (a broken block) and `product_missing` (a key for other products only) both + // `unreadable` (a broken block, or edited or missing prose) and `product_missing` (a key for other products only) both // resolve to an invalid key that restricts nothing; only their console messages differ. if (notifyConsole) { notifyEntitlementKey(licenseKey, license.reason, {licensedUntil: null, daysRemaining: null}) From 5a3edb945eb2416057833b85e9525d1d4a7c11fb Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 7 Oct 2026 07:31:33 +0000 Subject: [PATCH 34/54] Remove license status from VERSION function output Co-authored-by: Kuba Sekowski --- src/interpreter/plugin/VersionPlugin.ts | 29 +------------------------ 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/src/interpreter/plugin/VersionPlugin.ts b/src/interpreter/plugin/VersionPlugin.ts index 882dec373f..da65919a20 100644 --- a/src/interpreter/plugin/VersionPlugin.ts +++ b/src/interpreter/plugin/VersionPlugin.ts @@ -3,21 +3,12 @@ * Copyright (c) 2025 Handsoncode. All rights reserved. */ -import {entitlementKeyChecksumOf, LicenseKeyValidityState} from '../../helpers/licenseKeyValidator' import {HyperFormula} from '../../HyperFormula' -import {detectLicenseKeyFormat} from '../../license/handsontable-license-key-parser/detectFormat' import {ProcedureAst} from '../../parser' import {InterpreterState} from '../InterpreterState' import {InterpreterValue} from '../InterpreterValue' import {FunctionPlugin, FunctionPluginTypecheck, ImplementedFunctions} from './FunctionPlugin' -const LICENSE_STATUS_MAP = new Map([ - ['gpl-v3', 1], - [LicenseKeyValidityState.MISSING, 2], - [LicenseKeyValidityState.INVALID, 3], - [LicenseKeyValidityState.EXPIRED, 4], -]) - export class VersionPlugin extends FunctionPlugin implements FunctionPluginTypecheck { public static implementedFunctions: ImplementedFunctions = { 'VERSION': { @@ -28,25 +19,7 @@ export class VersionPlugin extends FunctionPlugin implements FunctionPluginTypec public version(ast: ProcedureAst, state: InterpreterState): InterpreterValue { return this.runFunction(ast.args, state, this.metadata('VERSION'), () => { - const { - licenseKeyValidityState: validityState, - licenseKey, - } = this.config - let status - - if (LICENSE_STATUS_MAP.has(licenseKey)) { - status = LICENSE_STATUS_MAP.get(licenseKey) - } else if (LICENSE_STATUS_MAP.has(validityState)) { - status = LICENSE_STATUS_MAP.get(validityState) - } else if (validityState === LicenseKeyValidityState.VALID) { - // An entitlement key may end in its closing bracket, whitespace or a line break saved as - // text, so its status is read from the checksum, not from the end of the string. - status = detectLicenseKeyFormat(licenseKey) === 'entitlement' - ? entitlementKeyChecksumOf(licenseKey).slice(-5) - : licenseKey.slice(-5) - } - - return `HyperFormula v${HyperFormula.version}, ${status}` + return `HyperFormula v${HyperFormula.version}` }) } } From 42a3c7c2619990fe3f3f7a599f7f2a741df9cc9c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 7 Oct 2026 07:34:55 +0000 Subject: [PATCH 35/54] Remove unused entitlementKeyChecksumOf function Co-authored-by: Kuba Sekowski --- src/helpers/licenseKeyValidator.ts | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index 1170446bd0..f4ae5b8475 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -3,7 +3,6 @@ * Copyright (c) 2025 Handsoncode. All rights reserved. */ -import {CHECKSUM_LENGTH} from '../license/handsontable-license-key-parser/constants' import {stringToUtf8Bytes} from '../license/handsontable-license-key-parser/encoding' import {sha512} from '../license/handsontable-license-key-parser/sha512' import {LicenseState, UnlicensedReason} from '../license/handsontable-license-key-parser/types' @@ -219,22 +218,6 @@ function keyIdentityOf(licenseKey: string): string { return sha512(stringToUtf8Bytes(withoutIgnoredCharacters(licenseKey).normalize('NFC'))) } -/** - * The checksum of an entitlement key: the last 128 characters of its block. The block is found - * the way the reader finds it - the last `[` and the first `]` after it - and read without the - * characters the reader ignores, so a key wrapped inside its block, or followed by a line break, - * reports the same checksum as its one-line form. - * - * @param {string} licenseKey - an entitlement key, as the user passed it - * @returns {string} the checksum - */ -export function entitlementKeyChecksumOf(licenseKey: string): string { - const blockStart = licenseKey.lastIndexOf('[') - const blockEnd = licenseKey.indexOf(']', blockStart + 1) - - return withoutIgnoredCharacters(licenseKey.slice(blockStart + 1, blockEnd)).slice(-CHECKSUM_LENGTH) -} - /** * The text without the characters the reader ignores anywhere in a key: every line break or tab * saved as text (`\n`, `\r`, `\t`, as a `.env` file stores one), then every whitespace character. From d97478c83c3e72215df0f1323835d51f68eb1a95 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 12:47:31 +0200 Subject: [PATCH 36/54] HF-307: read the license once per interpreter and resolve aliases in one place The interpreter now reads the license decisions from its config once, in its constructor, instead of through the config's getters on every function call, and skips the alias and table lookups for a key that grants every function. A config never changes after it is built, and updateConfig builds a new interpreter, so the cached values cannot go stale. test:performance shows no regression against develop. Alias canonicalisation, used by both the interpreter and the function metadata API, moves to FunctionRegistry.getCanonicalFunctionId. Co-Authored-By: Claude Opus 5.5 --- src/HyperFormula.ts | 4 +-- src/interpreter/FunctionRegistry.ts | 12 +++++++++ src/interpreter/Interpreter.ts | 39 +++++++++++++++++------------ 3 files changed, 36 insertions(+), 19 deletions(-) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 2369a68fa4..aedae7934d 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -738,9 +738,7 @@ export class HyperFormula implements TypedEmitter { if (FunctionRegistry.functionIsProtected(functionId)) { return true } - const plugin = functionRegistry.getFunctionPlugin(functionId) - const canonicalId = plugin?.aliases?.[functionId] ?? functionId - return licenseAllowsFunction(config.capabilityRegistry, config.licenseCapabilities, canonicalId) + return licenseAllowsFunction(config.capabilityRegistry, config.licenseCapabilities, functionRegistry.getCanonicalFunctionId(functionId)) } /** diff --git a/src/interpreter/FunctionRegistry.ts b/src/interpreter/FunctionRegistry.ts index 5038fec654..4a38ed70a1 100644 --- a/src/interpreter/FunctionRegistry.ts +++ b/src/interpreter/FunctionRegistry.ts @@ -233,6 +233,18 @@ export class FunctionRegistry { return this.instancePlugins.get(functionId) } + /** + * Returns the id a function is registered as an alias of (`plugin.aliases`), or the id itself + * when it is not an alias. The license capability table lists canonical names only, so both the + * interpreter and the function metadata API resolve an id through this before consulting it: + * calling a gated function through its alias must be gated exactly like calling it by name. + * + * @param {string} functionId - the id as registered, which may be an alias + */ + public getCanonicalFunctionId(functionId: string): string { + return this.getFunctionPlugin(functionId)?.aliases?.[functionId] ?? functionId + } + /** * Returns the ids of all functions the function-metadata API (`getAvailableFunctions`/`getFunctionDetails`) * should describe: every function registered in this instance (aliases and any custom/user-registered functions diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index ba7c5b6636..274fcf3d2a 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -13,7 +13,7 @@ import {DependencyGraph} from '../DependencyGraph' import {FormulaVertex} from '../DependencyGraph/FormulaVertex' import {ErrorMessage} from '../error-message' import {LicenseKeyValidityState} from '../helpers/licenseKeyValidator' -import {licenseAllowsFunction} from '../license/CapabilityRegistry' +import {CapabilityRegistry, licenseAllowsFunction, ResolvedCapabilities} from '../license/CapabilityRegistry' import {ColumnSearchStrategy} from '../Lookup/SearchStrategy' import {Maybe} from '../Maybe' import {NamedExpressions} from '../NamedExpressions' @@ -46,6 +46,19 @@ import { AddressWithSheet } from '../parser/Address' export class Interpreter { public readonly criterionBuilder: CriterionBuilder + /* + * The license decisions applied to every function call, read once from the config instead of + * through its getters (a WeakMap lookup each) on the hottest path of evaluation. They cannot go + * stale: a Config never changes once built, and `updateConfig` builds a new engine, and with it a + * new Interpreter. + */ + private readonly licenseBlocksEvaluation: boolean + private readonly licenseKeyValidityState: LicenseKeyValidityState + private readonly capabilityRegistry: CapabilityRegistry + private readonly licenseCapabilities: ResolvedCapabilities + /** `false` for a key that grants every function, which lets a call skip the alias and table lookups. */ + private readonly licenseRestrictsFunctions: boolean + constructor( public readonly config: Config, public readonly dependencyGraph: DependencyGraph, @@ -60,17 +73,11 @@ export class Interpreter { ) { this.functionRegistry.initializePlugins(this) this.criterionBuilder = new CriterionBuilder(config) - } - - /** - * Resolves a function id to the name it is covered by in the capability table. A function - * registered purely as an alias of another one (`plugin.aliases`) must gate identically to - * its canonical name — otherwise calling a gated function through its alias would silently - * bypass the entitlement check. - */ - private canonicalFunctionId(functionId: string): string { - const plugin = this.functionRegistry.getFunctionPlugin(functionId) - return plugin?.aliases?.[functionId] ?? functionId + this.licenseBlocksEvaluation = config.licenseBlocksEvaluation + this.licenseKeyValidityState = config.licenseKeyValidityState + this.capabilityRegistry = config.capabilityRegistry + this.licenseCapabilities = config.licenseCapabilities + this.licenseRestrictsFunctions = config.licenseCapabilities.functions !== 'all' } public evaluateAst(ast: Ast, state: InterpreterState): InterpreterValue { @@ -190,12 +197,12 @@ export class Interpreter { } case AstNodeType.FUNCTION_CALL: { if (!FunctionRegistry.functionIsProtected(ast.procedureName)) { - if (this.config.licenseBlocksEvaluation) { - return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(this.config.licenseKeyValidityState)) + if (this.licenseBlocksEvaluation) { + return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(this.licenseKeyValidityState)) } - const canonicalId = this.canonicalFunctionId(ast.procedureName) - if (!licenseAllowsFunction(this.config.capabilityRegistry, this.config.licenseCapabilities, canonicalId)) { + if (this.licenseRestrictsFunctions + && !licenseAllowsFunction(this.capabilityRegistry, this.licenseCapabilities, this.functionRegistry.getCanonicalFunctionId(ast.procedureName))) { return new CellError(ErrorType.LIC, ErrorMessage.LicenseCapability(ast.procedureName)) } } From 3076f280afc8ef7a470083f0563edd9d80ccf4be Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 12:47:31 +0200 Subject: [PATCH 37/54] HF-307: expose the missing feature on the license error, and trim the license model - LicenseCapabilityMissingError carries the feature the call needed in its feature property, and FeatureId is exported (by name and as HyperFormula.FeatureId), so callers no longer parse the message. Its description now also covers a key that blocks every gated feature. - Entitlement-key console messages print every time a key is resolved; the per-key de-duplication, and with it the use of the reader's internal sha512 and encoding modules, is gone. The reader's types are imported through its index. - The unlicensed-key messages get their own notifier, and the message helpers take non-null parameters and have JSDoc. - Remove FeatureId.CustomFunctions and LicenseEntitlement.unrecognizedCapabilities, which nothing used, and stop exporting FUNCTION_GROUPS. - TypeDoc no longer documents the vendored reader. Co-Authored-By: Claude Opus 5.5 --- .typedoc.ts | 1 + src/errors.ts | 8 +- src/helpers/licenseKeyValidator.ts | 128 ++++++++---------- src/index.ts | 3 + src/license/LicenseEntitlement.ts | 14 +- src/license/featureCapabilities.ts | 3 - src/license/functionCapabilities.ts | 8 +- .../PROVENANCE.md | 10 +- src/license/licenseResolution.ts | 31 ++--- 9 files changed, 88 insertions(+), 118 deletions(-) diff --git a/.typedoc.ts b/.typedoc.ts index 0001ced876..d7d1f28152 100644 --- a/.typedoc.ts +++ b/.typedoc.ts @@ -7,6 +7,7 @@ module.exports = { "./src/dependencyTransformers/**", "./src/DependencyGraph/**", "./src/ColumnSearch/**", + "./src/license/handsontable-license-key-parser/**", ], "mode": "file", "out": "./typedoc", diff --git a/src/errors.ts b/src/errors.ts index 2cdb802852..367c74b38b 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -397,7 +397,9 @@ export class AliasAlreadyExisting extends Error { /** * Error thrown when a public API method is called for a {@link FeatureId} that the current - * license entitlement does not grant. Mirrors gate B's `ErrorMessage.LicenseCapability`, but + * license entitlement does not grant, or when the license key itself blocks every gated feature + * (missing, invalid, or expired in a way that blocks evaluation); the message then names the + * key's state instead. Mirrors gate B's `ErrorMessage.LicenseCapability`, but * this one guards the API surface itself rather than a formula evaluation, so it * is thrown synchronously instead of surfacing as a cell error. * @@ -438,6 +440,9 @@ export class AliasAlreadyExisting extends Error { * @see [[suspendEvaluation]] */ export class LicenseCapabilityMissingError extends Error { + /** The gated feature the call needed. */ + public readonly feature: FeatureId + /** * @param {FeatureId} feature - the gated feature that was called * @param {LicenseKeyValidityState} [blockingState] - the key's state when the key itself blocks @@ -448,5 +453,6 @@ export class LicenseCapabilityMissingError extends Error { super(blockingState === undefined ? `Feature ${feature} is not included in your license.` : `License key is ${blockingState}. Feature ${feature} is not available.`) + this.feature = feature } } diff --git a/src/helpers/licenseKeyValidator.ts b/src/helpers/licenseKeyValidator.ts index f4ae5b8475..7ea39eb5ca 100644 --- a/src/helpers/licenseKeyValidator.ts +++ b/src/helpers/licenseKeyValidator.ts @@ -3,9 +3,7 @@ * Copyright (c) 2025 Handsoncode. All rights reserved. */ -import {stringToUtf8Bytes} from '../license/handsontable-license-key-parser/encoding' -import {sha512} from '../license/handsontable-license-key-parser/sha512' -import {LicenseState, UnlicensedReason} from '../license/handsontable-license-key-parser/types' +import {LicenseState, UnlicensedReason} from '../license/handsontable-license-key-parser' import {checkKeySchema, extractTime} from './licenseKeyHelper' /** @@ -46,38 +44,51 @@ const consoleMessages: ConsoleMessages = { let _notified = false /** - * What an entitlement-key console message is built from: the date exactly as the key carries it + * What an entitlement-key lifecycle message is built from: the date exactly as the key carries it * (never rebuilt from a timestamp) and the whole UTC days left until it. */ export interface EntitlementMessageParams { - licensedUntil: string | null, + licensedUntil: string, + /** `null` for a `release_until` key, which is compared with the build date and reads no clock. */ daysRemaining: number | null, } /** - * One console notification for an entitlement-key lifecycle state: its severity and its text. Kept - * as one record so a state cannot get a text without a severity. A warning while the license still - * works, an error once it has run out. + * One console notification for an entitlement key: its severity and its text. Kept as one record + * so a state cannot get a text without a severity. A warning while the license still works, an + * error once it has run out. */ -interface EntitlementConsoleNotification { +interface EntitlementConsoleNotification { severity: 'warn' | 'error', - message: (params: EntitlementMessageParams) => string, + message: (params: Params) => string, } const PURCHASE_LICENSE_TEXT = 'To continue using HyperFormula, you need to purchase a license.' /** - * A `usage_until` date is compared against the clock in UTC, so it is printed with the marker; a - * `release_until` date involves no clock and carries none. + * Formats a `usage_until` date for a message. It is compared against the clock in UTC, so it is + * printed with the marker; a `release_until` date involves no clock and is printed without one. + * + * @param {string} isoDate - the date as the key carries it, `YYYY-MM-DD` */ -function utcDay(isoDate: string | null): string { +function utcDay(isoDate: string): string { return `${isoDate} (UTC)` } -function expiryClause(days: number | null): string { +/** + * The countdown of a trial notice: `expires today`, `expires in 1 day` or `expires in N days`. + * + * @param {number} days - the whole UTC days left until the last licensed day + */ +function expiryClause(days: number): string { return days === 0 ? 'expires today' : `expires in ${days} ${days === 1 ? 'day' : 'days'}` } +/** + * The message of a subscription past its `usage_until` date, inside its grace period or after it. + * + * @param {EntitlementMessageParams} params - the key's own date + */ function subscriptionExpiredMessage({licensedUntil}: EntitlementMessageParams): string { return `Your HyperFormula subscription license expired on ${utcDay(licensedUntil)}. To continue using the software, contact sales@handsontable.com to purchase a valid license key.` } @@ -90,10 +101,11 @@ function subscriptionExpiredMessage({licensedUntil}: EntitlementMessageParams): * maintenance date) have no entry. A non-trial key past its grace keeps the soft-stop message: it * never blocks a paying customer. */ -const ENTITLEMENT_CONSOLE_NOTIFICATIONS: Partial> = { +const ENTITLEMENT_CONSOLE_NOTIFICATIONS: Partial>> = { trial_notice: { severity: 'warn', - message: ({daysRemaining}) => `Your HyperFormula license key ${expiryClause(daysRemaining)}. ${PURCHASE_LICENSE_TEXT}`, + // A trial in its notice window is always a `usage_until` key, so the reader counted its days. + message: ({daysRemaining}) => `Your HyperFormula license key ${expiryClause(daysRemaining as number)}. ${PURCHASE_LICENSE_TEXT}`, }, trial_soft_stop: { severity: 'error', @@ -119,7 +131,7 @@ const ENTITLEMENT_CONSOLE_NOTIFICATIONS: Partial = { +const UNLICENSED_CONSOLE_NOTIFICATIONS: Record> = { unreadable: { severity: 'error', message: () => 'The license key for HyperFormula is invalid. If you need any help, contact us at support@handsontable.com.', @@ -131,19 +143,10 @@ const UNLICENSED_CONSOLE_NOTIFICATIONS: Record() - -/** - * Clears the once-per-page-load flag {@link notifyLicenseKeyState} keeps, and the per-key set - * {@link notifyEntitlementKey} keeps. + * Clears the once-per-page-load flag {@link notifyLicenseKeyState} keeps. * - * Exists for tests only. Both are module-level and never otherwise reset, so without this the - * whole console-message path is unobservable: the first spec to build any engine consumes the + * Exists for tests only. The flag is module-level and never otherwise reset, so without this the + * classic-key message path is unobservable: the first spec to build any engine consumes the * message and every later assertion sees silence regardless of what the code does. Under Karma * every spec shares one browser context, so spec-order tricks do not work there at all. * @@ -151,7 +154,6 @@ const _notifiedEntitlementKeys = new Set() */ export function resetLicenseKeyNotificationForTests(): void { _notified = false - _notifiedEntitlementKeys.clear() } /** @@ -173,59 +175,45 @@ export function notifyLicenseKeyState(state: LicenseKeyValidityState, keyValidit } /** - * Prints the console message for an entitlement key, at most once per distinct key per page. + * Prints the console message for an entitlement key's lifecycle state, every time a key is + * resolved: unlike classic keys, entitlement keys keep no record of what they already printed. + * States inside the term print nothing. * - * @param {string} licenseKey - the raw key; only its identity is retained - * @param {LicenseState | UnlicensedReason} state - the reader's lifecycle state, or why the key does not license HyperFormula + * @param {LicenseState} state - the reader's lifecycle state * @param {EntitlementMessageParams} params - the key's own date and days remaining */ -export function notifyEntitlementKey(licenseKey: string, state: LicenseState | UnlicensedReason, params: EntitlementMessageParams): void { - const notification: EntitlementConsoleNotification | undefined = state === 'unreadable' || state === 'product_missing' - ? UNLICENSED_CONSOLE_NOTIFICATIONS[state] - : ENTITLEMENT_CONSOLE_NOTIFICATIONS[state] +export function notifyEntitlementKey(state: LicenseState, params: EntitlementMessageParams): void { + const notification = ENTITLEMENT_CONSOLE_NOTIFICATIONS[state] - if (notification === undefined) { - return + if (notification !== undefined) { + printNotification(notification.severity, notification.message(params)) } - - // Keyed by the key AND the text, not the key alone: on a page that stays open while a key moves - // from its notice window into expiry, the expiry message is a different message and must still - // print. A soft stop and a hard stop share one text, so the hard stop does not repeat it. - const text = notification.message(params) - const identity = `${keyIdentityOf(licenseKey)}\n${text}` - - if (_notifiedEntitlementKeys.has(identity)) { - return - } - - if (notification.severity === 'error') { - console.error(text) - } else { - console.warn(text) - } - _notifiedEntitlementKeys.add(identity) } /** - * The identity of a key: the SHA-512 of the key with every character the reader ignores removed, - * unique per distinct key content. A rewrapped key and its one-line form are one license to the - * reader, so they are one identity here too. Two keys that share a block but differ in their prose - * are two keys - the payload carries a digest of the prose - so they are two identities. Hashed - * because the set lives as long as the page: a server building one engine per customer key would - * otherwise keep every full key string it has ever seen. + * Prints the console message for an entitlement key that does not license HyperFormula, every + * time such a key is resolved. + * + * @param {UnlicensedReason} reason - why the reader does not license HyperFormula with the key */ -function keyIdentityOf(licenseKey: string): string { - return sha512(stringToUtf8Bytes(withoutIgnoredCharacters(licenseKey).normalize('NFC'))) +export function notifyUnlicensedEntitlementKey(reason: UnlicensedReason): void { + const notification = UNLICENSED_CONSOLE_NOTIFICATIONS[reason] + + printNotification(notification.severity, notification.message()) } /** - * The text without the characters the reader ignores anywhere in a key: every line break or tab - * saved as text (`\n`, `\r`, `\t`, as a `.env` file stores one), then every whitespace character. - * Removed in the reader's order, escapes first; `\s` is exactly the set of characters the reader - * treats as whitespace. + * Prints `text` on the console channel that matches `severity`. + * + * @param {'warn' | 'error'} severity - `warn` while the license still works, `error` once it does not + * @param {string} text - the message */ -function withoutIgnoredCharacters(text: string): string { - return text.replace(/\\[nrt]/g, '').replace(/\s+/g, '') +function printNotification(severity: 'warn' | 'error', text: string): void { + if (severity === 'error') { + console.error(text) + } else { + console.warn(text) + } } /** diff --git a/src/index.ts b/src/index.ts index fa0db7f306..f48715c9f4 100644 --- a/src/index.ts +++ b/src/index.ts @@ -52,6 +52,7 @@ import enGB from './i18n/languages/enGB' import {FunctionArgument, FunctionPlugin, FunctionPluginDefinition, FunctionArgumentType, ImplementedFunctions, FunctionMetadata, EmptyValue} from './interpreter' import {FunctionCategory, FunctionDetails, FunctionListEntry, FunctionParameterDescription} from './interpreter/functionMetadata/FunctionDescription' import {FormatInfo} from './interpreter/InterpreterValue' +import {FeatureId} from './license/LicenseEntitlement' import * as plugins from './interpreter/plugin' import {SimpleRangeValue} from './SimpleRangeValue' import {NamedExpression, NamedExpressionOptions} from './NamedExpressions' @@ -65,6 +66,7 @@ import {ConfigParams} from './ConfigParams' class HyperFormulaNS extends HyperFormula { public static HyperFormula = HyperFormula public static ErrorType = ErrorType + public static FeatureId = FeatureId public static CellError = CellError public static CellType = CellType public static CellValueType = CellValueType @@ -152,6 +154,7 @@ export { CellValueType, CellValueDetailedType, ErrorType, + FeatureId, ExportedCellChange, ExportedNamedExpressionChange, DetailedCellError, diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index 1d06e2243a..042db4d8af 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -6,16 +6,15 @@ /** * Identifies a feature area of the public API that a license entitlement can gate. * - * `CustomFunctions` is reserved vocabulary: it exists so a license payload is free to carry it, - * but registering a custom function is never gated, so no capability grant maps to it. + * Public, as the type of [[LicenseCapabilityMissingError]]'s `feature`, so that a caller can tell + * which feature a call needed without parsing the error message. */ -export const enum FeatureId { +export enum FeatureId { NamedExpressions = 'named_expressions', Clipboard = 'clipboard', Crud = 'crud', UndoRedo = 'undo_redo', Batching = 'batching', - CustomFunctions = 'custom_functions', } /** @@ -52,12 +51,6 @@ export interface LicenseEntitlement { unrestricted: boolean, /** Capability tokens this entitlement grants, recognized by this library version. */ capabilities: ReadonlySet, - /** - * Tokens present on the license payload that this library version does not recognize. - * Kept for diagnostics and tests; nothing public reads this field — an - * unrecognized token never grants a capability, and it does so silently. - */ - unrecognizedCapabilities: readonly string[], expiry: LicenseExpiry, /** * When `true`, resolving this entitlement must not print a console message of any kind. @@ -85,7 +78,6 @@ export function unrestrictedEntitlement(): LicenseEntitlement { return { unrestricted: true, capabilities: new Set(), - unrecognizedCapabilities: [], expiry: {kind: 'none', date: null, noticeDays: 0, graceDays: 0}, silent: false, isTrial: false, diff --git a/src/license/featureCapabilities.ts b/src/license/featureCapabilities.ts index 49d7704860..73fa5d5c96 100644 --- a/src/license/featureCapabilities.ts +++ b/src/license/featureCapabilities.ts @@ -8,9 +8,6 @@ import {FeatureId} from './LicenseEntitlement' /** * One entry per single-area feature token. `feat:all` is derived from this list rather than * spelled out beside it, so a new gated area reaches it by being added here and nowhere else. - * - * {@link FeatureId.CustomFunctions} deliberately has no token: registering a custom function is - * never gated, so nothing may grant it. */ const singleFeatureEntries: [string, readonly FeatureId[]][] = [ ['feat:crud', [FeatureId.Crud]], diff --git a/src/license/functionCapabilities.ts b/src/license/functionCapabilities.ts index 7e817b8895..c271c0c9ed 100644 --- a/src/license/functionCapabilities.ts +++ b/src/license/functionCapabilities.ts @@ -21,13 +21,7 @@ * The doc freezes group names as API surface: once shipped inside license keys, a rename is a * breaking change. */ -// Exported for the paired suite's drift checks, which compare this transcription against the -// packaging document group by group and member by member. Without the export the specs still run -// and still go red, but they die on `Cannot read properties of undefined` instead of comparing -// anything - so the comparison is lost while the suite looks merely broken. Measured on all three -// paths: `tsc --noEmit` says nothing (tsconfig includes `src` only, so the specs are not in its -// program), and Jest - which is what CI runs - throws at run time. -export const FUNCTION_GROUPS: ReadonlyMap = new Map([ +const FUNCTION_GROUPS: ReadonlyMap = new Map([ ['fun:math.a', ['ABS', 'LOG', 'MOD', 'POWER', 'PRODUCT', 'ROUND', 'ROUNDDOWN', 'ROUNDUP', 'SQRT', 'SUM']], ['fun:stat.a', ['AVERAGE', 'COUNT', 'MAX', 'MIN']], ['fun:logic.a', ['IF']], diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 683ef71073..79e1a6d99b 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -39,14 +39,12 @@ pin. Without credentials to the private repository it fails rather than skips. ## What HyperFormula uses from it `readEntitlementLicense`, the single entry point upstream prescribes, plus `detectLicenseKeyFormat`, -`toIsoBuildDate`, `CHECKSUM_LENGTH`, `sha512`, `stringToUtf8Bytes` and the types - from -`src/license/licenseResolution.ts`, `src/helpers/licenseKeyValidator.ts` and -`src/interpreter/plugin/VersionPlugin.ts`, which sit outside the copy, as upstream's guide -prescribes. The reader verifies the key (the checksum and, from format version 2, the prose +`toIsoBuildDate` and the types - from +`src/license/licenseResolution.ts` and `src/helpers/licenseKeyValidator.ts`, which sit outside the +copy, as upstream's guide prescribes. The reader verifies the key (the checksum and, from format version 2, the prose digest), picks HyperFormula's entry, places it in its lifecycle window and reads its flags. HyperFormula keeps what the guide leaves to the product: the meaning of the capability tokens -(`src/license/capabilities.ts`), the console messages, and the identity a key is printed once -under. The test suite mints keys with the test-only exports `canonicalizeProse`, +(`src/license/capabilities.ts`) and the console messages. The test suite mints keys with the test-only exports `canonicalizeProse`, `computeProseDigest`, `computePayloadChecksum` and `stringToBase64Url`, as upstream's README shows. Upstream's `README.md` in this directory is the integration guide; `AGENTS.md` is theirs too. diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index 7b18a866f3..a85ef845c7 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -7,8 +7,8 @@ import { checkLicenseKeyValidity, LicenseKeyValidityState, notifyEntitlementKey, + notifyUnlicensedEntitlementKey, } from '../helpers/licenseKeyValidator' -import {CAPABILITY_TABLE, normalizeCapabilityToken} from './capabilities' import {LicenseEntitlement, LicenseExpiry, unrestrictedEntitlement} from './LicenseEntitlement' import {detectLicenseKeyFormat} from './handsontable-license-key-parser/detectFormat' import {readEntitlementLicense} from './handsontable-license-key-parser/readLicense' @@ -87,9 +87,8 @@ function expiryOf(entry: ProductEntitlement): LicenseExpiry { /** * Turns HyperFormula's entry of a valid entitlement key into the entitlement it grants. * - * This is fail-closed and silent: a token this version does not recognize - * is recorded in `unrecognizedCapabilities` and grants nothing, without a warning, a message, or - * anything public to read it back from. "Silent" there means the *grant* is silent — whether the + * This is fail-closed and silent: a token this version does not recognize grants nothing, without + * a warning, a message, or anything public to read it back from. "Silent" there means the *grant* is silent — whether the * key's console messages are suppressed is decided solely by its `no-console-warns` flag, never * by the presence of an unrecognized token; coupling the two would suppress expiry notices as a * side effect of a vocabulary mismatch. @@ -99,22 +98,13 @@ function expiryOf(entry: ProductEntitlement): LicenseExpiry { * @param {boolean} silent - whether the key closes the console channel */ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: boolean): LicenseEntitlement { - // Appended one by one rather than with `push(...entry.capabilities)`. The array comes from an - // attacker-influenced payload and the format sets no size limit, and spreading an array into a - // call puts one argument per stack slot: measured, a checksum-valid key carrying 125 000 tokens - // threw `RangeError: Maximum call stack size exceeded` out of `HyperFormula.buildFromArray` - // instead of resolving to a verdict. - const capabilityTokens: string[] = [] - entry.capabilities.forEach((token) => capabilityTokens.push(token)) - - const unrecognizedCapabilities = capabilityTokens.filter( - (token) => !CAPABILITY_TABLE.has(normalizeCapabilityToken(token)), - ) - return { unrestricted: false, - capabilities: new Set(capabilityTokens), - unrecognizedCapabilities, + // Never spread into a call (`push(...entry.capabilities)`): the array comes from an + // attacker-influenced payload with no size limit, and a spread puts one argument per stack + // slot - measured, a checksum-valid key carrying 125 000 tokens threw `RangeError: Maximum + // call stack size exceeded` out of `HyperFormula.buildFromArray`. + capabilities: new Set(entry.capabilities), expiry: expiryOf(entry), silent, isTrial, @@ -180,7 +170,7 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true // `unreadable` (a broken block, or edited or missing prose) and `product_missing` (a key for other products only) both // resolve to an invalid key that restricts nothing; only their console messages differ. if (notifyConsole) { - notifyEntitlementKey(licenseKey, license.reason, {licensedUntil: null, daysRemaining: null}) + notifyUnlicensedEntitlementKey(license.reason) } return {validityState: LicenseKeyValidityState.INVALID, blocksEvaluation: true, entitlement: unrestrictedEntitlement()} @@ -194,7 +184,8 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true // The message is chosen by the reader's state and prints the key's own date (the key // specification's text, the same table Handsontable uses). The `no-console-warns` flag closes the channel. if (notifyConsole && channels.console) { - notifyEntitlementKey(licenseKey, lifecycle.state, {licensedUntil: lifecycle.licensedUntil, daysRemaining: lifecycle.daysRemaining}) + // The reader sets `licensedUntil` for every key it licenses: the entry's own governing date. + notifyEntitlementKey(lifecycle.state, {licensedUntil: lifecycle.licensedUntil as string, daysRemaining: lifecycle.daysRemaining}) } return { From 9f34759a76b6262ba1ac23a692d67dba61ff62b2 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 12:47:31 +0200 Subject: [PATCH 38/54] HF-307: document that a bad key blocks the gated API, and VERSION's new output - The license key guide says that a missing or invalid key blocks every gated API method with a LicenseCapabilityMissingError, lists the gated methods, and says what keeps working. - VERSION's catalogue description and the changelog say that it returns only the version. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ docs/guide/license-key.md | 18 ++++++++++++------ .../functionMetadata/categories/information.ts | 2 +- 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cd87687dfe..23225fb8e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Added support for the new license key format. A proprietary key can now grant a subset of the library: a function your key does not include evaluates to a `#LIC!` error, and the matching parts of the API throw a `LicenseCapabilityMissingError`. `getAvailableFunctions()` and `getFunctionDetails()` describe only the functions your key includes. [#1728](https://github.com/handsontable/hyperformula/pull/1728) +### Changed + +- Changed the `VERSION` function to return only the HyperFormula version (e.g. `HyperFormula v3.4.0`), without the license key status. [#1728](https://github.com/handsontable/hyperformula/pull/1728) + ### Fixed - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index 362dc413d5..7a6139eb3c 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -70,18 +70,24 @@ If your key grants only part of the library, then: functions your key includes, so a function picker built from them never offers a function that then fails. - ## License key notifications If your license key is missing, invalid, or expired, you see a corresponding notification in the console. -A missing or invalid key makes every licence-gated function call evaluate to a `#LIC!` error — but -no API method starts throwing, and `getAvailableFunctions()` still describes the full set of -functions. A key problem never narrows what the library reports it can do. +A missing or invalid key blocks the library: + +* Every function call evaluates to a `#LIC!` error, except `VERSION()` and `OFFSET()`. +* Every license-gated API method throws a `LicenseCapabilityMissingError` that names the key's + state, for example: `License key is missing. Feature crud is not available.` The gated methods + are the ones that edit cells, rows, columns, and sheets, `copy()`, `cut()`, `paste()`, `undo()`, + `redo()`, `batch()`, `suspendEvaluation()`, and the methods that add, change, or remove named + expressions. Building an engine with named expressions throws the same error. +* Getters and clean-up methods, such as `clearClipboard()` and `resumeEvaluation()`, keep working, + and `getAvailableFunctions()` still describes the full set of functions. -Depending on your license terms, an expired key either behaves the same way, or keeps working with -what it grants and prints an error in the console. +Depending on your license terms, an expired key either blocks the library in the same way, or keeps +working with what it grants and prints an error in the console. ## License key support diff --git a/src/interpreter/functionMetadata/categories/information.ts b/src/interpreter/functionMetadata/categories/information.ts index 56fb78adba..fd18cd79b6 100644 --- a/src/interpreter/functionMetadata/categories/information.ts +++ b/src/interpreter/functionMetadata/categories/information.ts @@ -135,7 +135,7 @@ export const INFORMATION_DOCS: Record = { // repeatLastArgs) is authored separately in `PROTECTED_FUNCTION_METADATA`. VERSION: { category: 'Information', - shortDescription: 'Returns the HyperFormula version and the license key status as a single text value, e.g. "HyperFormula v3.0.0, 1" (a status code, or the last five characters of the license key).', + shortDescription: 'Returns the HyperFormula version as a text value, e.g. "HyperFormula v3.0.0".', parameters: [], documentationUrl: 'https://hyperformula.handsontable.com/docs/guide/built-in-functions.html', examples: ['=VERSION()'], From c341a14423e8ad3ce1f1876cd05f1f852b773259 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 12:47:31 +0200 Subject: [PATCH 39/54] HF-307: make the vendored-reader drift check robust - Requests time out after 30 s and the job after 10 minutes; a failure is reported as an access, network or configuration problem (a 301 is a moved or renamed repository), never as drift. - Only files git tracks are compared, as git stores them, so untracked files and CRLF checkouts no longer fail the check. - Tags are read 100 per page following the pagination, a leading "v" and prerelease suffixes are understood, and files are fetched at the pinned commit rather than the tag. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/vendored-parser.yml | 1 + script/check-license-key-parser-drift.js | 143 ++++++++++++++++------- 2 files changed, 100 insertions(+), 44 deletions(-) diff --git a/.github/workflows/vendored-parser.yml b/.github/workflows/vendored-parser.yml index 306152cac2..7202b0e694 100644 --- a/.github/workflows/vendored-parser.yml +++ b/.github/workflows/vendored-parser.yml @@ -28,6 +28,7 @@ jobs: drift: if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest + timeout-minutes: 10 steps: - name: Checkout uses: actions/checkout@722adc63f1aa60a57ec37892e133b1d319cae598 # https://github.com/actions/checkout/releases/tag/v2.0.0 diff --git a/script/check-license-key-parser-drift.js b/script/check-license-key-parser-drift.js index b5b7e61d11..09fd8d1b4b 100755 --- a/script/check-license-key-parser-drift.js +++ b/script/check-license-key-parser-drift.js @@ -12,9 +12,9 @@ * from a tagged release, and do not edit the copy ... add a drift check to CI"). This is that check. * * What it does, per `upstream.json`: - * - lists the upstream directory at the pinned `tag` and compares EVERY file byte for byte - * against the local one - upstream's `diff -r`, without needing a clone; - * - fails on a local file upstream does not have (other than `own_files`) - a shadowing + * - lists the upstream directory at the pinned `commit` and compares EVERY file byte for byte + * against the local one as git tracks it - upstream's `diff -r`, without needing a clone; + * - fails on a tracked local file upstream does not have (other than `own_files`) - a shadowing * `foo.ts` beside a copied `foo.ts` would otherwise win module resolution silently; * - fails on an upstream file that is missing locally; * - checks that the pinned `tag` still points at the pinned `commit`, so a moved tag or an edited @@ -42,7 +42,8 @@ const crypto = require('crypto') const https = require('https') const {execFileSync} = require('child_process') -const DIR = path.resolve(__dirname, '../src/license/handsontable-license-key-parser') +const REPO_ROOT = path.resolve(__dirname, '..') +const DIR = path.resolve(REPO_ROOT, 'src/license/handsontable-license-key-parser') const PIN = path.join(DIR, 'upstream.json') function token() { @@ -58,12 +59,16 @@ function token() { } } +/** How long a request may wait for the API before the check gives up on it. */ +const REQUEST_TIMEOUT_MS = 30000 + function get(apiPath, accept, auth) { return new Promise((resolve, reject) => { - https.get({ + const request = https.get({ hostname: 'api.github.com', path: apiPath, headers: {'Accept': accept, 'User-Agent': 'hyperformula-vendored-parser-check', 'Authorization': `Bearer ${auth}`}, + timeout: REQUEST_TIMEOUT_MS, }, (response) => { const chunks = [] @@ -80,25 +85,67 @@ function get(apiPath, accept, auth) { reject(error) } }) - }).on('error', reject) + }) + + request.on('timeout', () => request.destroy(new Error(`no response within ${REQUEST_TIMEOUT_MS / 1000} s`))) + request.on('error', reject) }) } +/** + * Why a request failed, worded so that it is never mistaken for drift: a 301 is a renamed or moved + * repository (a configuration problem), any other HTTP status is an access problem, and an error + * with no status (a timeout, a dropped connection) is a network problem. + */ +function describeFailure(error) { + if (error.statusCode === 301) { + return 'HTTP 301: the repository moved or was renamed - update `repository` in upstream.json. A configuration problem, not drift' + } + if (error.statusCode !== undefined) { + return `HTTP ${error.statusCode} - access, not drift` + } + + return `${error.message} - a network problem, not drift` +} + const sha256 = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex') -function semverGreater(a, b) { - const pa = a.split('.').map(Number) - const pb = b.split('.').map(Number) +/** + * The `[major, minor, patch]` a tag names, or `null` for a tag that is not a version. A leading `v` + * is ignored, and so is a prerelease suffix (`-rc.1`): a prerelease counts as newer than the pin + * only when the version it leads up to is newer. + */ +function baseVersionOf(tag) { + const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?$/.exec(tag) + + return match === null ? null : [Number(match[1]), Number(match[2]), Number(match[3])] +} +/** Whether version `a` (`[major, minor, patch]`) is greater than version `b`. */ +function versionGreater(a, b) { for (let i = 0; i < 3; i++) { - if ((pa[i] || 0) !== (pb[i] || 0)) { - return (pa[i] || 0) > (pb[i] || 0) + if (a[i] !== b[i]) { + return a[i] > b[i] } } return false } +/** Every tag of an upstream repository, following the pagination, 100 per page. */ +async function listTags(repo, auth) { + const tags = [] + + for (let page = 1; ; page++) { + const batch = JSON.parse((await get(`/repos/${repo}/tags?per_page=100&page=${page}`, 'application/vnd.github+json', auth)).toString('utf8')) + + tags.push(...batch) + if (batch.length < 100) { + return tags + } + } +} + /** Every file under an upstream directory at a ref, recursively, as `relative path -> api path`. */ async function listUpstream(repo, dir, ref, auth) { const out = new Map() @@ -121,24 +168,28 @@ async function listUpstream(repo, dir, ref, auth) { return out } -/** Every file under the local directory, recursively, relative. */ -function listLocal(root) { - const out = [] - const walk = (sub) => { - fs.readdirSync(path.join(root, sub), {withFileTypes: true}).forEach((entry) => { - const rel = sub ? `${sub}/${entry.name}` : entry.name +/** A path under the repository root as git spells it: relative, with forward slashes. */ +const gitPath = (absolute) => path.relative(REPO_ROOT, absolute).split(path.sep).join('/') - if (entry.isDirectory()) { - walk(rel) - } else { - out.push(rel) - } - }) - } +/** + * Every file git tracks under the local directory, recursively, relative to it. Untracked files + * (`.DS_Store`, editor leftovers) are not part of the copy, so they are not compared. + */ +function listTracked(root) { + const prefix = `${gitPath(root)}/` - walk('') + return execFileSync('git', ['ls-files', '-z', '--', prefix], {cwd: REPO_ROOT, encoding: 'utf8'}) + .split('\0') + .filter((file) => file !== '') + .map((file) => file.slice(prefix.length)) +} - return out +/** + * A tracked file's content as git stores it (the index), not as it was checked out, so a checkout + * that converts line endings to CRLF does not read as drift. An edit is compared once it is staged. + */ +function readTracked(root, rel) { + return execFileSync('git', ['show', `:${gitPath(path.join(root, rel))}`], {cwd: REPO_ROOT, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024}) } async function main() { @@ -159,7 +210,7 @@ async function main() { // The pin first: a tag that moved, or a pin edited by hand, is named as that - before any // listing at the tag can fail for a different reason and blame access. try { - const tags = JSON.parse((await get(`/repos/${pin.repository}/tags?per_page=20`, 'application/vnd.github+json', auth)).toString('utf8')) + const tags = await listTags(pin.repository, auth) const pinned = tags.find((t) => t.name === pin.tag) if (pinned === undefined) { @@ -168,41 +219,45 @@ async function main() { problems.push(`tag ${pin.tag} points at ${pinned.commit.sha.slice(0, 9)}, the pin says ${pin.commit.slice(0, 9)} - the tag moved or the pin was edited`) } - const pinIsRelease = /^\d+\.\d+\.\d+$/.test(pin.tag) - const newer = pinIsRelease - ? tags.map((t) => t.name).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && semverGreater(name, pin.tag)) - : [] + const pinVersion = baseVersionOf(pin.tag) + const newer = pinVersion === null + ? [] + : tags.map((t) => t.name).filter((name) => { + const version = baseVersionOf(name) + + return version !== null && versionGreater(version, pinVersion) + }) if (newer.length > 0) { problems.push(`upstream has released ${newer.join(', ')} after ${pin.tag}. Review the change and re-take the copy from the newest tag.`) } } catch (error) { - problems.push(`could not list upstream tags (HTTP ${error.message}) - access, not drift`) + problems.push(`could not list upstream tags: ${describeFailure(error)}`) } let upstream try { - upstream = await listUpstream(pin.repository, pin.directory, pin.tag, auth) + // At the pinned commit, not the tag: a tag moved after the check above cannot change what is compared. + upstream = await listUpstream(pin.repository, pin.directory, pin.commit, auth) } catch (error) { // Whatever the pin check already found is the more likely cause of this failure - say it first. problems.forEach((p) => console.error(`\nFAIL ${p}`)) - console.error(`\nFAIL could not list ${pin.repository}/${pin.directory} at ${pin.tag}: HTTP ${error.message}.`) - console.error(error.statusCode === 404 - ? ' 404 from a private repository means the token has no access to it, the tag does not exist, or the directory does not exist at that ref. This is not drift.' - : ' This is an access or network problem, not drift.') + console.error(`\nFAIL could not list ${pin.repository}/${pin.directory} at ${pin.tag}: ${describeFailure(error)}.`) + if (error.statusCode === 404) { + console.error(' 404 from a private repository means the token has no access to it, the tag does not exist, or the directory does not exist at that ref.') + } process.exit(1) } const divergences = new Map((pin.allowed_divergences || []).map((d) => [d.file, d])) const own = new Set(pin.own_files || []) - const local = listLocal(DIR).filter((rel) => !own.has(rel)) + const tracked = new Set(listTracked(DIR)) + const local = Array.from(tracked).filter((rel) => !own.has(rel)) for (const [rel, apiPath] of upstream) { - const localPath = path.join(DIR, rel) - - if (!fs.existsSync(localPath)) { + if (!tracked.has(rel)) { problems.push(`${rel}: in upstream at ${pin.tag}, missing here`) console.log(` GONE ${rel}`) continue @@ -211,9 +266,9 @@ async function main() { let theirs try { - theirs = (await get(`/repos/${pin.repository}/contents/${apiPath}?ref=${encodeURIComponent(pin.tag)}`, 'application/vnd.github.raw', auth)).toString('utf8') + theirs = (await get(`/repos/${pin.repository}/contents/${apiPath}?ref=${encodeURIComponent(pin.commit)}`, 'application/vnd.github.raw', auth)).toString('utf8') } catch (error) { - problems.push(`${rel}: upstream could not be read (HTTP ${error.message}) - access, not drift`) + problems.push(`${rel}: upstream could not be read: ${describeFailure(error)}`) console.log(` ???? ${rel}`) continue } @@ -231,7 +286,7 @@ async function main() { theirs = theirs.replace(shim.upstream, shim.local) } - const ours = fs.readFileSync(localPath, 'utf8') + const ours = readTracked(DIR, rel) if (sha256(Buffer.from(ours)) === sha256(Buffer.from(theirs))) { console.log(` ok ${rel}${shim ? ' (1 allowed divergence applied)' : ''}`) From 459ef8268c6d2da43dd0944f41e6c46672a179df Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 14:03:59 +0200 Subject: [PATCH 40/54] HF-307: classify drift-check failures precisely and name the pinned commit - Read tracked files with `:./path`, so they resolve from the repository root like the listing does, also when the checkout sits inside another repository. - Failures are classified as a moved repository (301), no access (401/403/404), a GitHub API problem (any other status), a network problem (a socket error or timeout) or an unexpected response. - Messages and the 404 hint name the pinned commit the files are read at, not only the tag. Co-Authored-By: Claude Opus 5.5 --- script/check-license-key-parser-drift.js | 41 +++++++++++++------ .../PROVENANCE.md | 4 +- 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/script/check-license-key-parser-drift.js b/script/check-license-key-parser-drift.js index 09fd8d1b4b..5a64d371d9 100755 --- a/script/check-license-key-parser-drift.js +++ b/script/check-license-key-parser-drift.js @@ -88,24 +88,39 @@ function get(apiPath, accept, auth) { }) request.on('timeout', () => request.destroy(new Error(`no response within ${REQUEST_TIMEOUT_MS / 1000} s`))) - request.on('error', reject) + // Anything the socket reports - a timeout, a refused or dropped connection, a failed DNS lookup - + // is a network problem; describeFailure tells it apart from an HTTP status or a bad response. + request.on('error', (error) => { + error.network = true + reject(error) + }) }) } +/** HTTP statuses that mean the token cannot see the repository, the ref or the path. */ +const ACCESS_STATUSES = [401, 403, 404] + /** * Why a request failed, worded so that it is never mistaken for drift: a 301 is a renamed or moved - * repository (a configuration problem), any other HTTP status is an access problem, and an error - * with no status (a timeout, a dropped connection) is a network problem. + * repository (a configuration problem), 401/403/404 are access problems, any other HTTP status is a + * problem on GitHub's side (an outage or a rate limit), a socket error is a network problem, and + * anything else is a response this check could not read. */ function describeFailure(error) { if (error.statusCode === 301) { return 'HTTP 301: the repository moved or was renamed - update `repository` in upstream.json. A configuration problem, not drift' } - if (error.statusCode !== undefined) { + if (ACCESS_STATUSES.indexOf(error.statusCode) !== -1) { return `HTTP ${error.statusCode} - access, not drift` } + if (error.statusCode !== undefined) { + return `HTTP ${error.statusCode} - a GitHub API problem (an outage or a rate limit), not drift` + } + if (error.network === true) { + return `${error.message} - a network problem, not drift` + } - return `${error.message} - a network problem, not drift` + return `${error.message} - an unexpected response from the GitHub API, not drift` } const sha256 = (buffer) => crypto.createHash('sha256').update(buffer).digest('hex') @@ -189,14 +204,16 @@ function listTracked(root) { * that converts line endings to CRLF does not read as drift. An edit is compared once it is staged. */ function readTracked(root, rel) { - return execFileSync('git', ['show', `:${gitPath(path.join(root, rel))}`], {cwd: REPO_ROOT, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024}) + // `:./` resolves the path from REPO_ROOT, as `git ls-files` does above; a bare `:` would resolve + // it from the top of the work tree, which is not REPO_ROOT when this repository sits inside another. + return execFileSync('git', ['show', `:./${gitPath(path.join(root, rel))}`], {cwd: REPO_ROOT, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024}) } async function main() { const pin = JSON.parse(fs.readFileSync(PIN, 'utf8')) const auth = token() - console.log(`vendored reader: ${pin.repository}/${pin.directory} @ ${pin.tag}`) + console.log(`vendored reader: ${pin.repository}/${pin.directory} @ ${pin.tag} (${pin.commit.slice(0, 9)})`) if (auth === null) { console.error('\nFAIL no credentials for a private repository.') @@ -244,9 +261,9 @@ async function main() { } catch (error) { // Whatever the pin check already found is the more likely cause of this failure - say it first. problems.forEach((p) => console.error(`\nFAIL ${p}`)) - console.error(`\nFAIL could not list ${pin.repository}/${pin.directory} at ${pin.tag}: ${describeFailure(error)}.`) + console.error(`\nFAIL could not list ${pin.repository}/${pin.directory} at commit ${pin.commit.slice(0, 9)}: ${describeFailure(error)}.`) if (error.statusCode === 404) { - console.error(' 404 from a private repository means the token has no access to it, the tag does not exist, or the directory does not exist at that ref.') + console.error(' 404 from a private repository means the token has no access to it, the pinned commit does not exist upstream, or the directory does not exist at that commit.') } process.exit(1) } @@ -258,7 +275,7 @@ async function main() { for (const [rel, apiPath] of upstream) { if (!tracked.has(rel)) { - problems.push(`${rel}: in upstream at ${pin.tag}, missing here`) + problems.push(`${rel}: in upstream at ${pin.tag} (${pin.commit.slice(0, 9)}), missing here`) console.log(` GONE ${rel}`) continue } @@ -291,7 +308,7 @@ async function main() { if (sha256(Buffer.from(ours)) === sha256(Buffer.from(theirs))) { console.log(` ok ${rel}${shim ? ' (1 allowed divergence applied)' : ''}`) } else { - problems.push(`${rel}: differs from upstream at ${pin.tag}`) + problems.push(`${rel}: differs from upstream at ${pin.tag} (${pin.commit.slice(0, 9)})`) console.log(` DIFF ${rel}`) } } @@ -302,7 +319,7 @@ async function main() { }) if (problems.length === 0) { - console.log(`\nOK - the directory is upstream's ${pin.directory} at ${pin.tag}, byte for byte${divergences.size ? `, with ${divergences.size} declared divergence(s)` : ''}`) + console.log(`\nOK - the directory is upstream's ${pin.directory} at ${pin.tag} (${pin.commit.slice(0, 9)}), byte for byte${divergences.size ? `, with ${divergences.size} declared divergence(s)` : ''}`) return } diff --git a/src/license/handsontable-license-key-parser/PROVENANCE.md b/src/license/handsontable-license-key-parser/PROVENANCE.md index 79e1a6d99b..36aa544e85 100644 --- a/src/license/handsontable-license-key-parser/PROVENANCE.md +++ b/src/license/handsontable-license-key-parser/PROVENANCE.md @@ -18,7 +18,7 @@ and re-taken: a local fix makes two products disagree about the same key. `extractKeyData.ts`, one line: `Object.keys(current)` → `Object.keys(current as object)`. HyperFormula compiles with TypeScript 4.0.8, which does not narrow `unknown` through `!== null && typeof === 'object'`; upstream compiles under 5.9, and TypeScript 4.5 is where the line starts to compile -uncast. The cast changes no behaviour. It is recorded in `upstream.json` with its reason, and the +uncast. The cast changes no behavior. It is recorded in `upstream.json` with its reason, and the check below applies it before comparing. A tag is immutable, so the check does not see upstream fix the line on a branch; it sees the next tag - a newer tag fails the check - and at the re-take the swap stops matching once upstream has changed the line, so the fix cannot be missed. A tag that leaves the @@ -31,7 +31,7 @@ npm run check:license-key-parser-drift ``` Checks that the pinned tag still resolves to the pinned commit, lists the upstream directory at that -tag and compares every file byte for byte. Fails on a moved tag or an edited pin, on any difference, +commit and compares every file git tracks here with it byte for byte. Fails on a moved tag or an edited pin, on any difference, on a file here that upstream does not have (a shadowing `.ts` would win module resolution silently), on an upstream file missing here, and on a **newer upstream tag** than the pin. Without credentials to the private repository it fails rather than skips. From 0d00cec6a36b0fb165ae8ff66f4617396dae81ae Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 14:03:59 +0200 Subject: [PATCH 41/54] HF-307: make isItPossibleTo* agree with the license, and correct the license docs - The isItPossibleTo* predicates answer false when the method they ask about would throw a LicenseCapabilityMissingError: under a key that blocks evaluation, or a key without the feature. isFeatureAllowed is the one rule behind them and ensureFeatureAllowed. - Comments and the API reference distinguish a key that blocks evaluation (missing, invalid, an expired classic key, a trial past its grace period), which restricts nothing by grant, from an expired key that keeps evaluating with its own grants. The @throws lines of the gated methods also cover a key that blocks evaluation. - The static getRegisteredFunctionNames no longer claims the instance form answers under the license. - types-of-errors.md and the license key guide describe the same rules. - The changelog gains a Fixed entry for the time-zone bug in classic-key validation that this PR fixes. - Use US spelling. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/guide/license-key.md | 2 + docs/guide/types-of-errors.md | 2 +- src/HyperFormula.ts | 189 +++++++++++++++++++++------- src/errors.ts | 8 +- src/license/LicenseEntitlement.ts | 21 +++- src/license/capabilities.ts | 4 +- src/license/ensureFeatureAllowed.ts | 31 +++-- src/license/functionCapabilities.ts | 2 +- src/license/licenseResolution.ts | 32 ++--- 10 files changed, 208 insertions(+), 84 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 23225fb8e1..86e10ac598 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Fixed +- Fixed the validation of classic (25-character) license keys depending on the time zone: east of UTC, a key that expired the day before the build was released was still accepted, and west of UTC, the console message printed an expiry date one day too early. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) - Fixed the localized names of `VSTACK` and `HSTACK` in 14 language packs to match Microsoft Excel. [#1748](https://github.com/handsontable/hyperformula/pull/1748) - Fixed the MAXPOOL and MEDIANPOOL functions throwing an uncaught `TypeError` instead of returning the `#VALUE!` error when the range dimensions are not a whole multiple of the window size and the stride. [#1718](https://github.com/handsontable/hyperformula/pull/1718) diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index 7a6139eb3c..3537113d2c 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -65,6 +65,7 @@ If your key grants only part of the library, then: [error value](types-of-errors.md). Everything else in the sheet keeps calculating. * An API method your key doesn't include throws a `LicenseCapabilityMissingError` when you call it. Getters never throw; `copy()` and `cut()` do, because they belong to the clipboard feature. + The matching `isItPossibleTo*()` methods, such as `isItPossibleToAddRows()`, return `false`. * [`getAvailableFunctions()`](../api/classes/hyperformula.md#getavailablefunctions) and [`getFunctionDetails()`](../api/classes/hyperformula.md#getfunctiondetails) describe only the functions your key includes, so a function picker built from them never offers a function that @@ -83,6 +84,7 @@ A missing or invalid key blocks the library: are the ones that edit cells, rows, columns, and sheets, `copy()`, `cut()`, `paste()`, `undo()`, `redo()`, `batch()`, `suspendEvaluation()`, and the methods that add, change, or remove named expressions. Building an engine with named expressions throws the same error. +* The `isItPossibleTo*()` methods return `false` for every gated method. * Getters and clean-up methods, such as `clearClipboard()` and `resumeEvaluation()`, keep working, and `getAvailableFunctions()` still describes the full set of functions. diff --git a/docs/guide/types-of-errors.md b/docs/guide/types-of-errors.md index 3a0ab3b45c..8a7ba22c4a 100644 --- a/docs/guide/types-of-errors.md +++ b/docs/guide/types-of-errors.md @@ -37,4 +37,4 @@ according to the language settings. | #VALUE! | Wrong type of argument | It occurs when a formula tries to improperly use different types of data. For example, you will see this error when you will try to add a string to a number. | | #CYCLE! | Circular reference | It occurs when a formula refers to its own cell, both directly and indirectly. | | #ERROR! | An error occurred | It indicates that there is an unknown error in a formula. | -| #LIC! | License key problem | It occurs when the license key is invalid, expired, or missing, or when the function is not included in the [feature package](license-key.md#feature-packages-and-add-ons) your license key grants. | \ No newline at end of file +| #LIC! | License key problem | It occurs when the license key is missing or invalid, when it has expired and your [license terms](license-key.md#license-key-notifications) stop it from working after that, or when the function is not included in the [feature package](license-key.md#feature-packages-and-add-ons) your license key grants. | \ No newline at end of file diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index aedae7934d..a67b61c132 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -44,7 +44,7 @@ import {Evaluator} from './Evaluator' import {ExportedChange, Exporter} from './Exporter' import {LicenseKeyValidityState} from './helpers/licenseKeyValidator' import {licenseAllowsFunction} from './license/CapabilityRegistry' -import {ensureFeatureAllowed} from './license/ensureFeatureAllowed' +import {ensureFeatureAllowed, isFeatureAllowed} from './license/ensureFeatureAllowed' import {FeatureId} from './license/LicenseEntitlement' import {buildTranslationPackage, RawTranslationPackage, TranslationPackage} from './i18n' import {FunctionPluginDefinition} from './interpreter' @@ -256,7 +256,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits * @throws [[InvalidArgumentsError]] when sheet is not an array of arrays * @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata - * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the current license entitlement does not grant the NamedExpressions feature + * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the license key is missing or invalid, has expired and blocks evaluation, or does not grant the NamedExpressions feature * * @example * ```js @@ -297,7 +297,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[SheetSizeLimitExceededError]] when sheet size exceeds the limits * @throws [[InvalidArgumentsError]] when any sheet is not an array of arrays * @throws [[FunctionPluginValidationError]] when plugin class definition is not consistent with metadata - * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the current license entitlement does not grant the NamedExpressions feature + * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the license key is missing or invalid, has expired and blocks evaluation, or does not grant the NamedExpressions feature * * @example * ```js @@ -340,7 +340,7 @@ export class HyperFormula implements TypedEmitter { * @param {Partial} configInput - engine configuration * @param {SerializedNamedExpression[]} namedExpressions - starting named expressions * - * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the current license entitlement does not grant the NamedExpressions feature + * @throws [[LicenseCapabilityMissingError]] if namedExpressions is non-empty and the license key is missing or invalid, has expired and blocks evaluation, or does not grant the NamedExpressions feature * * @example * ```js @@ -604,7 +604,9 @@ export class HyperFormula implements TypedEmitter { * * The two forms answer different questions and neither replaces the other: this one translates * into any registered language without building an engine, while the instance method of the same - * name answers for the engine you actually hold, under that instance's own language and license. + * name answers for the engine you actually hold, in that instance's own language. Neither form + * looks at the license key: to list only the functions an instance can evaluate, use + * [[getAvailableFunctions]]. * * @param {string} code - language code * @@ -718,17 +720,19 @@ export class HyperFormula implements TypedEmitter { * Whether an instance's license lets it evaluate the given function id, and therefore whether the * metadata API may describe it. Mirrors the gate-B branch the interpreter runs per function call * (`Interpreter.evaluateAstWithoutPostprocessing`, the `FUNCTION_CALL` case), through the same - * [[licenseAllowsFunction]] rule and the same alias canonicalisation, so a listed function is + * [[licenseAllowsFunction]] rule and the same alias canonicalization, so a listed function is * always one that actually evaluates. * - * Gate B only, deliberately — never the license key's validity state. A missing, invalid or expired - * key resolves to an unrestricted entitlement (the invariant `resolveLicense` documents), so it + * Gate B only, deliberately — never the license key's validity state. A key that blocks + * evaluation (a missing or invalid key, an expired classic key, or a trial past its grace period) + * resolves to an unrestricted entitlement (the invariant `resolveLicense` documents), so it * reaches this method with both `licenseCapabilities` axes set to `'all'` and every function * stays listed. * That is the intended answer: a key problem is reported on the console and by `#LIC!` in cells, - * and narrowing the catalogue to the two protected built-ins would leave an integrator who has not + * and narrowing the catalog to the two protected built-ins would leave an integrator who has not * wired up their key yet with an empty function picker and no clue why. The list narrows only for - * a *valid* key that genuinely does not include a function — the case where the answer is useful. + * a key that evaluates (a valid one, or an expired one that keeps working with its own grants) and + * genuinely does not include a function — the case where the answer is useful. * * @param {string} functionId - the id as registered, which may be an alias * @param {FunctionRegistry} functionRegistry - the engine's registry, which resolves the alias map @@ -1269,7 +1273,7 @@ export class HyperFormula implements TypedEmitter { * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoOperationToUndoError]] when there is no operation running that can be undone - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the UndoRedo feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the UndoRedo feature * * @example * ```js @@ -1305,7 +1309,7 @@ export class HyperFormula implements TypedEmitter { * @fires [[valuesUpdated]] if recalculation was triggered by this change * * @throws [[NoOperationToRedoError]] when there is no operation running that can be re-done - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the UndoRedo feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the UndoRedo feature * * @example * ```js @@ -1383,6 +1387,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to change the content in a rectangular area bounded by the box. * If returns `true`, doing [[setCellContents]] operation won't throw any errors. * Returns `false` if the address is invalid or the sheet does not exist. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {SimpleCellAddress | SimpleCellRange} address - single cell or block of cells to check * @@ -1408,6 +1413,9 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public isItPossibleToSetCellContents(address: SimpleCellAddress | SimpleCellRange): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } let range if (isSimpleCellAddress(address)) { range = new AbsoluteCellRange(address, address) @@ -1443,7 +1451,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[InvalidArgumentsError]] when the value is not an array of arrays or a raw cell value * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding * @throws [[ExpectedValueOfTypeError]] if topLeftCornerAddress argument is of wrong type - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -1483,7 +1491,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -1524,6 +1532,7 @@ export class HyperFormula implements TypedEmitter { /** * Checks if it is possible to reorder rows of a sheet according to a source-target mapping. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - ID of a sheet to operate on * @param {[number, number][]} rowMapping - array mapping original positions to final positions of rows @@ -1548,6 +1557,9 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public isItPossibleToSwapRowIndexes(sheetId: number, rowMapping: [number, number][]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') try { this._crudOperations.validateSwapRowIndexes(sheetId, rowMapping) @@ -1580,7 +1592,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when rowMapping does not define correct row permutation for some subset of rows of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -1609,6 +1621,7 @@ export class HyperFormula implements TypedEmitter { /** * Checks if it is possible to reorder rows of a sheet according to a permutation. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * Parameter `newRowOrder` should have the form `[ newPositionForRow0, newPositionForRow1, newPositionForRow2, ... ]`, * i.e. the value at index `i` is the new position for the row that is currently at index `i`. @@ -1637,6 +1650,9 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public isItPossibleToSetRowOrder(sheetId: number, newRowOrder: number[]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') try { const rowMapping = this._crudOperations.mappingFromOrder(sheetId, newRowOrder, 'row') @@ -1664,7 +1680,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -1704,6 +1720,7 @@ export class HyperFormula implements TypedEmitter { /** * Checks if it is possible to reorder columns of a sheet according to a source-target mapping. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @fires [[valuesUpdated]] if recalculation was triggered by this change * @@ -1725,6 +1742,9 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public isItPossibleToSwapColumnIndexes(sheetId: number, columnMapping: [number, number][]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') try { this._crudOperations.validateSwapColumnIndexes(sheetId, columnMapping) @@ -1757,7 +1777,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when columnMapping does not define correct column permutation for some subset of columns of the given sheet * @throws [[SourceLocationHasArrayError]] when the selected position has array inside - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -1784,6 +1804,7 @@ export class HyperFormula implements TypedEmitter { /** * Checks if it is possible to reorder columns of a sheet according to a permutation. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * Parameter `newColumnOrder` should have the form `[ newPositionForColumn0, newPositionForColumn1, newPositionForColumn2, ... ]`, * i.e. the value at index `i` is the new position for the column that is currently at index `i`. @@ -1810,6 +1831,9 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public isItPossibleToSetColumnOrder(sheetId: number, newColumnOrder: number[]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') try { const columnMapping = this._crudOperations.mappingFromOrder(sheetId, newColumnOrder, 'column') @@ -1826,6 +1850,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that addRows can be called. * If returns `true`, doing [[addRows]] operation won't throw any errors. * Returns `false` if adding rows would exceed the sheet size limit or given arguments are invalid. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - sheet ID in which rows will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [row, amount], where row is a row number above which the rows will be added @@ -1846,6 +1871,9 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public isItPossibleToAddRows(sheetId: number, ...indexes: ColumnRowIndex[]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') const normalizedIndexes = normalizeAddedIndexes(indexes) try { @@ -1872,7 +1900,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -1900,6 +1928,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that removeRows can be called. * If returns `true`, doing [[removeRows]] operation won't throw any errors. * Returns `false` if given arguments are invalid. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - sheet ID from which rows will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [row, amount] @@ -1921,6 +1950,9 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public isItPossibleToRemoveRows(sheetId: number, ...indexes: ColumnRowIndex[]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') const normalizedIndexes = normalizeRemovedIndexes(indexes) try { @@ -1947,7 +1979,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -1974,6 +2006,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that addColumns can be called. * If returns `true`, doing [[addColumns]] operation won't throw any errors. * Returns `false` if adding columns would exceed the sheet size limit or given arguments are invalid. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - sheet ID in which columns will be added * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format: [column, amount], where column is a column number from which new columns will be added @@ -1994,6 +2027,9 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public isItPossibleToAddColumns(sheetId: number, ...indexes: ColumnRowIndex[]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') const normalizedIndexes = normalizeAddedIndexes(indexes) try { @@ -2021,7 +2057,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SheetSizeLimitExceededError]] when performing this operation would result in sheet size limits exceeding - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -2052,6 +2088,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that removeColumns can be called. * If returns `true`, doing [[removeColumns]] operation won't throw any errors. * Returns `false` if given arguments are invalid. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - sheet ID from which columns will be removed * @param {ColumnRowIndex[]} indexes - non-contiguous indexes with format [column, amount] @@ -2072,6 +2109,9 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public isItPossibleToRemoveColumns(sheetId: number, ...indexes: ColumnRowIndex[]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') const normalizedIndexes = normalizeRemovedIndexes(indexes) try { @@ -2098,7 +2138,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when the given arguments are invalid - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -2129,6 +2169,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that moveCells can be called. * If returns `true`, doing [[moveCells]] operation won't throw any errors. * Returns `false` if the operation might be disrupted and causes side effects by the fact that there is an array inside the selected columns, the target location includes an array or the provided address is invalid. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {SimpleCellRange} source - range for a moved block * @param {SimpleCellAddress} destinationLeftCorner - upper left address of the target cell block @@ -2155,6 +2196,9 @@ export class HyperFormula implements TypedEmitter { * @category Cells */ public isItPossibleToMoveCells(source: SimpleCellRange, destinationLeftCorner: SimpleCellAddress): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } if (!isSimpleCellAddress(destinationLeftCorner)) { throw new ExpectedValueOfTypeError('SimpleCellAddress', 'destinationLeftCorner') } @@ -2189,7 +2233,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -2230,6 +2274,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that moveRows can be called. * If returns `true`, doing [[moveRows]] operation won't throw any errors. * Returns `false` if the operation might be disrupted and causes side effects by the fact that there is an array inside the selected rows, the target location includes an array or the provided address is invalid. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - a sheet number in which the operation will be performed * @param {number} startRow - number of the first row to move @@ -2253,6 +2298,9 @@ export class HyperFormula implements TypedEmitter { * @category Rows */ public isItPossibleToMoveRows(sheetId: number, startRow: number, numberOfRows: number, targetRow: number): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') validateArgToType(startRow, 'number', 'startRow') validateArgToType(numberOfRows, 'number', 'numberOfRows') @@ -2284,7 +2332,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -2315,6 +2363,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that moveColumns can be called. * If returns `true`, doing [[moveColumns]] operation won't throw any errors. * Returns `false` if the operation might be disrupted and causes side effects by the fact that there is an array inside the selected columns, the target location includes an array or the provided address is invalid. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - a sheet number in which the operation will be performed * @param {number} startColumn - number of the first column to move @@ -2337,6 +2386,9 @@ export class HyperFormula implements TypedEmitter { * @category Columns */ public isItPossibleToMoveColumns(sheetId: number, startColumn: number, numberOfColumns: number, targetColumn: number): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') validateArgToType(startColumn, 'number', 'startColumn') validateArgToType(numberOfColumns, 'number', 'numberOfColumns') @@ -2368,7 +2420,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[InvalidArgumentsError]] when the given arguments are invalid * @throws [[SourceLocationHasArrayError]] when the source location has array inside - array cannot be moved * @throws [[TargetLocationHasArrayError]] when the target location has array inside - cells cannot be replaced by the array - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -2411,7 +2463,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Clipboard feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Clipboard feature * * @example * ```js @@ -2453,7 +2505,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if source is of wrong type * @throws [[SheetsNotEqual]] if range provided has distinct sheet numbers for start and end * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Clipboard feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Clipboard feature * * @example * ```js @@ -2503,7 +2555,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NothingToPasteError]] when clipboard is empty * @throws [[TargetLocationHasArrayError]] when the selected target area has array inside * @throws [[ExpectedValueOfTypeError]] if targetLeftCorner is of wrong type - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Clipboard feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Clipboard feature * * @example * ```js @@ -2798,6 +2850,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that addSheet can be called. * If returns `true`, doing [[addSheet]] operation won't throw any errors, and it is possible to add sheet with provided name. * Returns `false` if the chosen name is already used. + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {string} sheetName - sheet name, case-insensitive * @@ -2817,6 +2870,9 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public isItPossibleToAddSheet(sheetName: string): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetName, 'string', 'sheetName') try { this._crudOperations.ensureItIsPossibleToAddSheet(sheetName) @@ -2837,7 +2893,7 @@ export class HyperFormula implements TypedEmitter { * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[SheetNameAlreadyTakenError]] when sheet with a given name already exists - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -2871,6 +2927,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to remove sheet for the engine. * Returns `true` if the provided sheet exists, and therefore it can be removed, doing [[removeSheet]] operation won't throw any errors. * Returns `false` otherwise + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - sheet ID. * @@ -2890,6 +2947,9 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public isItPossibleToRemoveSheet(sheetId: number): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') try { this._crudOperations.ensureScopeIdIsValid(sheetId) @@ -2913,7 +2973,7 @@ export class HyperFormula implements TypedEmitter { * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -2947,6 +3007,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to clear a specified sheet. * If returns `true`, doing [[clearSheet]] operation won't throw any errors, provided sheet exists and its content can be cleared. * Returns `false` otherwise + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - sheet ID. * @@ -2966,6 +3027,9 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public isItPossibleToClearSheet(sheetId: number): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') try { this._crudOperations.ensureScopeIdIsValid(sheetId) @@ -2988,7 +3052,7 @@ export class HyperFormula implements TypedEmitter { * * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -3019,6 +3083,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to replace the sheet content. * If returns `true`, doing [[setSheetContent]] operation won't throw any errors, the provided sheet exists and then its content can be replaced. * Returns `false` otherwise + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - sheet ID. * @param {RawCellContent[][]} values - array of new values @@ -3040,6 +3105,9 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public isItPossibleToReplaceSheetContent(sheetId: number, values: RawCellContent[][]): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') try { this._crudOperations.ensureScopeIdIsValid(sheetId) @@ -3061,7 +3129,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[InvalidArgumentsError]] when values argument is not an array of arrays - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -3708,6 +3776,7 @@ export class HyperFormula implements TypedEmitter { * Returns information whether it is possible to rename sheet. * Returns `true` if the sheet with provided id exists and new name is available * Returns `false` if sheet cannot be renamed + * Returns `false` also when the license key does not allow the Crud feature (see [[LicenseCapabilityMissingError]]). * * @param {number} sheetId - a sheet number * @param {string} newName - a name of the sheet to be given @@ -3728,6 +3797,9 @@ export class HyperFormula implements TypedEmitter { * @category Sheets */ public isItPossibleToRenameSheet(sheetId: number, newName: string): boolean { + if (!this.isCapabilityAllowed(FeatureId.Crud)) { + return false + } validateArgToType(sheetId, 'number', 'sheetId') validateArgToType(newName, 'string', 'newName') try { @@ -3751,7 +3823,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NoSheetWithIdError]] when the given sheet ID does not exist * @throws [[SheetNameAlreadyTakenError]] when the provided sheet name already exists - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Crud feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Crud feature * * @example * ```js @@ -3790,7 +3862,7 @@ export class HyperFormula implements TypedEmitter { * @fires [[evaluationSuspended]] always * @fires [[evaluationResumed]] after the recomputation of necessary values * - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Batching feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Batching feature * * @example * ```js @@ -3834,7 +3906,7 @@ export class HyperFormula implements TypedEmitter { * * @fires [[evaluationSuspended]] always * - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the Batching feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the Batching feature * * @example * ```js @@ -3941,6 +4013,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that addNamedExpression can be called. * If returns `true`, doing [[addNamedExpression]] operation won't throw any errors. * Returns `false` if the operation might be disrupted. + * Returns `false` also when the license key does not allow the NamedExpressions feature (see [[LicenseCapabilityMissingError]]). * * @param {string} expressionName - a name of the expression to be added * @param {RawCellContent} expression - the expression @@ -3962,6 +4035,9 @@ export class HyperFormula implements TypedEmitter { * @category Named Expressions */ public isItPossibleToAddNamedExpression(expressionName: string, expression: RawCellContent, scope?: number): boolean { + if (!this.isCapabilityAllowed(FeatureId.NamedExpressions)) { + return false + } validateArgToType(expressionName, 'string', 'expressionName') if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') @@ -3994,7 +4070,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NamedExpressionNameIsInvalidError]] when the named-expression name is not valid * @throws [[NoRelativeAddressesAllowedError]] when the named-expression formula contains relative references * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the NamedExpressions feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the NamedExpressions feature * * @example * ```js @@ -4166,6 +4242,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that changeNamedExpression can be called. * If returns `true`, doing [[changeNamedExpression]] operation won't throw any errors. * Returns `false` if the operation might be disrupted. + * Returns `false` also when the license key does not allow the NamedExpressions feature (see [[LicenseCapabilityMissingError]]). * * @param {string} expressionName - an expression name, case-insensitive. * @param {RawCellContent} newExpression - a new expression @@ -4190,6 +4267,9 @@ export class HyperFormula implements TypedEmitter { * @category Named Expressions */ public isItPossibleToChangeNamedExpression(expressionName: string, newExpression: RawCellContent, scope?: number): boolean { + if (!this.isCapabilityAllowed(FeatureId.NamedExpressions)) { + return false + } validateArgToType(expressionName, 'string', 'expressionName') if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') @@ -4221,7 +4301,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists * @throws [[ArrayFormulasNotSupportedError]] when the named expression formula is an array formula * @throws [[NoRelativeAddressesAllowedError]] when the named expression formula contains relative references - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the NamedExpressions feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the NamedExpressions feature * * @example * ```js @@ -4253,6 +4333,7 @@ export class HyperFormula implements TypedEmitter { * Checks against particular rules to ascertain that removeNamedExpression can be called. * If returns `true`, doing [[removeNamedExpression]] operation won't throw any errors. * Returns `false` if the operation might be disrupted. + * Returns `false` also when the license key does not allow the NamedExpressions feature (see [[LicenseCapabilityMissingError]]). * * @param {string} expressionName - an expression name, case-insensitive. * @param {number?} scope - scope definition, `sheetId` for local scope or `undefined` for global scope @@ -4276,6 +4357,9 @@ export class HyperFormula implements TypedEmitter { * @category Named Expressions */ public isItPossibleToRemoveNamedExpression(expressionName: string, scope?: number): boolean { + if (!this.isCapabilityAllowed(FeatureId.NamedExpressions)) { + return false + } validateArgToType(expressionName, 'string', 'expressionName') if (scope !== undefined) { validateArgToType(scope, 'number', 'scope') @@ -4304,7 +4388,7 @@ export class HyperFormula implements TypedEmitter { * @throws [[ExpectedValueOfTypeError]] if any of its basic type argument is of wrong type * @throws [[NamedExpressionDoesNotExistError]] when the given expression does not exist. * @throws [[NoSheetWithIdError]] if no sheet with given sheetId exists - * @throws [[LicenseCapabilityMissingError]] if the current license entitlement does not grant the NamedExpressions feature + * @throws [[LicenseCapabilityMissingError]] if the license key is missing or invalid, has expired and blocks evaluation, or does not grant the NamedExpressions feature * * @example * ```js @@ -4643,13 +4727,16 @@ export class HyperFormula implements TypedEmitter { * A function the instance's license key does not include is omitted for the same reason: it would evaluate to a * `#LIC!` error. The list therefore answers "what can this engine compute", not "what does this package contain". * Two consequences worth knowing: - * - A missing, invalid or expired license key does **not** shorten the list. Such a key restricts nothing by - * entitlement — it is reported on the console, and every licence-gated function call evaluates to `#LIC!` — so - * the full catalogue is still described. `VERSION()` and `OFFSET()` are protected built-ins outside the licence - * system, so they keep evaluating. Use it to build a function picker before a key is configured. + * - A key that blocks evaluation (a missing or invalid key, an expired classic key, or a trial past its grace + * period) does **not** shorten the list. Such a key restricts nothing by entitlement — it is reported on the + * console, and every license-gated function call evaluates to `#LIC!` — so the full catalog is still described. + * `VERSION()` and `OFFSET()` are protected built-ins outside the license system, so they keep evaluating. Use it to + * build a function picker before a key is configured. An expired key that keeps evaluating (a subscription past + * its grace period, or a key whose `release_until` is before this build) keeps its own grants, so the list stays + * exactly what it was while the key was current. * - A custom (user-registered) function is omitted only if it took a built-in id the key excludes. The rule is * "not covered by the capability table", not "not user-registered", so a plugin registered under an id the - * built-in catalogue already uses is treated as that built-in. Registered under an id of its own, a custom + * built-in catalog already uses is treated as that built-in. Registered under an id of its own, a custom * function is never omitted. See {@link getFunctionDetails}, which states the same exception. * * @example @@ -4681,7 +4768,7 @@ export class HyperFormula implements TypedEmitter { * exposed as `aliasOf`. Returns `undefined` when the function id is unknown, not registered in this instance, has * no translation entry for the configured language, or is not included in this instance's license key (neither an * untranslated nor an unlicensed id can be evaluated, so neither is described — which keeps this method consistent - * with [[getAvailableFunctions]], including its behaviour for a missing, invalid or expired key). + * with [[getAvailableFunctions]], including its behavior for a key that blocks evaluation). * For a custom function, `category` is `'Custom'`, there is no `shortDescription`, `documentationUrl` or * `examples`, and parameters are reported positionally (`Arg1`, `Arg2`, ...). A custom plugin registered over a * built-in id is the exception: the catalogue is keyed by function id, so it reports that built-in's authored @@ -4905,13 +4992,15 @@ export class HyperFormula implements TypedEmitter { /** * Throws an error if the current license does not allow the given feature: either the key's - * state blocks every gated feature (missing, invalid or expired), or the key does not grant it. + * state blocks every gated feature (a missing or invalid key, an expired classic key, or a trial + * past its grace period), or the key does not grant it. * * Where the line is drawn, so a later change does not move it by accident: * - **Gated:** methods that create value by mutating the sheet, the clipboard, the undo * history, or the named-expression set. * - **Not gated:** reads (`getCellValue`, `listNamedExpressions`, - * `getAllNamedExpressionsSerialized`, the `isItPossibleTo*` predicates) and teardown or + * `getAllNamedExpressionsSerialized`, the `isItPossibleTo*` predicates, which answer `false` + * instead of throwing when the method they ask about is not allowed) and teardown or * cleanup that only ever removes state (`clearClipboard`, `clearUndoStack`, * `clearRedoStack`, `destroy`). Gating cleanup would let a restricted entitlement strand * an integration mid-teardown while giving a licensee nothing, and mirrors gate B, which @@ -4931,6 +5020,16 @@ export class HyperFormula implements TypedEmitter { ensureFeatureAllowed(this._config, feature) } + /** + * Whether the current license allows the given feature: the answer [[ensureCapability]] acts on, + * for the `isItPossibleTo*` predicates, which answer `false` instead of throwing. + * + * @internal + */ + private isCapabilityAllowed(feature: FeatureId): boolean { + return isFeatureAllowed(this._config, feature) + } + /** * Parses a formula string and extracts its AST and dependencies. * diff --git a/src/errors.ts b/src/errors.ts index 367c74b38b..16baf2b889 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -398,8 +398,8 @@ export class AliasAlreadyExisting extends Error { /** * Error thrown when a public API method is called for a {@link FeatureId} that the current * license entitlement does not grant, or when the license key itself blocks every gated feature - * (missing, invalid, or expired in a way that blocks evaluation); the message then names the - * key's state instead. Mirrors gate B's `ErrorMessage.LicenseCapability`, but + * (a missing or invalid key, an expired classic key, or a trial past its grace period); the + * message then names the key's state instead. Mirrors gate B's `ErrorMessage.LicenseCapability`, but * this one guards the API surface itself rather than a formula evaluation, so it * is thrown synchronously instead of surfacing as a cell error. * @@ -446,8 +446,8 @@ export class LicenseCapabilityMissingError extends Error { /** * @param {FeatureId} feature - the gated feature that was called * @param {LicenseKeyValidityState} [blockingState] - the key's state when the key itself blocks - * every gated feature (missing, invalid or expired); omit when the key is valid but does not - * grant `feature` + * every gated feature (a missing or invalid key, an expired classic key, or a trial past its grace + * period); omit when the key evaluates but does not grant `feature` */ constructor(feature: FeatureId, blockingState?: LicenseKeyValidityState) { super(blockingState === undefined diff --git a/src/license/LicenseEntitlement.ts b/src/license/LicenseEntitlement.ts index 042db4d8af..d067943dfd 100644 --- a/src/license/LicenseEntitlement.ts +++ b/src/license/LicenseEntitlement.ts @@ -47,9 +47,17 @@ export interface LicenseExpiry { * configured key. */ export interface LicenseEntitlement { - /** `true` for every key that restricts nothing: legacy keys, `gpl-v3`, and any missing, invalid or expired key. */ + /** + * `true` for every key that restricts nothing: classic keys, `gpl-v3`, and any key that blocks + * evaluation (a missing or invalid key, an expired classic key, or a trial past its grace + * period). An entitlement key that has expired but keeps evaluating is not one of them: it keeps + * its own grants. + */ unrestricted: boolean, - /** Capability tokens this entitlement grants, recognized by this library version. */ + /** + * The capability tokens the key carries, spelled as the key spells them, recognized or not. Only + * the ones this library version recognizes grant anything. + */ capabilities: ReadonlySet, expiry: LicenseExpiry, /** @@ -57,8 +65,8 @@ export interface LicenseEntitlement { * * Set from the key's own `no-console-warns` flag ONLY, as the vendored reader reads it (its * `channels.console`). An unrecognized token does NOT - * set it: an unknown token makes the *grant* silent (it grants nothing, with no message and no - * diagnostics getter), which is a different thing from muting the key's console output. + * set it: an unknown token makes the *grant* silent (it grants nothing, and nothing reports it), + * which is a different thing from muting the key's console output. * Coupling them would suppress expiry notices as a side effect of a vocabulary mismatch. */ silent: boolean, @@ -66,8 +74,9 @@ export interface LicenseEntitlement { } /** - * The unrestricted entitlement: legacy keys, `gpl-v3`, and every missing, invalid or expired - * entitlement key resolve to this. + * The unrestricted entitlement: classic keys, `gpl-v3`, and every key that blocks evaluation (a + * missing or invalid key, an expired classic key, or a trial past its grace period) resolve to + * this. An entitlement key that has expired but keeps evaluating does not: it keeps its own grants. * * Unrecognized tokens fail closed and silently, so an entitlement key whose tokens this library * version does not recognize at all does not map here — it resolves to an entitlement with an empty, diff --git a/src/license/capabilities.ts b/src/license/capabilities.ts index 3cb209692f..577699fa73 100644 --- a/src/license/capabilities.ts +++ b/src/license/capabilities.ts @@ -43,7 +43,7 @@ export interface CapabilityGrant { * that a consumer holding a grant cannot reach back into a sub-table's arrays. * * No token here names a package, and no grant refers to another token. Which tokens a commercial - * package consists of is the generator's knowledge, expressed by the bigger licence simply + * package consists of is the generator's knowledge, expressed by the bigger license simply * listing more tokens — so a key's function set is the union of everything it names that this * table recognizes, and an unrecognized token is inert. * Legacy keys resolve to the unrestricted entitlement and never consult this table at all. @@ -70,7 +70,7 @@ export const CAPABILITY_TABLE: ReadonlyMap = new Map = new Map([ * Enumerated rather than taken from the function registry at run time, even though "everything * not in a group" would be the shorter way to say it. Reading the registry would sweep in * functions registered through `HyperFormula.registerFunctionPlugin`, putting a user's OWN custom - * function under a licence token and returning `#LIC!` for it, while custom functions must never + * function under a license token and returning `#LIC!` for it, while custom functions must never * be gated. A function this table does not list is not * gated at all, which is exactly the treatment a custom function should get. */ diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index a85ef845c7..f7c5543f8c 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -36,10 +36,11 @@ const VALID_STATES: LicenseState[] = [ ] /** - * Lifecycle states in which a non-trial key has run out but still lets this build evaluate - * formulas, printing an error to the console instead. An expired license never blocks a paying - * customer, as the reader's guide and the key specification both say. A trial hard stop still - * blocks. + * Lifecycle states in which a key has run out but still lets this build evaluate formulas, + * printing an error to the console instead: a subscription past its grace period, and any key whose + * `release_until` is before the build. An expired license never blocks a paying customer, as the + * reader's guide and the key specification both say. A trial past its grace period + * (`trial_hard_stop`) still blocks. * * The key keeps its own grants: the reader reports it as licensed, so an expired key is never * granted more than the same key was granted while it was current. @@ -53,12 +54,12 @@ const EXPIRED_WITHOUT_BLOCKING_STATES: LicenseState[] = ['usage_hard_stop', 'rel * string, and parsing it twice would let them disagree about what it says. */ export interface ResolvedLicense { - /** The key's state, as reported by `VERSION()` and the console messages. */ + /** The key's state, as the console messages and the `#LIC!` and E3 error messages report it. */ validityState: LicenseKeyValidityState, /** * Gate A — `true` when function calls must return `#LIC!`. Usually `validityState !== VALID`; - * the exception is an expired non-trial entitlement key, which reports `EXPIRED` but keeps - * evaluating (see {@link EXPIRED_WITHOUT_BLOCKING_STATES}). + * the exception is an entitlement key in one of {@link EXPIRED_WITHOUT_BLOCKING_STATES}, which + * reports `EXPIRED` but keeps evaluating. */ blocksEvaluation: boolean, /** Gate B — which functions and API features the key grants. */ @@ -118,7 +119,7 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool * literals, then the trailing bracketed block that marks an * entitlement key, then the legacy 25-character shape. Everything that is not an entitlement key * — `gpl-v3`, a legacy key, an empty string — falls through to {@link checkLicenseKeyValidity} - * completely unchanged, which is what keeps this from touching existing behaviour. A string that + * completely unchanged, which is what keeps this from touching existing behavior. A string that * carries a bracketed block routes here even when the block is garbage: such a key is INVALID, * not a legacy key that happens to contain brackets. * @@ -127,13 +128,14 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool * digest), picks HyperFormula's entry, places it in its lifecycle window and reads its flags. Only * the meaning of the capability tokens and the console messages live here. * - * **The invariant this function exists to protect.** Only a VALID entitlement key resolves to a - * restricted entitlement. Every other outcome — missing, invalid, or expired, for an entitlement - * key as much as for a legacy one — resolves to {@link unrestrictedEntitlement}. A bad key is - * stopped by gate A alone, through `blocksEvaluation`: formulas yield `#LIC!` and every gated API - * feature throws with the key's state (see `ensureFeatureAllowed`). Gate B never reports a bad - * key, so its "not included in your license" error is reserved for a valid key that lacks the - * grant. The fail-closed rule governs unrecognized tokens INSIDE an otherwise valid key; it is not + * **The invariant this function exists to protect.** Only an entitlement key that lets this build + * evaluate — a valid one, or one in {@link EXPIRED_WITHOUT_BLOCKING_STATES} — resolves to a + * restricted entitlement, and an expired one keeps exactly the grants it had while current. Every + * key that blocks evaluation (a missing or invalid key, an expired classic key, or a trial past its grace period) resolves to + * {@link unrestrictedEntitlement}, and so does every classic key. A key that blocks is stopped by + * gate A alone, through `blocksEvaluation`: formulas yield `#LIC!` and every gated API feature throws + * with the key's state (see `ensureFeatureAllowed`). Gate B never reports such a key, so its "not + * included in your license" error is reserved for a key that evaluates but lacks the grant. The fail-closed rule governs unrecognized tokens INSIDE an otherwise valid key; it is not * a rule about invalid keys. * * A checksum-valid key whose payload shape cannot be read is INVALID, not a crash and not a free From 5f41ad03db83e2f6e095e9496fec10435ae48242 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 15:14:03 +0200 Subject: [PATCH 42/54] HF-307: classify every lifecycle state of the key reader in one exhaustive table Replace the two state lists, with their implicit "blocks" default, by a Record. A state added upstream now fails compilation until it is classified. Behavior is unchanged. Co-Authored-By: Claude Opus 5.5 --- src/license/licenseResolution.ts | 73 ++++++++++++++++++-------------- 1 file changed, 42 insertions(+), 31 deletions(-) diff --git a/src/license/licenseResolution.ts b/src/license/licenseResolution.ts index f7c5543f8c..fad5804b2c 100644 --- a/src/license/licenseResolution.ts +++ b/src/license/licenseResolution.ts @@ -23,29 +23,41 @@ import {LicenseState, ProductEntitlement} from './handsontable-license-key-parse export const HYPERFORMULA_PRODUCT_NAME = 'hyperformula' /** - * Lifecycle states in which an entitlement key still lets this build evaluate formulas. - * - * The soft-stop states are here on purpose: the grace period keeps evaluating and prints the - * specification's error (see `notifyEntitlementKey`). What happens after the grace period is - * {@link EXPIRED_WITHOUT_BLOCKING_STATES}. + * What one lifecycle state of a licensed entitlement key means for this build: the validity state it + * reports, and whether it blocks evaluation. */ -const VALID_STATES: LicenseState[] = [ - 'usage_valid', 'usage_notice', 'usage_soft_stop', - 'trial_valid', 'trial_notice', 'trial_soft_stop', - 'release_valid', -] +interface LifecycleVerdict { + validityState: LicenseKeyValidityState.VALID | LicenseKeyValidityState.EXPIRED, + blocksEvaluation: boolean, +} /** - * Lifecycle states in which a key has run out but still lets this build evaluate formulas, - * printing an error to the console instead: a subscription past its grace period, and any key whose - * `release_until` is before the build. An expired license never blocks a paying customer, as the - * reader's guide and the key specification both say. A trial past its grace period - * (`trial_hard_stop`) still blocks. + * The verdict for every lifecycle state the vendored reader reports. A `Record` over + * {@link LicenseState}, so a state added upstream fails compilation here until it is classified, + * instead of falling into a default. * - * The key keeps its own grants: the reader reports it as licensed, so an expired key is never - * granted more than the same key was granted while it was current. + * - The valid and notice states, and `release_valid`, report VALID and evaluate. + * - The soft-stop states report VALID and evaluate on purpose: the grace period keeps working and + * prints the specification's error (see `notifyEntitlementKey`). + * - A subscription past its grace period (`usage_hard_stop`) and a key whose `release_until` is + * before the build (`release_expired`) report EXPIRED but keep evaluating, printing an error to + * the console instead. An expired license never blocks a paying customer, as the reader's guide + * and the key specification both say. Such a key keeps its own grants: the reader reports it as + * licensed, so it is never granted more than the same key was granted while it was current. + * - A trial past its grace period (`trial_hard_stop`) reports EXPIRED and blocks. */ -const EXPIRED_WITHOUT_BLOCKING_STATES: LicenseState[] = ['usage_hard_stop', 'release_expired'] +const LIFECYCLE_VERDICTS: Record = { + usage_valid: {validityState: LicenseKeyValidityState.VALID, blocksEvaluation: false}, + usage_notice: {validityState: LicenseKeyValidityState.VALID, blocksEvaluation: false}, + usage_soft_stop: {validityState: LicenseKeyValidityState.VALID, blocksEvaluation: false}, + usage_hard_stop: {validityState: LicenseKeyValidityState.EXPIRED, blocksEvaluation: false}, + trial_valid: {validityState: LicenseKeyValidityState.VALID, blocksEvaluation: false}, + trial_notice: {validityState: LicenseKeyValidityState.VALID, blocksEvaluation: false}, + trial_soft_stop: {validityState: LicenseKeyValidityState.VALID, blocksEvaluation: false}, + trial_hard_stop: {validityState: LicenseKeyValidityState.EXPIRED, blocksEvaluation: true}, + release_valid: {validityState: LicenseKeyValidityState.VALID, blocksEvaluation: false}, + release_expired: {validityState: LicenseKeyValidityState.EXPIRED, blocksEvaluation: false}, +} /** * Both halves of the license decision, resolved from one reading of the key. @@ -58,8 +70,8 @@ export interface ResolvedLicense { validityState: LicenseKeyValidityState, /** * Gate A — `true` when function calls must return `#LIC!`. Usually `validityState !== VALID`; - * the exception is an entitlement key in one of {@link EXPIRED_WITHOUT_BLOCKING_STATES}, which - * reports `EXPIRED` but keeps evaluating. + * the exception is an entitlement key whose {@link LIFECYCLE_VERDICTS} entry reports `EXPIRED` + * but keeps evaluating. */ blocksEvaluation: boolean, /** Gate B — which functions and API features the key grants. */ @@ -129,9 +141,10 @@ function entitlementOf(entry: ProductEntitlement, isTrial: boolean, silent: bool * the meaning of the capability tokens and the console messages live here. * * **The invariant this function exists to protect.** Only an entitlement key that lets this build - * evaluate — a valid one, or one in {@link EXPIRED_WITHOUT_BLOCKING_STATES} — resolves to a - * restricted entitlement, and an expired one keeps exactly the grants it had while current. Every - * key that blocks evaluation (a missing or invalid key, an expired classic key, or a trial past its grace period) resolves to + * evaluate — a valid one, or an expired one whose {@link LIFECYCLE_VERDICTS} entry does not + * block — resolves to a restricted entitlement, and an expired one keeps exactly the grants it had + * while current. Every key that blocks evaluation (a missing or invalid key, an expired classic key, + * or a trial past its grace period) resolves to * {@link unrestrictedEntitlement}, and so does every classic key. A key that blocks is stopped by * gate A alone, through `blocksEvaluation`: formulas yield `#LIC!` and every gated API feature throws * with the key's state (see `ensureFeatureAllowed`). Gate B never reports such a key, so its "not @@ -179,9 +192,7 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true } const {entitlement: entry, lifecycle, channels} = license - const expiredWithoutBlocking = EXPIRED_WITHOUT_BLOCKING_STATES.indexOf(lifecycle.state) !== -1 - const isValid = VALID_STATES.indexOf(lifecycle.state) !== -1 - const state = isValid ? LicenseKeyValidityState.VALID : LicenseKeyValidityState.EXPIRED + const {validityState, blocksEvaluation} = LIFECYCLE_VERDICTS[lifecycle.state] // The message is chosen by the reader's state and prints the key's own date (the key // specification's text, the same table Handsontable uses). The `no-console-warns` flag closes the channel. @@ -191,10 +202,10 @@ export function resolveLicense(licenseKey: string, notifyConsole: boolean = true } return { - validityState: state, - blocksEvaluation: !isValid && !expiredWithoutBlocking, - entitlement: isValid || expiredWithoutBlocking - ? entitlementOf(entry, lifecycle.isTrial, !channels.console) - : unrestrictedEntitlement(), + validityState, + blocksEvaluation, + entitlement: blocksEvaluation + ? unrestrictedEntitlement() + : entitlementOf(entry, lifecycle.isTrial, !channels.console), } } From bf6b8048a24021353e8bb4e3ad30fb85d07a38af Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 15:14:03 +0200 Subject: [PATCH 43/54] HF-307: the getAvailableFunctions docs no longer name a key field The JSDoc is published by TypeDoc; describe the expired perpetual key without naming the payload field, as the license guide does. Co-Authored-By: Claude Opus 5.5 --- src/HyperFormula.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index a67b61c132..dc54b2445c 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -4732,8 +4732,8 @@ export class HyperFormula implements TypedEmitter { * console, and every license-gated function call evaluates to `#LIC!` — so the full catalog is still described. * `VERSION()` and `OFFSET()` are protected built-ins outside the license system, so they keep evaluating. Use it to * build a function picker before a key is configured. An expired key that keeps evaluating (a subscription past - * its grace period, or a key whose `release_until` is before this build) keeps its own grants, so the list stays - * exactly what it was while the key was current. + * its grace period, or a perpetual key whose maintenance doesn't cover this build) keeps its own grants, so the + * list stays exactly what it was while the key was current. * - A custom (user-registered) function is omitted only if it took a built-in id the key excludes. The rule is * "not covered by the capability table", not "not user-registered", so a plugin registered under an id the * built-in catalog already uses is treated as that built-in. Registered under an id of its own, a custom From 867774ef02c618e9091799cdface59aadbb43275 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 15:14:03 +0200 Subject: [PATCH 44/54] HF-307: changelog notes what a blocking key does to the gated API Under a missing or invalid key, an expired classic key, or a trial past its grace period, the gated methods throw, a build with named expressions throws, and isItPossibleTo* returns false. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 86e10ac598..5ecca643a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed - Changed the `VERSION` function to return only the HyperFormula version (e.g. `HyperFormula v3.4.0`), without the license key status. [#1728](https://github.com/handsontable/hyperformula/pull/1728) +- Changed the API methods gated by the license key to throw a `LicenseCapabilityMissingError` when the key is missing or invalid, when a classic key has expired, or when a trial key is past its grace period. The gated methods are the ones that edit cells, rows, columns, and sheets, `copy()`, `cut()`, `paste()`, `undo()`, `redo()`, `batch()`, `suspendEvaluation()`, and the methods that add, change, or remove named expressions. Building an engine with named expressions throws the same error, and the matching `isItPossibleTo*()` methods return `false`. [#1728](https://github.com/handsontable/hyperformula/pull/1728) ### Fixed From 0efee299afbe9e7e34bc9586d5a42efdd7c0bd46 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 15:14:03 +0200 Subject: [PATCH 45/54] HF-307: pass a license key in every guide example Without a key, the gated methods the examples call now throw. Every engine built in docs/guide gets licenseKey: 'gpl-v3', as the docs content guide requires. Co-Authored-By: Claude Opus 5.5 --- docs/guide/ai-sdk.md | 2 +- docs/guide/basic-operations.md | 4 ++-- docs/guide/batch-operations.md | 6 +++--- docs/guide/cell-references.md | 2 +- docs/guide/clipboard-operations.md | 6 +++--- docs/guide/compatibility-with-google-sheets.md | 1 + docs/guide/compatibility-with-microsoft-excel.md | 1 + docs/guide/currency-handling.md | 8 ++++---- docs/guide/custom-functions.md | 2 +- docs/guide/dependency-graph.md | 4 ++-- docs/guide/integration-with-langchain.md | 2 +- docs/guide/known-limitations.md | 2 +- docs/guide/localizing-functions.md | 1 + docs/guide/migration-from-0.6-to-1.0.md | 8 ++++---- docs/guide/migration-from-2.x-to-3.0.md | 1 + docs/guide/named-expressions.md | 6 +++--- docs/guide/sorting-data.md | 12 ++++++------ docs/guide/types-of-values.md | 6 +++--- 18 files changed, 39 insertions(+), 35 deletions(-) diff --git a/docs/guide/ai-sdk.md b/docs/guide/ai-sdk.md index 4ef063cb25..7eb0b7c593 100644 --- a/docs/guide/ai-sdk.md +++ b/docs/guide/ai-sdk.md @@ -41,7 +41,7 @@ const hf = HyperFormula.buildFromArray([ ['Revenue', 100], ['Cost', 60], ['Profit', '=B1-B2'], -]); +], { licenseKey: 'gpl-v3' }); // Pass the spreadsheet tools straight into generateText. const result = await generateText({ diff --git a/docs/guide/basic-operations.md b/docs/guide/basic-operations.md index 966bd96116..b49f000bc7 100644 --- a/docs/guide/basic-operations.md +++ b/docs/guide/basic-operations.md @@ -356,7 +356,7 @@ easily check if that action is allowed, and if it is not, throw an error. // an instance with some example data const hfInstance = HyperFormula.buildFromArray([ ['1', '2'], -]); +], { licenseKey: 'gpl-v3' }); // a variable used to carry the message for the user let messageUsedInUI; @@ -395,7 +395,7 @@ const hf = HyperFormula.buildFromArray([ [1], ['=SUM(A1:A2)'], ['=COUNTBLANK(A1:A3)'], -]); +], { licenseKey: 'gpl-v3' }); // insert an empty row between the row 0 and the row 1 const changes = hf.addRows(0, [1, 1]); diff --git a/docs/guide/batch-operations.md b/docs/guide/batch-operations.md index 87799085f2..c113c7af8d 100644 --- a/docs/guide/batch-operations.md +++ b/docs/guide/batch-operations.md @@ -30,7 +30,7 @@ operation together with their absolute addresses and new values. const hfInstance = HyperFormula.buildFromSheets({ MySheet1: [ ['1'] ], MySheet2: [ ['10'] ], -}); +}, { licenseKey: 'gpl-v3' }); // multiple operations in a single callback will trigger evaluation only once // and only one set of changes will be returned as a combined result of all @@ -58,7 +58,7 @@ operation together with their absolute addresses and new values. const hfInstance = HyperFormula.buildFromSheets({ MySheet1: [ ['1'] ], MySheet2: [ ['10'] ], -}); +}, { licenseKey: 'gpl-v3' }); // suspend the evaluation hfInstance.suspendEvaluation(); @@ -82,7 +82,7 @@ When you need to check if the evaluation is suspended you can call the [`isEvaluationSuspended`](../api/classes/hyperformula.md#isevaluationsuspended) method. ```javascript -const hfInstance = HyperFormula.buildEmpty(); +const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); // suspend the evaluation hfInstance.suspendEvaluation(); diff --git a/docs/guide/cell-references.md b/docs/guide/cell-references.md index 5fcd811e18..e707e00871 100644 --- a/docs/guide/cell-references.md +++ b/docs/guide/cell-references.md @@ -132,7 +132,7 @@ This example shows the change after the move operation was done: // build with a simple dataset const hfInstance = HyperFormula.buildFromArray([ ['=B2', '=A1', ''], -]); +], { licenseKey: 'gpl-v3' }); // these are the coordinates for a move operation const source = { sheet: 0, col: 1, row: 0 }; diff --git a/docs/guide/clipboard-operations.md b/docs/guide/clipboard-operations.md index 0c13991c3b..6eaec8933c 100644 --- a/docs/guide/clipboard-operations.md +++ b/docs/guide/clipboard-operations.md @@ -20,7 +20,7 @@ To copy the contents of a cell or range, use the [`copy()`](../api/classes/hyper ```javascript const hfInstance = HyperFormula.buildFromArray([ ['1', '2'], -]); +], { licenseKey: 'gpl-v3' }); // copy [ [ 2 ] ] const clipboardContent = hfInstance.copy({ @@ -40,7 +40,7 @@ Any CRUD operation called after the [`cut()`](../api/classes/hyperformula.md#cut ```javascript const hfInstance = HyperFormula.buildFromArray([ ['1', '2'], -]); +], { licenseKey: 'gpl-v3' }); // returns the values that were cut: [ [ 1 ] ] const clipboardContent = hfInstance.cut({ @@ -58,7 +58,7 @@ To paste the contents of a cell or range, use the [`paste()`](../api/classes/hyp ```javascript const hfInstance = HyperFormula.buildFromArray([ ['1', '2'], -]); +], { licenseKey: 'gpl-v3' }); // [ [ 2 ] ] was copied const clipboardContent = hfInstance.copy({ diff --git a/docs/guide/compatibility-with-google-sheets.md b/docs/guide/compatibility-with-google-sheets.md index d4d39ff528..6ac2aa1dc5 100644 --- a/docs/guide/compatibility-with-google-sheets.md +++ b/docs/guide/compatibility-with-google-sheets.md @@ -107,6 +107,7 @@ This configuration aligns HyperFormula with the default behavior of Google Sheet ```js // define options const options = { + licenseKey: 'gpl-v3', dateFormats: ['MM/DD/YYYY', 'MM/DD/YY', 'YYYY/MM/DD'], timeFormats: ['hh:mm', 'hh:mm:ss.sss'], // set by default currencySymbol: ['$', 'USD'], diff --git a/docs/guide/compatibility-with-microsoft-excel.md b/docs/guide/compatibility-with-microsoft-excel.md index c0e86520bc..7309548158 100644 --- a/docs/guide/compatibility-with-microsoft-excel.md +++ b/docs/guide/compatibility-with-microsoft-excel.md @@ -179,6 +179,7 @@ This configuration aligns HyperFormula with the default behavior of Microsoft Ex ```js // define options const options = { + licenseKey: 'gpl-v3', dateFormats: ['MM/DD/YYYY', 'MM/DD/YY', 'YYYY/MM/DD'], timeFormats: ['hh:mm', 'hh:mm:ss.sss'], // set by default currencySymbol: ['$', 'USD'], diff --git a/docs/guide/currency-handling.md b/docs/guide/currency-handling.md index 25e415b82b..0d3917a361 100644 --- a/docs/guide/currency-handling.md +++ b/docs/guide/currency-handling.md @@ -25,7 +25,7 @@ By default, HyperFormula recognizes `$` as a currency symbol in cell input. To a ```javascript const hf = HyperFormula.buildFromArray( [['100 zł', '=A1 * 1.23']], - { currencySymbol: ['$', 'zł'] } + { licenseKey: 'gpl-v3', currencySymbol: ['$', 'zł'] } ); console.log(hf.getCellValue({ sheet: 0, col: 0, row: 0 })); // 100 @@ -53,7 +53,7 @@ With no `stringifyCurrency` configured, the built-in formatter handles simple `$ const hf = HyperFormula.buildFromArray([ [1234.5, '=TEXT(A1, "$0.00")'], [1234.5, '=TEXT(A2, "$#.00")'], -]); +], { licenseKey: 'gpl-v3' }); console.log(hf.getCellValue({ sheet: 0, col: 1, row: 0 })); // "$1234.50" console.log(hf.getCellValue({ sheet: 0, col: 1, row: 1 })); // "$1234.50" @@ -62,7 +62,7 @@ console.log(hf.getCellValue({ sheet: 0, col: 1, row: 1 })); // "$1234.50" A non-`$` symbol used purely as a suffix (no thousands grouping, no decimal-comma) also passes through unchanged: ```javascript -const hf = HyperFormula.buildFromArray([[1234.5, '=TEXT(A1, "0.00 zł")']]); +const hf = HyperFormula.buildFromArray([[1234.5, '=TEXT(A1, "0.00 zł")']], { licenseKey: 'gpl-v3' }); console.log(hf.getCellValue({ sheet: 0, col: 1, row: 0 })); // "1234.50 zł" ``` @@ -92,7 +92,7 @@ const stringifyCurrency = (value, fmt) => const hf = HyperFormula.buildFromArray([ [1234.5, '=TEXT(A1, "$#,##0.00")'], -], { stringifyCurrency }); +], { licenseKey: 'gpl-v3', stringifyCurrency }); console.log(hf.getCellValue({ sheet: 0, col: 1, row: 0 })); // "$1234.50" ``` diff --git a/docs/guide/custom-functions.md b/docs/guide/custom-functions.md index 5c68d8c114..903e30d45e 100644 --- a/docs/guide/custom-functions.md +++ b/docs/guide/custom-functions.md @@ -160,7 +160,7 @@ Now, you're ready to use your GREET function in a formula. ```js // build a HyperFormula instance where you can use your function directly -const hfInstance = HyperFormula.buildFromArray([['Anthony', '=GREET(A1)']]); +const hfInstance = HyperFormula.buildFromArray([['Anthony', '=GREET(A1)']], { licenseKey: 'gpl-v3' }); // read the value of cell B1 const result = hfInstance.getCellValue({ sheet: 0, col: 1, row: 0 }); diff --git a/docs/guide/dependency-graph.md b/docs/guide/dependency-graph.md index dbf7b3af0a..55ce99713d 100644 --- a/docs/guide/dependency-graph.md +++ b/docs/guide/dependency-graph.md @@ -87,7 +87,7 @@ node and avoid duplicating the work during computation. To get the immediate precedents of a cell or a range (the in-neighbors of the cell node or the range node), use the [`getCellPrecedents()`](../api/classes/hyperformula.html#getcellprecedents) method: ```js -const hfInstance = HyperFormula.buildFromArray([[ '1', '2', '=A1', '=B1+C1' ]]); +const hfInstance = HyperFormula.buildFromArray([[ '1', '2', '=A1', '=B1+C1' ]], { licenseKey: 'gpl-v3' }); hfInstance.getCellPrecedents({ sheet: 0, col: 3, row: 0 }); // returns [{ sheet: 0, col: 1, row: 0 }, { sheet: 0, col: 2, row: 0 }] @@ -98,7 +98,7 @@ hfInstance.getCellPrecedents({ sheet: 0, col: 3, row: 0 }); To get the immediate dependents of a cell or a range (the out-neighbors of the cell node or the range node), use the [`getCellDependents()`](../api/classes/hyperformula.html#getcelldependents) method: ```js -const hfInstance = HyperFormula.buildFromArray([[ '1', '=A1', '=A1+B1', '=B1+C1' ]]) +const hfInstance = HyperFormula.buildFromArray([[ '1', '=A1', '=A1+B1', '=B1+C1' ]], { licenseKey: 'gpl-v3' }) hfInstance.getCellDependents({ sheet: 0, col: 0, row: 0 }) // returns [{ sheet: 0, col: 1, row: 0 }, { sheet: 0, col: 2, row: 0 }] diff --git a/docs/guide/integration-with-langchain.md b/docs/guide/integration-with-langchain.md index 1be8f3f99a..807699b59d 100644 --- a/docs/guide/integration-with-langchain.md +++ b/docs/guide/integration-with-langchain.md @@ -38,7 +38,7 @@ const hf = HyperFormula.buildFromArray([ ['Revenue', 100], ['Cost', 60], ['Profit', '=B1-B2'], -]); +], { licenseKey: 'gpl-v3' }); const agent = createReactAgent({ llm: new ChatOpenAI({ model: 'gpt-4o' }), diff --git a/docs/guide/known-limitations.md b/docs/guide/known-limitations.md index 91b161d94a..d78cac018d 100644 --- a/docs/guide/known-limitations.md +++ b/docs/guide/known-limitations.md @@ -91,6 +91,6 @@ HyperFormula resolves the OFFSET function at parse time rather than during evalu * OFFSET is resolved at parse time, so `getCellFormula` returns the computed reference, not the original `OFFSET` call. ```js - const hf = HyperFormula.buildFromArray([[1, 45, '=OFFSET(A1, 0, 1)']]); + const hf = HyperFormula.buildFromArray([[1, 45, '=OFFSET(A1, 0, 1)']], { licenseKey: 'gpl-v3' }); hf.getCellFormula({ sheet: 0, row: 0, col: 2 }); // '=B1' ``` diff --git a/docs/guide/localizing-functions.md b/docs/guide/localizing-functions.md index 39b6d1dcb8..68cab2c623 100644 --- a/docs/guide/localizing-functions.md +++ b/docs/guide/localizing-functions.md @@ -104,6 +104,7 @@ HyperFormula.registerLanguage('es', spanish); // Use it in your configuration const hf = HyperFormula.buildEmpty({ + licenseKey: 'gpl-v3', language: 'es' }); ``` diff --git a/docs/guide/migration-from-0.6-to-1.0.md b/docs/guide/migration-from-0.6-to-1.0.md index 4444c557c1..402448c05c 100644 --- a/docs/guide/migration-from-0.6-to-1.0.md +++ b/docs/guide/migration-from-0.6-to-1.0.md @@ -54,7 +54,7 @@ Before: const hfInstance = HyperFormula.buildFromSheets({ MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], MySheet2: [ ['10'] ], -}); +}, { licenseKey: 'gpl-v3' }); const changes = hfInstance.clearSheet('MySheet2'); ``` @@ -64,7 +64,7 @@ After: const hfInstance = HyperFormula.buildFromSheets({ MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], MySheet2: [ ['10'] ], -}); +}, { licenseKey: 'gpl-v3' }); // use `sheetId` instead of `sheetName` const changes = hfInstance.clearSheet(1); @@ -170,7 +170,7 @@ Before: ```js const hfInstance = HyperFormula.buildFromArray([ ['1', '2'], -]); +], { licenseKey: 'gpl-v3' }); // takes `simpleCellAddress`, `width`, and `height` // returns: [ [ 2 ] ] @@ -181,7 +181,7 @@ After: ```js const hfInstance = HyperFormula.buildFromArray([ ['1', '2'], -]); +], { licenseKey: 'gpl-v3' }); // takes `simpleCellRange` // returns: [ [ 2 ] ] diff --git a/docs/guide/migration-from-2.x-to-3.0.md b/docs/guide/migration-from-2.x-to-3.0.md index 26ddf035e6..dd1130487b 100644 --- a/docs/guide/migration-from-2.x-to-3.0.md +++ b/docs/guide/migration-from-2.x-to-3.0.md @@ -104,6 +104,7 @@ HyperFormula 3.0.0 introduces a change in the default value of the `precisionRou ```javascript const hf = HyperFormula.buildEmpty({ + licenseKey: 'gpl-v3', precisionRounding: 14 }); ``` \ No newline at end of file diff --git a/docs/guide/named-expressions.md b/docs/guide/named-expressions.md index 99249cb25b..1f4e7cd96a 100644 --- a/docs/guide/named-expressions.md +++ b/docs/guide/named-expressions.md @@ -166,11 +166,11 @@ const namedExpressions = [ ]; // Create engine with named expressions -const hfInstance = HyperFormula.buildEmpty({}, namedExpressions); +const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }, namedExpressions); // or -const hfInstance = HyperFormula.buildFromArray(sheetData, {}, namedExpressions); +const hfInstance = HyperFormula.buildFromArray(sheetData, { licenseKey: 'gpl-v3' }, namedExpressions); // or -const hfInstance = HyperFormula.buildFromSheets(sheetsData, {}, namedExpressions); +const hfInstance = HyperFormula.buildFromSheets(sheetsData, { licenseKey: 'gpl-v3' }, namedExpressions); ``` **After engine creation**: You can add a named expression by using the `addNamedExpression` method. It accepts name for the expression, the expression as a raw cell content, and optionally the scope. If you do not define the scope it will be set to global, meaning the expression name will be valid for the whole workbook. If you want to add many of them, it is advised to do so in a [batch](batch-operations.md). This method returns [an array of changed cells](basic-operations.md#changes-array). diff --git a/docs/guide/sorting-data.md b/docs/guide/sorting-data.md index f69468720c..8fffb0087a 100644 --- a/docs/guide/sorting-data.md +++ b/docs/guide/sorting-data.md @@ -36,7 +36,7 @@ const hfInstance = HyperFormula.buildFromArray([ ['A'], ['B'], ['C'], -]); +], { licenseKey: 'gpl-v3' }); // we'll set the row order to [1, 2, 0] in the next steps // the resulting sheet will be: [['C'], ['A'], ['B']] @@ -65,7 +65,7 @@ const hfInstance = HyperFormula.buildFromArray([ ['A'], ['B'], ['C'], -]); +], { licenseKey: 'gpl-v3' }); // a variable to carry the user message let messageUsedInUI; @@ -88,7 +88,7 @@ const hfInstance = HyperFormula.buildFromArray([ ['A'], ['B'], ['C'], -]); +], { licenseKey: 'gpl-v3' }); let messageUsedInUI; @@ -132,7 +132,7 @@ For example, if you want to move the last column to the front of a 3-column shee // a HyperFormula instance with example data const hfInstance = HyperFormula.buildFromArray([ ['A', 'B', 'C'] -]); +], { licenseKey: 'gpl-v3' }); // we'll set the column order to [1, 2, 0] in the next steps // the resulting sheet will be: [['C', 'A', 'B']] @@ -157,7 +157,7 @@ Use the [`isItPossibleToSetColumnOrder`](../api/classes/hyperformula.md#isitposs ```js const hfInstance = HyperFormula.buildFromArray([ ['A', 'B', 'C'] -]); +], { licenseKey: 'gpl-v3' }); // a variable to carry the user message let messageUsedInUI; @@ -178,7 +178,7 @@ If your specified column number permutation is valid, change the column order: ```js const hfInstance = HyperFormula.buildFromArray([ ['A', 'B', 'C'] -]); +], { licenseKey: 'gpl-v3' }); let messageUsedInUI; diff --git a/docs/guide/types-of-values.md b/docs/guide/types-of-values.md index e433164fdf..b4f483c963 100644 --- a/docs/guide/types-of-values.md +++ b/docs/guide/types-of-values.md @@ -48,7 +48,7 @@ const hf = HyperFormula.buildFromArray([ [true], // Logical [new Date()], // Date/DateTime [null], // Empty -]); +], { licenseKey: 'gpl-v3' }); ``` ### For string values @@ -76,7 +76,7 @@ const hf = HyperFormula.buildFromArray([ ["22/06/2022"], // Date ["10:40:16"], // Time ["Hello"], // Text -]); +], { licenseKey: 'gpl-v3' }); ``` ### Forcing the text value type @@ -92,7 +92,7 @@ const hf = HyperFormula.buildFromArray([ ["'11201"], // a string: "11201" ["22/06/2022"], // a date: June 22nd 2022 ["'22/06/2022"], // a string: "22/06/2022" -]); +], { licenseKey: 'gpl-v3' }); // a formula: SUM(B1,B2) hf.setCellContents({ col: 0, row: 4, sheet: 0 }, [["=SUM(B1,B2)"]]); From 83324a7db8f8740fe314d2d061310aab344e47a1 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 15:14:03 +0200 Subject: [PATCH 46/54] HF-307: describe src/license and the capability table in DEV_DOCS Adds src/license and the vendored reader to the layout and the core modules, and a step to the new-function checklist: a built-in missing from functionCapabilities.ts is not gated at all. Co-Authored-By: Claude Opus 5.5 --- DEV_DOCS.md | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/DEV_DOCS.md b/DEV_DOCS.md index 95444dc80d..daa15138f5 100644 --- a/DEV_DOCS.md +++ b/DEV_DOCS.md @@ -23,7 +23,9 @@ Canonical reference for everyone working on the HyperFormula source code: mainta │ │ └── plugin/ # Built-in spreadsheet function plugins │ ├── DependencyGraph/ # Cell dependency tracking and recalculation order │ ├── CrudOperations.ts # Create/read/update/delete operations on sheets and cells -│ └── i18n/ # Function-name translations per language +│ ├── i18n/ # Function-name translations per language +│ └── license/ # License key reading, capability tables, and license gating +│ └── handsontable-license-key-parser/ # Vendored key reader; do not edit ├── test/ # Test suite ├── docs/ # Public documentation portal (VuePress) │ ├── guide/ # Markdown guides (building, contributing, usage…) @@ -51,6 +53,13 @@ Canonical reference for everyone working on the HyperFormula source code: mainta - `src/interpreter/` — formula evaluation engine - `src/DependencyGraph/` — cell dependency tracking and recalculation order - `src/CrudOperations.ts` — create/read/update/delete operations on sheets and cells +- `src/license/` — license key handling: reads the key, maps its capability tokens to functions (`functionCapabilities.ts`) and public API features (`featureCapabilities.ts`), and gates function calls and API methods + +### License key reader (`src/license/handsontable-license-key-parser/`) + +A copy of the entitlement-key reader published by the `handsontable/license-key` repository, taken whole from a tagged release. Don't edit it: fix the problem upstream and take the copy again, as described in `PROVENANCE.md` in that directory. ESLint ignores the directory. + +`npm run check:license-key-parser-drift` compares the copy with the pinned upstream commit and fails on any difference or on a newer upstream tag. It needs read access to the upstream repository, so it runs in its own CI workflow rather than in `npm run test` or `npm run lint`. ### Function plugins (`src/interpreter/plugin/`) @@ -125,8 +134,9 @@ Adding a built-in function is similar to adding a [custom function](docs/guide/c 2. Add function metadata to `implementedFunctions`. 3. Implement the function method. 4. Add a catalogue entry to `src/interpreter/functionMetadata/categories/.ts` (see below). -5. Add translations to all language files in `src/i18n/languages/`. -6. Add tests in `test/unit/interpreter/`. +5. Add the function to the license capability table in `src/license/functionCapabilities.ts` (see below). +6. Add translations to all language files in `src/i18n/languages/`. +7. Add tests in `test/unit/interpreter/`. ### The function metadata catalogue @@ -155,6 +165,14 @@ Note what the drift warning does **not** cover: **optionality is not cross-check Descriptions must describe **HyperFormula's** behaviour, not Excel's. Much of the catalogue was seeded from a hand-written page that documented Excel, and HyperFormula deliberately deviates in places (`INT` truncates toward zero, `ISEVEN`/`ISODD` do not truncate, `CEILING.MATH`/`FLOOR.MATH` honour only `mode` = 1). Verify a claim against the implementation before authoring it, and record any deviation in [the list of differences](docs/guide/list-of-differences.md). +### The license capability table + +`src/license/functionCapabilities.ts` decides which license keys can call a built-in function. Add every new built-in either to its group in `FUNCTION_GROUPS` or, if it belongs to no group, to `UNGROUPED_FUNCTIONS`. An ungrouped function is granted only by `fun:all` and by its own `fun:` token. Both lists use canonical names: an alias needs no entry, because it is gated as its canonical function. + +A built-in missing from the table escapes the entitlement check: every key that lets formulas evaluate can call it, including a key that grants no functions. The completeness check in the private test suite (`unit/license/capability-registry.spec.ts`) fails on such a function, but the public smoke tests do not. + +Group names are part of the license key format, so never rename a group or remove a function from one. Adding a function to a group grants it to every key that already carries that group's token. + ## Internationalization and function translations HyperFormula supports internationalization and provides localized function names for all built-in languages. Translation files live in `src/i18n/languages/`. New functions must include translations for all built-in languages. From f05cd2d3c3b10055a92cbb9bd3e9786943a44409 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 18:01:06 +0200 Subject: [PATCH 47/54] HF-307: pass a license key in every API reference example Without a key, the gated methods the examples call now throw a LicenseCapabilityMissingError. Every engine built in a JSDoc @example block of HyperFormula and of its events, and in the API reference landing page, now gets licenseKey: 'gpl-v3', as the guide examples already do. Co-Authored-By: Claude Opus 5.5 --- docs/api-ref-readme.md | 2 +- src/Emitter.ts | 16 +-- src/HyperFormula.ts | 224 ++++++++++++++++++++--------------------- 3 files changed, 121 insertions(+), 121 deletions(-) diff --git a/docs/api-ref-readme.md b/docs/api-ref-readme.md index 69f252437f..dc647c341c 100644 --- a/docs/api-ref-readme.md +++ b/docs/api-ref-readme.md @@ -43,7 +43,7 @@ For example, subscribing to `sheetAdded` event: const hfInstance = HyperFormula.buildFromSheets({ MySheet1: [ ['1'] ], MySheet2: [ ['10'] ], -}); +}, { licenseKey: 'gpl-v3' }); const handler = ( ) => { console.log('baz') } diff --git a/src/Emitter.ts b/src/Emitter.ts index b2f1d6fff0..ce079ec634 100644 --- a/src/Emitter.ts +++ b/src/Emitter.ts @@ -27,7 +27,7 @@ export interface Listeners { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = (addedSheetDisplayName) => { console.log('baz') } @@ -64,7 +64,7 @@ export interface Listeners { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = (removedSheetDisplayName, changes) => { console.log('baz') } @@ -101,7 +101,7 @@ export interface Listeners { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = (oldName, newName) => { console.log(`Sheet ${oldName} was renamed to ${newName}`) } @@ -137,7 +137,7 @@ export interface Listeners { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = (namedExpressionName, changes) => { console.log('baz') } @@ -173,7 +173,7 @@ export interface Listeners { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = (namedExpressionName, changes) => { console.log('baz') } @@ -212,7 +212,7 @@ export interface Listeners { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=A1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = (changes) => { console.log('baz') } @@ -246,7 +246,7 @@ export interface Listeners { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ] - * }); + * }, { licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = ( ) => { console.log('baz') } @@ -285,7 +285,7 @@ export interface Listeners { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ] - * }); + * }, { licenseKey: 'gpl-v3' }); * * // define a function to be called when the event occurs * const handler = (changes) => { console.log('baz') } diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index dc54b2445c..286e2b91f0 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -275,7 +275,7 @@ export class HyperFormula implements TypedEmitter { * ]; * * // method with optional config parameter maxColumns - * const hfInstance = HyperFormula.buildFromArray(sheetData, { maxColumns: 1000 }, namedExpressions); + * const hfInstance = HyperFormula.buildFromArray(sheetData, { licenseKey: 'gpl-v3', maxColumns: 1000 }, namedExpressions); * ``` * * @category Factories @@ -323,7 +323,7 @@ export class HyperFormula implements TypedEmitter { * ]; * * // method with optional config parameter useColumnIndex - * const hfInstance = HyperFormula.buildFromSheets(sheetData, { useColumnIndex: true }, namedExpressions); + * const hfInstance = HyperFormula.buildFromSheets(sheetData, { licenseKey: 'gpl-v3', useColumnIndex: true }, namedExpressions); * ``` * * @category Factories @@ -352,7 +352,7 @@ export class HyperFormula implements TypedEmitter { * ]; * * // build with no initial data and with optional config parameter maxColumns - * const hfInstance = HyperFormula.buildEmpty({ maxColumns: 1000 }, namedExpressions); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3', maxColumns: 1000 }, namedExpressions); * ``` * * @category Factories @@ -405,7 +405,7 @@ export class HyperFormula implements TypedEmitter { * ```js * // return registered language * HyperFormula.registerLanguage('enUS', enUS); - * const engine = HyperFormula.buildEmpty({language: 'enUS'}); + * const engine = HyperFormula.buildEmpty({licenseKey: 'gpl-v3', language: 'enUS'}); * ``` * * @category Static Methods @@ -852,7 +852,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // get value of A1 cell, should be '6' * const A1Value = hfInstance.getCellValue({ sheet: 0, col: 0, row: 0 }); @@ -883,7 +883,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '0'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return a normalized A1 cell formula: '=SUM(1, 2, 3)' * const A1Formula = hfInstance.getCellFormula({ sheet: 0, col: 0, row: 0 }); @@ -913,7 +913,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=HYPERLINK("https://hyperformula.handsontable.com/", "HyperFormula")', '0'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return url of 'HYPERLINK': https://hyperformula.handsontable.com/ * const A1Hyperlink = hfInstance.getCellHyperlink({ sheet: 0, col: 0, row: 0 }); @@ -945,7 +945,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '0'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return serialized content of A1 cell: '=SUM(1, 2, 3)' * const cellA1Serialized = hfInstance.getCellSerialized({ sheet: 0, col: 0, row: 0 }); @@ -980,7 +980,7 @@ export class HyperFormula implements TypedEmitter { * ['0', '=SUM(1, 2, 3)', '=A1'], * ['1', '=TEXT(A2, "0.0%")', '=C1'], * ['2', '=SUM(A1:C1)', '=C1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return all values of a sheet: [[0, 6, 0], [1, '1.0%', 0], [2, 6, 0]] * const sheetValues = hfInstance.getSheetValues(0); @@ -1008,7 +1008,7 @@ export class HyperFormula implements TypedEmitter { * ['0', '=SUM(1, 2, 3)', '=A1'], * ['1', '=TEXT(A2, "0.0%")', '=C1'], * ['2', '=SUM(A1:C1)', '=C1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return all formulas of a sheet: * // [ @@ -1041,7 +1041,7 @@ export class HyperFormula implements TypedEmitter { * ['0', '=SUM(1, 2, 3)', '=A1'], * ['1', '=TEXT(A2, "0.0%")', '=C1'], * ['2', '=SUM(A1:C1)', '=C1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return: * // [ @@ -1075,7 +1075,7 @@ export class HyperFormula implements TypedEmitter { * ['3'], * ['4'], * ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return the dimensions of all sheets: * // { Sheet1: { width: 3, height: 1 }, Sheet2: { width: 1, height: 2 } } @@ -1103,7 +1103,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=Sheet2!$A1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return provided sheet's dimensions: { width: 3, height: 1 } * const sheetDimensions = hfInstance.getSheetDimensions(0); @@ -1128,7 +1128,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '=A1+10', '3'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return all sheets values: { Sheet1: [ [ 1, 11, 3 ] ] } * const allSheetsValues = hfInstance.getAllSheetsValues(); @@ -1148,7 +1148,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=A1+10'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return only formulas: { Sheet1: [ [ undefined, undefined, '=A1+10' ] ] } * const allSheetsFormulas = hfInstance.getAllSheetsFormulas(); @@ -1171,7 +1171,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', 2, '=A1+10'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return all sheets serialized content: { Sheet1: [ [ '1', 2, '=A1+10' ] ] } * // note: the string '1' stays a string and the number 2 stays a number @@ -1199,7 +1199,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a config param, for example maxColumns, * // you can check the configuration with getConfig method @@ -1280,7 +1280,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], * ['3', ''], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // perform CRUD operation, for example remove the second row * hfInstance.removeRows(0, [1, 1]); @@ -1317,7 +1317,7 @@ export class HyperFormula implements TypedEmitter { * ['1'], * ['2'], * ['3'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // perform CRUD operation, for example remove the second row * hfInstance.removeRows(0, [1, 1]); @@ -1348,7 +1348,7 @@ export class HyperFormula implements TypedEmitter { * ['1'], * ['2'], * ['3'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // perform CRUD operation, for example remove the second row * hfInstance.removeRows(0, [1, 1]); @@ -1398,7 +1398,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // top left corner * const address1 = { col: 0, row: 0, sheet: 0 }; @@ -1457,7 +1457,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '=A1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should set the content, returns: * // [{ @@ -1499,7 +1499,7 @@ export class HyperFormula implements TypedEmitter { * [1], * [2], * [4, 5], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should set swap rows 0 and 2 in place, returns: * // [{ @@ -1545,7 +1545,7 @@ export class HyperFormula implements TypedEmitter { * [1], * [2], * [4, 5], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // returns true * const isSwappable = hfInstance.isItPossibleToSwapRowIndexes(0, [[0, 2], [2, 0]]); @@ -1600,7 +1600,7 @@ export class HyperFormula implements TypedEmitter { * ['A'], * ['B'], * ['C'] - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // Move 'A' to index 1, 'B' to index 2, and 'C' to index 0. * const newRowOrder = [1, 2, 0]; // [ newPosForA, newPosForB, newPosForC ] @@ -1638,7 +1638,7 @@ export class HyperFormula implements TypedEmitter { * ['A'], * ['B'], * ['C'] - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // returns true * hfInstance.isItPossibleToSetRowOrder(0, [1, 2, 0]); @@ -1687,7 +1687,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * [1, 2, 4], * [5] - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should set swap columns 0 and 2 in place, returns: * // [{ @@ -1730,7 +1730,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * [1, 2, 4], * [5] - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // returns true * hfInstance.isItPossibleToSwapColumnIndexes(0, [[0, 2], [2, 0]]); @@ -1783,7 +1783,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['A', 'B', 'C'] - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // Move 'A' to index 1, 'B' to index 2, and 'C' to index 0. * const newColumnOrder = [1, 2, 0]; // [ newPosForA, newPosForB, newPosForC ] @@ -1819,7 +1819,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['A', 'B', 'C'] - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // returns true * hfInstance.isItPossibleToSetColumnOrder(0, [1, 2, 0]); @@ -1861,7 +1861,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' for this example, * // it is possible to add one row in the second row of sheet 0 @@ -1907,7 +1907,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values @@ -1940,7 +1940,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' for this example * // it is possible to remove one row from row 1 of sheet 0 @@ -1986,7 +1986,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return: [{ sheet: 0, col: 1, row: 2, value: null }] for this example * const changes = hfInstance.removeRows(0, [1, 1]); @@ -2017,7 +2017,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' for this example, * // it is possible to add 1 column in sheet 0, at column 1 @@ -2063,7 +2063,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=RAND()', '42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, for this example: @@ -2099,7 +2099,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' for this example * // it is possible to remove one column, in place of the second column of sheet 0 @@ -2144,7 +2144,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['0', '=SUM(1, 2, 3)', '=A1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, in this example it will return: @@ -2181,7 +2181,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // choose the coordinates and assign them to variables * const source = { sheet: 0, col: 1, row: 0 }; @@ -2239,7 +2239,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=RAND()', '42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // choose the coordinates and assign them to variables * const source = { sheet: 0, col: 1, row: 0 }; @@ -2288,7 +2288,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' for this example * // it is possible to move one row from row 0 into row 2 @@ -2339,7 +2339,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * ['1'], * ['2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values @@ -2376,7 +2376,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' for this example * // it is possible to move one column from column 1 into column 2 of sheet 0 @@ -2426,7 +2426,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3', '=RAND()', '=SUM(A1:C1)'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, for this example: @@ -2469,7 +2469,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // it copies [ [ 2 ] ] * const clipboardContent = hfInstance.copy({ @@ -2511,7 +2511,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // returns the values that were cut: [ [ 1 ] ] * const clipboardContent = hfInstance.cut({ @@ -2561,7 +2561,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // [ [ 2 ] ] was copied * const clipboardContent = hfInstance.copy({ @@ -2597,7 +2597,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // copy desired content * const clipboardContent = hfInstance.copy({ @@ -2643,7 +2643,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // do an operation, for example remove columns * hfInstance.removeColumns(0, [0, 1]); @@ -2673,7 +2673,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2', '3'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // do an operation, for example remove columns * hfInstance.removeColumns(0, [0, 1]); @@ -2706,7 +2706,7 @@ export class HyperFormula implements TypedEmitter { * ['=SUM(1, 2)', '2', '10'], * ['5', '6', '7'], * ['40', '30', '20'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * * // returns calculated cells content: [ [ 3, 2 ], [ 5, 6 ] ] @@ -2742,7 +2742,7 @@ export class HyperFormula implements TypedEmitter { * ['=SUM(1, 2)', '2', '10'], * ['5', '6', '7'], * ['40', '30', '20'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // returns cell formulas of a given range only: * // [ [ '=SUM(1, 2)', undefined ], [ undefined, undefined ] ] @@ -2781,7 +2781,7 @@ export class HyperFormula implements TypedEmitter { * ['=SUM(1, 2)', 2, 10], * [5, 6, 7], * [40, 30, 20], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return serialized cell content for the given range: * // [ [ '=SUM(1, 2)', 2 ], [ 5, 6 ] ] @@ -2815,7 +2815,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildFromArray([[1, '=A1'], ['=$A$1', '2']]); + * const hfInstance = HyperFormula.buildFromArray([[1, '=A1'], ['=$A$1', '2']], { licenseKey: 'gpl-v3' }); * * // should return [['2', '=$A$1', '2'], ['=A3', 1, '=C3'], ['2', '=$A$1', '2']] * hfInstance.getFillRangeData( {start: {sheet: 0, row: 0, col: 0}, end: {sheet: 0, row: 1, col: 1}}, @@ -2861,7 +2861,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return 'false' because 'MySheet2' already exists * const isAddable = hfInstance.isItPossibleToAddSheet('MySheet2'); @@ -2900,7 +2900,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return 'MySheet3' * const nameProvided = hfInstance.addSheet('MySheet3'); @@ -2938,7 +2938,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return 'true' because sheet with ID 1 exists and is removable * const isRemovable = hfInstance.isItPossibleToRemoveSheet(1); @@ -2980,7 +2980,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, in this example it will return: @@ -3018,7 +3018,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return 'true' because 'MySheet2' exists and can be cleared * const isClearable = hfInstance.isItPossibleToClearSheet(1); @@ -3059,7 +3059,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['=SUM(MySheet2!A1:A2)'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, in this example it will return: @@ -3095,7 +3095,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return 'true' because sheet of ID 0 exists * // and the provided content can be placed in this sheet @@ -3136,7 +3136,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values @@ -3166,7 +3166,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * * // returns { sheet: 42, col: 0, row: 0 } @@ -3204,7 +3204,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * * // should return { start: { sheet: 0, col: 0, row: 0 }, end: { sheet: 0, col: 1, row: 0 } } @@ -3231,7 +3231,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * const addr = { sheet: 0, col: 1, row: 1 }; * @@ -3284,7 +3284,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * hfInstance.addSheet('Sheet0'); //sheetId = 0 * const range = { start: { sheet: 0, col: 1, row: 1 }, end: { sheet: 0, col: 2, row: 1 } }; * @@ -3335,7 +3335,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildFromArray( [ ['1', '=A1', '=A1+B1'] ] ); + * const hfInstance = HyperFormula.buildFromArray( [ ['1', '=A1', '=A1+B1'] ] , { licenseKey: 'gpl-v3' }); * * hfInstance.getCellDependents({ sheet: 0, col: 0, row: 0}); * // returns [{ sheet: 0, col: 1, row: 0}, { sheet: 0, col: 2, row: 0}] @@ -3373,7 +3373,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildFromArray( [ ['1', '=A1', '=A1+B1'] ] ); + * const hfInstance = HyperFormula.buildFromArray( [ ['1', '=A1', '=A1+B1'] ] , { licenseKey: 'gpl-v3' }); * * hfInstance.getCellPrecedents({ sheet: 0, col: 2, row: 0}); * // returns [{ sheet: 0, col: 0, row: 0}, { sheet: 0, col: 1, row: 0}] @@ -3408,7 +3408,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return 'MySheet2' as this sheet is the second one * const sheetName = hfInstance.getSheetName(1); @@ -3430,7 +3430,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return all sheets names: ['MySheet1', 'MySheet2'] * const sheetNames = hfInstance.getSheetNames(); @@ -3454,7 +3454,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return '0' because 'MySheet1' is of ID '0' * const sheetID = hfInstance.getSheetId('MySheet1'); @@ -3479,7 +3479,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // should return 'true' since 'MySheet1' exists * const sheetExist = hfInstance.doesSheetExist('MySheet1'); @@ -3505,7 +3505,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(A2:A3)', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'FORMULA', the cell of given coordinates is of this type * const cellA1Type = hfInstance.getCellType({ sheet: 0, col: 0, row: 0 }); @@ -3537,7 +3537,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(A2:A3)', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' since the selected cell contains a simple value * const isA1Simple = hfInstance.doesCellHaveSimpleValue({ sheet: 0, col: 0, row: 0 }); @@ -3568,7 +3568,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(A2:A3)', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' since the A1 cell contains a formula * const A1Formula = hfInstance.doesCellHaveFormula({ sheet: 0, col: 0, row: 0 }); @@ -3600,7 +3600,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * [null, '1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true', cell of provided coordinates is empty * const isEmpty = hfInstance.isCellEmpty({ sheet: 0, col: 0, row: 0 }); @@ -3631,7 +3631,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['{=TRANSPOSE(B1:B1)}'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true', cell of provided coordinates is a part of an array * const isPartOfArray = hfInstance.isCellPartOfArray({ sheet: 0, col: 0, row: 0 }); @@ -3663,7 +3663,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['=SUM(1, 2, 3)', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'NUMBER', cell value type of provided coordinates is a number * const cellValue = hfInstance.getCellValueType({ sheet: 0, col: 1, row: 0 }); @@ -3699,7 +3699,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1%', '1$'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'NUMBER_PERCENT', cell value type of provided coordinates is a number with a format inference percent. * const cellType = hfInstance.getCellValueDetailedType({ sheet: 0, col: 0, row: 0 }); @@ -3733,7 +3733,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1$', '1'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return '$', cell value type of provided coordinates is a number with a format inference currency, parsed as using '$' as currency. * const cellFormat = hfInstance.getCellValueFormat({ sheet: 0, col: 0, row: 0 }); @@ -3760,7 +3760,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['1', '2'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return the number of sheets which is '1' * const sheetsCount = hfInstance.countSheets(); @@ -3788,7 +3788,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // returns true * hfInstance.isItPossibleToRenameSheet(0, 'MySheet0'); @@ -3830,7 +3830,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // renames the sheet 'MySheet1' * hfInstance.renameSheet(0, 'MySheet0'); @@ -3869,7 +3869,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // multiple operations in a single callback will trigger evaluation only once * // and only one set of changes is returned as a combined result of all @@ -3913,7 +3913,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // similar to batch() but operations are not within a callback, * // one method suspends the recalculation @@ -3950,7 +3950,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * MySheet1: [ ['1'] ], * MySheet2: [ ['10'] ], - * }); + * }, { licenseKey: 'gpl-v3' }); * * // similar to batch() but operations are not within a callback, * // one method suspends the recalculation @@ -3990,7 +3990,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // suspend the evaluation * hfInstance.suspendEvaluation(); @@ -4025,7 +4025,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // should return 'true' for this example, * // it is possible to add named expression to global scope @@ -4076,7 +4076,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add own expression, scope limited to 'Sheet1' (sheetId=0), the method should return a list of cells which values * // changed after the operation, their absolute addresses and new values @@ -4118,7 +4118,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a named expression, only 'Sheet1' (sheetId=0) considered as it is the scope * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 'Sheet1'); @@ -4159,7 +4159,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a named expression in 'Sheet1' (sheetId=0) * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); @@ -4200,7 +4200,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a named expression in 'Sheet1' (sheetId=0) * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); @@ -4254,7 +4254,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a named expression * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); @@ -4307,7 +4307,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a named expression, scope limited to 'Sheet1' (sheetId=0) * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); @@ -4344,7 +4344,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a named expression * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); @@ -4394,7 +4394,7 @@ export class HyperFormula implements TypedEmitter { * ```js * const hfInstance = HyperFormula.buildFromArray([ * ['42'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add a named expression * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); @@ -4439,7 +4439,7 @@ export class HyperFormula implements TypedEmitter { * ['42'], * ['50'], * ['60'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add two named expressions and one scoped * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); @@ -4474,7 +4474,7 @@ export class HyperFormula implements TypedEmitter { * ['42'], * ['50'], * ['60'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // add two named expressions and one scoped * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); @@ -4511,7 +4511,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromArray([ * ['42'], * ['50'], - * ]); + * ], { licenseKey: 'gpl-v3' }); * * // returns '=Sheet1!$A$1+10' * const normalizedFormula = hfInstance.normalizeFormula('=SHEET1!$A$1+10'); @@ -4546,7 +4546,7 @@ export class HyperFormula implements TypedEmitter { * const hfInstance = HyperFormula.buildFromSheets({ * Sheet1: [['58']], * Sheet2: [['1', '2', '3'], ['4', '5', '6']] - * }); + * }, { licenseKey: 'gpl-v3' }); * * // returns the calculated formula's value * // for this example, returns `68` @@ -4580,7 +4580,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // returns a list of named expressions used by a formula * // for this example, returns ['foo', 'bar'] @@ -4641,7 +4641,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // return translated names of all functions, assign to a variable * const allNames = hfInstance.getRegisteredFunctionNames(); @@ -4668,7 +4668,7 @@ export class HyperFormula implements TypedEmitter { * // import your own plugin * import { MyExamplePlugin } from './file_with_your_plugin'; * - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // register a plugin * HyperFormula.registerFunctionPlugin(MyExamplePlugin); @@ -4689,7 +4689,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // return classes of all plugins registered, assign to a variable * const allNames = hfInstance.getAllFunctionPlugins(); @@ -4741,7 +4741,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // get the list of available functions, translated for the configured language * const functions = hfInstance.getAvailableFunctions(); @@ -4787,7 +4787,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // get the details of the SUMIF function, translated for the configured language * const details = hfInstance.getFunctionDetails('SUMIF'); @@ -4812,7 +4812,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // pass the number of days since nullDate * // the method should return formatted date and time, for this example: @@ -4839,7 +4839,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // pass the number of days since nullDate * // the method should return formatted date, for this example: @@ -4865,7 +4865,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // pass a number to be interpreted as a time * // should return {hours: 26, minutes: 24} for this example @@ -4888,7 +4888,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // subscribe to a 'sheetAdded', pass a simple handler * hfInstance.on('sheetAdded', ( ) => { console.log('foo') }); @@ -4913,7 +4913,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // subscribe to a 'sheetAdded', pass a simple handler * hfInstance.once('sheetAdded', ( ) => { console.log('foo') }); @@ -4939,7 +4939,7 @@ export class HyperFormula implements TypedEmitter { * * @example * ```js - * const hfInstance = HyperFormula.buildEmpty(); + * const hfInstance = HyperFormula.buildEmpty({ licenseKey: 'gpl-v3' }); * * // define a simple function to be called upon emitting an event * const handler = ( ) => { console.log('baz') } From bf5ceebb1ec9943817e9b79e4774648625420262 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 18:01:07 +0200 Subject: [PATCH 48/54] HF-307: fix four API reference examples that threw for their own reasons The license error used to stop them first. moveColumns moved a column to where it already was, getNamedExpressionValue passed a sheet name as the scope, changeNamedExpression changed a global expression that did not exist, and getAllNamedExpressionsSerialized added a name that is not a valid named-expression name. The expected results in their comments now match what the examples return. Co-Authored-By: Claude Opus 5.5 --- src/HyperFormula.ts | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index 286e2b91f0..e313ceb563 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -2428,16 +2428,17 @@ export class HyperFormula implements TypedEmitter { * ['1', '2', '3', '=RAND()', '=SUM(A1:C1)'], * ], { licenseKey: 'gpl-v3' }); * + * // move column B before column D; the SUM range follows its cells and becomes A1:B1 * // should return a list of cells which values changed after the operation, * // their absolute addresses and new values, for this example: * // [{ - * // address: { sheet: 0, col: 1, row: 0 }, - * // newValue: 0.16210054671639, - * // }, { * // address: { sheet: 0, col: 4, row: 0 }, - * // newValue: 6.16210054671639, + * // newValue: 4, + * // }, { + * // address: { sheet: 0, col: 3, row: 0 }, + * // newValue: 0.16210054671639, * // }] - * const changes = hfInstance.moveColumns(0, 1, 1, 2); + * const changes = hfInstance.moveColumns(0, 1, 1, 3); * ``` * * @category Columns @@ -4121,10 +4122,10 @@ export class HyperFormula implements TypedEmitter { * ], { licenseKey: 'gpl-v3' }); * * // add a named expression, only 'Sheet1' (sheetId=0) considered as it is the scope - * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 'Sheet1'); + * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); * - * // returns the calculated value of a passed named expression, '142' for this example - * const myFormula = hfInstance.getNamedExpressionValue('prettyName', 'Sheet1'); + * // returns the calculated value of a passed named expression, 142 for this example + * const myFormula = hfInstance.getNamedExpressionValue('prettyName', 0); * ``` * * @category Named Expressions @@ -4312,8 +4313,8 @@ export class HyperFormula implements TypedEmitter { * // add a named expression, scope limited to 'Sheet1' (sheetId=0) * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100', 0); * - * // change the named expression - * const changes = hfInstance.changeNamedExpression('prettyName', '=Sheet1!$A$1+200'); + * // change the named expression in the same scope + * const changes = hfInstance.changeNamedExpression('prettyName', '=Sheet1!$A$1+200', 0); * ``` * * @category Named Expressions @@ -4479,7 +4480,7 @@ export class HyperFormula implements TypedEmitter { * // add two named expressions and one scoped * hfInstance.addNamedExpression('prettyName', '=Sheet1!$A$1+100'); * hfInstance.addNamedExpression('anotherPrettyName', '=Sheet1!$A$2+100'); - * hfInstance.addNamedExpression('prettyName3', '=Sheet1!$A$3+100', 0); + * hfInstance.addNamedExpression('alsoPrettyName', '=Sheet1!$A$3+100', 0); * * // get all expressions serialized * // should return: From 8020cf6b87b84a1ca4375a0e56b83cdd770911d4 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 18:01:07 +0200 Subject: [PATCH 49/54] HF-307: isThereSomethingToUndo and isThereSomethingToRedo answer false without undo_redo The undo history records operations whatever the key grants, so the predicate answered true for an undo() that then threw. Both now answer false when the license does not allow the UndoRedo feature, like the isItPossibleTo* predicates. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- docs/guide/license-key.md | 7 +++++-- src/HyperFormula.ts | 16 +++++++++++++--- src/license/ensureFeatureAllowed.ts | 5 +++-- 4 files changed, 22 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5ecca643a9..bc329ed510 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,7 +14,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Changed - Changed the `VERSION` function to return only the HyperFormula version (e.g. `HyperFormula v3.4.0`), without the license key status. [#1728](https://github.com/handsontable/hyperformula/pull/1728) -- Changed the API methods gated by the license key to throw a `LicenseCapabilityMissingError` when the key is missing or invalid, when a classic key has expired, or when a trial key is past its grace period. The gated methods are the ones that edit cells, rows, columns, and sheets, `copy()`, `cut()`, `paste()`, `undo()`, `redo()`, `batch()`, `suspendEvaluation()`, and the methods that add, change, or remove named expressions. Building an engine with named expressions throws the same error, and the matching `isItPossibleTo*()` methods return `false`. [#1728](https://github.com/handsontable/hyperformula/pull/1728) +- Changed the API methods gated by the license key to throw a `LicenseCapabilityMissingError` when the key is missing or invalid, when a classic key has expired, or when a trial key is past its grace period. The gated methods are the ones that edit cells, rows, columns, and sheets, `copy()`, `cut()`, `paste()`, `undo()`, `redo()`, `batch()`, `suspendEvaluation()`, and the methods that add, change, or remove named expressions. Building an engine with named expressions throws the same error, and the matching `isItPossibleTo*()` methods, `isThereSomethingToUndo()`, and `isThereSomethingToRedo()` return `false`. [#1728](https://github.com/handsontable/hyperformula/pull/1728) ### Fixed diff --git a/docs/guide/license-key.md b/docs/guide/license-key.md index 3537113d2c..3e8ae8d905 100644 --- a/docs/guide/license-key.md +++ b/docs/guide/license-key.md @@ -65,7 +65,9 @@ If your key grants only part of the library, then: [error value](types-of-errors.md). Everything else in the sheet keeps calculating. * An API method your key doesn't include throws a `LicenseCapabilityMissingError` when you call it. Getters never throw; `copy()` and `cut()` do, because they belong to the clipboard feature. - The matching `isItPossibleTo*()` methods, such as `isItPossibleToAddRows()`, return `false`. + The matching `isItPossibleTo*()` methods, such as `isItPossibleToAddRows()`, return `false`, + and so do `isThereSomethingToUndo()` and `isThereSomethingToRedo()` when your key doesn't + include undo and redo. * [`getAvailableFunctions()`](../api/classes/hyperformula.md#getavailablefunctions) and [`getFunctionDetails()`](../api/classes/hyperformula.md#getfunctiondetails) describe only the functions your key includes, so a function picker built from them never offers a function that @@ -84,7 +86,8 @@ A missing or invalid key blocks the library: are the ones that edit cells, rows, columns, and sheets, `copy()`, `cut()`, `paste()`, `undo()`, `redo()`, `batch()`, `suspendEvaluation()`, and the methods that add, change, or remove named expressions. Building an engine with named expressions throws the same error. -* The `isItPossibleTo*()` methods return `false` for every gated method. +* The `isItPossibleTo*()` methods return `false` for every gated method, and + `isThereSomethingToUndo()` and `isThereSomethingToRedo()` return `false`. * Getters and clean-up methods, such as `clearClipboard()` and `resumeEvaluation()`, keep working, and `getAvailableFunctions()` still describes the full set of functions. diff --git a/src/HyperFormula.ts b/src/HyperFormula.ts index e313ceb563..ac5313eeaa 100644 --- a/src/HyperFormula.ts +++ b/src/HyperFormula.ts @@ -1339,6 +1339,7 @@ export class HyperFormula implements TypedEmitter { /** * Checks if there is at least one operation that can be undone. + * Returns `false` also when the license key does not allow the UndoRedo feature (see [[LicenseCapabilityMissingError]]). * * For more information, see the [Undo-Redo guide](/guide/undo-redo.md). * @@ -1361,11 +1362,15 @@ export class HyperFormula implements TypedEmitter { * @category Undo and Redo */ public isThereSomethingToUndo(): boolean { + if (!this.isCapabilityAllowed(FeatureId.UndoRedo)) { + return false + } return this._crudOperations.isThereSomethingToUndo() } /** * Checks if there is at least one operation that can be re-done. + * Returns `false` also when the license key does not allow the UndoRedo feature (see [[LicenseCapabilityMissingError]]). * * For more information, see the [Undo-Redo guide](/guide/undo-redo.md). * @@ -1380,6 +1385,9 @@ export class HyperFormula implements TypedEmitter { * @category Undo and Redo */ public isThereSomethingToRedo(): boolean { + if (!this.isCapabilityAllowed(FeatureId.UndoRedo)) { + return false + } return this._crudOperations.isThereSomethingToRedo() } @@ -5000,8 +5008,9 @@ export class HyperFormula implements TypedEmitter { * - **Gated:** methods that create value by mutating the sheet, the clipboard, the undo * history, or the named-expression set. * - **Not gated:** reads (`getCellValue`, `listNamedExpressions`, - * `getAllNamedExpressionsSerialized`, the `isItPossibleTo*` predicates, which answer `false` - * instead of throwing when the method they ask about is not allowed) and teardown or + * `getAllNamedExpressionsSerialized`, the `isItPossibleTo*` predicates and + * `isThereSomethingToUndo`/`isThereSomethingToRedo`, which answer `false` instead of throwing + * when the method they ask about is not allowed) and teardown or * cleanup that only ever removes state (`clearClipboard`, `clearUndoStack`, * `clearRedoStack`, `destroy`). Gating cleanup would let a restricted entitlement strand * an integration mid-teardown while giving a licensee nothing, and mirrors gate B, which @@ -5023,7 +5032,8 @@ export class HyperFormula implements TypedEmitter { /** * Whether the current license allows the given feature: the answer [[ensureCapability]] acts on, - * for the `isItPossibleTo*` predicates, which answer `false` instead of throwing. + * for the `isItPossibleTo*` predicates and `isThereSomethingToUndo`/`isThereSomethingToRedo`, + * which answer `false` instead of throwing. * * @internal */ diff --git a/src/license/ensureFeatureAllowed.ts b/src/license/ensureFeatureAllowed.ts index e288741e06..f03e9001b9 100644 --- a/src/license/ensureFeatureAllowed.ts +++ b/src/license/ensureFeatureAllowed.ts @@ -15,8 +15,9 @@ import {FeatureId} from './LicenseEntitlement' * key, or a trial past its grace period) blocks every gated feature, whatever the entitlement says; * - then gate B: a key that evaluates must grant `feature`. * - * The one rule behind {@link ensureFeatureAllowed} and the `isItPossibleTo*` predicates, so a - * predicate never answers `true` for a call that then throws a license error. + * The one rule behind {@link ensureFeatureAllowed}, the `isItPossibleTo*` predicates and + * `isThereSomethingToUndo`/`isThereSomethingToRedo`, so a predicate never answers `true` for a call + * that then throws a license error. * * @param {Config} config - the config whose resolved license is checked * @param {FeatureId} feature - the gated feature being asked about From 402bca4f5b15c8e40b76f1b0ab4f77034be2db48 Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 18:01:08 +0200 Subject: [PATCH 50/54] HF-307: a stopped array function evaluates to #LIC! in its own cell The array size predictor sized a call the license stops like any other, so the call filled its whole spill range with #LIC!, or showed #SPILL! instead when a cell in that range was not empty. The rule that decides which calls the license stops now lives in FunctionCallLicenseGate, which both the interpreter and the predictor use; the predictor sizes a stopped call as a single cell. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/ArraySize.ts | 10 ++++ src/interpreter/Interpreter.ts | 35 +++-------- src/license/FunctionCallLicenseGate.ts | 80 ++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 28 deletions(-) create mode 100644 src/license/FunctionCallLicenseGate.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index bc329ed510..6384d795c0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Fixed +- Fixed an array function stopped by the license key reserving its spill range: it filled the whole range with `#LIC!`, or showed `#SPILL!` instead of `#LIC!` when a cell in that range was not empty. It now evaluates to `#LIC!` in its own cell only. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the validation of classic (25-character) license keys depending on the time zone: east of UTC, a key that expired the day before the build was released was still accepted, and west of UTC, the console message printed an expiry date one day too early. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) - Fixed the localized names of `VSTACK` and `HSTACK` in 14 language packs to match Microsoft Excel. [#1748](https://github.com/handsontable/hyperformula/pull/1748) diff --git a/src/ArraySize.ts b/src/ArraySize.ts index dc658ee29a..1b41d1b9b6 100644 --- a/src/ArraySize.ts +++ b/src/ArraySize.ts @@ -9,6 +9,7 @@ import {Config} from './Config' import {FunctionRegistry} from './interpreter/FunctionRegistry' import {InterpreterState} from './interpreter/InterpreterState' import {FunctionArgumentType} from './interpreter' +import {FunctionCallLicenseGate} from './license/FunctionCallLicenseGate' import {Ast, AstNodeType, ProcedureAst} from './parser' export class ArraySize { @@ -40,10 +41,13 @@ function arraySizeForUnaryOp(arraySize: ArraySize): ArraySize { } export class ArraySizePredictor { + private readonly functionCallLicenseGate: FunctionCallLicenseGate + constructor( private config: Config, private functionRegistry: FunctionRegistry, ) { + this.functionCallLicenseGate = new FunctionCallLicenseGate(config, functionRegistry) } public checkArraySize(ast: Ast, formulaAddress: SimpleCellAddress): ArraySize { @@ -123,6 +127,12 @@ export class ArraySizePredictor { } private checkArraySizeForFunction(ast: ProcedureAst, state: InterpreterState): ArraySize { + // A call the license stops evaluates to a single #LIC! error. Sized as one cell, it reserves + // no spill range, so a non-empty cell below it cannot turn that error into #SPILL!. + if (this.functionCallLicenseGate.stopsCall(ast.procedureName)) { + return ArraySize.scalar() + } + const pluginArraySizeFunction = this.functionRegistry.getArraySizeFunction(ast.procedureName) if (pluginArraySizeFunction !== undefined) { diff --git a/src/interpreter/Interpreter.ts b/src/interpreter/Interpreter.ts index 274fcf3d2a..6444332537 100644 --- a/src/interpreter/Interpreter.ts +++ b/src/interpreter/Interpreter.ts @@ -12,8 +12,7 @@ import {DateTimeHelper} from '../DateTimeHelper' import {DependencyGraph} from '../DependencyGraph' import {FormulaVertex} from '../DependencyGraph/FormulaVertex' import {ErrorMessage} from '../error-message' -import {LicenseKeyValidityState} from '../helpers/licenseKeyValidator' -import {CapabilityRegistry, licenseAllowsFunction, ResolvedCapabilities} from '../license/CapabilityRegistry' +import {FunctionCallLicenseGate} from '../license/FunctionCallLicenseGate' import {ColumnSearchStrategy} from '../Lookup/SearchStrategy' import {Maybe} from '../Maybe' import {NamedExpressions} from '../NamedExpressions' @@ -46,18 +45,8 @@ import { AddressWithSheet } from '../parser/Address' export class Interpreter { public readonly criterionBuilder: CriterionBuilder - /* - * The license decisions applied to every function call, read once from the config instead of - * through its getters (a WeakMap lookup each) on the hottest path of evaluation. They cannot go - * stale: a Config never changes once built, and `updateConfig` builds a new engine, and with it a - * new Interpreter. - */ - private readonly licenseBlocksEvaluation: boolean - private readonly licenseKeyValidityState: LicenseKeyValidityState - private readonly capabilityRegistry: CapabilityRegistry - private readonly licenseCapabilities: ResolvedCapabilities - /** `false` for a key that grants every function, which lets a call skip the alias and table lookups. */ - private readonly licenseRestrictsFunctions: boolean + /** Decides which function calls the license stops; see {@link FunctionCallLicenseGate}. */ + private readonly functionCallLicenseGate: FunctionCallLicenseGate constructor( public readonly config: Config, @@ -73,11 +62,7 @@ export class Interpreter { ) { this.functionRegistry.initializePlugins(this) this.criterionBuilder = new CriterionBuilder(config) - this.licenseBlocksEvaluation = config.licenseBlocksEvaluation - this.licenseKeyValidityState = config.licenseKeyValidityState - this.capabilityRegistry = config.capabilityRegistry - this.licenseCapabilities = config.licenseCapabilities - this.licenseRestrictsFunctions = config.licenseCapabilities.functions !== 'all' + this.functionCallLicenseGate = new FunctionCallLicenseGate(config, functionRegistry) } public evaluateAst(ast: Ast, state: InterpreterState): InterpreterValue { @@ -196,15 +181,9 @@ export class Interpreter { return this.unaryRangeWrapper(this.percentOp, result, state) } case AstNodeType.FUNCTION_CALL: { - if (!FunctionRegistry.functionIsProtected(ast.procedureName)) { - if (this.licenseBlocksEvaluation) { - return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(this.licenseKeyValidityState)) - } - - if (this.licenseRestrictsFunctions - && !licenseAllowsFunction(this.capabilityRegistry, this.licenseCapabilities, this.functionRegistry.getCanonicalFunctionId(ast.procedureName))) { - return new CellError(ErrorType.LIC, ErrorMessage.LicenseCapability(ast.procedureName)) - } + const licenseError = this.functionCallLicenseGate.stoppedCallError(ast.procedureName) + if (licenseError !== undefined) { + return licenseError } const pluginFunction = this.functionRegistry.getFunction(ast.procedureName) if (pluginFunction !== undefined) { diff --git a/src/license/FunctionCallLicenseGate.ts b/src/license/FunctionCallLicenseGate.ts new file mode 100644 index 0000000000..a29ae4e053 --- /dev/null +++ b/src/license/FunctionCallLicenseGate.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright (c) 2025 Handsoncode. All rights reserved. + */ + +import {CellError, ErrorType} from '../Cell' +import {Config} from '../Config' +import {ErrorMessage} from '../error-message' +import {LicenseKeyValidityState} from '../helpers/licenseKeyValidator' +import {FunctionRegistry} from '../interpreter/FunctionRegistry' +import {CapabilityRegistry, licenseAllowsFunction, ResolvedCapabilities} from './CapabilityRegistry' + +/** + * Decides whether the license stops a function call, and with which `#LIC!` error. + * + * The one rule behind two consumers: the interpreter, which evaluates a stopped call to that + * error, and the array size predictor, which sizes a stopped call as a single cell. A stopped call + * therefore reserves no spill range, so its `#LIC!` appears in its own cell only and a non-empty + * cell below it cannot turn it into `#SPILL!`. Sharing one object keeps the two from disagreeing + * about the same call. + * + * Built from an engine's config, once per consumer. The license decisions are read off the config + * here rather than through its getters (a WeakMap lookup each), because the interpreter asks on the + * hottest path of evaluation. They cannot go stale: a Config never changes once built, and + * `updateConfig` builds a new engine, and with it new consumers. + */ +export class FunctionCallLicenseGate { + private readonly blocksEvaluation: boolean + private readonly validityState: LicenseKeyValidityState + private readonly capabilityRegistry: CapabilityRegistry + private readonly capabilities: ResolvedCapabilities + /** `false` for a key that grants every function, which lets a call skip the alias and table lookups. */ + private readonly restrictsFunctions: boolean + + /** + * @param {Config} config - the engine's config, holding its resolved license + * @param {FunctionRegistry} functionRegistry - the engine's registry, which resolves aliases + */ + constructor(config: Config, private readonly functionRegistry: FunctionRegistry) { + this.blocksEvaluation = config.licenseBlocksEvaluation + this.validityState = config.licenseKeyValidityState + this.capabilityRegistry = config.capabilityRegistry + this.capabilities = config.licenseCapabilities + this.restrictsFunctions = config.licenseCapabilities.functions !== 'all' + } + + /** + * Returns the `#LIC!` error a call to the function evaluates to, or `undefined` when the license + * lets the call run. The checks run in the specification's order: a protected function always + * runs; a key that blocks evaluation stops every other call (C1); a key that evaluates stops a + * call to a function it does not grant (C2), checking an alias as its canonical function. + * + * @param {string} procedureName - the function id as written in the formula + */ + public stoppedCallError(procedureName: string): CellError | undefined { + if (FunctionRegistry.functionIsProtected(procedureName)) { + return undefined + } + + if (this.blocksEvaluation) { + return new CellError(ErrorType.LIC, ErrorMessage.LicenseKey(this.validityState)) + } + + if (this.restrictsFunctions + && !licenseAllowsFunction(this.capabilityRegistry, this.capabilities, this.functionRegistry.getCanonicalFunctionId(procedureName))) { + return new CellError(ErrorType.LIC, ErrorMessage.LicenseCapability(procedureName)) + } + + return undefined + } + + /** + * Whether the license stops a call to the function, so that the call evaluates to `#LIC!`. + * + * @param {string} procedureName - the function id as written in the formula + */ + public stopsCall(procedureName: string): boolean { + return this.stoppedCallError(procedureName) !== undefined + } +} From d952c7d01d607c8baba282e08e2c257f366f7e8c Mon Sep 17 00:00:00 2001 From: Kuba Sekowski Date: Wed, 7 Oct 2026 18:01:09 +0200 Subject: [PATCH 51/54] HF-307: moving or pasting a formula with an undefined name no longer adds a named expression Moving or pasting a formula across sheets copies a name the source sheet defines locally to the global scope. It also did so for a name defined nowhere: the placeholder kept for an undefined name became an empty global named expression, the formula's #NAME? turned into an empty value, and the workbook serialized a named expression its author never added - which, with the license gate, a key without named_expressions could not build again. Only a name the source sheet defines locally is copied now. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/Operations.ts | 9 ++++++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6384d795c0..57a51f763d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Fixed +- Fixed moving or pasting a formula that refers to an undefined name to another sheet adding that name as an empty global named expression: the formula's `#NAME?` error turned into an empty value, and the workbook listed and serialized a named expression nobody added. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed an array function stopped by the license key reserving its spill range: it filled the whole range with `#LIC!`, or showed `#SPILL!` instead of `#LIC!` when a cell in that range was not empty. It now evaluates to `#LIC!` in its own cell only. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the validation of classic (25-character) license keys depending on the time zone: east of UTC, a key that expired the day before the build was released was still accepted, and west of UTC, the console message printed an expiry date one day too early. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) diff --git a/src/Operations.ts b/src/Operations.ts index 6a0e5ccdd4..df6d41264f 100644 --- a/src/Operations.ts +++ b/src/Operations.ts @@ -958,10 +958,17 @@ export class Operations { const expressionName = namedExpressionDependency.name const sourceVertex = this.dependencyGraph.fetchNamedExpressionVertex(expressionName, sourceSheet).vertex const namedExpressionInTargetScope = this.namedExpressions.isExpressionInScope(expressionName, targetAddress.sheet) + const namedExpressionInSourceScope = this.namedExpressions.isExpressionInScope(expressionName, sourceSheet) + // A name the source sheet does not define locally resolves to the same workbook-level vertex + // from either sheet: a global named expression, or the placeholder of a name defined nowhere. + // There is nothing to copy then, and copying would turn an undefined name into an empty + // global named expression, changing the formula's #NAME? into an empty value. const targetScopeExpressionVertex = namedExpressionInTargetScope ? this.dependencyGraph.fetchNamedExpressionVertex(expressionName, targetAddress.sheet).vertex - : this.copyOrFetchGlobalNamedExpressionVertex(expressionName, sourceVertex, addedGlobalNamedExpressions) + : namedExpressionInSourceScope + ? this.copyOrFetchGlobalNamedExpressionVertex(expressionName, sourceVertex, addedGlobalNamedExpressions) + : sourceVertex if (targetScopeExpressionVertex !== sourceVertex) { this.dependencyGraph.graph.removeEdgeIfExists(sourceVertex, vertex) From 3e8ffcf7b5b0c30b9938e61edb4bda3d0410c17b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 7 Oct 2026 16:14:27 +0000 Subject: [PATCH 52/54] Rephrase and shorten changelog entry for undefined name bug fix Co-authored-by: Kuba Sekowski --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 57a51f763d..73d9989dca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), - Fixed the localized names of `VSTACK` and `HSTACK` in 14 language packs to match Microsoft Excel. [#1748](https://github.com/handsontable/hyperformula/pull/1748) - Fixed the MAXPOOL and MEDIANPOOL functions throwing an uncaught `TypeError` instead of returning the `#VALUE!` error when the range dimensions are not a whole multiple of the window size and the stride. [#1718](https://github.com/handsontable/hyperformula/pull/1718) - Fixed the `MOD` function returning a remainder with the sign of the dividend instead of the sign of the divisor, which made the results differ from Excel and Google Sheets for arguments with opposite signs (e.g. `=MOD(-3, 12)` now returns `9` instead of `-3`). [#1747](https://github.com/handsontable/hyperformula/issues/1747) +- Fixed a bug where moving or pasting a formula with an undefined name to another sheet incorrectly added an empty global named expression. [#1728](https://github.com/handsontable/hyperformula/pull/1728) ## [3.4.0] - 2026-08-10 From c6ccee46021cdbcecee5d8be99d21ecac1944328 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 7 Oct 2026 16:15:11 +0000 Subject: [PATCH 53/54] Remove duplicate changelog entry (keep shorter version) Co-authored-by: Kuba Sekowski --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 73d9989dca..47d1bc6c19 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Fixed -- Fixed moving or pasting a formula that refers to an undefined name to another sheet adding that name as an empty global named expression: the formula's `#NAME?` error turned into an empty value, and the workbook listed and serialized a named expression nobody added. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed an array function stopped by the license key reserving its spill range: it filled the whole range with `#LIC!`, or showed `#SPILL!` instead of `#LIC!` when a cell in that range was not empty. It now evaluates to `#LIC!` in its own cell only. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the validation of classic (25-character) license keys depending on the time zone: east of UTC, a key that expired the day before the build was released was still accepted, and west of UTC, the console message printed an expiry date one day too early. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) From f9819f7ac32d14c6db6cfc93be2a3485125d1987 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 7 Oct 2026 16:16:33 +0000 Subject: [PATCH 54/54] Remove array function spill range changelog entry Co-authored-by: Kuba Sekowski --- CHANGELOG.md | 1 - 1 file changed, 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 47d1bc6c19..787c642ad9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,7 +18,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ### Fixed -- Fixed an array function stopped by the license key reserving its spill range: it filled the whole range with `#LIC!`, or showed `#SPILL!` instead of `#LIC!` when a cell in that range was not empty. It now evaluates to `#LIC!` in its own cell only. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the validation of classic (25-character) license keys depending on the time zone: east of UTC, a key that expired the day before the build was released was still accepted, and west of UTC, the console message printed an expiry date one day too early. [#1728](https://github.com/handsontable/hyperformula/pull/1728) - Fixed the `AVERAGEIF` function returning a division-by-zero error when the calculated average was `0`. [#1733](https://github.com/handsontable/hyperformula/pull/1733) - Fixed the localized names of `VSTACK` and `HSTACK` in 14 language packs to match Microsoft Excel. [#1748](https://github.com/handsontable/hyperformula/pull/1748)