/** * @module keystone/delegate/delegate-helpers * * Foundational pure helper functions for keystone delegation, secret derivation, * capability detection, expiration evaluation, and sync delegate factory construction. */ import { extractErrorMsg, hash, HashAlgorithm, getUUID, getSaferSubstring } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs"; import { GLOBAL_LOG_A_LOT } from "../../core-constants.mjs"; import { kdf_recursiveSaltWrap } from "../kdf/kdf-helpers.mjs"; import { KeystoneData_V1, KeystoneIbGib_V1 } from "../keystone-types.mjs"; import { KeystoneProfileBuilder } from "../policy/keystone-profile-builder.mjs"; import { KeystoneService_V1 } from "../keystone-service-v1.mjs"; import { CUSTODIAN_POOL_ID_PREFIX, KEYSTONE_ROLE_CUSTODIAL_SYNC, KEYSTONE_ROLE_SYNC_DELEGATE, KEYSTONE_ROLE_AUTHOR_DELEGATE } from "./delegate-constants.mjs"; import { CreateSyncDelegateOpts, CreateAuthorDelegateOpts, DelegateKeystoneInfo, KeystoneCapabilities, SsoProviderId, } from "./delegate-types.mjs"; const logalot = GLOBAL_LOG_A_LOT; /** * Derives a deterministic delegate secret from a masterSecret using KDF. * Salt is the sha512 hash of the masterSecret. * Number of rounds is hardcoded to 1000. */ export async function deriveDelegateSecret({ masterSecret, }: { masterSecret: string; }): Promise { const salt = await hash({ s: masterSecret, algorithm: HashAlgorithm.sha_512 }); return await kdf_recursiveSaltWrap({ masterSecret, salt, rounds: 1000, algorithm: HashAlgorithm.sha_512 }); } /** * Generates or derives a high-entropy standalone 512-bit delegate secret for a local device delegate. */ export async function deriveDeviceDelegateSecret({ primaryTjpAddr, deviceTag, }: { primaryTjpAddr: string; deviceTag?: string; }): Promise { if (!primaryTjpAddr) { throw new Error('primaryTjpAddr is required to derive device delegate secret (E: dc67084e43e8863ed8295e286a6c9826)'); } const rawEntropy = await getUUID(32); const context = `${primaryTjpAddr}_${deviceTag || ''}_${rawEntropy}`; return await hash({ s: context, algorithm: HashAlgorithm.sha_512 }); } /** * Pure factory function for creating an outward sync delegate keystone. * Handles profile building, frame details injection, config compilation, and genesis. */ export async function createSyncDelegateKeystone({ profileName, profileTemplate, username, deviceTag, primaryTjpAddr, delegateSecret, custodianReqs, expirationUTC, additionalFrameDetails, metaspace, space, }: CreateSyncDelegateOpts): Promise { const lc = `[${createSyncDelegateKeystone.name}]`; try { if (!profileName && !profileTemplate) { throw new Error('profileName or profileTemplate is required (E: 73c18f85c5280c7548a468d812f05826)'); } if (!primaryTjpAddr) { throw new Error('primaryTjpAddr is required (E: 85efd879ee027c06384d7df88b460826)'); } if (!delegateSecret) { throw new Error('delegateSecret is required (E: ae4d5f261e3817e078cc9f984bbadb26)'); } const tag = deviceTag || 'primary-device'; const builder = profileTemplate ? KeystoneProfileBuilder.fromTemplate(profileTemplate) : KeystoneProfileBuilder.buildKeystone(profileName!); const safeTagForUsername = getSaferSubstring({ text: tag, keepLiterals: ['-'] }) || 'device'; const safeUserForUsername = getSaferSubstring({ text: username, keepLiterals: ['-'] }) || 'user'; builder .withUsername(`${safeUserForUsername}-sync-${safeTagForUsername}`.slice(0, 60)) .withDescription(`Sync Delegate for ${username} on ${tag}`) .withDetails({ client: 'space-gib-web', role: KEYSTONE_ROLE_SYNC_DELEGATE, deviceTag: tag, primaryTjpAddr, authorUsername: username, ...(custodianReqs ? { custodianReqs } : {}), ...(additionalFrameDetails || {}) }); if (expirationUTC) { builder.withExpiration(expirationUTC); } const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const keystoneService = new KeystoneService_V1(); const delegateKeystone = await keystoneService.genesis({ masterSecret: delegateSecret, configs, metaspace, space, frameDetails, isPrimary: false }); return delegateKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Pure factory function for creating an outward author delegate keystone. * Handles profile building, frame details injection, config compilation, and genesis. */ export async function createAuthorDelegateKeystone({ profileName, profileTemplate, username, deviceTag, primaryTjpAddr, delegateSecret, expirationUTC, additionalFrameDetails, metaspace, space, }: CreateAuthorDelegateOpts): Promise { const lc = `[${createAuthorDelegateKeystone.name}]`; try { if (!primaryTjpAddr) { throw new Error('primaryTjpAddr is required (E: 85efd879ee027c06384d7df88b460826)'); } if (!delegateSecret) { throw new Error('delegateSecret is required (E: ae4d5f261e3817e078cc9f984bbadb26)'); } const tag = deviceTag || 'primary-device'; const defaultProfile = 'author-profile.dev'; const builder = profileTemplate ? KeystoneProfileBuilder.fromTemplate(profileTemplate) : KeystoneProfileBuilder.buildKeystone(profileName || defaultProfile); const safeTagForUsername = getSaferSubstring({ text: tag, keepLiterals: ['-'] }) || 'device'; const safeUserForUsername = getSaferSubstring({ text: username, keepLiterals: ['-'] }) || 'user'; builder .withUsername(`${safeUserForUsername}-author-${safeTagForUsername}`.slice(0, 60)) .withDescription(`Author Delegate for ${username} on ${tag}`) .withDetails({ client: 'space-gib-web', role: KEYSTONE_ROLE_AUTHOR_DELEGATE, deviceTag: tag, primaryTjpAddr, authorUsername: username, ...(additionalFrameDetails || {}) }); if (expirationUTC) { builder.withExpiration(expirationUTC); } const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const keystoneService = new KeystoneService_V1(); const delegateKeystone = await keystoneService.genesis({ masterSecret: delegateSecret, configs, metaspace, space, frameDetails, isPrimary: false }); return delegateKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Checks if a generic keystone identity or frame has expired based on its frameDetails.expirationUTC. */ export function isKeystoneExpired({ keystone, nowUTC, }: { keystone: KeystoneIbGib_V1 | null | undefined; nowUTC?: string | number | Date; }): boolean { if (!keystone || !keystone.data?.frameDetails?.expirationUTC) { return false; } const expirationMs = Date.parse(keystone.data.frameDetails.expirationUTC); if (isNaN(expirationMs)) { return false; } const currentMs = nowUTC !== undefined ? (typeof nowUTC === 'number' ? nowUTC : (nowUTC instanceof Date ? nowUTC.getTime() : Date.parse(nowUTC))) : Date.now(); return currentMs > expirationMs; } /** * Checks if a delegate keystone has expired. * Works against either the parent's registered `delegateInfo` OR the `delegateKeystone` itself. */ export function isDelegateExpired({ delegateInfo, delegateKeystone, nowUTC, }: { delegateInfo?: DelegateKeystoneInfo | null; delegateKeystone?: KeystoneIbGib_V1 | null; nowUTC?: string | number | Date; }): boolean { if (!delegateInfo && !delegateKeystone) { throw new Error(`either delegateInfo or delegateKeystone required. (E: d1baa55ca8d23b26f8562a28179d2126)`); } if (delegateKeystone) { return isKeystoneExpired({ keystone: delegateKeystone, nowUTC }); } if (!delegateInfo || !delegateInfo.expirationUTC) { return false; } const expirationMs = Date.parse(delegateInfo.expirationUTC); if (isNaN(expirationMs)) { return false; } const currentMs = nowUTC !== undefined ? (typeof nowUTC === 'number' ? nowUTC : (nowUTC instanceof Date ? nowUTC.getTime() : Date.parse(nowUTC))) : Date.now(); return currentMs > expirationMs; } /** * Checks if a keystone contains an active custodian challenge pool or origin for the given SSO provider. */ export function isSsoProviderLinked({ keystone, aggregatedDetails, providerId, }: { keystone: KeystoneIbGib_V1; aggregatedDetails?: any; providerId: SsoProviderId; }): boolean { const lc = `[${isSsoProviderLinked.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 1db5581127983918ff303dd8370daf26)`); } const targetPoolId = `${CUSTODIAN_POOL_ID_PREFIX}${providerId}`; // 1. Check foreign challenge pools (e.g. custodian-manage-google) if (keystone.data?.challengePools?.some(p => p.id === targetPoolId)) { return true; } // 2. Check primary origin provider on full-custodial keystones (where pool is still just 'manage' before elevation) const isHybridMode = (keystone.data?.frameDetails?.custodyMode === 'hybrid') || (aggregatedDetails?.custodyMode === 'hybrid') || ((keystone.data as any)?.custodyMode === 'hybrid'); if (!isHybridMode) { const originProvider = aggregatedDetails?.custodianProvider || keystone.data?.frameDetails?.custodianProvider || (keystone.data as any)?.custodianProvider; if (originProvider && String(originProvider).toLowerCase() === String(providerId).toLowerCase()) { return true; } } return false; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Determines whether a delegate registration or delegate keystone represents a custodial / foreign SSO delegate. */ export function isCustodialDelegate({ delegateInfo, delegateKeystone, providerId, }: { delegateInfo?: Partial | null; delegateKeystone?: KeystoneIbGib_V1 | null; providerId?: SsoProviderId | string; }): boolean { if (!delegateInfo && !delegateKeystone) { return false; } const role = delegateInfo?.role || delegateKeystone?.data?.frameDetails?.role; const deviceName = delegateInfo?.deviceName || delegateKeystone?.data?.frameDetails?.deviceTag; const metadataProvider = (delegateInfo?.metadata as any)?.provider || (delegateKeystone?.data?.frameDetails as any)?.custodianProvider || (delegateKeystone?.data?.frameDetails as any)?.metadata?.provider; // 1. Explicit role check const isExplicitCustodialRole = role === KEYSTONE_ROLE_CUSTODIAL_SYNC || role === 'custodial-sync'; // 2. Metadata provider check if (metadataProvider) { if (providerId) { return String(metadataProvider).toLowerCase() === String(providerId).toLowerCase(); } return true; } // 3. Provider-specific or generic deviceName checks if (deviceName) { const lowerDevice = deviceName.toLowerCase(); if (providerId) { const lowerProvider = String(providerId).toLowerCase(); return lowerDevice.includes(lowerProvider) || (isExplicitCustodialRole && lowerDevice.includes('custodian')); } if ( lowerDevice.includes('custodian') || lowerDevice.includes('oauth2') || lowerDevice.includes('google') || lowerDevice.includes('github') || lowerDevice.startsWith('email-') || lowerDevice.includes('@') ) { return true; } } // 4. Fallback to explicit role if no specific provider was requested if (!providerId && isExplicitCustodialRole) { return true; } return false; } /** * Inspects a primary keystone to determine its dynamic capabilities (Sovereign, Custodial, Hybrid). */ export function getKeystoneCapabilities({ keystone, aggregatedDetails, }: { keystone: KeystoneIbGib_V1; aggregatedDetails?: Partial; }): KeystoneCapabilities { if (!keystone) { return { isSovereign: false, isCustodial: false, isHybrid: false, providers: [], emails: [] }; } const emails = aggregatedDetails?.emails || keystone.data?.frameDetails?.emails || []; const pools = keystone.data?.challengePools || []; // Origin provider (e.g. 'google', 'github') recorded at genesis const originProvider = (aggregatedDetails?.custodianProvider || keystone.data?.frameDetails?.custodianProvider || (keystone.data as any)?.custodianProvider) as SsoProviderId | undefined; // Check custody mode: 'hybrid' indicates sovereign elevation has occurred const isHybridMode = (keystone.data?.frameDetails?.custodyMode === 'hybrid') || (aggregatedDetails?.custodyMode === 'hybrid') || ((keystone.data as any)?.custodyMode === 'hybrid'); // Full custodial mode: has an origin provider and is NOT yet in hybrid mode, // OR explicitly marked custodyMode: 'full' const isFullCustodialMode = !isHybridMode && ( !!originProvider || (keystone.data?.frameDetails?.custodyMode === 'full') || (aggregatedDetails?.custodyMode === 'full') || ((keystone.data as any)?.custodyMode === 'full') ); // Collect all linked SSO provider IDs from foreign challenge pools and origin metadata const providersSet = new Set(); for (const pool of pools) { if (pool.id.startsWith(CUSTODIAN_POOL_ID_PREFIX)) { const provider = pool.id.substring(CUSTODIAN_POOL_ID_PREFIX.length) as SsoProviderId; if (provider) { providersSet.add(provider); } } } // If in full custody mode (before elevation), the origin provider is the active provider if (isFullCustodialMode && originProvider) { providersSet.add(originProvider); } const providers = Array.from(providersSet); const hasCustodianPools = providers.length > 0 || isFullCustodialMode; const hasManagePool = pools.some(p => p.id === 'manage'); const passkeyPools = pools.filter(p => p.id.startsWith('passkey-manage-')); const passkeyCount = passkeyPools.length || (keystone.data?.credentialIds ? keystone.data.credentialIds.length : 0); const hasPasskeys = passkeyCount > 0; const hasPassword = hasManagePool && !isFullCustodialMode; // An identity is sovereign if it has a native manage pool or passkey pool and is NOT in full-custody only mode const isSovereign = (hasManagePool || hasPasskeys) && !isFullCustodialMode; const isCustodial = hasCustodianPools; const isHybrid = isSovereign && isCustodial; return { isSovereign, isCustodial, isHybrid, providers, emails, hasPasskeys, passkeyCount, hasPassword }; }