Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
@@ -0,0 +1,201 @@
|
||||
// Ops seed — HR-Hub demo data (AK-P17a/b), idempotent, DEMO-TENANTS ONLY.
|
||||
//
|
||||
// Purpose: populate the employee directory, locations, the encrypted emergency
|
||||
// contacts and an encrypted team password-safe so the HR screens render with
|
||||
// real data on staging. Personnel-document rows are intentionally NOT seeded:
|
||||
// they require real File bytes and are created through the wired upload flow.
|
||||
//
|
||||
// Self-contained on purpose: it inlines the AD-8 envelope crypto (a faithful copy
|
||||
// of packages/foundation/src/crypto/{envelope,key-wrapper}.ts) so it runs even in
|
||||
// a deployed image where `@hivegrid/foundation` is bundled-not-resolvable. It
|
||||
// reuses the SAME per-tenant DEK the app stores in TenantEncryptionKey (read, or
|
||||
// create+wrap with CRYPTO_SECRET exactly like getOrCreateTenantDek), so every
|
||||
// ciphertext it writes is decryptable by the running app 1:1.
|
||||
//
|
||||
// Prisma writes to RLS-protected HR tables go through a transaction that sets the
|
||||
// tenant GUC (mirrors withTenantRLS). Safe to re-run: keyed on natural keys +
|
||||
// isDemoData=true, upserts where a unique constraint exists.
|
||||
//
|
||||
// Run (inside the staging web container, which has CRYPTO_SECRET + DATABASE_URL):
|
||||
// docker exec <web> sh -lc 'cd /myapp && node_modules/.bin/tsx scripts/ops/seed-hr-demo.mts'
|
||||
// Flags: --dry-run (no writes, report only) · --verify (decrypt one value back).
|
||||
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
|
||||
import { getDbClient } from "@hivegrid/db/client.server";
|
||||
|
||||
// ---- inlined AD-8 crypto (exact copy of the app primitives) -----------------
|
||||
const ALGO = "aes-256-gcm";
|
||||
const IV = 12;
|
||||
const DEK_BYTES = 32;
|
||||
const FMT = "v1";
|
||||
|
||||
function masterKey(): Buffer {
|
||||
const secret = process.env.CRYPTO_SECRET;
|
||||
if (!secret) throw new Error("CRYPTO_SECRET env variable not set");
|
||||
return createHash("sha256").update(secret).digest();
|
||||
}
|
||||
function wrapDek(dek: Buffer): Buffer {
|
||||
const iv = randomBytes(IV);
|
||||
const c = createCipheriv(ALGO, masterKey(), iv);
|
||||
const ct = Buffer.concat([c.update(dek), c.final()]);
|
||||
return Buffer.concat([iv, c.getAuthTag(), ct]);
|
||||
}
|
||||
function unwrapDek(blob: Buffer): Buffer {
|
||||
const iv = blob.subarray(0, IV);
|
||||
const tag = blob.subarray(IV, IV + 16);
|
||||
const ct = blob.subarray(IV + 16);
|
||||
const d = createDecipheriv(ALGO, masterKey(), iv);
|
||||
d.setAuthTag(tag);
|
||||
return Buffer.concat([d.update(ct), d.final()]);
|
||||
}
|
||||
function seal(dek: Buffer, plaintext: string, keyVersion = 1): string {
|
||||
const iv = randomBytes(IV);
|
||||
const c = createCipheriv(ALGO, dek, iv);
|
||||
const ct = Buffer.concat([c.update(plaintext, "utf8"), c.final()]);
|
||||
return [FMT, String(keyVersion), iv.toString("base64url"), c.getAuthTag().toString("base64url"), ct.toString("base64url")].join(":");
|
||||
}
|
||||
function open(dek: Buffer, envelope: string): string {
|
||||
const [v, , ivB, tagB, ctB] = envelope.split(":");
|
||||
if (v !== FMT) throw new Error("malformed envelope");
|
||||
const d = createDecipheriv(ALGO, dek, Buffer.from(ivB, "base64url"));
|
||||
d.setAuthTag(Buffer.from(tagB, "base64url"));
|
||||
return Buffer.concat([d.update(Buffer.from(ctB, "base64url")), d.final()]).toString("utf8");
|
||||
}
|
||||
|
||||
// ---- config -----------------------------------------------------------------
|
||||
const DEMO_SLUGS = ["demo-starter-crm", "demo-pro-crm", "demo-business-crm"];
|
||||
const DRY = process.argv.includes("--dry-run");
|
||||
const VERIFY = process.argv.includes("--verify");
|
||||
|
||||
const db = getDbClient() as any;
|
||||
|
||||
/** Get-or-create the tenant DEK exactly like getOrCreateTenantDek (envelope). */
|
||||
async function tenantDek(tenantId: string): Promise<{ dek: Buffer; keyVersion: number }> {
|
||||
const row = await db.tenantEncryptionKey.findUnique({ where: { tenantId }, select: { wrappedDek: true, keyVersion: true } });
|
||||
if (row) return { dek: unwrapDek(Buffer.from(row.wrappedDek)), keyVersion: row.keyVersion };
|
||||
const dek = randomBytes(DEK_BYTES);
|
||||
if (DRY) return { dek, keyVersion: 1 };
|
||||
await db.tenantEncryptionKey.create({ data: { tenantId, wrappedDek: wrapDek(dek), keyVersion: 1 } });
|
||||
return { dek, keyVersion: 1 };
|
||||
}
|
||||
|
||||
/** Run a callback inside a tenant-scoped RLS transaction (mirrors withTenantRLS). */
|
||||
async function rls<T>(tenantId: string, cb: (tx: any) => Promise<T>): Promise<T> {
|
||||
return db.$transaction(async (tx: any) => {
|
||||
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
|
||||
return cb(tx);
|
||||
});
|
||||
}
|
||||
|
||||
type Member = { userId: string; email: string; first: string; last: string };
|
||||
|
||||
function memberData(members: Member[]) {
|
||||
// Resolve the three canonical staging users by email; fall back by order.
|
||||
const byEmail = (e: string) => members.find((m) => m.email.toLowerCase() === e);
|
||||
const admin = byEmail("staging-admin@hivegrid.de") ?? members[0];
|
||||
const john = byEmail("john.doe@company.com") ?? members[1];
|
||||
const luna = byEmail("luna.davis@company.com") ?? members[2];
|
||||
return { admin, john, luna };
|
||||
}
|
||||
|
||||
async function seedTenant(t: { id: string; slug: string }) {
|
||||
const tenantId = t.id;
|
||||
const tus = await db.tenantUser.findMany({ where: { tenantId }, select: { userId: true } });
|
||||
const users: any[] = await db.user.findMany({ where: { id: { in: tus.map((x: any) => x.userId) } }, select: { id: true, email: true, firstName: true, lastName: true } });
|
||||
const members: Member[] = users.map((u) => ({ userId: u.id, email: u.email, first: u.firstName, last: u.lastName }));
|
||||
const { admin, john, luna } = memberData(members);
|
||||
const { dek, keyVersion } = await tenantDek(tenantId);
|
||||
const enc = (plain: string) => seal(dek, plain, keyVersion);
|
||||
|
||||
const summary: string[] = [];
|
||||
|
||||
await rls(tenantId, async (tx) => {
|
||||
// --- Locations (idempotent by tenantId+name) ---
|
||||
async function ensureLocation(name: string, data: Record<string, unknown>, isDefault: boolean): Promise<string> {
|
||||
const existing = await tx.hrLocation.findFirst({ where: { tenantId, name }, select: { id: true } });
|
||||
if (existing) return existing.id;
|
||||
if (DRY) { summary.push(`+location ${name}`); return "dry"; }
|
||||
const created = await tx.hrLocation.create({ data: { tenantId, name, isDefault, isDemoData: true, ...data }, select: { id: true } });
|
||||
summary.push(`+location ${name}`);
|
||||
return created.id;
|
||||
}
|
||||
const berlin = await ensureLocation("Zentrale Berlin", { addressLine1: "Torstraße 1", postalCode: "10119", city: "Berlin", country: "DE", phone: "+49 30 1234000" }, true);
|
||||
const muc = await ensureLocation("Standort München", { addressLine1: "Sendlinger Str. 12", postalCode: "80331", city: "München", country: "DE", phone: "+49 89 9876000" }, false);
|
||||
|
||||
// --- Profiles (upsert on tenantId_userId) ---
|
||||
async function ensureProfile(m: Member, p: { position: string; team: string; locationId: string; personalNumber: string; managerUserId?: string; emergency?: { name: string; phone: string; relation: string } }) {
|
||||
const data: Record<string, unknown> = {
|
||||
position: p.position, team: p.team, locationId: p.locationId === "dry" ? null : p.locationId,
|
||||
personalNumber: p.personalNumber, managerUserId: p.managerUserId ?? null, isDemoData: true,
|
||||
};
|
||||
if (p.emergency) data.emergencyContactCiphertext = enc(JSON.stringify(p.emergency));
|
||||
if (DRY) { summary.push(`~profile ${m.email}`); return; }
|
||||
await tx.hrEmployeeProfile.upsert({
|
||||
where: { tenantId_userId: { tenantId, userId: m.userId } },
|
||||
update: data,
|
||||
create: { tenantId, userId: m.userId, ...data },
|
||||
});
|
||||
summary.push(`~profile ${m.email}${p.emergency ? " (+emergency)" : ""}`);
|
||||
}
|
||||
if (admin) await ensureProfile(admin, { position: "Geschäftsführung", team: "Leitung", locationId: berlin, personalNumber: "P-0001", emergency: { name: "Sabine Berger", phone: "+49 170 1112233", relation: "Ehepartnerin" } });
|
||||
if (john) await ensureProfile(john, { position: "Vertriebsmitarbeiter", team: "Sales", locationId: berlin, personalNumber: "P-0002", managerUserId: admin?.userId, emergency: { name: "Maria Doe", phone: "+49 171 4455667", relation: "Schwester" } });
|
||||
if (luna) await ensureProfile(luna, { position: "HR-Managerin", team: "People", locationId: muc, personalNumber: "P-0003", managerUserId: admin?.userId, emergency: { name: "Tom Davis", phone: "+49 172 8899001", relation: "Ehepartner" } });
|
||||
|
||||
// --- Password safe: one vault + access + entries ---
|
||||
const vaultName = "Team-Zugänge (Demo)";
|
||||
let vaultId = (await tx.employeePasswordSafeVault.findFirst({ where: { tenantId, name: vaultName }, select: { id: true } }))?.id ?? null;
|
||||
if (!vaultId && !DRY && admin) {
|
||||
vaultId = (await tx.employeePasswordSafeVault.create({ data: { tenantId, name: vaultName, description: "Gemeinsame Zugangsdaten des Teams.", createdByUserId: admin.userId, isDemoData: true }, select: { id: true } })).id;
|
||||
summary.push(`+vault ${vaultName}`);
|
||||
}
|
||||
if (vaultId && !DRY) {
|
||||
// Access grants: admin=admin, john=read, luna=write.
|
||||
async function grant(m: Member | undefined, level: "read" | "write" | "admin") {
|
||||
if (!m || !admin) return;
|
||||
await tx.employeePasswordSafeAccess.upsert({
|
||||
where: { vaultId_userId: { vaultId, userId: m.userId } },
|
||||
update: { permissionLevel: level, grantedByUserId: admin.userId },
|
||||
create: { tenantId, vaultId, userId: m.userId, permissionLevel: level, grantedByUserId: admin.userId },
|
||||
});
|
||||
}
|
||||
await grant(admin, "admin"); await grant(john, "read"); await grant(luna, "write");
|
||||
summary.push("~access admin/read/write");
|
||||
|
||||
// Entries (idempotent by tenantId+vaultId+title), secrets encrypted.
|
||||
async function ensureEntry(title: string, url: string | null, username: string, password: string, notes: string) {
|
||||
const exists = await tx.employeePasswordSafeEntry.findFirst({ where: { tenantId, vaultId, title }, select: { id: true } });
|
||||
if (exists) return;
|
||||
await tx.employeePasswordSafeEntry.create({
|
||||
data: { tenantId, vaultId, title, url, tags: [], isDemoData: true, usernameCiphertext: enc(username), passwordCiphertext: enc(password), notesCiphertext: notes ? enc(notes) : null },
|
||||
});
|
||||
summary.push(`+entry ${title}`);
|
||||
}
|
||||
await ensureEntry("Firmen-WLAN", null, "hivegrid-guest", "Sommer2026!", "Nur für Gäste, monatlich wechseln.");
|
||||
await ensureEntry("Microsoft 365 Sammelkonto", "https://portal.office.com", "team@company.com", "Xk9$mPq2Lz7w", "Nicht für Einzel-Logins verwenden.");
|
||||
await ensureEntry("Newsletter-Tool", "https://newsletter.example.com", "marketing", "N3wsL!2026#", "");
|
||||
}
|
||||
return null;
|
||||
});
|
||||
|
||||
// --- optional verify: decrypt one emergency contact back ---
|
||||
if (VERIFY && !DRY) {
|
||||
const prof = await rls(tenantId, (tx) => tx.hrEmployeeProfile.findFirst({ where: { tenantId, emergencyContactCiphertext: { not: null } }, select: { userId: true, emergencyContactCiphertext: true } }));
|
||||
if (prof?.emergencyContactCiphertext) {
|
||||
const back = open(dek, prof.emergencyContactCiphertext);
|
||||
summary.push(`verify decrypt ok: ${back}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`\n[${t.slug}] (${tenantId})`);
|
||||
for (const line of summary) console.log(" " + line);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const tenants = await db.tenant.findMany({ where: { slug: { in: DEMO_SLUGS } }, select: { id: true, slug: true } });
|
||||
if (tenants.length === 0) { console.error("No demo tenants found — aborting (safety guard)."); process.exit(1); }
|
||||
console.log(`HR demo seed — ${DRY ? "DRY RUN" : "WRITE"}${VERIFY ? " +verify" : ""} — tenants: ${tenants.map((t: any) => t.slug).join(", ")}`);
|
||||
for (const t of tenants) await seedTenant(t);
|
||||
console.log("\nDone.");
|
||||
}
|
||||
|
||||
main().then(() => process.exit(0)).catch((e) => { console.error("SEED-ERR", e); process.exit(1); });
|
||||
Reference in new issue
Block a user