import { extractErrorMsg, mergeMapsOrArrays_Naive, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr, getIbAndGib } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGibAddr } from '@ibgib/ts-gib/dist/types.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../core-constants.mjs'; import { KeystoneData_V1, KeystoneIbGib_V1, KeystonePoolConfig, KeystoneClaim, KeystoneChallengePool, KeystoneReplenishStrategy, KeystoneRevocationInfo, DelegateKeystoneStatus, KeystoneClaimType, KeystoneFrameDetails, ClaimDetails_AddPool, ClaimDetails_RemovePool, ClaimDetails_ReplacePool, ClaimDetails_ChangePassword } from './keystone-types.mjs'; import { KEYSTONE_VERB_REVOKE, KEYSTONE_VERB_MANAGE, KEYSTONE_CHECKPOINT_FREQUENCY, POOL_ID_MANAGE, } from './keystone-constants.mjs'; import { createKeystoneIbGibImpl, evolvePersistAndRegisterKeystone, resolveTargetPool, selectChallengeIds, solveAndReplenish, validateKeystoneTransition, validateGenesisKeystone, validateKeystoneGraph, generatePoolChallenges, rotatePoolChallenges, verifyPoolSecret } from './keystone-helpers.mjs'; import { getLatestAddrs, parseSpaceIb } from '../witness/space/space-helper.mjs'; import { IbGibSpaceAny } from '../witness/space/space-base-v1.mjs'; import { MetaspaceService } from '../witness/space/metaspace/metaspace-types.mjs'; import { FlatIbGibGraph } from '../common/other/graph-types.mjs'; import { getTjpAddr } from '../common/other/ibgib-helper.mjs'; import { deriveDelegateSecret, isCustodialDelegate, isDelegateExpired, isKeystoneExpired } from './delegate/delegate-helpers.mjs'; const logalot = GLOBAL_LOG_A_LOT; /** * Facade for managing Keystone Identities. * * Handles Genesis, Authorized Evolution (Signing), and Validation. */ export class KeystoneService_V1 { protected lc: string = `[${KeystoneService_V1.name}]`; /** * Creates a brand new Keystone Identity Timeline. */ async genesis({ masterSecret, emails, frameDetails, credentialIds, dataToPatch, configs, metaspace, space, isPrimary, }: { masterSecret: string; emails?: string[]; frameDetails?: KeystoneFrameDetails; credentialIds?: string[]; dataToPatch?: Partial; configs: KeystonePoolConfig[]; metaspace: MetaspaceService; space: IbGibSpaceAny; isPrimary?: boolean; }): Promise { const lc = `${this.lc}[${this.genesis.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: c98ae8adbc5888dbf84c5aced7610b25)`); } const challengePools: KeystoneChallengePool[] = []; for (const config of configs) { const challenges = await generatePoolChallenges({ config, masterSecret }); challengePools.push({ id: config.id, config, challenges, }); } if (challengePools.length === 0) { throw new Error(`No challenge pools created. (E: 38e538530996940e1f16a8b199995825)`); } const data: KeystoneData_V1 = { challengePools, proofs: [] }; if (emails && emails.length > 0) { data.emails = [...emails]; } if (credentialIds && credentialIds.length > 0) { data.credentialIds = [...credentialIds]; } if (frameDetails || isPrimary !== undefined) { data.frameDetails = { ...(frameDetails || {}) }; if (isPrimary !== undefined) { data.frameDetails!.isPrimary = isPrimary; } } if (dataToPatch) { Object.assign(data, dataToPatch); } const keystoneIbGib = await createKeystoneIbGibImpl({ data, metaspace, space }); return keystoneIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Signs a claim by solving challenges from a specific pool and evolving the Keystone timeline. * * Uses a hybrid selection strategy: Mandatory IDs (Alice) + Sequential (FIFO) + Random (Stochastic). * * Supports Delegation via `poolFilter` to find specific foreign pools. * * todo: wrap this and other entire keystone sign/method implementations in locks on the keystone's tjpGib. */ async sign({ latestKeystone, masterSecret, claim, poolId, poolFilter, requiredChallengeIds = [], frameDetails, metaspace, space, dataToPatch, }: { latestKeystone: KeystoneIbGib_V1; /** * The secret used to solve the challenges. * If signing with a native pool, this is the User's Master Secret. * If signing with a foreign/delegated pool, this is the Delegate's Secret. */ masterSecret: string; claim: Partial; /** * Explicit ID of the pool to use. */ poolId?: string; /** * Optional predicate to find a pool. * Useful for finding delegates via metadata without knowing the exact ID. * e.g. (p) => p.metadata?.delegate === 'Bob' */ poolFilter?: (pool: KeystoneChallengePool) => boolean; requiredChallengeIds?: string[]; frameDetails?: any; metaspace: MetaspaceService; space: IbGibSpaceAny; dataToPatch?: Partial; }): Promise { const lc = `${this.lc}[${this.sign.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } const prevData = latestKeystone.data!; if (prevData.revocationInfo) { throw new Error(`Keystone has been revoked. Cannot sign. (E: 4f2198c39116d15c48ba191940316825)`); } if (isKeystoneExpired({ keystone: latestKeystone })) { throw new Error(`Keystone is expired (${prevData.frameDetails?.expirationUTC}). Cannot sign. (E: 7f2198c39116d15c48ba191940316825)`); } // 1. Identify Authority (Resolve Pool) const pool = resolveTargetPool({ pools: prevData.challengePools, poolId, poolFilter, verb: claim.verb }); if (logalot) { console.log(`${lc} Selected pool: ${pool.id} (size: ${Object.keys(pool.challenges).length}) (I: 6b26d6f4aad18380f2b3a0989b592826)`); } // 2. Calculate Costs (Select IDs) const idsToSolve = await selectChallengeIds({ pool, targetAddr: claim.target, requiredChallengeIds }); // 3. Pay the Cost (Solve & Replenish) // This helper handles the Strategy creation, Secret derivation, Solving, // and the calculation of the Next state for ALL pools. const { proof, nextPools } = await solveAndReplenish({ targetPoolId: pool.id, prevPools: prevData.challengePools, masterSecret, challengeIds: idsToSolve, claim, requiredChallengeIds }); // 4. Construct New Data const n = (prevData.n ?? 0) + 1; let checkpointDetails: any | undefined; if (n % KEYSTONE_CHECKPOINT_FREQUENCY === 0) { // Generate a temporary view of the keystone as it would be in this frame // to calculate the aggregated state. const currentFrameView: KeystoneIbGib_V1 = { ...latestKeystone, data: { ...prevData, frameDetails } }; checkpointDetails = await this.getAggregateDetails({ latestKeystone: currentFrameView, metaspace, space }); } const newData: KeystoneData_V1 = { challengePools: nextPools, proofs: [proof], frameDetails, checkpointDetails, ...(prevData.delegates ? { delegates: prevData.delegates } : {}), ...dataToPatch, }; // 5. Commit (Evolve, Persist, Register) const resKeystone = await evolvePersistAndRegisterKeystone({ prevIbGib: latestKeystone, newData, metaspace, space }); return resKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates a keystone. * * ## NOTES * * Atow (12/22/2025) this only validates the transition from Prev -> Curr. * * @returns Array of validation error strings. Empty array means Valid. * * @see {@link validateKeystoneTransition} */ async validate({ currentIbGib, prevIbGib, }: { currentIbGib: KeystoneIbGib_V1; prevIbGib: KeystoneIbGib_V1; }): Promise { // todo: change this to validate the entire keystone graph. the next // step is to walk the history and validate each transition. const errors = await validateKeystoneTransition({ currentIbGib, prevIbGib }); return errors; } /** * Registers a delegate keystone on the parent keystone by appending its information * to the parent's `delegates` map. This operation is signed using the parent's `manage` pool. * Validates the delegate keystone's entire graph/timeline before registering. */ async registerDelegate({ parentKeystone, delegateKeystone, masterSecret, signingPoolId, frameDetails, metaspace, space, allowedVerbs, deviceName, expirationUTC, ttlSeconds, }: { parentKeystone: KeystoneIbGib_V1; delegateKeystone: KeystoneIbGib_V1; masterSecret: string; /** * The specific challenge pool ID used to authorize this delegation. * (e.g. 'manage', 'passkey-manage-1234', or 'custodian-google-manage') */ signingPoolId: string; frameDetails?: any; metaspace: MetaspaceService; space: IbGibSpaceAny; allowedVerbs: string[]; deviceName?: string; expirationUTC?: string; ttlSeconds?: number; }): Promise { const lc = `${this.lc}[${this.registerDelegate.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } if (!signingPoolId) { throw new Error(`signingPoolId is required (E: ab8e7813123a2afd37703c2810e57c26)`); } // 1. Validate the delegate keystone's entire graph/timeline const validationErrors = await validateKeystoneGraph({ keystoneIbGib: delegateKeystone, getLatest: true, invalidIfMoreRecentKeystoneFoundInSpace: false, space, }); if (validationErrors.length > 0) { throw new Error(`Delegate keystone validation failed: ${validationErrors.join(', ')} (E: cb8993698eda39d041b2d9ef4f36e6d5)`); } // 2. Verify that parent contains the specified signing pool const prevData = parentKeystone.data!; const signingPool = prevData.challengePools.find(p => p.id === signingPoolId); if (!signingPool) { throw new Error(`Parent keystone does not contain signing pool: ${signingPoolId} (E: a1dc3a9933cb1966ba39f1682c26fee9)`); } if (signingPool.config.allowedVerbs && signingPool.config.allowedVerbs.length > 0) { if (!signingPool.config.allowedVerbs.includes(KEYSTONE_VERB_MANAGE)) { throw new Error(`Signing pool ${signingPoolId} is not authorized for verb: ${KEYSTONE_VERB_MANAGE} (E: 9c19c848437ea4132d8158b42ec90500)`); } } const delegateTjpAddr = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjpAddr) { throw new Error(`(UNEXPECTED) delegateTjpAddr falsy? (E: d4d6e8ad03c8925d4838b9a87b8f2826)`); } // 3. Prepare the claim const claim: Partial = { target: delegateTjpAddr, verb: KEYSTONE_VERB_MANAGE, }; // 4. Update the delegates map const currentDelegates = prevData.delegates ? { ...prevData.delegates } : {}; const spaceId = parseSpaceIb({ spaceIb: space.ib }).spaceId; const effectiveExpirationUTC = expirationUTC ?? (ttlSeconds ? new Date(Date.now() + ttlSeconds * 1000).toISOString() : undefined) ?? delegateKeystone.data?.frameDetails?.expirationUTC; currentDelegates[delegateTjpAddr] = { delegateTjpAddr, delegateAddr: getIbGibAddr({ ibGib: delegateKeystone }), thisAddr: getIbGibAddr({ ibGib: parentKeystone }), deviceName, allowedVerbs, spaceId, expirationUTC: effectiveExpirationUTC, role: delegateKeystone.data?.frameDetails?.role, }; // 5. Sign & evolve parent keystone using the specified pool const evolved = await this.sign({ latestKeystone: parentKeystone, masterSecret, claim, poolId: signingPoolId, frameDetails: frameDetails || { ...(prevData.frameDetails || {}), action: 'register_delegate', }, metaspace, space, dataToPatch: { delegates: currentDelegates } }); return evolved; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Unregisters a delegate keystone from the parent keystone by removing its entry * from the parent's `delegates` map. */ async unregisterDelegate({ parentKeystone, delegateTjpAddr, masterSecret, signingPoolId, frameDetails, metaspace, space, }: { parentKeystone: KeystoneIbGib_V1; delegateTjpAddr: IbGibAddr; masterSecret: string; /** * The specific challenge pool ID used to authorize this unregistration. */ signingPoolId: string; frameDetails?: any; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.unregisterDelegate.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } if (!signingPoolId) { throw new Error(`signingPoolId is required (E: b2c3d4e5f6a13889f8ab28c9b60e6899)`); } // 1. Verify that parent contains the specified signing pool const prevData = parentKeystone.data!; const signingPool = prevData.challengePools.find(p => p.id === signingPoolId); if (!signingPool) { throw new Error(`Parent keystone does not contain signing pool: ${signingPoolId} (E: 7d2fd0de6b3e959dd708b6d7f614abf0)`); } if (signingPool.config.allowedVerbs && signingPool.config.allowedVerbs.length > 0) { if (!signingPool.config.allowedVerbs.includes(KEYSTONE_VERB_MANAGE)) { throw new Error(`Signing pool ${signingPoolId} is not authorized for verb: ${KEYSTONE_VERB_MANAGE} (E: 9e48b07909bb496b5b6ff24e6090427c)`); } } // 2. Prepare the claim const claim: Partial = { target: delegateTjpAddr, verb: KEYSTONE_VERB_MANAGE, }; // 3. Update the delegates map const currentDelegates = prevData.delegates ? { ...prevData.delegates } : {}; if (!currentDelegates[delegateTjpAddr]) { throw new Error(`Delegate ${delegateTjpAddr} is not registered on this parent. (E: fa3d823c2fea910dae0caf5d0c8d8fdf)`); } delete currentDelegates[delegateTjpAddr]; // 4. Sign & evolve parent keystone using the specified pool const evolved = await this.sign({ latestKeystone: parentKeystone, masterSecret, claim, poolId: signingPoolId, frameDetails: frameDetails || { ...(prevData.frameDetails || {}), action: 'unregister_delegate', }, metaspace, space, dataToPatch: { delegates: currentDelegates } }); return evolved; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Gets the registration status of a delegate keystone from the parent's latest tip frame. */ async getDelegateStatus({ parentTjpAddr, delegateTjpAddr, metaspace, space, }: { parentTjpAddr: IbGibAddr; delegateTjpAddr: IbGibAddr; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.getDelegateStatus.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } const { ib, gib } = getIbAndGib({ ibGibAddr: parentTjpAddr }); const parentIbGib: IbGib_V1 = { ib, gib }; const resGetLatest = await getLatestAddrs({ ibGibs: [parentIbGib], space, }); if (!resGetLatest.data?.latestAddrsMap) { return { registered: false }; } const latestAddr = resGetLatest.data.latestAddrsMap[parentTjpAddr]; if (!latestAddr) { return { registered: false }; } const resGet = await metaspace.get({ addr: latestAddr, space }); const latestParent = resGet.ibGibs?.at(0) as KeystoneIbGib_V1; if (!latestParent || !latestParent.data) { return { registered: false }; } const delegates = latestParent.data.delegates || {}; const delegateInfo = delegates[delegateTjpAddr]; const registered = !!delegateInfo && !isDelegateExpired({ delegateInfo }); return { registered, delegateInfo, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates a genesis keystone. * * @returns Array of validation error strings. Empty array means Valid. */ async validateGenesisKeystone({ keystoneIbGib, }: { keystoneIbGib: KeystoneIbGib_V1; }): Promise { return await validateGenesisKeystone({ keystoneIbGib }); } /** * Retrieves the latest keystone frame for the given address. * * Uses `metaspace.getLatestAddr` to find the actual tip instead of trusting * an incoming payload's `past` rel8n. * * @see `ibgib-get-pattern` SKILL.md */ async getLatestKeystone({ addr, metaspace, space, }: { addr: string; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.getLatestKeystone.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } const latestAddr = await metaspace.getLatestAddr({ addr, space }); if (!latestAddr) { throw new Error(`could not find latest addr for ${addr}`); } const resGet = await metaspace.get({ addr: latestAddr, space }); if (resGet.success && resGet.ibGibs && resGet.ibGibs.length > 0) { return resGet.ibGibs[0] as KeystoneIbGib_V1; } else { const resIbGib = resGet.rawResultIbGib as any; const addrsNotFound = resIbGib?.data?.addrsNotFound ?? 'unknown'; throw new Error(`couldn't find latest keystone at ${latestAddr}. addrsNotFound: ${addrsNotFound}? resGet.errorMsg: ${resGet.errorMsg}`); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Validates an entire keystone graph from tip to genesis. * * @returns Array of validation error strings. Empty array means Valid. */ async validateKeystoneGraph({ keystoneIbGib, dependencyGraph, getLatest, invalidIfMoreRecentKeystoneFoundInSpace, space, }: { keystoneIbGib: KeystoneIbGib_V1, /** * set this if you already have a reference to the graph. It is the caller's * responsibility to enforce {@link getLatest}. */ dependencyGraph?: FlatIbGibGraph, /** * if true, then this will get the latest keystone known in the incoming * {@link keystoneIbGib} timeline, as found in {@link space}. */ getLatest: boolean, invalidIfMoreRecentKeystoneFoundInSpace: boolean, space: IbGibSpaceAny, }): Promise { const lc = `${this.lc}[${this.validateKeystoneGraph.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 01c5cd455038c270cbf1effc1704af26)`); } return await validateKeystoneGraph({ keystoneIbGib, dependencyGraph, getLatest, invalidIfMoreRecentKeystoneFoundInSpace, space }); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Permanently revokes the Identity. * * Logic: * 1. Locates the 'revoke' pool. * 2. Solves required challenges to prove ownership. * 3. Wipes the pool (via the delete all strategy in solveAndReplenish). * 4. Sets the revocationInfo on the new frame. */ async revoke({ latestKeystone, masterSecret, reason = "User initiated revocation", frameDetails, metaspace, space, }: { latestKeystone: KeystoneIbGib_V1; masterSecret: string; reason?: string; frameDetails?: any; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.revoke.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } const prevData = latestKeystone.data!; // 1. Identify Authority (Resolve Revoke Pool by verb) const pool = resolveTargetPool({ pools: prevData.challengePools, verb: KEYSTONE_VERB_REVOKE }); // 2. Construct Claim const claim: Partial = { verb: KEYSTONE_VERB_REVOKE, target: getIbGibAddr({ ibGib: latestKeystone }) }; // 3. Calculate Costs const idsToSolve = await selectChallengeIds({ pool, targetAddr: claim.target, requiredChallengeIds: [] }); if (idsToSolve.length === 0) { throw new Error(`Revocation policy selected 0 challenges? Check config for pool ${pool.id}. Revocation requires proof. (E: 97e5a8356d241ae7b882db791cb1f825)`); } // 4. Pay the Cost & Scorched Earth // The revoke pool config should have 'replenishStrategy: // KeystoneReplenishStrategy.deleteAll', causing solveAndReplenish // to return an empty pool in nextPools. const { proof, nextPools } = await solveAndReplenish({ targetPoolId: pool.id, prevPools: prevData.challengePools, masterSecret, challengeIds: idsToSolve, claim, requiredChallengeIds: [] }); // warn if nextPools contains pool.id that isn't empty (we were // supposed to do "scorched earth" which empties the pool) if (nextPools.find(p => p.id === pool.id && Object.keys(p.challenges).length > 0)) { console.warn(`${lc} revocation pool ${pool.id} is not empty after revocation. Is the revocation pool replenish strategy set to ${KeystoneReplenishStrategy.deleteAll}? (W: 300c28bc8b98fc3e3c0b0d988344f825)`); } // 5. Construct Revocation Info const revocationInfo: KeystoneRevocationInfo = { reason, proof }; // 6. Construct New Data const n = (prevData.n ?? 0) + 1; let checkpointDetails: any | undefined; if (n % KEYSTONE_CHECKPOINT_FREQUENCY === 0) { const currentFrameView: KeystoneIbGib_V1 = { ...latestKeystone, data: { ...prevData, frameDetails, revocationInfo } }; checkpointDetails = await this.getAggregateDetails({ latestKeystone: currentFrameView, metaspace, space }); } const newData: KeystoneData_V1 = { challengePools: nextPools, proofs: [proof], revocationInfo, frameDetails, checkpointDetails, ...(prevData.delegates ? { delegates: prevData.delegates } : {}), }; // 7. Commit const newKeystone = await evolvePersistAndRegisterKeystone({ prevIbGib: latestKeystone, newData, metaspace, space }); return newKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Structural evolution: Adds new challenge pools to the keystone. * * Use Case: Adding a delegate (Server) for SSO, adding a recovery key, * or rotating to a new set of pools. * * Requires the Master Secret to authorize the change via a pool containing * the 'manage' verb. */ async addPools({ latestKeystone, masterSecret, signingPoolId, newPools, frameDetails, dataToPatch, metaspace, space, }: { latestKeystone: KeystoneIbGib_V1; /** * Alice's Master Secret. * Required to solve challenges from the Admin/Manage pool to authorize this change. */ masterSecret: string; /** * The specific pool ID authorized to perform management operations (e.g. 'manage' or 'passkey-manage-*'). */ signingPoolId: string; /** * The pools to add. * NOTE: These are fully constructed Pool objects. * If they are foreign (Bob's), Alice must have constructed them * using Bob's challenges + Her config restrictions + isForeign=true. */ newPools: KeystoneChallengePool[]; frameDetails?: KeystoneFrameDetails; dataToPatch?: Partial; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.addPools.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } if (!latestKeystone.data) { throw new Error(`(UNEXPECTED) latestKeystone.data falsy? (E: 7334c8faed128166a999d428c7805b25)`); } const prevData = latestKeystone.data; if (prevData.revocationInfo) { throw new Error(`Keystone has been revoked. Cannot add pools. (E: 8599f8f51c78d722252ddb2894fdbe25)`); } if (newPools.length === 0) { throw new Error(`No new pools provided to add. (E: 6599f8f51c78d722252ddb2894fdbe25)`); } // 1. Identify Authority (Resolve Admin Pool) const adminPool = resolveTargetPool({ pools: prevData.challengePools, poolId: signingPoolId, verb: KEYSTONE_VERB_MANAGE, }); if (logalot) { console.log(`${lc} Authorized via pool: ${adminPool.id}`); } // 2. Construct the Management Claim with typed details const target = getIbGibAddr({ ibGib: latestKeystone }); const claim: Partial = { verb: KEYSTONE_VERB_MANAGE, target, // I am managing myself details: { type: KeystoneClaimType.add_pool, info: { add: newPools.map(p => p.id) } as ClaimDetails_AddPool } }; // 3. Calculate Costs const idsToSolve = await selectChallengeIds({ pool: adminPool, targetAddr: target }); // 4. Pay the Cost (Solve & Replenish) // This authorizes the change by evolving the admin pool. const { proof, nextPools: replenishedExistingPools } = await solveAndReplenish({ targetPoolId: adminPool.id, prevPools: prevData.challengePools, masterSecret, challengeIds: idsToSolve, claim, }); // 5. Mutate Structure (Add the new pools) // We verify ID uniqueness cheaply here to prevent blatant errors const existingIds = new Set(replenishedExistingPools.map(p => p.id)); for (const newPool of newPools) { if (existingIds.has(newPool.id)) { throw new Error(`Cannot add pool. ID collision: ${newPool.id} (E: 2b5388a28a935b61c8fbf3ce06c21b26)`); } } const finalPools = [...replenishedExistingPools, ...newPools]; // 6. Construct New Data const n = (prevData.n ?? 0) + 1; let checkpointDetails: any | undefined; if (n % KEYSTONE_CHECKPOINT_FREQUENCY === 0) { const currentFrameView: KeystoneIbGib_V1 = { ...latestKeystone, data: { ...prevData, challengePools: finalPools, frameDetails } }; checkpointDetails = await this.getAggregateDetails({ latestKeystone: currentFrameView, metaspace, space }); } const newData: KeystoneData_V1 = { challengePools: finalPools, proofs: [proof], // The proof authorizes the structure change frameDetails, checkpointDetails, ...(prevData.delegates ? { delegates: prevData.delegates } : {}), ...dataToPatch, }; // 7. Commit const newKeystone = await evolvePersistAndRegisterKeystone({ prevIbGib: latestKeystone, newData, metaspace, space }); return newKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Structural evolution: Removes challenge pools from the keystone. * * Use Case: Unlinking a custodian or delegate SSO pool. * * Requires the Master Secret to authorize the change via a pool containing * the 'manage' verb (the administrative manage pool). */ async removePools({ latestKeystone, masterSecret, signingPoolId, poolIds, frameDetails, dataToPatch, metaspace, space, }: { latestKeystone: KeystoneIbGib_V1; /** * Alice's Master Secret. * Required to solve challenges from the Admin/Manage pool to authorize this change. */ masterSecret: string; /** * The specific pool ID authorized to perform management operations (e.g. 'manage' or 'passkey-manage-*'). */ signingPoolId: string; /** * The IDs of the pools to remove. */ poolIds: string[]; frameDetails?: KeystoneFrameDetails; dataToPatch?: Partial; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.removePools.name}]`; try { if (logalot) { console.log(`${lc} starting...`); } if (!latestKeystone.data) { throw new Error(`(UNEXPECTED) latestKeystone.data falsy? (E: 8334c8faed128166a999d428c7805b25)`); } const prevData = latestKeystone.data; if (prevData.revocationInfo) { throw new Error(`Keystone has been revoked. Cannot remove pools. (E: 9599f8f51c78d722252ddb2894fdbe25)`); } if (poolIds.length === 0) { throw new Error(`No pool IDs provided to remove. (E: 7599f8f51c78d722252ddb2894fdbe25)`); } // 1. Identify Authority (Resolve Admin Pool) const adminPool = resolveTargetPool({ pools: prevData.challengePools, poolId: signingPoolId, verb: KEYSTONE_VERB_MANAGE, }); if (logalot) { console.log(`${lc} Authorized via pool: ${adminPool.id}`); } // 2. Construct the Management Claim with typed details const target = getIbGibAddr({ ibGib: latestKeystone }); const claim: Partial = { verb: KEYSTONE_VERB_MANAGE, target, details: { type: KeystoneClaimType.remove_pool, info: { remove: poolIds } as ClaimDetails_RemovePool } }; // 3. Calculate Costs const idsToSolve = await selectChallengeIds({ pool: adminPool, targetAddr: target }); // 4. Pay the Cost (Solve & Replenish) const { proof, nextPools: replenishedExistingPools } = await solveAndReplenish({ targetPoolId: adminPool.id, prevPools: prevData.challengePools, masterSecret, challengeIds: idsToSolve, claim, }); // 5. Mutate Structure (Remove the pools) const removeSet = new Set(poolIds); const finalPools = replenishedExistingPools.filter(p => !removeSet.has(p.id)); // Verify that we actually removed the expected count of pools if (finalPools.length !== replenishedExistingPools.length - poolIds.length) { const missingIds = poolIds.filter(id => !replenishedExistingPools.some(p => p.id === id)); throw new Error(`Cannot remove pool. Pool IDs not found in keystone: ${missingIds.join(', ')} (E: d584889fbeb6c7c378fa38a596d13826)`); } // 6. Construct New Data const n = (prevData.n ?? 0) + 1; let checkpointDetails: any | undefined; if (n % KEYSTONE_CHECKPOINT_FREQUENCY === 0) { const currentFrameView: KeystoneIbGib_V1 = { ...latestKeystone, data: { ...prevData, challengePools: finalPools, frameDetails } }; checkpointDetails = await this.getAggregateDetails({ latestKeystone: currentFrameView, metaspace, space }); } const newData: KeystoneData_V1 = { challengePools: finalPools, proofs: [proof], frameDetails, checkpointDetails, ...(prevData.delegates ? { delegates: prevData.delegates } : {}), ...dataToPatch, }; // 7. Commit const newKeystone = await evolvePersistAndRegisterKeystone({ prevIbGib: latestKeystone, newData, metaspace, space }); return newKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Consolidates the state of a Keystone identity across its history. * Walks back until it hits a checkpoint or genesis. */ async getAggregateDetails({ latestKeystone, metaspace, space, }: { latestKeystone: KeystoneIbGib_V1; metaspace: MetaspaceService; space?: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.getAggregateDetails.name}]`; try { let aggregated: any = {}; let current = latestKeystone; while (current) { const data = current.data!; // 1. If we hit a checkpoint, merge it and STOP. if (data.checkpointDetails) { aggregated = mergeMapsOrArrays_Naive({ dominant: aggregated, recessive: data.checkpointDetails }); break; } // 2. Merge this frame's details if (data.frameDetails) { aggregated = mergeMapsOrArrays_Naive({ dominant: aggregated, recessive: data.frameDetails }); } // 3. Genesis check (n=0) if (data.n === 0) { break; } // 4. Walk back const past = current.rel8ns?.past; const prevAddr = (past && past.length > 0) ? past[past.length - 1] : undefined; if (!prevAddr) { break; } const res = await metaspace.get({ addr: prevAddr, space }); if (!res.success || !res.ibGibs || res.ibGibs.length === 0) { console.warn(`${lc} Could not find previous keystone frame at ${prevAddr} (W: e3d069b22e11e550e58844889ddb5325). Returning aggregated details collected so far.`); break; } current = res.ibGibs[0] as KeystoneIbGib_V1; } // Prune any tombstoned (null) keys from the aggregated result this.pruneTombstoneNulls(aggregated); return aggregated; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Retrieves common aggregated info for a keystone timeline. */ async getKeystoneCommonInfo({ addr, ibGib, metaspace, space, }: { addr?: string; ibGib?: KeystoneIbGib_V1; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise<{ name: string; description: string; isPrimary: boolean; aggregateDetails: any; latestFrameDetails: any; n: number; timestamp?: string; timestampMs?: number; }> { const lc = `${this.lc}[getKeystoneCommonInfo]`; try { let targetAddr = addr; let targetIbGib: any = ibGib; if (!targetAddr) { if (!targetIbGib) { throw new Error(`Both addr and ibGib are falsy. Expected at least one parameter to resolve keystone info. (E: 3a2890b1c28f7449c5d8693a7d4a2828)`); } targetAddr = getIbGibAddr({ ibGib: targetIbGib }); } if (!targetIbGib) { const { ib, gib } = getIbAndGib({ ibGibAddr: targetAddr }); targetIbGib = { ib, gib }; } const resGetLatest = await getLatestAddrs({ ibGibs: [targetIbGib], space, }); if (!resGetLatest.data?.latestAddrsMap) { throw new Error(`Could not get latest address map for keystone ${targetAddr} in local space. (E: 4a2890b1c28f7449c5d8693a7d4a2829)`); } const latestAddr = resGetLatest.data.latestAddrsMap[targetAddr] || Object.values(resGetLatest.data.latestAddrsMap)[0]; if (!latestAddr) { throw new Error(`No latest address found in map for keystone ${targetAddr} in local space. (E: 5a2890b1c28f7449c5d8693a7d4a2830)`); } const resGet = await metaspace.get({ addr: latestAddr, space }); const latestKeystone = resGet.ibGibs?.at(0) as KeystoneIbGib_V1; if (!latestKeystone || !latestKeystone.data) { throw new Error(`Keystone ${latestAddr} not found or missing data in local space. (E: 6a2890b1c28f7449c5d8693a7d4a2831)`); } const latestFrameDetails = latestKeystone.data.frameDetails || {}; const aggregateDetails = await this.getAggregateDetails({ latestKeystone, metaspace, space }); const name = aggregateDetails?.username || aggregateDetails?.name || aggregateDetails?.profile?.name || latestFrameDetails?.username || latestFrameDetails?.name || ''; const description = aggregateDetails?.description || aggregateDetails?.profile?.description || latestFrameDetails?.description || ''; const isPrimary = !!aggregateDetails?.isPrimary || !!aggregateDetails?.profile?.isPrimary || !!latestFrameDetails?.isPrimary; const n = latestKeystone.data.n ?? 0; const timestamp = latestFrameDetails?.timestamp || aggregateDetails?.timestamp || ''; const timestampMs = latestFrameDetails?.timestampMs || aggregateDetails?.timestampMs || undefined; return { name, description, isPrimary, aggregateDetails, latestFrameDetails, n, timestamp, timestampMs }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } } /** * Replaces a challenge pool (such as manage or custodian-manage) with a new pool, * authorizing the transition via the specified signing pool. * * @param latestKeystone The current tip frame of the keystone timeline. * - Visibility: Public (Public Merkle frame, safe for logs/ledger). * - Generator: Client/Server (Constructed locally and synced). * * @param newPool The fully constructed new pool to place in the next frame. * - Visibility: Public (Public configuration and public challenges, safe for ledger). * - Generator: Client/Server (Generated dynamically by the party proposing the update). * * @param signingSecret The master secret or derived KDF secret of the pool authorizing the change. * - Visibility: Private (Confidential secret credential. Must never go over the wire). * - Generator: Client/Server (Known only to the signing party). * * @param signingPoolId The ID of the pool used to authorize the transition (defaults to 'manage'). * - Visibility: Public (Non-sensitive configuration string). * - Generator: Client/Server (From pool configuration). */ async replacePool({ latestKeystone, newPool, signingSecret, signingPoolId = POOL_ID_MANAGE, frameDetails, metaspace, space, }: { latestKeystone: KeystoneIbGib_V1; newPool: KeystoneChallengePool; signingSecret: string; signingPoolId?: string; frameDetails?: any; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise { const lc = `${this.lc}[${this.replacePool.name}]`; try { if (logalot) { console.log(`${lc} starting... replacing pool: ${newPool.id}`); } if (!latestKeystone.data) { throw new Error(`(UNEXPECTED) latestKeystone.data falsy? (E: 1334c8faed128166a999d428c7805b25)`); } const prevData = latestKeystone.data; if (prevData.revocationInfo) { throw new Error(`Keystone has been revoked. Cannot replace pool. (E: 2599f8f51c78d722252ddb2894fdbe25)`); } // 1. Identify Authority (Resolve Signing Pool) const prevPools = prevData.challengePools; const signingPool = prevPools.find(p => p.id === signingPoolId); if (!signingPool) { throw new Error(`Signing pool not found: ${signingPoolId} (E: 3599f8f51c78d722252ddb2894fdbe25)`); } // 2. Construct the Management Claim with typed details const target = getIbGibAddr({ ibGib: latestKeystone }); const claim: Partial = { verb: KEYSTONE_VERB_MANAGE, target, details: { type: KeystoneClaimType.replace_pool, info: { replace: newPool.id } as ClaimDetails_ReplacePool } }; // 3. Calculate Costs const idsToSolve = await selectChallengeIds({ pool: signingPool, targetAddr: target }); // 4. Pay the Cost (Solve & Replenish) const { proof, nextPools } = await solveAndReplenish({ targetPoolId: signingPoolId, prevPools, masterSecret: signingSecret, challengeIds: idsToSolve, claim, }); // 5. Replace target pool in nextPools const targetIdx = nextPools.findIndex(p => p.id === newPool.id); if (targetIdx === -1) { throw new Error(`Target pool to replace '${newPool.id}' not found in keystone challenge pools.`); } nextPools[targetIdx] = newPool; // 6. Construct New Data const n = (prevData.n ?? 0) + 1; let checkpointDetails: any | undefined; if (n % KEYSTONE_CHECKPOINT_FREQUENCY === 0) { const currentFrameView: KeystoneIbGib_V1 = { ...latestKeystone, data: { ...prevData, frameDetails } }; checkpointDetails = await this.getAggregateDetails({ latestKeystone: currentFrameView, metaspace, space }); } const newData: KeystoneData_V1 = { challengePools: nextPools, proofs: [proof], frameDetails, checkpointDetails, ...(prevData.delegates ? { delegates: prevData.delegates } : {}), }; // 7. Commit const newKeystone = await evolvePersistAndRegisterKeystone({ prevIbGib: latestKeystone, newData, metaspace, space }); return newKeystone; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Evolve the keystone by rotating the primary user manage pool (`manage`) to a new master secret (password). * This creates a new frame signed by the specified `signingPoolId` using `signingSecret`. * * Supports recovery (signing via `custodian-manage` using the custodian secret) and normal rotation * (signing via `manage` using the old password). **I DONT THINK THIS IS POSSIBLE. WE WOULD NEED CUSTODIAN MANAGE POOLS ON ALL THE DELEGATES AS WELL** * * @param signingSecret * * @param signingPoolId */ async changePassword({ keystoneIbGib, keystoneAddr, newMasterSecret, signingSecret, signingPoolId = POOL_ID_MANAGE, poolIds, frameDetails, metaspace, space, }: { /** * The keystone IBGIB whose password we are changing. Does NOT have to * be the tip, as we will get the latest keystone in the implementation * of this function. * - Visibility: Public (Public Merkle frame, safe for ledger). * - Generator: Client/Server (Constructed locally and synced). * * NOTE: You can provide {@link keystoneIbGib} or {@link keystoneAddr}, * but either way the latest keystone ibgib will be gotten first. */ keystoneIbGib?: KeystoneIbGib_V1; /** * The keystone ADDRESS whose password we are changing. Does NOT have to * be the tip, as we will get the latest keystone in the implementation * of this function. * - Visibility: Public (Public Merkle frame, safe for ledger). * - Generator: Client/Server (Constructed locally and synced). * * NOTE: You can provide {@link keystoneIbGib} or {@link keystoneAddr}, * but either way the latest keystone ibgib will be gotten first. */ keystoneAddr?: IbGibAddr; /** * The new password/master secret to set for the user's primary pools. * - Visibility: Private (Confidential secret credential. Must never go * over the wire). * - Generator: Client (From user input in settings). */ newMasterSecret: string; /** * The secret of the pool authorizing this change (either old password * or derived custodian secret). * - Visibility: Private (Confidential secret. Never over the wire). * - Generator: Client/Server (Known only to the signing party). */ signingSecret: string; /** * The ID of the pool used to authorize the rotation. Defaults to * "manage" for user password changes, or if rotating custodian, should * be the custodian's corresponding manage pool. * - Visibility: Public (Non-sensitive ID string). * - Generator: Client/Server (From pool configuration). */ signingPoolId?: string; /** * If provided, password will only be changed for these pools. * NOTE: **delegate passwords will NOT be changed if poolIds are * explicitly provided.** */ poolIds?: string[]; frameDetails?: any; metaspace: MetaspaceService; space: IbGibSpaceAny; }): Promise<{ newKeystone: KeystoneIbGib_V1, newDelegates?: KeystoneIbGib_V1[] }> { const lc = `${this.lc}[${this.changePassword.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 9e3ff83ebd74511f9dad784a1020d926)`); } if (!keystoneIbGib && !keystoneAddr) { throw new Error(`Either keystoneIbGib or keystoneAddr required. (E: d1b8c8cb75f2c022284e69b8c30af826)`); } if (keystoneIbGib && keystoneAddr) { // double check addr matches ibgib const checkAddr = getIbGibAddr({ ibGib: keystoneIbGib }); if (checkAddr !== keystoneAddr) { throw new Error(`(UNEXPECTED) both keystoneIbGib (addr: ${checkAddr}) and keystoneAddr (${keystoneAddr}) provided, but the addrs are unequal? Note that only one is required for this function, but if both are provided the addrs must match exactly. (E: c5574f7e353a48b0bba94a1862af4e26)`); } } keystoneAddr ??= getIbGibAddr({ ibGib: keystoneIbGib }); const latestKeystone = await this.getLatestKeystone({ addr: keystoneAddr, metaspace, space, }); if (!latestKeystone.data) { throw new Error(`latestKeystone.data falsy (E: 22e498eb8308a33e68b812d8d3905826)`); } if (latestKeystone.data.revocationInfo) { throw new Error(`Keystone has been revoked. Cannot change password. (E: 726298617e8508b3c83b5e985a03e826)`); } const prevPools = latestKeystone.data.challengePools; const signingPool = prevPools.find(p => p.id === signingPoolId); if (!signingPool) { throw new Error(`Signing pool not found: ${signingPoolId} (E: 3599f8f51c78d722252ddb2894fdbe25)`); } // 1. Resolve target pools to rotate let targets: KeystoneChallengePool[] = []; if (poolIds && poolIds.length > 0) { for (const id of poolIds) { const found = prevPools.find(p => p.id === id); if (!found) { throw new Error(`Target pool to rotate not found: ${id} (E: 4599f8f51c78d722252ddb2894fdbe25)`); } targets.push(found); } } else { targets = prevPools.filter(p => !p.isForeign); if (targets.length === 0) { throw new Error(`No non-foreign pools found to rotate. (E: 5599f8f51c78d722252ddb2894fdbe25)`); } } // 2. Rotate the target pools const rotatedPools: KeystoneChallengePool[] = []; for (const targetPool of targets) { const rotated = await rotatePoolChallenges({ prevPool: targetPool, newMasterSecret }); rotatedPools.push(rotated); } // 3. Construct Management Claim with typed details const target = getIbGibAddr({ ibGib: latestKeystone }); const claim: Partial = { verb: KEYSTONE_VERB_MANAGE, target, details: { type: KeystoneClaimType.change_password, info: { change: rotatedPools.map(p => p.id) } as ClaimDetails_ChangePassword } }; // 4. Calculate Costs const idsToSolve = await selectChallengeIds({ pool: signingPool, targetAddr: target }); // 5. Pay the Cost (Solve & Replenish) const { proof, nextPools } = await solveAndReplenish({ targetPoolId: signingPoolId, prevPools, masterSecret: signingSecret, challengeIds: idsToSolve, claim }); // 6. Swap the rotated pools in nextPools for (const rotated of rotatedPools) { const idx = nextPools.findIndex(p => p.id === rotated.id); if (idx === -1) { throw new Error(`Rotated pool ${rotated.id} not found in next pools list. (E: 6599f8f51c78d722252ddb2894fdbe25)`); } nextPools[idx] = rotated; } // 7. Construct New Data const n = (latestKeystone.data.n ?? 0) + 1; let checkpointDetails: any | undefined; if (n % KEYSTONE_CHECKPOINT_FREQUENCY === 0) { const currentFrameView: KeystoneIbGib_V1 = { ...latestKeystone, data: { ...latestKeystone.data, challengePools: nextPools } }; checkpointDetails = await this.getAggregateDetails({ latestKeystone: currentFrameView, metaspace, space }); } const newData: KeystoneData_V1 = { challengePools: nextPools, proofs: [proof], frameDetails, checkpointDetails, ...(latestKeystone.data.delegates ? { delegates: latestKeystone.data.delegates } : undefined), }; // 8. Commit const newKeystoneIbGib = await evolvePersistAndRegisterKeystone({ prevIbGib: latestKeystone, newData, metaspace, space }); // update delegates' passwords also, **BUT ONLY IF NOT DOING // SPECIFIC POOLS**. const newDelegates: KeystoneIbGib_V1[] = []; if ((poolIds ?? []).length === 0) { const delegateSigningSecret = await deriveDelegateSecret({ masterSecret: signingSecret }); const delegateNewMasterSecret = await deriveDelegateSecret({ masterSecret: newMasterSecret }); const delegatesMap = latestKeystone.data.delegates ?? {}; for (const [delegateTjpAddr, delegateInfo] of Object.entries(delegatesMap)) { // Skip custodial-sync and foreign delegates because their secrets are independent / server-authorized if (isCustodialDelegate({ delegateInfo })) { if (logalot) { console.log(`${lc} Skipping custodial delegate rotation for ${delegateTjpAddr} (${delegateInfo.deviceName})`); } continue; } try { const { newKeystone: newDelegate, newDelegates: newDelegatesSecondOrder } = await this.changePassword({ keystoneAddr: delegateTjpAddr, metaspace, space, newMasterSecret: delegateNewMasterSecret, signingSecret: delegateSigningSecret, signingPoolId, poolIds: undefined, frameDetails, }); if (newDelegatesSecondOrder && newDelegatesSecondOrder.length > 0) { throw new Error(`(UNEXPECTED) Delegate keystone has its own delegate(s)? ATOW (07/20/2026) second order delegates are not supported. (E: de45a7b7d9b8f61f6e58158269acba26)`); } newDelegates.push(newDelegate); } catch (delegateErr) { console.warn(`${lc} Error rotating user delegate ${delegateTjpAddr}: ${extractErrorMsg(delegateErr)}. Continuing.`); } } } return { newKeystone: newKeystoneIbGib, newDelegates: newDelegates.length > 0 ? newDelegates : undefined }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Verifies if a candidate signing secret (password) is correct for a specific challenge pool. * Does not mutate any state. */ /** * Verifies if a given secret successfully solves challenges in the specified pool * (or any candidate manage pool if poolId is omitted). */ async verifySigningSecret({ keystoneIbGib, signingSecret, poolId, verb = KEYSTONE_VERB_MANAGE, }: { keystoneIbGib: KeystoneIbGib_V1; signingSecret: string; poolId?: string; verb?: string; }): Promise { const lc = `${this.lc}[${this.verifySigningSecret.name}]`; try { if (!keystoneIbGib.data) return false; const pools = keystoneIbGib.data.challengePools; if (poolId) { const pool = pools.find(p => p.id === poolId); if (!pool) return false; return await verifyPoolSecret({ pool, signingSecret }); } // Test candidate pools authorizing this verb (or manage pools) const candidatePools = pools.filter(p => p.id === 'manage' || p.id.startsWith('passkey-manage-') || (p.config.allowedVerbs && verb && p.config.allowedVerbs.includes(verb)) ); for (const candidate of candidatePools) { const isValid = await verifyPoolSecret({ pool: candidate, signingSecret }); if (isValid) { return true; } } return false; } catch (error) { console.warn(`${lc} Exception during verification: ${extractErrorMsg(error)}`); return false; } } /** * Recursively prunes keys whose value is strictly `null` (tombstone records) * from aggregated detail maps/arrays. */ private pruneTombstoneNulls(obj: any): any { if (obj === null || obj === undefined || typeof obj !== 'object') { return obj; } if (Array.isArray(obj)) { return obj.filter(item => item !== null).map(item => this.pruneTombstoneNulls(item)); } for (const key of Object.keys(obj)) { if (obj[key] === null) { delete obj[key]; } else if (obj[key] !== null && typeof obj[key] === 'object') { this.pruneTombstoneNulls(obj[key]); } } return obj; } }