/** * @module keystone/admin/admin-helpers * * Cryptographic derivation and lifecycle helpers for the One-Off Challenge Keystone Admin Review subsystem. */ import { extractErrorMsg, hash, HashAlgorithm } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs"; import { getIbGibAddr } from "@ibgib/ts-gib/dist/helper.mjs"; import { GLOBAL_LOG_A_LOT } from "../../core-constants.mjs"; import { kdf_recursiveSaltWrap } from "../kdf/kdf-helpers.mjs"; import { KEYSTONE_ATOM, KeystoneVerb, POOL_ID_ACCEPT, POOL_ID_REJECT, KEYSTONE_VERB_ACCEPT, KEYSTONE_VERB_REJECT } from "../keystone-constants.mjs"; import { KeystoneIbGib_V1 } from "../keystone-types.mjs"; import { validateGenesisKeystone, validateKeystoneTransition } from "../keystone-helpers.mjs"; import { KeystoneService_V1 } from "../keystone-service-v1.mjs"; import { KeystoneProfileBuilder, KeystoneProfileName } from "../policy/keystone-profile-builder.mjs"; import { createInMemoryTempMetaspaceAndSpace } from "../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace.mjs"; import { DEFAULT_ADMIN_CHALLENGE_HASH_ALGORITHM, DEFAULT_ADMIN_CHALLENGE_KDF_ROUNDS } from "./admin-constants.mjs"; import { AdminRequestIbGib_V1 } from "./admin-request/index.mjs"; const logalot = GLOBAL_LOG_A_LOT || true; /** * Derives a deterministic, high-entropy challenge secret for an administrative action. * * @param masterSecret - Admin secret or master password. * @param nonce - High-entropy UUID nonce stored on the genesis keystone frame. * @param scope - Administrative domain or scope (e.g. 'exception-keys'). * @param verb - Target action verb (e.g. KeystoneVerb.ACCEPT or KeystoneVerb.REJECT). * @param rounds - Number of KDF key stretching rounds (defaults to DEFAULT_ADMIN_CHALLENGE_KDF_ROUNDS). * @param algorithm - Hash algorithm (defaults to SHA-256). * * Cryptographic Construction: * 1. Compound salt: Hash(scope + "_" + verb + "_" + nonce) * 2. Key stretching: kdf_recursiveSaltWrap(masterSecret, salt, rounds) * * Guarantees: * - Forward secrecy & verb isolation: Knowing `accept` reveals zero information about `reject`. * - Replay proofing: Bound strictly to the unique nonce of the challenge instance. */ export async function deriveAdminChallengeSecret({ masterSecret, nonce, scope, verb, rounds = DEFAULT_ADMIN_CHALLENGE_KDF_ROUNDS, algorithm = DEFAULT_ADMIN_CHALLENGE_HASH_ALGORITHM, }: { masterSecret: string; nonce: string; scope: string; verb: KeystoneVerb | string; rounds?: number; algorithm?: HashAlgorithm; }): Promise { const lc = `[${deriveAdminChallengeSecret.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: ad8701e9a3b24f5a892b1dc7189c4d26)`); } if (!masterSecret) { throw new Error(`masterSecret is required (E: ad1082ef784a44f7b6cf389146187b26)`); } if (!nonce) { throw new Error(`nonce is required (E: 2c19e34891b046a0ba92e0719e71df26)`); } if (!scope) { throw new Error(`scope is required (E: b7e8a91c33f24dc99071f654b0292126)`); } if (!verb) { throw new Error(`verb is required (E: 9918bc3d67f14652a92610582fb24c26)`); } if (rounds <= 0) { throw new Error(`rounds must be a positive integer, got ${rounds} (E: e317bb2049b14f8fa95861b55928d226)`); } const compoundSaltRaw = `${scope}_${verb}_${nonce}`; const salt = await hash({ s: compoundSaltRaw, algorithm, }); const derivedSecret = await kdf_recursiveSaltWrap({ masterSecret, salt, rounds, algorithm, }); return derivedSecret; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } export interface CreateAdminChallengeGenesisKeystoneParams { masterSecret: string; adminId?: string; adminRequestIbGib?: AdminRequestIbGib_V1; adminRequestAddr?: string; nonce: string; scope: string; targetIdentifier?: string; applicantDetails?: Record; poolIds?: string[]; expirationUTC?: string; rounds?: number; algorithm?: HashAlgorithm; profileName?: KeystoneProfileName; } /** * Creates a brand-new One-Off Challenge Genesis Keystone ($n=0$) containing * mutually exclusive challenge pools (by default, `accept` and `reject`). * * Employs standard `KeystoneService_V1.genesis` backed by `KeystoneProfileBuilder` * and an ephemeral in-memory space via `createInMemoryTempMetaspaceAndSpace`. */ export async function createAdminChallengeGenesisKeystone({ masterSecret, adminId, adminRequestIbGib, adminRequestAddr, nonce, scope, targetIdentifier, applicantDetails, poolIds = [POOL_ID_ACCEPT, POOL_ID_REJECT], expirationUTC, rounds, algorithm, profileName, }: CreateAdminChallengeGenesisKeystoneParams): Promise { const lc = `[${createAdminChallengeGenesisKeystone.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: d8a901bc32e443f68a72cf9148b29c26)`); } if (!masterSecret) { throw new Error(`masterSecret is required (E: 7c8910eb34f24da0bb91cf28374a5626)`); } if (!nonce) { throw new Error(`nonce is required (E: a1b2c3d4e5f647890123456789abcdef)`); } if (!scope) { throw new Error(`scope is required (E: 1029384756abcdef0192837465bcdeff)`); } const resolvedProfileName: KeystoneProfileName = profileName || (process.env.KEYSTONE_PROFILE_ADMIN_CHALLENGE as KeystoneProfileName) || (process.env.NODE_ENV === 'production' ? 'admin-profile.prod' : 'admin-profile.dev'); const username = nonce.replace(/-/g, '').slice(0, 63); const finalAdminRequestAddr = adminRequestAddr || (adminRequestIbGib ? getIbGibAddr({ ibGib: adminRequestIbGib }) : undefined); const finalTargetIdentifier = targetIdentifier || adminRequestIbGib?.data?.targetIdentifier; const finalApplicantDetails = applicantDetails || adminRequestIbGib?.data?.applicantDetails; const detailsPayload: Record = { nonce, scope, targetIdentifier: finalTargetIdentifier, applicantDetails: finalApplicantDetails, }; if (adminId) { detailsPayload.adminId = adminId; } if (finalAdminRequestAddr) { detailsPayload.adminRequestAddr = finalAdminRequestAddr; if (adminRequestIbGib?.gib) { detailsPayload.adminRequestGib = adminRequestIbGib.gib; } } const builder = KeystoneProfileBuilder.buildKeystone(resolvedProfileName) .withUsername(username) .withDetails(detailsPayload) .withExpiration(expirationUTC); if (rounds) { for (const poolId of poolIds) { builder.customizePool(poolId, { rounds }); } } if (algorithm) { for (const poolId of poolIds) { builder.customizePool(poolId, { algo: algorithm }); } } const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const { metaspace, space } = await createInMemoryTempMetaspaceAndSpace(); // If admin request stone is present, register it in the ephemeral space if (adminRequestIbGib) { await metaspace.put({ ibGib: adminRequestIbGib, space }); await metaspace.registerNewIbGib({ ibGib: adminRequestIbGib, space }); } const keystoneService = new KeystoneService_V1(); const genesisKeystone = await keystoneService.genesis({ masterSecret, configs, frameDetails, metaspace, space, }); return genesisKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } export interface AdminGenesisKeystoneInfo { adminId: string; genesisKeystone: KeystoneIbGib_V1; tjpGib: string; } export interface CreateAdminChallengeGenesisKeystonesParams { admins: Array<{ id: string; password: string }>; adminRequestIbGib: AdminRequestIbGib_V1; nonce: string; poolIds?: string[]; expirationUTC?: string; rounds?: number; algorithm?: HashAlgorithm; profileName?: KeystoneProfileName; } /** * Creates individual One-Off Challenge Genesis Keystones for each configured admin, * all targeting the same immutable AdminRequest stone. */ export async function createAdminChallengeGenesisKeystones({ admins, adminRequestIbGib, nonce, poolIds = [POOL_ID_ACCEPT, POOL_ID_REJECT], expirationUTC, rounds, algorithm, profileName, }: CreateAdminChallengeGenesisKeystonesParams): Promise> { const lc = `[${createAdminChallengeGenesisKeystones.name}]`; try { if (logalot) { console.log(`${lc} starting for ${admins.length} admins... (I: c8192039485716253401928374650192)`); } if (!admins || admins.length === 0) { throw new Error(`admins list is required (E: a9182374650192837465019283746501)`); } if (!adminRequestIbGib?.data) { throw new Error(`valid adminRequestIbGib is required (E: b8192374650192837465019283746502)`); } const result: Record = {}; const scope = adminRequestIbGib.data.scope; const targetIdentifier = adminRequestIbGib.data.targetIdentifier; const applicantDetails = adminRequestIbGib.data.applicantDetails; for (const admin of admins) { const genesisKeystone = await createAdminChallengeGenesisKeystone({ masterSecret: admin.password, adminId: admin.id, adminRequestIbGib, nonce, scope, targetIdentifier, applicantDetails, poolIds, expirationUTC, rounds, algorithm, profileName, }); const tjpGib = genesisKeystone.gib; if (!tjpGib) { throw new Error(`Failed to generate canonical tjpGib for admin '${admin.id}' (E: c8192374650192837465019283746503)`); } result[admin.id] = { adminId: admin.id, genesisKeystone, tjpGib, }; } return result; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } export interface SolveAdminChallengeKeystoneParams { genesisKeystone: KeystoneIbGib_V1; masterSecret: string; poolId: string; adminRequestIbGib?: AdminRequestIbGib_V1; adminRequestAddr?: string; resolutionNotes?: string; } /** * Solves a single target pool on a One-Off Challenge Genesis Keystone, evolving * the keystone to frame $n=1$ with cryptographic proof of resolution. * * Uses standard `KeystoneService_V1.sign` with an ephemeral in-memory metaspace/space. */ export async function solveAdminChallengeKeystone({ genesisKeystone, masterSecret, poolId, adminRequestIbGib, adminRequestAddr, resolutionNotes, }: SolveAdminChallengeKeystoneParams): Promise { const lc = `[${solveAdminChallengeKeystone.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: f1a2b3c4d5e647890123456789abcdef)`); } if (!genesisKeystone?.data) { throw new Error(`Invalid genesisKeystone (E: 5938472910ab4fcd8739182746501928)`); } const prevData = genesisKeystone.data; const pool = prevData.challengePools.find(p => p.id === poolId); if (!pool) { throw new Error(`Pool not found: ${poolId} (E: 84920193847561029384756102938475)`); } const verb = poolId === POOL_ID_REJECT ? KEYSTONE_VERB_REJECT : KEYSTONE_VERB_ACCEPT; // 1. Create in-memory temp metaspace & space const { metaspace, space } = await createInMemoryTempMetaspaceAndSpace(); // 2. Put and register the admin request stone if provided if (adminRequestIbGib) { await metaspace.put({ ibGib: adminRequestIbGib, space }); await metaspace.registerNewIbGib({ ibGib: adminRequestIbGib, space }); } // 3. Put and register the genesis keystone into the ephemeral space await metaspace.put({ ibGib: genesisKeystone, space }); await metaspace.registerNewIbGib({ ibGib: genesisKeystone, space }); // Target address: bound to the admin request stone if available, else keystone self-address const targetAddr = adminRequestAddr || (adminRequestIbGib ? getIbGibAddr({ ibGib: adminRequestIbGib }) : undefined) || prevData.frameDetails?.adminRequestAddr || getIbGibAddr({ ibGib: genesisKeystone }); // 4. Use standard KeystoneService_V1 to sign and evolve const keystoneService = new KeystoneService_V1(); const frameDetails = { // ...prevData.frameDetails, resolvedPoolId: poolId, resolvedAtIso: new Date().toISOString(), resolutionNotes, }; if (logalot) { console.log(`${lc} frameDetails: ${frameDetails} (I: cebd583aa5b7c4b4a80ec2f81bad9626)`); } const solvedKeystone = await keystoneService.sign({ latestKeystone: genesisKeystone, masterSecret, claim: { verb, target: targetAddr, }, poolId, frameDetails, metaspace, space, }); return solvedKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates the resolution transition of a challenge keystone from genesis ($n=0$) * to solved frame ($n=1$), checking cryptographic correctness and pool ID matching. * * Runs canonical `validateGenesisKeystone` and `validateKeystoneTransition`. * * @returns Array of validation error strings (empty if resolution is cryptographically valid). */ export async function verifyAdminChallengeResolution({ genesisKeystone, solvedKeystone, expectedPoolId, expectedTargetAddr, }: { genesisKeystone: KeystoneIbGib_V1; solvedKeystone: KeystoneIbGib_V1; expectedPoolId?: string; expectedTargetAddr?: string; }): Promise { const lc = `[${verifyAdminChallengeResolution.name}]`; try { const errors: string[] = []; const genesisErrors = await validateGenesisKeystone({ keystoneIbGib: genesisKeystone }); if (genesisErrors.length > 0) { errors.push(...genesisErrors.map(e => `${lc} [Genesis Error] ${e}`)); } const transitionErrors = await validateKeystoneTransition({ currentIbGib: solvedKeystone, prevIbGib: genesisKeystone, }); if (transitionErrors.length > 0) { errors.push(...transitionErrors.map(e => `${lc} [Transition Error] ${e}`)); } if (expectedPoolId) { const solvedProofPoolId = solvedKeystone.data?.proofs?.[0]?.solutions?.[0]?.poolId; if (solvedProofPoolId !== expectedPoolId) { errors.push(`${lc} Expected solution for pool '${expectedPoolId}', but got '${solvedProofPoolId}'`); } } if (expectedTargetAddr) { const solvedTargetAddr = solvedKeystone.data?.proofs?.[0]?.claim?.target; if (solvedTargetAddr !== expectedTargetAddr) { errors.push(`${lc} Expected claim target '${expectedTargetAddr}', but got '${solvedTargetAddr}'`); } } return errors; } catch (error) { return [`${lc} ${extractErrorMsg(error)}`]; } }