Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,61 @@
import { describe, expect, it } from "vitest";
import { getDefaultProductBlueprint, getProductBlueprint, productBlueprintIds, productBlueprints } from "./index.js";
describe("product blueprint lookups", () => {
it("resolves the CRM SaaS blueprint by id and returns the shared registry instance", () => {
const blueprint = getProductBlueprint(productBlueprintIds.crmSaas);
expect(blueprint).toBeDefined();
expect(blueprint?.id).toBe(productBlueprintIds.crmSaas);
// The lookup must hand back the frozen registry instance, not a fresh copy.
expect(blueprint).toBe(productBlueprints[0]);
expect(getProductBlueprint(productBlueprintIds.crmSaas)).toBe(getDefaultProductBlueprint());
});
it("returns undefined for an unknown blueprint id without throwing", () => {
expect(getProductBlueprint("missing-blueprint")).toBeUndefined();
expect(getProductBlueprint("")).toBeUndefined();
});
it("exposes the default showcase blueprint as the CRM SaaS core", () => {
const blueprint = getDefaultProductBlueprint();
expect(blueprint.id).toBe(productBlueprintIds.crmSaas);
expect(blueprint.defaultShowcase).toBe(true);
expect(blueprint.version).toBe("2026.05.15");
});
it("keeps blueprint fixtures deeply immutable", () => {
expect(Object.isFrozen(productBlueprints)).toBe(true);
for (const blueprint of productBlueprints) {
expect(Object.isFrozen(blueprint)).toBe(true);
expect(Object.isFrozen(blueprint.features)).toBe(true);
for (const feature of blueprint.features) {
expect(Object.isFrozen(feature)).toBe(true);
}
}
const target = getDefaultProductBlueprint();
expect(() => {
(target as { version: string }).version = "tampered";
}).toThrow(TypeError);
expect(getDefaultProductBlueprint().version).toBe("2026.05.15");
});
it("gates every CRM SaaS feature behind a tenant role permission and enables it by default", () => {
const blueprint = getDefaultProductBlueprint();
const featureKeysInBlueprint = blueprint.features.map((feature) => feature.featureKey);
// Feature keys are unique within the blueprint feature set.
expect(new Set(featureKeysInBlueprint).size).toBe(featureKeysInBlueprint.length);
for (const feature of blueprint.features) {
expect(feature.defaultEnabled, `${feature.featureKey} default enabled`).toBe(true);
expect(typeof feature.requiresTenantRolePermission, `${feature.featureKey} required permission`).toBe("string");
expect(feature.requiresTenantRolePermission, `${feature.featureKey} non-empty permission`).not.toBe("");
}
});
});
@@ -41,16 +41,28 @@ export const productBlueprints = Object.freeze([
id: productBlueprintIds.crmSaas,
version: "2026.05.15",
title: "CRM SaaS",
description: "Default CRM SaaS product core with support, knowledge base, marketing, API, AI credits, workflow automation, and optional tenant MCP.",
description: "Default CRM SaaS product core with support, knowledge base, marketing, billing, search, automation, API, and optional tenant MCP.",
defaultShowcase: true,
features: Object.freeze([
blueprintFeature(featureKeys.dashboard, true, false, "dashboard.read"),
blueprintFeature(featureKeys.crmBasic, true, false, "app.dashboard.view"),
blueprintFeature(featureKeys.leads, true, true, "leads.read_own"),
blueprintFeature(featureKeys.projects, true, true, "projects.read_own"),
blueprintFeature(featureKeys.files, true, true, "files.read_own"),
blueprintFeature(featureKeys.tasks, true, true, "tasks.read_own"),
blueprintFeature(featureKeys.hr, true, true, "hr.read_own"),
blueprintFeature(featureKeys.integrations, true, true, "integrations.read"),
blueprintFeature(featureKeys.booking, true, true, "bookings.read_own"),
blueprintFeature(featureKeys.forms, true, true, "forms.basic"),
blueprintFeature(featureKeys.signature, true, true, "signature.read"),
blueprintFeature(featureKeys.billing, true, true, "app.settings.subscription.view"),
blueprintFeature(featureKeys.search, true, true, "search.use"),
blueprintFeature(featureKeys.automation, true, true, "automation.read"),
blueprintFeature(featureKeys.supportTickets, true, true, "app.dashboard.view"),
blueprintFeature(featureKeys.knowledgeBaseRead, true, true, "app.dashboard.view"),
blueprintFeature(featureKeys.knowledgeBaseTenant, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.emailMarketing, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.emailInbox, true, true, "email.read_own"),
blueprintFeature(featureKeys.importedLists, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.crmBasedLists, true, true, "app.settings.roles.set"),
blueprintFeature(featureKeys.onboarding, true, true, "app.settings.roles.set"),
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const sourceRoot = dirname(fileURLToPath(import.meta.url));
const forbiddenImportPattern = /(?:from\s+["']|import\s*\(\s*["'])(~\/|app\/|@toolctrl\/(?:db|config)(?:\/|$)|react(?:\/|$)|react-router(?:\/|$)|stripe(?:\/|$)|@prisma\/client(?:\/|$)|\.prisma\/client(?:\/|$)|prisma(?:\/|$))/;
const forbiddenImportPattern = /(?:from\s+["']|import\s*\(\s*["'])(~\/|app\/|@hivegrid\/(?:db|config)(?:\/|$)|react(?:\/|$)|react-router(?:\/|$)|@prisma\/client(?:\/|$)|\.prisma\/client(?:\/|$)|prisma(?:\/|$))/;
const diagnosticTemplatePattern = /(?:message\s*[:=]|new\s+\w*Error\s*\()[^;\n]*/g;
const unsafeDiagnosticPattern = /tenant|customer|user|api[-_\s]?key|subscription[-_\s]?id|secret|sk_[a-z0-9]/i;
@@ -0,0 +1,123 @@
import { describe, expect, it } from "vitest";
import { entitlementLimitTypes, evaluateEntitlement } from "./index.js";
describe("evaluateEntitlement boundary behaviour", () => {
it("allows an active trial even when the subscription flag is explicitly false", () => {
const decision = evaluateEntitlement({
featureKey: "api",
hasSubscription: false,
trialActive: true,
limitType: entitlementLimitTypes.included,
});
expect(decision.allowed).toBe(true);
expect(decision.reason).toBe("trial-active");
});
it("lets an active trial bypass an otherwise exhausted usage quota", () => {
const decision = evaluateEntitlement({
featureKey: "users",
trialActive: true,
limitType: entitlementLimitTypes.max,
limit: 1,
used: 99,
});
// The trial branch short-circuits before any limit math, so no usage fields leak through.
expect(decision.allowed).toBe(true);
expect(decision.reason).toBe("trial-active");
expect(decision.remaining).toBeUndefined();
expect(decision.limit).toBeUndefined();
expect(decision.used).toBeUndefined();
});
it("treats a missing usage counter as zero on the allowed path for max limits", () => {
const decision = evaluateEntitlement({
featureKey: "users",
hasSubscription: true,
limitType: entitlementLimitTypes.max,
limit: 5,
});
expect(decision).toMatchObject({
allowed: true,
reason: "max-remaining",
limit: 5,
used: 0,
remaining: 5,
});
});
it("treats a missing usage counter as zero on the allowed path for monthly limits", () => {
const decision = evaluateEntitlement({
featureKey: "ai-credits",
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 250,
period: "2026-06",
});
expect(decision).toMatchObject({
allowed: true,
reason: "monthly-remaining",
limit: 250,
used: 0,
remaining: 250,
period: "2026-06",
});
});
it("normalizes an explicit null usage counter to zero", () => {
const decision = evaluateEntitlement({
featureKey: "users",
hasSubscription: true,
limitType: entitlementLimitTypes.max,
limit: 4,
used: null,
});
expect(decision).toMatchObject({
allowed: true,
reason: "max-remaining",
limit: 4,
used: 0,
remaining: 4,
});
});
it("denies a zero-limit usage quota as exhausted at the boundary", () => {
const decision = evaluateEntitlement({
featureKey: "ai-credits",
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 0,
used: 0,
period: "2026-06",
});
expect(decision).toMatchObject({
allowed: false,
reason: "monthly-exhausted",
limit: 0,
used: 0,
remaining: 0,
});
});
it("reports a missing subscription when the flag is explicitly false and no trial is set", () => {
const decision = evaluateEntitlement({
featureKey: "api",
hasSubscription: false,
limitType: entitlementLimitTypes.included,
});
expect(decision).toMatchObject({
allowed: false,
reason: "missing-subscription",
featureKey: "api",
});
// An undefined trial flag must not be mistaken for an expired trial.
expect(decision.reason).not.toBe("trial-expired");
});
});
@@ -241,6 +241,143 @@ describe("evaluateEntitlement", () => {
}
});
it("falls back to the generic message when an active trial omits a trial message", () => {
expect(
evaluateEntitlement({
featureKey: "api",
trialActive: true,
limitType: entitlementLimitTypes.included,
message: "Generic upgrade hint",
}),
).toEqual({
allowed: true,
reason: "trial-active",
featureKey: "api",
limitType: 1,
period: undefined,
trialPeriod: undefined,
message: "Generic upgrade hint",
});
});
it("prefers the trial message over the generic message when an expired trial provides one", () => {
expect(
evaluateEntitlement({
featureKey: "api",
trialActive: false,
trialPeriod: "trial-ended",
trialMessage: "Your trial has ended",
message: "Generic upgrade hint",
limitType: entitlementLimitTypes.included,
}),
).toMatchObject({
allowed: false,
reason: "trial-expired",
featureKey: "api",
limitType: 1,
trialPeriod: "trial-ended",
message: "Your trial has ended",
});
});
it("treats non-finite usage counters as zero for max-limited features", () => {
expect(
evaluateEntitlement({
featureKey: "users",
hasSubscription: true,
limitType: entitlementLimitTypes.max,
limit: Number.NaN,
used: Number.POSITIVE_INFINITY,
}),
).toMatchObject({
allowed: false,
reason: "max-exhausted",
featureKey: "users",
limitType: 3,
limit: 0,
used: 0,
remaining: 0,
});
});
it("clamps negative limit and usage counters to zero", () => {
expect(
evaluateEntitlement({
featureKey: "ai-credits",
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: -100,
used: -50,
period: "2026-06",
}),
).toMatchObject({
allowed: false,
reason: "monthly-exhausted",
featureKey: "ai-credits",
limitType: 2,
limit: 0,
used: 0,
remaining: 0,
period: "2026-06",
});
});
it("falls back to a missing limit as an exhausted quota for usage-limited features", () => {
expect(
evaluateEntitlement({
featureKey: "users",
hasSubscription: true,
limitType: entitlementLimitTypes.max,
}),
).toMatchObject({
allowed: false,
reason: "max-exhausted",
featureKey: "users",
limitType: 3,
limit: 0,
used: 0,
remaining: 0,
});
});
it("denies subscribed features when the limit type is unset (default branch)", () => {
expect(
evaluateEntitlement({
featureKey: "api",
hasSubscription: true,
}),
).toMatchObject({
allowed: false,
reason: "not-included",
featureKey: "api",
limitType: undefined,
limit: undefined,
used: undefined,
});
});
it("denies subscribed features for an unsupported limit type and reports normalized counters", () => {
expect(
evaluateEntitlement({
featureKey: "users",
hasSubscription: true,
limitType: 99 as never,
limit: 7,
used: 2,
period: "2026-06",
message: "Unsupported plan limit",
}),
).toMatchObject({
allowed: false,
reason: "not-included",
featureKey: "users",
limit: 7,
used: 2,
period: "2026-06",
message: "Unsupported plan limit",
});
});
it("keeps reason codes stable for package-boundary consumers", () => {
expect(stableReasonCodes).toEqual([
"included",
@@ -0,0 +1,33 @@
import { describe, expect, it } from "vitest";
import { assertKnownFeatureKey, getFeatureGate, isFeatureKey } from "./index.js";
describe("feature gate edge cases", () => {
it("includes the offending key in the assertion error message", () => {
expect(() => assertKnownFeatureKey("totally-made-up")).toThrow(RangeError);
expect(() => assertKnownFeatureKey("totally-made-up")).toThrow(/totally-made-up/);
});
it("rejects the empty string as a feature key", () => {
expect(isFeatureKey("")).toBe(false);
expect(getFeatureGate("")).toBeUndefined();
});
it("returns the full registry item for a known key via the lookup overload", () => {
const rateLimit = getFeatureGate("rate-limit-per-minute");
expect(rateLimit).toBeDefined();
expect(rateLimit?.category).toBe("usage");
// Rate limits are capped or off, never metered monthly.
expect(rateLimit?.supportedLimitTypes).toEqual(["not-included", "max", "unlimited"]);
expect(rateLimit?.supportedLimitTypes).not.toContain("monthly");
});
it("constrains pure access features to the access limit family", () => {
const knowledgeBaseRead = getFeatureGate("knowledge-base-read");
expect(knowledgeBaseRead?.supportedLimitTypes).toEqual(["not-included", "included", "unlimited"]);
expect(knowledgeBaseRead?.supportedLimitTypes).not.toContain("max");
expect(knowledgeBaseRead?.supportedLimitTypes).not.toContain("monthly");
});
});
@@ -3,13 +3,24 @@ import { describe, expect, it } from "vitest";
import { assertKnownFeatureKey, featureGateRegistry, featureKeys, getFeatureGate, isFeatureKey, type FeatureKey } from "./index.js";
const currentDefaultFeatureKeys = [
"dashboard",
"crm-basic",
"leads",
"projects",
"support-tickets",
"knowledge-base-read",
"knowledge-base-tenant",
"files",
"users",
"tasks",
"hr",
"integrations",
"booking",
"forms",
"signature",
"billing",
"search",
"automation",
"api",
"email-marketing",
"imported-lists",
@@ -19,6 +30,7 @@ const currentDefaultFeatureKeys = [
"mcp",
"advanced-builder",
"import-export",
"email-inbox",
"rate-limit-per-minute",
"rate-limit-per-second",
"priority-support",
@@ -1,12 +1,24 @@
export const featureKeys = {
dashboard: "dashboard",
crmBasic: "crm-basic",
leads: "leads",
projects: "projects",
files: "files",
tasks: "tasks",
hr: "hr",
integrations: "integrations",
booking: "booking",
forms: "forms",
signature: "signature",
billing: "billing",
search: "search",
automation: "automation",
supportTickets: "support-tickets",
knowledgeBaseRead: "knowledge-base-read",
knowledgeBaseTenant: "knowledge-base-tenant",
users: "users",
emailMarketing: "email-marketing",
emailInbox: "email-inbox",
importedLists: "imported-lists",
crmBasedLists: "crm-based-lists",
onboarding: "onboarding",
@@ -42,6 +54,14 @@ const quotaLimitTypes = ["not-included", "monthly", "max", "unlimited"] as const
const rateLimitTypes = ["not-included", "max", "unlimited"] as const satisfies readonly FeatureLimitType[];
export const featureGateRegistry = Object.freeze([
Object.freeze({
key: featureKeys.dashboard,
title: "Dashboard",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 4,
description: "Controls access to the tenant dashboard, role layouts, and dashboard widget catalog.",
}),
Object.freeze({
key: featureKeys.crmBasic,
title: "CRM basics",
@@ -50,12 +70,28 @@ export const featureGateRegistry = Object.freeze([
defaultOrder: 5,
description: "Controls access to the default CRM account, contact, and opportunity surfaces.",
}),
Object.freeze({
key: featureKeys.leads,
title: "Lead inbox",
category: "crm",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 6,
description: "Controls access to the lead intake, triage, anti-spam, and lead-to-project preparation surfaces.",
}),
Object.freeze({
key: featureKeys.projects,
title: "Projects and pipelines",
category: "crm",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 6.5,
description: "Controls access to the project core, pipeline engine, project CRUD, and sales pipeline surfaces.",
}),
Object.freeze({
key: featureKeys.supportTickets,
title: "Support tickets",
category: "support",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 6,
defaultOrder: 7,
description: "Controls support ticket creation and ticket volume.",
}),
Object.freeze({
@@ -63,7 +99,7 @@ export const featureGateRegistry = Object.freeze([
title: "Knowledge base read",
category: "support",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 7,
defaultOrder: 8,
description: "Controls read access to the global and product knowledge bases.",
}),
Object.freeze({
@@ -71,7 +107,7 @@ export const featureGateRegistry = Object.freeze([
title: "Tenant knowledge base",
category: "support",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 8,
defaultOrder: 9,
description: "Controls tenant-owned knowledge base authoring and publishing.",
}),
Object.freeze({
@@ -79,7 +115,7 @@ export const featureGateRegistry = Object.freeze([
title: "Files",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 9,
defaultOrder: 10,
description: "Controls access to the central file storage (chunked upload, preview, sharing).",
}),
Object.freeze({
@@ -87,7 +123,7 @@ export const featureGateRegistry = Object.freeze([
title: "Users",
category: "access",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 10,
defaultOrder: 11,
description: "Controls the number of workspace members available to an account.",
}),
Object.freeze({
@@ -95,9 +131,73 @@ export const featureGateRegistry = Object.freeze([
title: "Tasks",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 11,
defaultOrder: 12,
description: "Controls access to the cross-cutting task module (assignment, reminders, entity links).",
}),
Object.freeze({
key: featureKeys.hr,
title: "HR hub",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 13,
description: "Controls access to the HR hub (employee master data, locations, documents, encrypted password safe).",
}),
Object.freeze({
key: featureKeys.integrations,
title: "Integrations",
category: "automation",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 14,
description: "Controls the Apps-Engine integrations framework (OAuth/API-key connections, sync, health).",
}),
Object.freeze({
key: featureKeys.booking,
title: "Booking",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 15,
description: "Controls access to the Booking module (public booking pages, availability, appointment lifecycle).",
}),
Object.freeze({
key: featureKeys.forms,
title: "Forms",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 16,
description: "Controls access to the form builder, public form publishing, submissions, and post-submit actions.",
}),
Object.freeze({
key: featureKeys.signature,
title: "Signature",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 17,
description: "Controls access to the signature module (self-hosted SES default and optional provider adapters).",
}),
Object.freeze({
key: featureKeys.billing,
title: "Billing",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 17.5,
description: "Controls access to subscription, usage, billing recovery, and tenant-facing billing settings.",
}),
Object.freeze({
key: featureKeys.search,
title: "Global search",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 18,
description: "Controls access to permission-aware global search and recent searches.",
}),
Object.freeze({
key: featureKeys.automation,
title: "Automation",
category: "automation",
supportedLimitTypes: quotaLimitTypes,
defaultOrder: 19,
description: "Controls the typed automation engine, trigger/action registry, guards, templates, and execution volume.",
}),
Object.freeze({
key: featureKeys.api,
title: "API Access",
@@ -170,6 +270,14 @@ export const featureGateRegistry = Object.freeze([
defaultOrder: 28,
description: "Controls import/export heavy workflows and monthly operation volume.",
}),
Object.freeze({
key: featureKeys.emailInbox,
title: "Email inbox",
category: "access",
supportedLimitTypes: accessLimitTypes,
defaultOrder: 29,
description: "Controls access to the personal mailbox sync (Gmail/Microsoft), inbox surfaces, and mailbox sending.",
}),
Object.freeze({
key: featureKeys.rateLimitPerMinute,
title: "Rate limit per minute",
@@ -13,7 +13,7 @@ import {
describe("entitlements package shell", () => {
it("exports the package identity placeholder", () => {
expect(entitlementsPackageName).toBe("@toolctrl/entitlements");
expect(entitlementsPackageName).toBe("@hivegrid/entitlements");
});
it("defines the CRM SaaS product core blueprint as the default showcase", () => {
@@ -1,4 +1,4 @@
export const entitlementsPackageName = "@toolctrl/entitlements";
export const entitlementsPackageName = "@hivegrid/entitlements";
export {
assertKnownFeatureKey,
@@ -11,8 +11,8 @@ export { entitlementLimitTypes, evaluateEntitlement } from "./evaluate.js";
export {
entitlementPlanIds,
getStandardEntitlementPlan,
getStripePricePlaceholder,
getStripeProductPlaceholder,
getBillingProviderPricePlaceholder,
getBillingProviderProductPlaceholder,
listStandardEntitlementPlanIds,
standardEntitlementPlans,
} from "./plans.js";
@@ -5,8 +5,8 @@ import {
featureGateRegistry,
getFeatureGate,
getStandardEntitlementPlan,
getStripePricePlaceholder,
getStripeProductPlaceholder,
getBillingProviderPricePlaceholder,
getBillingProviderProductPlaceholder,
listStandardEntitlementPlanIds,
standardEntitlementPlans,
type EntitlementPlanFeatureAssignment,
@@ -15,13 +15,24 @@ import {
const expectedPlanIds = ["starter", "pro", "business"] as const;
const expectedFeatureKeys = [
"dashboard",
"crm-basic",
"leads",
"projects",
"support-tickets",
"knowledge-base-read",
"knowledge-base-tenant",
"files",
"users",
"tasks",
"hr",
"integrations",
"booking",
"forms",
"signature",
"billing",
"search",
"automation",
"api",
"email-marketing",
"imported-lists",
@@ -31,6 +42,7 @@ const expectedFeatureKeys = [
"mcp",
"advanced-builder",
"import-export",
"email-inbox",
"rate-limit-per-minute",
"rate-limit-per-second",
"priority-support",
@@ -110,28 +122,28 @@ describe("standardEntitlementPlans", () => {
it("exposes lookup helpers without mutating fixture order", () => {
expect(getStandardEntitlementPlan("pro")?.metadata.publicName).toBe("Pro");
expect(getStandardEntitlementPlan("pro")?.metadata.stripeProductId).toBe(getStripeProductPlaceholder("pro"));
expect(getStandardEntitlementPlan("pro")?.metadata.stripePriceId).toBe(getStripePricePlaceholder("pro"));
expect(getStandardEntitlementPlan("pro")?.metadata.billingProviderProductId).toBe(getBillingProviderProductPlaceholder("pro"));
expect(getStandardEntitlementPlan("pro")?.metadata.billingProviderPriceId).toBe(getBillingProviderPricePlaceholder("pro"));
expect(getStandardEntitlementPlan("unknown-plan")).toBeUndefined();
expect(listStandardEntitlementPlanIds()).toEqual(expectedPlanIds);
});
it("uses deterministic safe Stripe placeholders and no secret-looking fixture strings", () => {
it("uses deterministic safe Mollie placeholders and no secret-looking fixture strings", () => {
for (const plan of standardEntitlementPlans) {
expect(plan.metadata.stripeProductId, `${plan.id} product id placeholder`).toBe(getStripeProductPlaceholder(plan.id));
expect(plan.metadata.stripePriceId, `${plan.id} price id placeholder`).toBe(getStripePricePlaceholder(plan.id));
expect(plan.metadata.stripeProductId, `${plan.id} non-empty product placeholder`).not.toBe("");
expect(plan.metadata.stripePriceId, `${plan.id} non-empty price placeholder`).not.toBe("");
expect(getStandardEntitlementPlan(plan.id)?.metadata.stripeProductId, `${plan.id} lookup product placeholder`).toBe(plan.metadata.stripeProductId);
expect(getStandardEntitlementPlan(plan.id)?.metadata.stripePriceId, `${plan.id} lookup price placeholder`).toBe(plan.metadata.stripePriceId);
expect(plan.metadata.billingProviderProductId, `${plan.id} product id placeholder`).toBe(getBillingProviderProductPlaceholder(plan.id));
expect(plan.metadata.billingProviderPriceId, `${plan.id} price id placeholder`).toBe(getBillingProviderPricePlaceholder(plan.id));
expect(plan.metadata.billingProviderProductId, `${plan.id} non-empty product placeholder`).not.toBe("");
expect(plan.metadata.billingProviderPriceId, `${plan.id} non-empty price placeholder`).not.toBe("");
expect(getStandardEntitlementPlan(plan.id)?.metadata.billingProviderProductId, `${plan.id} lookup product placeholder`).toBe(plan.metadata.billingProviderProductId);
expect(getStandardEntitlementPlan(plan.id)?.metadata.billingProviderPriceId, `${plan.id} lookup price placeholder`).toBe(plan.metadata.billingProviderPriceId);
const strings = [
plan.id,
plan.metadata.slug,
plan.metadata.publicName,
plan.metadata.description,
plan.metadata.stripeProductId,
plan.metadata.stripePriceId,
plan.metadata.billingProviderProductId,
plan.metadata.billingProviderPriceId,
...plan.features.flatMap(assignmentStrings),
];
@@ -9,25 +9,25 @@ export const entitlementPlanIds = Object.freeze({
export type EntitlementPlanId = (typeof entitlementPlanIds)[keyof typeof entitlementPlanIds];
export const stripePlaceholderPrefixes = Object.freeze({
product: "fixture-stripe-product",
price: "fixture-stripe-price",
export const billingProviderPlaceholderPrefixes = Object.freeze({
product: "fixture-billing-provider-product",
price: "fixture-billing-provider-price",
} as const);
export function getStripeProductPlaceholder(planId: EntitlementPlanId): string {
return `${stripePlaceholderPrefixes.product}-${planId}`;
export function getBillingProviderProductPlaceholder(planId: EntitlementPlanId): string {
return `${billingProviderPlaceholderPrefixes.product}-${planId}`;
}
export function getStripePricePlaceholder(planId: EntitlementPlanId): string {
return `${stripePlaceholderPrefixes.price}-${planId}`;
export function getBillingProviderPricePlaceholder(planId: EntitlementPlanId): string {
return `${billingProviderPlaceholderPrefixes.price}-${planId}`;
}
export interface EntitlementPlanMetadata {
readonly slug: EntitlementPlanId;
readonly publicName: string;
readonly description: string;
readonly stripeProductId: string;
readonly stripePriceId: string;
readonly billingProviderProductId: string;
readonly billingProviderPriceId: string;
readonly sortOrder: number;
readonly isPublic: boolean;
}
@@ -60,15 +60,15 @@ function assignment(featureKey: FeatureKey, limitType: EntitlementLimitType, lim
function planStub(
id: EntitlementPlanId,
metadata: Omit<EntitlementPlanMetadata, "slug" | "stripeProductId" | "stripePriceId" | "isPublic">,
metadata: Omit<EntitlementPlanMetadata, "slug" | "billingProviderProductId" | "billingProviderPriceId" | "isPublic">,
features: readonly EntitlementPlanFeatureAssignment[]
): EntitlementPlanStub {
return Object.freeze({
id,
metadata: Object.freeze({
slug: id,
stripeProductId: getStripeProductPlaceholder(id),
stripePriceId: getStripePricePlaceholder(id),
billingProviderProductId: getBillingProviderProductPlaceholder(id),
billingProviderPriceId: getBillingProviderPricePlaceholder(id),
isPublic: true,
...metadata,
}),
@@ -85,14 +85,26 @@ export const standardEntitlementPlans = Object.freeze([
sortOrder: 10,
},
[
assignment(featureKeys.dashboard, entitlementLimitTypes.included, null, "Dashboard included"),
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.leads, entitlementLimitTypes.included, null, "Lead inbox included"),
assignment(featureKeys.projects, entitlementLimitTypes.included, null, "Projects and pipelines included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.hr, entitlementLimitTypes.included, null, "HR hub included"),
assignment(featureKeys.integrations, entitlementLimitTypes.included, null, "Integrations framework included"),
assignment(featureKeys.booking, entitlementLimitTypes.included, null, "Booking module included"),
assignment(featureKeys.forms, entitlementLimitTypes.included, null, "Forms module included"),
assignment(featureKeys.signature, entitlementLimitTypes.included, null, "Signature module included"),
assignment(featureKeys.billing, entitlementLimitTypes.included, null, "Billing module included"),
assignment(featureKeys.search, entitlementLimitTypes.included, null, "Global search included"),
assignment(featureKeys.automation, entitlementLimitTypes.notIncluded, null, "Automation engine not included"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.monthly, 50, "50 support tickets per month"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.notIncluded, null, "Tenant knowledge base authoring not included"),
assignment(featureKeys.users, entitlementLimitTypes.max, 3, "Up to 3 users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.notIncluded, null, "Email marketing not included"),
assignment(featureKeys.emailInbox, entitlementLimitTypes.notIncluded, null, "Mailbox sync not included"),
assignment(featureKeys.importedLists, entitlementLimitTypes.notIncluded, null, "Imported lists not included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.notIncluded, null, "CRM based lists not included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.notIncluded, null, "Onboarding builder not included"),
@@ -116,14 +128,26 @@ export const standardEntitlementPlans = Object.freeze([
sortOrder: 20,
},
[
assignment(featureKeys.dashboard, entitlementLimitTypes.included, null, "Dashboard included"),
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.leads, entitlementLimitTypes.included, null, "Lead inbox included"),
assignment(featureKeys.projects, entitlementLimitTypes.included, null, "Projects and pipelines included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.hr, entitlementLimitTypes.included, null, "HR hub included"),
assignment(featureKeys.integrations, entitlementLimitTypes.included, null, "Integrations framework included"),
assignment(featureKeys.booking, entitlementLimitTypes.included, null, "Booking module included"),
assignment(featureKeys.forms, entitlementLimitTypes.included, null, "Forms module included"),
assignment(featureKeys.signature, entitlementLimitTypes.included, null, "Signature module included"),
assignment(featureKeys.billing, entitlementLimitTypes.included, null, "Billing module included"),
assignment(featureKeys.search, entitlementLimitTypes.included, null, "Global search included"),
assignment(featureKeys.automation, entitlementLimitTypes.notIncluded, null, "Automation engine not included"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.monthly, 500, "500 support tickets per month"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.included, null, "Tenant knowledge base authoring included"),
assignment(featureKeys.users, entitlementLimitTypes.max, 10, "Up to 10 users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.monthly, 5000, "5,000 marketing sends per month"),
assignment(featureKeys.emailInbox, entitlementLimitTypes.included, null, "Mailbox sync (Gmail/Microsoft) included"),
assignment(featureKeys.importedLists, entitlementLimitTypes.included, null, "Imported lists included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.included, null, "CRM based lists included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.included, null, "Onboarding builder included"),
@@ -147,14 +171,26 @@ export const standardEntitlementPlans = Object.freeze([
sortOrder: 30,
},
[
assignment(featureKeys.dashboard, entitlementLimitTypes.included, null, "Dashboard included"),
assignment(featureKeys.crmBasic, entitlementLimitTypes.included, null, "CRM basics included"),
assignment(featureKeys.leads, entitlementLimitTypes.included, null, "Lead inbox included"),
assignment(featureKeys.projects, entitlementLimitTypes.included, null, "Projects and pipelines included"),
assignment(featureKeys.files, entitlementLimitTypes.included, null, "Central file storage included"),
assignment(featureKeys.tasks, entitlementLimitTypes.included, null, "Task management included"),
assignment(featureKeys.hr, entitlementLimitTypes.included, null, "HR hub included"),
assignment(featureKeys.integrations, entitlementLimitTypes.included, null, "Integrations framework included"),
assignment(featureKeys.booking, entitlementLimitTypes.included, null, "Booking module included"),
assignment(featureKeys.forms, entitlementLimitTypes.included, null, "Forms module included"),
assignment(featureKeys.signature, entitlementLimitTypes.included, null, "Signature module included"),
assignment(featureKeys.billing, entitlementLimitTypes.included, null, "Billing module included"),
assignment(featureKeys.search, entitlementLimitTypes.included, null, "Global search included"),
assignment(featureKeys.automation, entitlementLimitTypes.monthly, 10000, "10,000 automation runs per month"),
assignment(featureKeys.supportTickets, entitlementLimitTypes.unlimited, null, "Unlimited support tickets"),
assignment(featureKeys.knowledgeBaseRead, entitlementLimitTypes.included, null, "Global and tenant knowledge base reading"),
assignment(featureKeys.knowledgeBaseTenant, entitlementLimitTypes.included, null, "Tenant knowledge base authoring included"),
assignment(featureKeys.users, entitlementLimitTypes.unlimited, null, "Unlimited users"),
assignment(featureKeys.emailMarketing, entitlementLimitTypes.monthly, 50000, "50,000 marketing sends per month"),
assignment(featureKeys.emailInbox, entitlementLimitTypes.included, null, "Mailbox sync (Gmail/Microsoft) included"),
assignment(featureKeys.importedLists, entitlementLimitTypes.included, null, "Imported lists included"),
assignment(featureKeys.crmBasedLists, entitlementLimitTypes.included, null, "CRM based lists included"),
assignment(featureKeys.onboarding, entitlementLimitTypes.included, null, "Onboarding builder included"),
@@ -0,0 +1,59 @@
import { describe, expect, it } from "vitest";
import { entitlementLimitTypes, evaluateProductAccess, featureKeys, productBlueprintIds } from "./index.js";
const crmSaas = productBlueprintIds.crmSaas;
describe("evaluateProductAccess denied-entitlement passthrough", () => {
it("returns the missing-subscription entitlement under inherit without running the role gate", () => {
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.crmBasic,
hasSubscription: false,
limitType: entitlementLimitTypes.included,
// A valid permission is supplied, but the denied entitlement must short-circuit before the gate.
tenantRolePermissionNames: ["app.dashboard.view"],
});
expect(decision).toMatchObject({
allowed: false,
reason: "missing-subscription",
blueprintId: crmSaas,
tenantOverride: "inherit",
});
expect(decision.requiredTenantRolePermission).toBeUndefined();
});
it("passes an exhausted monthly quota straight through under an inherited override", () => {
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.supportTickets,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 50,
used: 50,
period: "2026-06",
tenantRolePermissionNames: ["app.dashboard.view"],
});
expect(decision).toMatchObject({
allowed: false,
reason: "monthly-exhausted",
blueprintId: crmSaas,
tenantOverride: "inherit",
remaining: 0,
period: "2026-06",
});
expect(decision.requiredTenantRolePermission).toBeUndefined();
});
it("defaults the tenant override to inherit when none is supplied", () => {
const decision = evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.crmBasic,
hasSubscription: false,
});
expect(decision.tenantOverride).toBe("inherit");
});
});
@@ -0,0 +1,172 @@
import { describe, expect, it } from "vitest";
import { entitlementLimitTypes, evaluateProductAccess, featureKeys, productBlueprintIds } from "./index.js";
const crmSaas = productBlueprintIds.crmSaas;
// supportTickets is tenant-toggleable in the blueprint and gated by "app.dashboard.view".
const toggleablePermission = ["app.dashboard.view"];
// workflowEngine is tenant-toggleable but gated by "app.settings.roles.set".
const rolesPermission = ["app.settings.roles.set"];
describe("evaluateProductAccess", () => {
it("denies access for an unknown product blueprint", () => {
expect(
evaluateProductAccess({
blueprintId: "unknown-blueprint",
featureKey: featureKeys.crmBasic,
hasSubscription: true,
limitType: entitlementLimitTypes.included,
tenantRolePermissionNames: toggleablePermission,
}),
).toMatchObject({
allowed: false,
reason: "blueprint-disabled",
blueprintId: "unknown-blueprint",
featureKey: featureKeys.crmBasic,
tenantOverride: "inherit",
});
});
it("denies access for a feature the blueprint does not define", () => {
// rate-limit-per-minute is a registered feature but is not part of the CRM SaaS blueprint feature set.
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.rateLimitPerMinute,
hasSubscription: true,
limitType: entitlementLimitTypes.max,
limit: 600,
used: 1,
tenantRolePermissionNames: rolesPermission,
}),
).toMatchObject({
allowed: false,
reason: "blueprint-disabled",
blueprintId: crmSaas,
featureKey: featureKeys.rateLimitPerMinute,
tenantOverride: "inherit",
});
});
it("inherits the plan entitlement when no tenant override is supplied", () => {
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.supportTickets,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 50,
used: 5,
period: "2026-06",
tenantRolePermissionNames: toggleablePermission,
}),
).toMatchObject({
allowed: true,
reason: "monthly-remaining",
blueprintId: crmSaas,
tenantOverride: "inherit",
remaining: 45,
period: "2026-06",
requiredTenantRolePermission: "app.dashboard.view",
});
});
it("rescues a denied plan entitlement when the tenant explicitly enables a toggleable feature", () => {
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.supportTickets,
hasSubscription: true,
limitType: entitlementLimitTypes.notIncluded,
tenantOverride: "enabled",
tenantRolePermissionNames: toggleablePermission,
}),
).toMatchObject({
allowed: true,
reason: "included",
blueprintId: crmSaas,
tenantOverride: "enabled",
requiredTenantRolePermission: "app.dashboard.view",
});
});
it("rescues an exhausted monthly quota when the tenant explicitly enables a toggleable feature", () => {
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 100,
tenantOverride: "enabled",
tenantRolePermissionNames: rolesPermission,
}),
).toMatchObject({
allowed: true,
reason: "included",
blueprintId: crmSaas,
tenantOverride: "enabled",
requiredTenantRolePermission: "app.settings.roles.set",
});
});
it("keeps the plan reason when an enabled override coincides with an allowed entitlement", () => {
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 10,
tenantOverride: "enabled",
tenantRolePermissionNames: rolesPermission,
}),
).toMatchObject({
allowed: true,
reason: "monthly-remaining",
blueprintId: crmSaas,
tenantOverride: "enabled",
remaining: 90,
});
});
it("blocks an enabled override when the tenant lacks the required role permission", () => {
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.notIncluded,
tenantOverride: "enabled",
tenantRolePermissionNames: [],
}),
).toMatchObject({
allowed: false,
reason: "tenant-role-missing",
blueprintId: crmSaas,
tenantOverride: "enabled",
requiredTenantRolePermission: "app.settings.roles.set",
});
});
it("treats a missing role permission list as no permissions", () => {
expect(
evaluateProductAccess({
blueprintId: crmSaas,
featureKey: featureKeys.workflowEngine,
hasSubscription: true,
limitType: entitlementLimitTypes.monthly,
limit: 100,
used: 10,
}),
).toMatchObject({
allowed: false,
reason: "tenant-role-missing",
blueprintId: crmSaas,
tenantOverride: "inherit",
requiredTenantRolePermission: "app.settings.roles.set",
});
});
});