import { hash } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs"; import { KeystonePoolConfig, KeystoneFrameDetails } from "../keystone-types.mjs"; import { KeystonePoolTemplate, KeystonePolicyConfigTemplate, KeystoneBehaviorProfileTemplate } from "../keystone-policy-types.mjs"; import { createPoolConfigFromJson } from "../keystone-config-builder.mjs"; import primaryProfileDev from "./profiles/primary/primary-profile.dev.json" with { type: "json" }; import primaryProfileStaging from "./profiles/primary/primary-profile.staging.json" with { type: "json" }; import primaryProfileProd from "./profiles/primary/primary-profile.prod.json" with { type: "json" }; import syncProfileDev from "./profiles/sync/sync-profile.dev.json" with { type: "json" }; import syncProfileStaging from "./profiles/sync/sync-profile.staging.json" with { type: "json" }; import syncProfileProd from "./profiles/sync/sync-profile.prod.json" with { type: "json" }; import authorProfileDev from "./profiles/author/author-profile.dev.json" with { type: "json" }; import authorProfileStaging from "./profiles/author/author-profile.staging.json" with { type: "json" }; import authorProfileProd from "./profiles/author/author-profile.prod.json" with { type: "json" }; import sessionProfile from "./profiles/profile-session.json" with { type: "json" }; import adminProfileDev from "./profiles/admin/admin-profile.dev.json" with { type: "json" }; import adminProfileStaging from "./profiles/admin/admin-profile.staging.json" with { type: "json" }; import adminProfileProd from "./profiles/admin/admin-profile.prod.json" with { type: "json" }; export type KeystoneProfileName = | 'primary-profile.dev' | 'primary-profile.staging' | 'primary-profile.prod' | 'sync-profile.dev' | 'sync-profile.staging' | 'sync-profile.prod' | 'sync-profile.test-short-ttl' | 'author-profile.dev' | 'author-profile.staging' | 'author-profile.prod' | 'admin-profile.dev' | 'admin-profile.staging' | 'admin-profile.prod' | 'session' | (string & {}) ; const _customProfiles: Map = new Map(); export class KeystoneProfileBuilder { private _template: KeystonePolicyConfigTemplate; private _username?: string; private _emails?: string[]; private _description?: string; private _details?: any; private _customizations: { [poolId: string]: { template?: Partial, behavior?: Partial } } = {}; private constructor(template: KeystonePolicyConfigTemplate) { // Deep copy the template to avoid modifying shared imports this._template = JSON.parse(JSON.stringify(template)); } /** * Registers a custom keystone policy config template in memory. * Accessible by name via `KeystoneProfileBuilder.buildKeystone(name)`. */ static registerCustomProfile({ name, template, }: { name: string; template: KeystonePolicyConfigTemplate; }): void { if (!name || typeof name !== 'string') { throw new Error(`Profile name is required to register a custom profile. (E: 1e50081dba682977cf6091d85166e826)`); } if (!template || typeof template !== 'object') { throw new Error(`Valid KeystonePolicyConfigTemplate is required to register custom profile '${name}'. (E: 7739b840ec780b84084435f8b6000826)`); } _customProfiles.set(name, JSON.parse(JSON.stringify(template))); } /** * Clears all dynamically registered custom profiles. */ static clearCustomProfiles(): void { _customProfiles.clear(); } /** * Directly creates a builder instance from any valid `KeystonePolicyConfigTemplate`. */ static fromTemplate(template: KeystonePolicyConfigTemplate): KeystoneProfileBuilder { if (!template || typeof template !== 'object') { throw new Error(`Valid KeystonePolicyConfigTemplate is required for KeystoneProfileBuilder.fromTemplate. (E: d468882543687c8fbcf921c8d807e826)`); } return new KeystoneProfileBuilder(template); } static buildKeystone(profileName: KeystoneProfileName | string): KeystoneProfileBuilder { if (!profileName || typeof profileName !== 'string') { throw new Error(`Profile name is required for KeystoneProfileBuilder. (E: 98c4c89520359b6dd10461884385d826)`); } const isDevProfile = profileName.endsWith('.dev') || profileName.startsWith('test') || profileName.includes('test'); if (process.env.NODE_ENV === 'production' && isDevProfile) { throw new Error(`Security Violation: Development keystone profile '${profileName}' is prohibited when NODE_ENV=production. (E: a940c7b1a88869b2e820aef89de41326)`); } // 1. Check custom registered profiles if (_customProfiles.has(profileName)) { return new KeystoneProfileBuilder(_customProfiles.get(profileName)!); } // 2. Check built-ins let selected: KeystonePolicyConfigTemplate; switch (profileName) { case 'primary-profile.dev': selected = primaryProfileDev as any; break; case 'primary-profile.staging': selected = primaryProfileStaging as any; break; case 'primary-profile.prod': selected = primaryProfileProd as any; break; case 'sync-profile.dev': selected = syncProfileDev as any; break; case 'sync-profile.staging': selected = syncProfileStaging as any; break; case 'sync-profile.prod': selected = syncProfileProd as any; break; case 'sync-profile.test-short-ttl': selected = { ...JSON.parse(JSON.stringify(syncProfileDev)), metadata: { ...syncProfileDev.metadata, name: 'sync-profile.test-short-ttl', description: 'Short 10-second TTL sync profile for testing session expiration and renewal.', defaultTtlSeconds: 10, } } as any; break; case 'author-profile.dev': selected = authorProfileDev as any; break; case 'author-profile.staging': selected = authorProfileStaging as any; break; case 'author-profile.prod': selected = authorProfileProd as any; break; case 'admin-profile.dev': selected = adminProfileDev as any; break; case 'admin-profile.staging': selected = adminProfileStaging as any; break; case 'admin-profile.prod': selected = adminProfileProd as any; break; case 'session': selected = sessionProfile as any; break; default: throw new Error(`Unknown keystone profile name: '${profileName}' (E: fc10a8ad482ef2bda871ac567d268d26)`); } return new KeystoneProfileBuilder(selected); } withUsername(username: string): this { this._username = username; return this; } withEmail(email: string): this { if (!this._emails) { this._emails = [email]; } else if (!this._emails.includes(email)) { this._emails.push(email); } return this; } withEmails(emails: string[]): this { this._emails = [...emails]; return this; } withDescription(description: string): this { this._description = description; return this; } withDetails(details: any): this { this._details = details; return this; } private _expirationUTC?: string; withExpiration(expirationUTC?: string): this { this._expirationUTC = expirationUTC; return this; } /** * Gets the default TTL in seconds defined in the profile metadata if present. */ getDefaultTtlSeconds(): number | undefined { return (this._template.metadata as any)?.defaultTtlSeconds; } customizePool( poolId: string, overrides: Omit, 'behavior'> & { behavior?: Partial } ): this { const { behavior, ...templateOverrides } = overrides; this._customizations[poolId] = { template: templateOverrides as any, behavior }; return this; } withPool(poolId: string, poolTemplate: KeystonePoolTemplate): this { this._template.pools[poolId] = JSON.parse(JSON.stringify(poolTemplate)); return this; } /** * Unifies username, emails, description, details, and expiration into a frameDetails object for genesis. */ getFrameDetails(): KeystoneFrameDetails { const details: KeystoneFrameDetails = { ...this._details }; if (this._username) { details.username = this._username; } if (this._emails && this._emails.length > 0) { details.emails = [...this._emails]; } if (this._description) { details.description = this._description; } if (this._expirationUTC) { details.expirationUTC = this._expirationUTC; } else { const ttl = this.getDefaultTtlSeconds(); if (ttl && ttl > 0) { details.expirationUTC = new Date(Date.now() + ttl * 1000).toISOString(); } } return details; } async compileConfigs(): Promise { const poolConfigs: KeystonePoolConfig[] = []; // Derive a unique user-specific base salt if username/emails is provided let userSalt = ""; if (this._username || (this._emails && this._emails.length > 0)) { const primaryEmail = this._emails?.[0] ?? ""; const seed = `${this._username || ""}:${primaryEmail}`; userSalt = await hash({ s: seed }); } else { // Fallback salt to guarantee unique challenge IDs even without user details userSalt = await hash({ s: "default-keystone-salt" }); } for (const [poolKey, poolTemplate] of Object.entries(this._template.pools)) { // Apply customization overrides const custom = this._customizations[poolTemplate.id]; if (custom) { if (custom.template) { Object.assign(poolTemplate, custom.template); } if (custom.behavior && poolTemplate.behavior) { Object.assign(poolTemplate.behavior, custom.behavior); } } // Derive a unique salt for this specific pool by hashing userSalt + poolId const saltSeed = `${userSalt}-${poolTemplate.id}`; const derivedSalt = await hash({ s: saltSeed }); const poolConfig = createPoolConfigFromJson({ template: poolTemplate, salt: derivedSalt }); poolConfigs.push(poolConfig); } return poolConfigs; } }