Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,89 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
/**
* PII / secret regression test for SeedService.
*
* SeedService creates the bootstrap admin user with a hard-coded
* default password. The legacy console.log statements printed raw
* email addresses; the bigger risk is the password constant leaking
* by accident if a future change passes `password` into a logger arg.
*
* Policy:
* - never log raw `email` — always emailFingerprint(email)
* - never log `password`, `passwordHash`, `adminPassword`, or
* anything looking like a credential
* - no live console.* calls remain
*/
describe("SeedService PII discipline", () => {
const SOURCE = readFileSync(resolve(__dirname, "SeedService.ts"), "utf8");
it("contains no live console.* call sites", () => {
const live = SOURCE.split("\n").filter((line, idx, all) => {
if (!/console\.(log|error|warn|info|debug)\s*\(/.test(line)) return false;
const trimmed = line.trimStart();
if (trimmed.startsWith("//") || trimmed.startsWith("*")) return false;
const prev = idx > 0 ? all[idx - 1].trim() : "";
if (/eslint-disable-next-line[^\n]*no-console/.test(prev)) return false;
return true;
});
expect(live).toEqual([]);
});
it("never passes raw email / password fields as own seedLogger arg keys", () => {
const pattern = /seedLogger\.(info|warn|error|debug)\s*\(\s*\{([\s\S]*?)\}/g;
const forbiddenKeys = [
"email",
"password",
"passwordHash",
"adminEmail",
"adminPassword",
"rawPassword",
"plainPassword",
"secret",
"token",
];
const offenders: string[] = [];
let match: RegExpExecArray | null;
while ((match = pattern.exec(SOURCE)) !== null) {
const objContent = match[2];
for (const key of forbiddenKeys) {
const keyRe = new RegExp(`(^|[\\s,{])${key}\\s*:`, "m");
if (keyRe.test(objContent)) offenders.push(`key "${key}" in ${match[0].slice(0, 100)}...`);
}
}
expect(offenders, `seedLogger must not log PII/secret fields: ${offenders.join("; ")}`).toEqual([]);
});
it("defines and uses emailFingerprint() for any email-related diagnostics", () => {
expect(SOURCE).toMatch(/function emailFingerprint\(/);
expect(SOURCE).toMatch(/createHash\(["']sha256["']\)/);
// Anywhere we mention "email" inside a seedLogger call must be via emailFingerprint(...)
// (Aliased as emailFingerprint key — never raw email value)
expect(SOURCE).toMatch(/emailFingerprint\(email\)/);
});
it("uses createScopedLogger('seed')", () => {
expect(SOURCE).toMatch(/createScopedLogger\(\s*["']seed["']\s*\)/);
});
it("does not interpolate DEFAULT_ADMIN_PASSWORD into any log message", () => {
// Hard-coded admin password constant exists in source; ensure it never
// ends up in a logger arg object or template string.
const lines = SOURCE.split("\n");
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (/seedLogger\.|`/.test(line) && /DEFAULT_ADMIN_PASSWORD/.test(line)) {
// Only legal use of the constant: assignment line like `password: DEFAULT_ADMIN_PASSWORD` in the seed-user record.
// It must NOT appear inside a logger arg or template literal.
if (/seedLogger\./.test(line)) {
throw new Error(`SeedService PII leak: DEFAULT_ADMIN_PASSWORD used in seedLogger call at line ${i + 1}: ${line.trim()}`);
}
if (/`[^`]*\$\{[^}]*DEFAULT_ADMIN_PASSWORD/.test(line)) {
throw new Error(`SeedService PII leak: DEFAULT_ADMIN_PASSWORD interpolated in template at line ${i + 1}: ${line.trim()}`);
}
}
}
});
});
@@ -0,0 +1,451 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
type SeedService = typeof import("./SeedService").default;
const dbMock = {
user: {
findUnique: vi.fn(async ({ where }: { where: { email: string } }) => ({ id: `user-${where.email}` })),
create: vi.fn(),
},
adminUser: {
findUnique: vi.fn(async () => ({ userId: "admin-id" })),
create: vi.fn(),
},
tenant: {
findUnique: vi.fn(async ({ where, include }: { where: { slug: string }; include?: unknown }) => ({
id: `tenant-${where.slug}`,
slug: where.slug,
name: where.slug,
...(include ? { subscription: { id: `subscription-${where.slug}`, products: [] } } : {}),
})),
create: vi.fn(),
update: vi.fn(),
},
tenantInboundAddress: {
findFirst: vi.fn(),
create: vi.fn(),
},
tenantSubscription: {
findUnique: vi.fn(async ({ where }: { where: { tenantId: string } }) => ({ id: `subscription-${where.tenantId}` })),
create: vi.fn(),
},
tenantUser: {
findFirst: vi.fn(),
create: vi.fn(),
},
subscriptionProduct: {
findFirst: vi.fn(async ({ where }: { where: { stripeId: string } }) => ({ id: `product-${where.stripeId}` })),
},
tenantSubscriptionProduct: {
create: vi.fn(),
},
tenantProductConfiguration: {
upsert: vi.fn(),
},
tenantFeatureOverride: {
upsert: vi.fn(),
},
entity: {
aggregate: vi.fn(async () => ({ _max: { order: 0 } })),
findMany: vi.fn(async () => []),
create: vi.fn(async ({ data }: { data: { name: string } }) => ({ id: `entity-${data.name}`, ...data })),
updateMany: vi.fn(),
},
entityWebhook: {
create: vi.fn(),
},
property: {
create: vi.fn(async ({ data }: { data: { name: string } }) => ({ id: `property-${data.name}`, ...data })),
},
propertyOption: {
deleteMany: vi.fn(),
create: vi.fn(),
},
propertyAttribute: {
deleteMany: vi.fn(),
create: vi.fn(),
},
permission: {
findMany: vi.fn(async ({ where }: { where: { name: { in: string[] } } }) => where.name.in.map((name) => ({ id: `permission-${name}`, name }))),
},
role: {
findFirst: vi.fn(),
create: vi.fn(async ({ data }: { data: { name: string } }) => ({ id: `role-${data.name}` })),
},
rolePermission: {
findFirst: vi.fn(),
create: vi.fn(),
},
userRole: {
findFirst: vi.fn(),
create: vi.fn(),
},
knowledgeBase: {
upsert: vi.fn(async ({ create }: { create: { slug: string } }) => ({ id: `kb-${create.slug}` })),
},
knowledgeBaseCategory: {
upsert: vi.fn(async ({ create }: { create: { slug: string } }) => ({ id: `category-${create.slug}` })),
},
knowledgeBaseArticle: {
upsert: vi.fn(),
},
supportTicket: {
upsert: vi.fn(),
},
};
const hashMock = vi.fn(async () => "hashed-password");
const genSaltMock = vi.fn(async () => "generated-salt");
const seedRolesAndPermissionsMock = vi.fn();
const seedStandardEntitlementsMock = vi.fn();
const originalEnv = { ...process.env };
const loggerInfo = vi.fn();
const loggerWarn = vi.fn();
const loggerError = vi.fn();
const loggerDebug = vi.fn();
vi.mock("~/utils/logger.server", () => ({
createScopedLogger: () => ({ info: loggerInfo, warn: loggerWarn, error: loggerError, debug: loggerDebug }),
}));
vi.mock("bcryptjs", () => ({ default: { genSalt: genSaltMock, hash: hashMock } }));
vi.mock("@toolctrl/db/entitlements-seed.server", () => ({
getEntitlementPlanStripeId: ({ id }: { id: string }) => `toolctrl_entitlement_plan_${id}`,
seedStandardEntitlements: seedStandardEntitlementsMock,
}));
vi.mock("@toolctrl/db/seed.server", async () => {
const actual = await vi.importActual<typeof import("@toolctrl/db/seed.server")>("@toolctrl/db/seed.server");
return actual;
});
vi.mock("~/utils/services/emailService", () => ({ getAvailableTenantInboundAddress: vi.fn(async () => "seed@example.test") }));
vi.mock("~/utils/services/rolesAndPermissionsService", () => ({ seedRolesAndPermissions: seedRolesAndPermissionsMock }));
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
async function loadSeedService(): Promise<SeedService> {
vi.resetModules();
const module = await import("./SeedService");
return module.default;
}
describe("SeedService", () => {
beforeEach(() => {
vi.clearAllMocks();
process.env = { ...originalEnv };
delete process.env.SEED_ADMIN_EMAIL;
delete process.env.SEED_ADMIN_PASSWORD;
delete process.env.SEED_DEMO_DATA;
delete process.env.ALLOW_STAGING_DEMO_SEED;
process.env.NODE_ENV = "test";
});
it("rejects default admin credentials in production before DB writes", async () => {
process.env.NODE_ENV = "production";
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
const SeedService = await loadSeedService();
await expect(SeedService.seed()).rejects.toThrow("default seed credentials");
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
expect(dbMock.user.create).not.toHaveBeenCalled();
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("password");
});
it("uses safe admin credential overrides in production", async () => {
process.env.NODE_ENV = "production";
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
const SeedService = await loadSeedService();
await SeedService.seed();
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "owner@example.com" } });
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "luna.davis@company.com" } });
expect(dbMock.tenant.findUnique).not.toHaveBeenCalled();
expect(genSaltMock).toHaveBeenCalledWith(10);
expect(hashMock).toHaveBeenCalledWith("safe-production-password", "generated-salt");
expect(seedRolesAndPermissionsMock).toHaveBeenCalledWith({
adminEmail: "owner@example.com",
diagnostics: expect.any(Function),
});
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ op: "db-seed", phase: "start", nodeEnv: "production" }),
"DB seed event",
);
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ op: "db-seed", phase: "success", nodeEnv: "production" }),
"DB seed event",
);
// The new logger redacts admin email behind a SHA-256 fingerprint. The
// raw email must never appear in any logger arg.
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("owner@example.com");
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("safe-production-password");
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("safe-production-password");
});
it("rejects blank admin credential overrides in production before DB writes", async () => {
process.env.NODE_ENV = "production";
process.env.SEED_ADMIN_EMAIL = "";
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
const SeedService = await loadSeedService();
await expect(SeedService.seed()).rejects.toThrow("missing seed credentials");
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
expect(dbMock.user.create).not.toHaveBeenCalled();
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
});
it("refuses to promote an existing non-admin user during production seed", async () => {
process.env.NODE_ENV = "production";
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
dbMock.user.findUnique.mockResolvedValueOnce({ id: "existing-user", email: "owner@example.com" } as never);
dbMock.adminUser.findUnique.mockResolvedValueOnce(null as never);
const SeedService = await loadSeedService();
await expect(SeedService.seed()).rejects.toThrow("Production seed refused to promote an existing non-admin user");
expect(dbMock.adminUser.create).not.toHaveBeenCalled();
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
});
it("skips local demo users and tenants unless explicitly enabled", async () => {
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
await SeedService.seed();
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
expect(dbMock.user.findUnique).not.toHaveBeenCalledWith({ where: { email: "luna.davis@company.com" } });
expect(dbMock.tenant.findUnique).not.toHaveBeenCalled();
expect(loggerInfo).not.toHaveBeenCalledWith(
expect.objectContaining({ op: "seed.createDemoUsers" }),
expect.anything(),
);
});
it("seeds local demo users and tenants only when explicitly enabled outside production", async () => {
process.env.SEED_DEMO_DATA = "true";
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
await SeedService.seed();
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "admin@email.com" } });
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "luna.davis@company.com" } });
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-pro-crm" } });
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-business-crm" } });
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { stripeId: "toolctrl_entitlement_plan_starter" },
select: { id: true },
});
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { stripeId: "toolctrl_entitlement_plan_pro" },
select: { id: true },
});
expect(dbMock.subscriptionProduct.findFirst).toHaveBeenCalledWith({
where: { stripeId: "toolctrl_entitlement_plan_business" },
select: { id: true },
});
expect(dbMock.tenantSubscriptionProduct.create).toHaveBeenCalledTimes(3);
expect(dbMock.entity.findMany).toHaveBeenCalledWith({
where: { name: { in: ["company", "contact", "opportunity"] } },
select: { id: true, name: true, type: true },
});
expect(dbMock.entity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "company", type: "all" }) }));
expect(dbMock.entity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "contact", type: "all" }) }));
expect(dbMock.entity.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "opportunity", type: "all" }) }));
expect(dbMock.entity.create).not.toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ name: "submission" }) }));
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalledTimes(3);
expect(dbMock.knowledgeBase.upsert).toHaveBeenCalledTimes(3);
expect(dbMock.supportTicket.upsert).toHaveBeenCalledTimes(6);
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ op: "seed.createDemoUsers", count: 2 }),
"Creating CRM SaaS demo users with tenants",
);
});
it("refuses demo data in production without the explicit staging override", async () => {
process.env.NODE_ENV = "production";
process.env.SEED_DEMO_DATA = "true";
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
const SeedService = await loadSeedService();
await expect(SeedService.seed()).rejects.toThrow("ALLOW_STAGING_DEMO_SEED=true");
expect(dbMock.user.findUnique).not.toHaveBeenCalled();
expect(seedRolesAndPermissionsMock).not.toHaveBeenCalled();
expect(seedStandardEntitlementsMock).not.toHaveBeenCalled();
});
it("allows explicit staging demo data while production runtime safety stays opt-in", async () => {
process.env.NODE_ENV = "production";
process.env.SEED_DEMO_DATA = "true";
process.env.ALLOW_STAGING_DEMO_SEED = "true";
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-production-password";
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
const SeedService = await loadSeedService();
await SeedService.seed();
expect(dbMock.user.findUnique).toHaveBeenCalledWith({ where: { email: "john.doe@company.com" } });
expect(dbMock.tenant.findUnique).toHaveBeenCalledWith({ where: { slug: "demo-starter-crm" } });
expect(dbMock.tenantProductConfiguration.upsert).toHaveBeenCalled();
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ op: "db-seed", phase: "start", nodeEnv: "staging-demo" }),
"DB seed event",
);
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("owner@example.com");
});
it("seeds standard entitlements once after roles and permissions", async () => {
const SeedService = await loadSeedService();
const calls: string[] = [];
seedRolesAndPermissionsMock.mockImplementation(async () => {
calls.push("roles");
});
seedStandardEntitlementsMock.mockImplementation(async () => {
calls.push("entitlements");
return {
planCount: 3,
featureCount: 9,
createdProducts: 3,
updatedProducts: 0,
deletedFeatures: 0,
createdFeatures: 9,
};
});
await SeedService.seed();
expect(seedRolesAndPermissionsMock).toHaveBeenCalledWith({
adminEmail: "admin@email.com",
diagnostics: expect.any(Function),
});
expect(seedStandardEntitlementsMock).toHaveBeenCalledOnce();
expect(seedStandardEntitlementsMock).toHaveBeenCalledWith({
client: dbMock,
diagnostics: expect.any(Function),
});
expect(calls).toEqual(["roles", "entitlements"]);
});
it("logs redacted DB seed failure diagnostics without raw secret errors", async () => {
process.env.SEED_ADMIN_EMAIL = "owner@example.com";
process.env.SEED_ADMIN_PASSWORD = "safe-secret-password";
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
const originalError = new Error("failed with safe-secret-password token sk_live_secret");
seedRolesAndPermissionsMock.mockRejectedValueOnce(originalError);
await expect(SeedService.seed()).rejects.toBe(originalError);
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({ op: "db-seed", phase: "failure", nodeEnv: "test" }),
"DB seed event",
);
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("owner@example.com");
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("safe-secret-password");
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("sk_live_secret");
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("safe-secret-password");
expect(JSON.stringify(consoleLog.mock.calls)).not.toContain("sk_live_secret");
});
it("logs redacted roles and permissions seed diagnostics from the helper", async () => {
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
seedRolesAndPermissionsMock.mockImplementation(async ({ diagnostics }) => {
await diagnostics?.({
phase: "success",
adminRoleCount: 1,
appRoleCount: 4,
defaultPermissionCount: 120,
dynamicEntityPermissionCount: 3,
adminUserAssignmentCount: 1,
tenantUserAssignmentCount: 8,
password: "password",
token: "sk_live_secret",
});
});
await SeedService.seed();
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({
op: "seed.rolesAndPermissions",
phase: "success",
adminRoleCount: 1,
appRoleCount: 4,
defaultPermissionCount: 120,
dynamicEntityPermissionCount: 3,
adminUserAssignmentCount: 1,
tenantUserAssignmentCount: 8,
}),
"Roles and permissions seed event",
);
// The helper-supplied `password` and `token` fields must be dropped
// before they hit the logger.
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("password");
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("sk_live_secret");
});
it("logs redacted entitlements seed diagnostics from the helper", async () => {
const SeedService = await loadSeedService();
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => undefined);
seedStandardEntitlementsMock.mockImplementation(async ({ diagnostics }) => {
await diagnostics?.({
phase: "failure",
planCount: 3,
featureCount: 9,
createdProducts: 1,
updatedProducts: 2,
deletedFeatures: 4,
createdFeatures: 5,
planId: "team",
error: {
name: "Error",
message: "Failed for [redacted]",
},
});
return {
planCount: 3,
featureCount: 9,
createdProducts: 1,
updatedProducts: 2,
deletedFeatures: 4,
createdFeatures: 5,
};
});
await SeedService.seed();
expect(loggerInfo).toHaveBeenCalledWith(
expect.objectContaining({
op: "seed.entitlements",
phase: "failure",
planCount: 3,
featureCount: 9,
createdProducts: 1,
updatedProducts: 2,
deletedFeatures: 4,
createdFeatures: 5,
planId: "team",
err: expect.objectContaining({ name: "Error", message: "Failed for [redacted]" }),
}),
"Entitlements seed event",
);
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("sk_live_");
expect(JSON.stringify(loggerInfo.mock.calls)).not.toContain("cus_secret");
});
});
@@ -0,0 +1,615 @@
import { createHash } from "node:crypto";
import bcrypt from "bcryptjs";
import { TenantUserJoined } from "~/application/enums/tenants/TenantUserJoined";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
import { getAvailableTenantInboundAddress } from "~/utils/services/emailService";
import { getEntitlementPlanStripeId, seedStandardEntitlements, type EntitlementsSeedDiagnosticEvent } from "@toolctrl/db/entitlements-seed.server";
import { runDbSeed, type DbSeedDiagnosticEvent } from "@toolctrl/db/seed.server";
import { entitlementPlanIds, featureKeys, productBlueprintIds, type EntitlementPlanId } from "@toolctrl/entitlements";
import { seedRolesAndPermissions, type RolesAndPermissionsSeedDiagnosticEvent } from "~/utils/services/rolesAndPermissionsService";
import { db } from "~/utils/db.server";
import { ensureProductCoreCrmEntities } from "~/modules/crm/services/ProductCoreCrmEntities.server";
import { createScopedLogger } from "~/utils/logger.server";
const seedLogger = createScopedLogger("seed");
/**
* Hashes an email (lower-cased + trimmed) so seed logs cannot leak the
* actual address but operators can still correlate diagnostics.
*/
function emailFingerprint(email: string): string {
return createHash("sha256").update(email.trim().toLowerCase(), "utf8").digest("hex").slice(0, 12);
}
const DEFAULT_ADMIN_EMAIL = "admin@email.com";
const DEFAULT_ADMIN_PASSWORD = "password";
const localDemoSeedUsers = [
{
userType: "app" as const,
firstName: "John",
lastName: "Doe",
email: "john.doe@company.com",
password: "password",
},
{
userType: "app" as const,
firstName: "Luna",
lastName: "Davis",
email: "luna.davis@company.com",
password: "password",
},
];
const demoCrmTenants = [
{ slug: "demo-starter-crm", name: "Demo Starter CRM", planId: entitlementPlanIds.starter },
{ slug: "demo-pro-crm", name: "Demo Pro CRM", planId: entitlementPlanIds.pro },
{ slug: "demo-business-crm", name: "Demo Business CRM", planId: entitlementPlanIds.business },
] as const;
const demoTenantRoleSeeds = [
{
name: "CRM Manager",
description: "Owns CRM records, imports, and tenant team coordination in the demo workspace.",
permissions: ["app.dashboard.view", "app.settings.members.view", "app.settings.roles.view"],
},
{
name: "Support Agent",
description: "Handles tenant support tickets and reads the tenant knowledge base in the demo workspace.",
permissions: ["app.dashboard.view"],
},
] as const;
const demoKnowledgeBaseCategoryTitle = "Product Core";
const demoKnowledgeBaseCategoryDescription = "Plan gates, tenant roles, support, and CRM SaaS setup.";
const demoKnowledgeBaseArticleTitle = "Plan gates overview";
const demoSupportTicketSubjects = {
welcome: "Welcome to the CRM SaaS demo workspace",
planGates: "Verify plan gates and tenant roles",
} as const;
const demoSupportTicketPlanGatesMessage =
"Use this ticket to confirm blueprint, plan, tenant override, and tenant-owned role access in the seeded workspace.";
function getAdminSeedUser() {
return {
email: process.env.SEED_ADMIN_EMAIL ?? DEFAULT_ADMIN_EMAIL,
password: process.env.SEED_ADMIN_PASSWORD ?? DEFAULT_ADMIN_PASSWORD,
firstName: "Admin",
lastName: "User",
};
}
async function seed() {
const adminUser = getAdminSeedUser();
const shouldSeedDemoData = shouldSeedCrmDemoData();
const seedCredentials = shouldSeedDemoData
? [
{ label: "admin", email: adminUser.email, password: adminUser.password },
...localDemoSeedUsers.map((user) => ({ label: user.email, email: user.email, password: user.password })),
]
: [{ label: "admin", email: adminUser.email, password: adminUser.password }];
return runDbSeed({
nodeEnv: getSeedSafetyEnvironment(),
adminEmail: adminUser.email,
adminPassword: adminUser.password,
seedCredentials,
diagnostics: logDbSeedDiagnostic,
seed: async () => {
const admin = await createUser({ userType: "admin", ...adminUser });
let demoUsers: Awaited<ReturnType<typeof createUser>>[] = [];
if (shouldSeedDemoData) {
seedLogger.info({ op: "seed.createDemoUsers", count: localDemoSeedUsers.length }, "Creating CRM SaaS demo users with tenants");
demoUsers = await Promise.all(localDemoSeedUsers.map((user) => createUser(user)));
const [user1, user2] = demoUsers;
await Promise.all(
demoCrmTenants.map((tenant, index) =>
createTenant(tenant.slug, tenant.name, [
{ ...admin, type: TenantUserType.ADMIN },
{ ...user1, type: index === 0 ? TenantUserType.ADMIN : TenantUserType.OWNER },
{ ...user2, type: TenantUserType.MEMBER },
])
)
);
}
if (shouldSeedDemoData) {
await ensureProductCoreCrmEntities({ ensurePermissions: false });
}
// Permissions
await seedRolesAndPermissions({
adminEmail: adminUser.email,
diagnostics: logRolesAndPermissionsSeedDiagnostic,
});
await seedStandardEntitlements({
client: db,
diagnostics: logEntitlementsSeedDiagnostic,
});
if (shouldSeedDemoData) {
await Promise.all(demoCrmTenants.map((tenant) => assignTenantPlan(tenant.slug, tenant.planId)));
await Promise.all(demoCrmTenants.map((tenant) => seedDemoProductCoreTenant(tenant.slug, tenant.planId, demoUsers)));
}
},
});
}
function shouldSeedCrmDemoData() {
if (process.env.SEED_DEMO_DATA !== "true") {
return false;
}
if (process.env.NODE_ENV !== "production") {
return true;
}
if (process.env.ALLOW_STAGING_DEMO_SEED === "true") {
return true;
}
throw new Error("Refusing to seed demo data in production without ALLOW_STAGING_DEMO_SEED=true.");
}
function getSeedSafetyEnvironment() {
if (process.env.NODE_ENV === "production" && process.env.SEED_DEMO_DATA === "true" && process.env.ALLOW_STAGING_DEMO_SEED === "true") {
return "staging-demo";
}
return process.env.NODE_ENV ?? "development";
}
function logDbSeedDiagnostic(event: DbSeedDiagnosticEvent) {
const { phase, nodeEnv, adminEmail } = event;
// Never log raw adminEmail (PII). Use fingerprint hash for correlation.
seedLogger.info(
{ op: "db-seed", phase, nodeEnv, adminEmailFingerprint: adminEmail ? emailFingerprint(adminEmail) : null },
"DB seed event",
);
}
function logRolesAndPermissionsSeedDiagnostic(event: RolesAndPermissionsSeedDiagnosticEvent) {
const {
phase,
adminRoleCount,
appRoleCount,
defaultPermissionCount,
dynamicEntityPermissionCount,
adminUserAssignmentCount,
tenantUserAssignmentCount,
error,
} = event;
seedLogger.info(
{
op: "seed.rolesAndPermissions",
phase,
adminRoleCount,
appRoleCount,
defaultPermissionCount,
dynamicEntityPermissionCount,
adminUserAssignmentCount,
tenantUserAssignmentCount,
...(error ? { err: error } : {}),
},
"Roles and permissions seed event",
);
}
function logEntitlementsSeedDiagnostic(event: EntitlementsSeedDiagnosticEvent) {
const { phase, planCount, featureCount, createdProducts, updatedProducts, deletedFeatures, createdFeatures, planId, error } = event;
seedLogger.info(
{
op: "seed.entitlements",
phase,
planCount,
featureCount,
createdProducts,
updatedProducts,
deletedFeatures,
createdFeatures,
...(planId ? { planId } : {}),
...(error ? { err: error } : {}),
},
"Entitlements seed event",
);
}
async function createUser({
firstName,
lastName,
email,
password,
userType,
}: {
firstName: string;
lastName: string;
email: string;
password: string;
userType: "admin" | "app";
}) {
// Never log raw `email` (PII) and never log `password` (secret).
// Use email fingerprint hash so operators can still correlate seed events.
seedLogger.info(
{ op: "seed.createUser", userType, emailFingerprint: emailFingerprint(email) },
userType === "admin" ? "Seeding admin user" : "Seeding app user",
);
const salt = await bcrypt.genSalt(10);
const passwordHash = await bcrypt.hash(password, salt);
let user = await db.user.findUnique({
where: { email },
});
if (user) {
const isAdmin = await db.adminUser.findUnique({ where: { userId: user.id } });
if (!isAdmin && userType === "admin") {
if (process.env.NODE_ENV === "production") {
throw new Error("Production seed refused to promote an existing non-admin user. Choose a new SEED_ADMIN_EMAIL or bootstrap the admin user explicitly.");
}
seedLogger.info(
{ op: "seed.promoteUserToAdmin", emailFingerprint: emailFingerprint(email) },
"User already exists; promoting to admin",
);
await db.adminUser.create({ data: { userId: user.id } });
} else {
seedLogger.info(
{ op: "seed.userExists", userType, emailFingerprint: emailFingerprint(email) },
"User already exists",
);
}
return user;
}
user = await db.user.create({
data: {
email,
passwordHash,
avatar: "",
firstName,
lastName,
phone: "",
},
});
if (userType === "admin") {
await db.adminUser.create({
data: { userId: user.id },
});
}
return user;
}
async function createTenant(slug: string, name: string, users: { id: string; type: TenantUserType }[]) {
seedLogger.info({ op: "seed.createTenant", tenantSlug: slug, tenantName: name }, "Creating tenant");
let tenant = await db.tenant.findUnique({
where: { slug },
});
if (tenant) {
seedLogger.info({ op: "seed.tenantExists", tenantSlug: slug }, "Tenant already exists");
await db.tenant.update({
where: { id: tenant.id },
data: { active: true },
});
await ensureTenantSubscription(tenant.id);
await ensureTenantInboundAddress(tenant.id, name);
await ensureTenantUsers(tenant.id, users);
return tenant;
}
const address = await getAvailableTenantInboundAddress(name);
tenant = await db.tenant.create({
data: {
name,
slug,
icon: "",
active: true,
inboundAddresses: {
create: {
address,
},
},
},
});
let tenantId = tenant.id;
await ensureTenantSubscription(tenantId);
await ensureTenantUsers(tenantId, users);
return tenant;
}
async function ensureTenantSubscription(tenantId: string) {
const existing = await db.tenantSubscription.findUnique({ where: { tenantId } });
if (existing) {
return existing;
}
return db.tenantSubscription.create({
data: {
tenantId,
stripeCustomerId: "",
},
});
}
async function ensureTenantInboundAddress(tenantId: string, tenantName: string) {
const existing = await db.tenantInboundAddress.findFirst({ where: { tenantId } });
if (existing) {
return existing;
}
const address = await getAvailableTenantInboundAddress(tenantName);
return db.tenantInboundAddress.create({
data: {
tenantId,
address,
},
});
}
async function ensureTenantUsers(tenantId: string, users: { id: string; type: TenantUserType }[]) {
for (const user of users) {
const tenantUser = await db.tenantUser.findFirst({
where: { tenantId, userId: user.id },
});
if (tenantUser) {
seedLogger.info({ op: "seed.tenantUserExists", userId: user.id, tenantId }, "User already in tenant");
continue;
}
await db.tenantUser.create({
data: {
tenantId,
userId: user.id,
type: user.type,
joined: TenantUserJoined.CREATOR,
status: TenantUserStatus.ACTIVE,
},
});
}
}
async function assignTenantPlan(tenantSlug: string, planId: EntitlementPlanId) {
const tenant = await db.tenant.findUnique({
where: { slug: tenantSlug },
include: { subscription: { include: { products: true } } },
});
if (!tenant?.subscription) {
return;
}
const product = await db.subscriptionProduct.findFirst({
where: { stripeId: getEntitlementPlanStripeId({ id: planId }) },
select: { id: true },
});
if (!product) {
return;
}
const existingProduct = tenant.subscription.products.find((item) => item.subscriptionProductId === product.id && !item.endsAt);
if (existingProduct) {
return;
}
await db.tenantSubscriptionProduct.create({
data: {
tenantSubscriptionId: tenant.subscription.id,
subscriptionProductId: product.id,
stripeSubscriptionId: null,
quantity: 1,
fromCheckoutSessionId: null,
customEntitlementPlanId: planId,
},
});
}
async function seedDemoProductCoreTenant(tenantSlug: string, planId: EntitlementPlanId, demoUsers: { id: string }[]) {
const tenant = await db.tenant.findUnique({
where: { slug: tenantSlug },
select: { id: true, name: true, slug: true },
});
if (!tenant) {
return;
}
await Promise.all([
seedDemoTenantProductConfiguration(tenant.id, planId),
seedDemoTenantRoles(tenant.id, demoUsers),
seedDemoTenantKnowledgeBase(tenant.id, tenant.slug, tenant.name, planId),
seedDemoSupportTickets(tenant.id, tenant.slug, planId, demoUsers[0]?.id),
]);
}
async function seedDemoTenantProductConfiguration(tenantId: string, planId: EntitlementPlanId) {
await db.tenantProductConfiguration.upsert({
where: { tenantId },
create: {
tenantId,
blueprintId: productBlueprintIds.crmSaas,
notes: `Seeded CRM SaaS product-core demo configuration for the ${planId} plan.`,
},
update: {
blueprintId: productBlueprintIds.crmSaas,
notes: `Seeded CRM SaaS product-core demo configuration for the ${planId} plan.`,
},
});
const overrides =
planId === entitlementPlanIds.business
? [{ featureKey: featureKeys.mcp, override: "enabled", reason: "Business demo tenant shows blueprint-enabled MCP access." }]
: [{ featureKey: featureKeys.workflowEngine, override: "disabled", reason: `${planId} demo tenant keeps workflow automation plan-gated.` }];
for (const override of overrides) {
await db.tenantFeatureOverride.upsert({
where: { tenantId_featureKey: { tenantId, featureKey: override.featureKey } },
create: { tenantId, ...override },
update: { override: override.override, reason: override.reason },
});
}
}
async function seedDemoTenantRoles(tenantId: string, demoUsers: { id: string }[]) {
const permissions = await db.permission.findMany({
where: {
name: {
in: [...new Set(demoTenantRoleSeeds.flatMap((role) => role.permissions))],
},
},
select: { id: true, name: true },
});
const permissionIdByName = new Map(permissions.map((permission) => [permission.name, permission.id]));
for (const [index, roleSeed] of demoTenantRoleSeeds.entries()) {
let role = await db.role.findFirst({
where: { tenantId, name: roleSeed.name, type: "app" },
select: { id: true },
});
if (!role) {
role = await db.role.create({
data: {
tenantId,
name: roleSeed.name,
description: roleSeed.description,
type: "app",
assignToNewUsers: index === 1,
isDefault: false,
order: 100 + index,
},
select: { id: true },
});
}
for (const permissionName of roleSeed.permissions) {
const permissionId = permissionIdByName.get(permissionName);
if (!permissionId) {
continue;
}
const existing = await db.rolePermission.findFirst({ where: { roleId: role.id, permissionId } });
if (!existing) {
await db.rolePermission.create({ data: { roleId: role.id, permissionId } });
}
}
const user = demoUsers[index];
if (user) {
const existing = await db.userRole.findFirst({ where: { tenantId, userId: user.id, roleId: role.id } });
if (!existing) {
await db.userRole.create({ data: { tenantId, userId: user.id, roleId: role.id } });
}
}
}
}
async function seedDemoTenantKnowledgeBase(tenantId: string, tenantSlug: string, tenantName: string, planId: EntitlementPlanId) {
const ownerKey = `tenant:${tenantId}`;
const slug = `${tenantSlug}-kb`;
const knowledgeBase = await db.knowledgeBase.upsert({
where: { ownerKey_slug: { ownerKey, slug } },
create: {
tenantId,
ownerKey,
basePath: "help",
slug,
title: `${tenantName} Knowledge Base`,
description: `Tenant-owned product-core demo knowledge base for the ${planId} plan.`,
defaultLanguage: "en",
layout: "articles",
color: 500,
enabled: true,
languages: "en,de",
links: "[]",
logo: "",
seoImage: "",
},
update: {
tenantId,
title: `${tenantName} Knowledge Base`,
description: `Tenant-owned product-core demo knowledge base for the ${planId} plan.`,
enabled: true,
},
});
const category = await db.knowledgeBaseCategory.upsert({
where: { knowledgeBaseId_slug: { knowledgeBaseId: knowledgeBase.id, slug: "product-core" } },
create: {
knowledgeBaseId: knowledgeBase.id,
slug: "product-core",
order: 1,
title: demoKnowledgeBaseCategoryTitle,
description: demoKnowledgeBaseCategoryDescription,
icon: "book-open",
language: "en",
seoImage: "",
},
update: {
title: demoKnowledgeBaseCategoryTitle,
description: demoKnowledgeBaseCategoryDescription,
},
});
const content = `<p>${tenantName} is seeded on the ${planId} plan with CRM SaaS blueprint gates, tenant roles, support tickets, and tenant-owned knowledge base content.</p>`;
await db.knowledgeBaseArticle.upsert({
where: { knowledgeBaseId_slug: { knowledgeBaseId: knowledgeBase.id, slug: "plan-gates-overview" } },
create: {
knowledgeBaseId: knowledgeBase.id,
categoryId: category.id,
slug: "plan-gates-overview",
title: demoKnowledgeBaseArticleTitle,
description: `What the ${planId} plan enables in this seeded tenant.`,
order: 1,
contentDraft: content,
contentPublished: content,
contentPublishedAsText: `${tenantName} is seeded on the ${planId} plan with CRM SaaS blueprint gates, tenant roles, support tickets, and tenant-owned knowledge base content.`,
contentType: "html",
language: "en",
seoImage: "",
publishedAt: new Date(),
},
update: {
categoryId: category.id,
title: demoKnowledgeBaseArticleTitle,
description: `What the ${planId} plan enables in this seeded tenant.`,
contentDraft: content,
contentPublished: content,
contentPublishedAsText: `${tenantName} is seeded on the ${planId} plan with CRM SaaS blueprint gates, tenant roles, support tickets, and tenant-owned knowledge base content.`,
publishedAt: new Date(),
},
});
}
async function seedDemoSupportTickets(tenantId: string, tenantSlug: string, planId: EntitlementPlanId, userId?: string) {
const tickets = [
{
inboundMessageId: `seed:${tenantSlug}:welcome`,
subject: demoSupportTicketSubjects.welcome,
message: `This ${planId} tenant includes seeded support-ticket data so HelpDesk can be reviewed immediately.`,
priority: "normal",
status: "open",
},
{
inboundMessageId: `seed:${tenantSlug}:plan-gates`,
subject: demoSupportTicketSubjects.planGates,
message: demoSupportTicketPlanGatesMessage,
priority: planId === entitlementPlanIds.business ? "high" : "normal",
status: "open",
},
];
for (const ticket of tickets) {
await db.supportTicket.upsert({
where: { inboundMessageId: ticket.inboundMessageId },
create: {
tenantId,
userId,
source: "seed",
fromEmail: "support-demo@example.test",
fromUrl: `/${tenantSlug}/dashboard`,
...ticket,
},
update: {
tenantId,
userId,
source: "seed",
fromEmail: "support-demo@example.test",
fromUrl: `/${tenantSlug}/dashboard`,
subject: ticket.subject,
message: ticket.message,
priority: ticket.priority,
status: ticket.status,
},
});
}
}
export default {
seed,
};