import { respecfully, iReckon, ifWe, firstOfAll, firstOfEach, lastOfAll, lastOfEach, respecfullyDear, ifWeMight } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs'; const maam = `[${import.meta.url}]`, sir = maam; import { clone, hash, getUUID, extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../core-constants.mjs'; import { KeystoneStrategyFactory } from './strategy/keystone-strategy-factory.mjs'; import { KeystoneChallengePool, KeystoneClaim, KeystoneIbGib_V1, KeystonePoolConfig_HashV1, KeystoneReplenishStrategy, KeystoneClaimType, ClaimDetails_ChangePassword, ClaimDetails_AddPool, ClaimDetails_ReplacePool } from './keystone-types.mjs'; import { createRevocationPoolConfig, createStandardPoolConfig } from './keystone-config-builder.mjs'; import { POOL_ID_DEFAULT, POOL_ID_REVOKE, KEYSTONE_VERB_REVOKE, KEYSTONE_VERB_MANAGE, POOL_ID_MANAGE, KEYSTONE_VERB_SYNC, POOL_ID_CUSTODIAN_MANAGE } from './keystone-constants.mjs'; import { KeystoneService_V1 } from './keystone-service-v1.mjs'; import { selectChallengeIds, validateChallengePool, validateKeystoneIb, validateKeystoneTransition, validateGenesisKeystone, rotatePoolChallenges } from './keystone-helpers.mjs'; import { KeystoneProfileBuilder } from './policy/keystone-profile-builder.mjs'; import { getTjpAddr } from '../common/other/ibgib-helper.mjs'; import { deriveDelegateSecret } from './strategy/hash-reveal-v1/hash-reveal-v1.mjs'; const logalot = GLOBAL_LOG_A_LOT; /** * A simple in-memory map acting as a Space. * Pure Storage. No Indexing logic. */ class MockIbGibSpace { store = new Map(); ib: string = 'witness space mock-space mock_space_id user'; constructor(public name: string = "mock_space") { } async put({ ibGib }: { ibGib: IbGib_V1 }): Promise { const addr = getIbGibAddr({ ibGib }); this.store.set(addr, JSON.parse(JSON.stringify(ibGib))); // Deep copy } async get({ addr }: { addr: string }): Promise { const data = this.store.get(addr); return data ? JSON.parse(JSON.stringify(data)) : null; } async argy({ argData, ibGibs }: { argData: any; ibGibs?: IbGib_V1[] }): Promise { return { ib: 'arg^gib', gib: 'arg_gib', data: argData, ibGibs, }; } async witness(arg: any): Promise { const cmd = arg.data?.cmd; const cmdModifiers = arg.data?.cmdModifiers || []; if (cmd === 'get') { const addrs = arg.data.ibGibAddrs || []; if (cmdModifiers.includes('latest') && cmdModifiers.includes('addrs')) { const latestAddrsMap: { [addr: string]: string } = {}; for (const queryAddr of addrs) { const queryTjpGib = queryAddr.includes('.') ? queryAddr.split('.')[1] : queryAddr.split('^')[1]; let latestAddr = queryAddr; let maxN = -1; for (const [addr, ibGib] of this.store.entries()) { const tjpGib = addr.includes('.') ? addr.split('.')[1] : addr.split('^')[1]; if (tjpGib === queryTjpGib) { const n = ibGib.data?.n ?? 0; if (n > maxN) { maxN = n; latestAddr = addr; } } } latestAddrsMap[queryAddr] = latestAddr; } return { data: { success: true, latestAddrsMap, } }; } else { const ibGibs: IbGib_V1[] = []; for (const addr of addrs) { const x = await this.get({ addr }); if (x) { ibGibs.push(x); } } return { data: { success: true }, ibGibs, }; } } return undefined; } } /** * A partial mock of Metaspace. * Handles: * 1. Retrieving the local space. * 2. Delegating 'put' to the space. * 3. 'registerNewIbGib': Tracking the HEAD of a timeline. */ class MockMetaspaceService { /** * Map of TJP Gib (Timeline ID) -> Latest IbGib Addr (Head) */ timelineHeads = new Map(); constructor(public space: MockIbGibSpace) { } async getLocalUserSpace({ lock }: { lock: boolean }): Promise { return this.space; } /** * Metaspace often acts as a facade for put, defaulting to local space. */ async put(args: any): Promise { const target = args.space || this.space; return target.put(args); } async get(args: { addr: string, space?: any }): Promise<{ success: boolean, ibGibs?: IbGib_V1[] }> { const target = args.space || this.space; const x = await target.get({ addr: args.addr }); return { success: !!x, ibGibs: x ? [x] : [], }; } /** * Tracks the latest version of an ibGib timeline. */ async registerNewIbGib(args: { ibGib: IbGib_V1, space?: any }): Promise { const { ibGib } = args; const targetSpace = args.space || this.space; // 1. Ensure it is stored await targetSpace.put({ ibGib }); // 2. Extract TJP (Timeline Identifier) // Simplified logic mirroring getGibInfo const gib = ibGib.gib || ''; let tjpGib = gib; if (gib.includes('.')) { // It's a frame in a timeline: "punctiliarHash.tjpHash" // The TJP is the suffix. const parts = gib.split('.'); tjpGib = parts.slice(1).join('.'); } // Else: It's a Primitive or a TJP itself (Genesis). // If Genesis (isTjp=true), the gib IS the tjpGib. const addr = getIbGibAddr({ ibGib }); this.timelineHeads.set(tjpGib, addr); } /** * Resolves the latest address for a timeline. */ async getLatestAddr({ addr, tjpAddr, space }: { addr?: string, tjpAddr?: string, space?: any }): Promise { const targetAddr = tjpAddr || addr; if (!targetAddr) return undefined; const targetSpace = space || this.space; const gib = targetAddr.split('^')[1] || ''; let tjpGib = gib.includes('.') ? gib.split('.').slice(1).join('.') : gib; if (this.timelineHeads.has(tjpGib)) { return this.timelineHeads.get(tjpGib); } if (targetSpace && typeof targetSpace.witness === 'function') { const res = await targetSpace.witness({ data: { cmd: 'get', cmdModifiers: ['latest', 'addrs'], ibGibAddrs: [targetAddr] } }); if (res?.data?.success && res?.data?.latestAddrsMap?.[targetAddr]) { return res.data.latestAddrsMap[targetAddr]; } } return targetAddr; } } // =========================================================================== // SUITE A: STRATEGY VECTORS (The Math) // =========================================================================== await respecfully(sir, 'Suite A: Strategy Vectors (HashRevealV1)', async () => { // Setup generic variables const masterSecret = "TestSecret_12345"; const poolId = "TestPool"; let config: KeystonePoolConfig_HashV1; firstOfAll(sir, async () => { // Use our standard builder to get a valid config object const salt = (await getUUID()).substring(0, 16); config = createStandardPoolConfig({ id: poolId, salt, }) as KeystonePoolConfig_HashV1; }); await respecfully(sir, 'Derivation Logic', async () => { await ifWe(sir, 'derivePoolSecret with same inputs returns same output', async () => { const strategy = KeystoneStrategyFactory.create({ config }); const secretA = await strategy.derivePoolSecret({ masterSecret }); const secretB = await strategy.derivePoolSecret({ masterSecret }); iReckon(sir, secretA).asTo('secret consistency').willEqual(secretB); iReckon(sir, secretA).asTo('secret length').isGonnaBeTruthy(); }); await ifWe(sir, 'derivePoolSecret with different master secret returns different output', async () => { const strategy = KeystoneStrategyFactory.create({ config }); const secretA = await strategy.derivePoolSecret({ masterSecret }); const secretB = await strategy.derivePoolSecret({ masterSecret: masterSecret + "_diff" }); iReckon(sir, secretA).asTo('secrets differ').not.willEqual(secretB); }); await ifWe(sir, 'derivePoolSecret with different salt returns different output', async () => { // Modify salt in a copy of config const configB = { ...config, salt: "OtherPool" }; const strategyA = KeystoneStrategyFactory.create({ config }); const strategyB = KeystoneStrategyFactory.create({ config: configB }); const secretA = await strategyA.derivePoolSecret({ masterSecret }); const secretB = await strategyB.derivePoolSecret({ masterSecret }); iReckon(sir, secretA).asTo('salt affects secret').not.willEqual(secretB); }); await ifWe(sir, 'deriveDelegateSecret derives a consistent secret using KDF', async () => { const secretA = await deriveDelegateSecret({ masterSecret }); const secretB = await deriveDelegateSecret({ masterSecret }); iReckon(sir, secretA).asTo('consistency').willEqual(secretB); iReckon(sir, secretA).asTo('truthy').isGonnaBeTruthy(); const secretC = await deriveDelegateSecret({ masterSecret: masterSecret + '_other' }); iReckon(sir, secretA).asTo('differ').not.willEqual(secretC); }); }); await respecfully(sir, 'Challenge/Solution Logic', async () => { await ifWe(sir, 'generateSolution -> generateChallenge -> validateSolution loop works', async () => { const strategy = KeystoneStrategyFactory.create({ config }); const poolSecret = await strategy.derivePoolSecret({ masterSecret }); const challengeId = "a3ff7843552870fc28bef2b"; // arbitrary random challengeId // 1. Generate Solution const solution = await strategy.generateSolution({ poolSecret, poolId: config.id, challengeId }); iReckon(sir, solution.value).asTo('solution value exists').isGonnaBeTruthy(); iReckon(sir, solution.challengeId).asTo('id matches').willEqual(challengeId); // 2. Generate Public Challenge from Solution const challenge = await strategy.generateChallenge({ solution }); iReckon(sir, challenge.hash).asTo('challenge hash exists').isGonnaBeTruthy(); // 3. Validate const isValid = await strategy.validateSolution({ solution, challenge }); iReckon(sir, isValid).asTo('valid pair should pass').isGonnaBeTrue(); }); await ifWe(sir, 'validateSolution fails for mismatched values', async () => { const strategy = KeystoneStrategyFactory.create({ config }); const poolSecret = await strategy.derivePoolSecret({ masterSecret }); const challengeId = "8c994f3ed598f150e25513"; // arbitrary random challengeId // Generate real pair const solution = await strategy.generateSolution({ poolSecret, poolId: config.id, challengeId }); const challenge = await strategy.generateChallenge({ solution }); // Tamper with solution value const badSolution = { ...solution, value: "hacked_value" }; const isValid = await strategy.validateSolution({ solution: badSolution, challenge }); iReckon(sir, isValid).asTo('tampered solution should fail').isGonnaBeFalse(); }); await ifWe(sir, 'validateSolution fails for mismatched challenge hashes', async () => { const strategy = KeystoneStrategyFactory.create({ config }); const poolSecret = await strategy.derivePoolSecret({ masterSecret }); // Generate pair A const challengeId_A = "416c38cfd6ee63dbf8d4e5ef36"; // arbitrary random challengeId const solutionA = await strategy.generateSolution({ poolSecret, poolId: config.id, challengeId: challengeId_A }); // Generate pair B const challengeId_B = "c487ef6b7878fae798c3"; // arbitrary random challengeId const solutionB = await strategy.generateSolution({ poolSecret, poolId: config.id, challengeId: challengeId_B }); const challengeB = await strategy.generateChallenge({ solution: solutionB }); // Check A against B const isValid = await strategy.validateSolution({ solution: solutionA, challenge: challengeB }); iReckon(sir, isValid).asTo('mismatched pair should fail').isGonnaBeFalse(); }); }); }); // =========================================================================== // SUITE B: SERVICE LIFECYCLE (Genesis -> Sign -> Validate) // =========================================================================== await respecfully(sir, 'Suite B: Service Lifecycle', async () => { const service = new KeystoneService_V1(); const masterSecret = "AliceSecretKey_987654321"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let genesisKeystone: KeystoneIbGib_V1; let signedKeystone: KeystoneIbGib_V1; firstOfAll(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); }); await respecfully(sir, 'Genesis', async () => { await ifWe(sir, 'creates a valid genesis frame and persists it', async () => { const salt = (await getUUID()).substring(0, 16); const config = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt, }); genesisKeystone = await service.genesis({ masterSecret, configs: [config], metaspace: mockMetaspace, space: mockSpace as any, }); // Verify Object iReckon(sir, genesisKeystone).asTo('genesis object').isGonnaBeTruthy(); iReckon(sir, genesisKeystone.data?.isTjp).asTo('isTjp').isGonnaBeTrue(); // Verify Persistence const addr = getIbGibAddr({ ibGib: genesisKeystone }); const saved = await mockSpace.get({ addr }); iReckon(sir, saved).asTo('persisted to space').isGonnaBeTruthy(); // Verify Registration (Timeline Tracking) // Genesis gib should be registered as a timeline head const head = mockMetaspace.timelineHeads.get(genesisKeystone.gib!); iReckon(sir, head).asTo('genesis registered as timeline head').willEqual(addr); }); }); await respecfully(sir, 'Signing (Evolution)', async () => { await ifWe(sir, 'evolves the keystone with a valid proof', async () => { const claim: Partial = { target: "comment 123^gib", verb: "post" }; const details = { note: "First post!" }; signedKeystone = await service.sign({ latestKeystone: genesisKeystone, masterSecret, claim, poolId: POOL_ID_DEFAULT, frameDetails: details, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, signedKeystone).asTo('new frame created').isGonnaBeTruthy(); iReckon(sir, signedKeystone).asTo('is different frame').not.isGonnaBe(genesisKeystone); // NOTE: If this fails, check if 'sign' calls 'space.put' or 'metaspace.put'! // In your current 'sign' implementation, you return the object but might have missed the save step. const addr = getIbGibAddr({ ibGib: signedKeystone }); const saved = await mockSpace.get({ addr }); iReckon(sir, saved).asTo('persisted to space').isGonnaBeTruthy(); }); }); await respecfully(sir, 'Validation', async () => { await ifWe(sir, 'validates the genesis->signed transition', async () => { const errors = await service.validate({ prevIbGib: genesisKeystone, currentIbGib: signedKeystone, // metaspace: mockMetaspace, // space: mockSpace as any, }); iReckon(sir, errors.length).asTo('signature validation has no errors').willEqual(0); }); }); }); // =========================================================================== // SUITE C: SECURITY & SAD PATHS // =========================================================================== await respecfully(sir, 'Suite C: Security Vectors', async () => { const service = new KeystoneService_V1(); const aliceSecret = "AliceSecret_111"; const eveSecret = "EveSecret_666"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let genesisKeystone: KeystoneIbGib_V1; firstOfAll(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); // Setup Alice's Identity const salt = (await getUUID()).substring(0, 16); const config = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt, targetBinding: 0, size: 10, }); // config.behavior.size = 10; genesisKeystone = await service.genesis({ masterSecret: aliceSecret, configs: [config], metaspace: mockMetaspace, space: mockSpace as any, }); }); await respecfully(sir, 'Wrong Secret (Forgery)', async () => { await ifWe(sir, 'prevents creation of forged frames', async () => { const claim: Partial = { target: "comment 123^gib", verb: "post" }; let errorCaught = false; let errorMsg = ""; try { // Eve tries to sign Alice's keystone. // This MUST fail because sign() calls evolve(), which calls validate(). await service.sign({ latestKeystone: genesisKeystone, masterSecret: eveSecret, claim, poolId: POOL_ID_DEFAULT, metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e: any) { errorCaught = true; errorMsg = e.message; } iReckon(sir, errorCaught).asTo('service rejected forgery').isGonnaBeTrue(); // Verify it was a crypto error, not something else iReckon(sir, errorMsg).asTo('error mentions crypto violation').includes('Crypto Violation'); }); }); await respecfully(sir, 'Policy Violation (Restricted Verbs)', async () => { await ifWe(sir, 'throws error if signing forbidden verb with restricted pool', async () => { // Create a specific restricted pool config manually const restrictedPoolId = "read_only_pool"; const restrictedConfig = createStandardPoolConfig({ id: restrictedPoolId, salt: restrictedPoolId, }); // Manually restrict it (since Builder defaults to undefined/allow-all) restrictedConfig.allowedVerbs = ['read']; const restrictedGenesis = await service.genesis({ masterSecret: aliceSecret, configs: [restrictedConfig], metaspace: mockMetaspace, space: mockSpace as any, }); // Try to sign "write" using "read_only_pool" const claim: Partial = { target: "data^gib", verb: "write" }; let errorCaught = false; try { await service.sign({ latestKeystone: restrictedGenesis, masterSecret: aliceSecret, claim, poolId: restrictedPoolId, // Force use of restricted pool metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e) { errorCaught = true; // Optional: Check error message contains "not authorized" } iReckon(sir, errorCaught).asTo('policy enforced').isGonnaBeTrue(); }); }); }); // =========================================================================== // SUITE D: REVOCATION // =========================================================================== await respecfully(sir, 'Suite D: Revocation', async () => { const service = new KeystoneService_V1(); const masterSecret = "AliceSecret_RevokeTest"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let genesisKeystone: KeystoneIbGib_V1; firstOfAll(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); // Setup Identity WITH a Revocation Pool const stdSalt = (await getUUID()).substring(0, 16); const revokeSalt = (await getUUID()).substring(0, 16); const stdConfig = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt: stdSalt, }); const revokeConfig = createRevocationPoolConfig({ id: POOL_ID_REVOKE, salt: revokeSalt, }); // Special Config genesisKeystone = await service.genesis({ masterSecret, configs: [stdConfig, revokeConfig], metaspace: mockMetaspace, space: mockSpace as any, }); }); await respecfully(sir, 'Revoke Lifecycle', async () => { let revokedKeystone: KeystoneIbGib_V1; await ifWe(sir, 'successfully creates a revocation frame', async () => { revokedKeystone = await service.revoke({ latestKeystone: genesisKeystone, masterSecret, reason: "Key compromised", metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, revokedKeystone).isGonnaBeTruthy(); // Check Data const data = revokedKeystone.data!; iReckon(sir, data.revocationInfo).asTo('revocation info present').isGonnaBeTruthy(); iReckon(sir, data.revocationInfo!.reason).willEqual("Key compromised"); iReckon(sir, data.revocationInfo!.proof.claim.verb).willEqual(KEYSTONE_VERB_REVOKE); }); await ifWe(sir, 'validates the revocation frame', async () => { const errors = await service.validate({ prevIbGib: genesisKeystone, currentIbGib: revokedKeystone!, // metaspace: mockMetaspace, // space: mockSpace as any, }); iReckon(sir, errors.length).asTo('no validation errors').willEqual(0); }); await ifWe(sir, 'consumed the revocation pool (Scorched Earth)', async () => { const data = revokedKeystone!.data!; const revokePool = data.challengePools.find(p => p.id === POOL_ID_REVOKE); // The pool should exist... iReckon(sir, revokePool).isGonnaBeTruthy(); // Should be empty (0 challenges) const remaining = Object.keys(revokePool!.challenges); iReckon(sir, remaining.length).asTo('pool depleted').willEqual(0); }); await ifWe(sir, 'fails to sign any new claims after revocation', async () => { let errorCaught = false; try { await service.sign({ latestKeystone: revokedKeystone, masterSecret, claim: { verb: "post", target: "some_target" }, metaspace: mockMetaspace, space: mockSpace as any, }); } catch (err: any) { errorCaught = true; iReckon(sir, err.message).includes("has been revoked"); } iReckon(sir, errorCaught).asTo('signing blocked after revocation').isGonnaBeTrue(); }); await ifWe(sir, 'fails to evolve or add pools after revocation', async () => { let errorCaught = false; try { const dummyConfig = createStandardPoolConfig({ id: "dummy", salt: "dummy" }); const dummyPool = { id: "dummy", config: dummyConfig, challenges: {} }; await service.addPools({ latestKeystone: revokedKeystone, masterSecret, signingPoolId: POOL_ID_DEFAULT, newPools: [dummyPool], metaspace: mockMetaspace, space: mockSpace as any, }); } catch (err: any) { errorCaught = true; iReckon(sir, err.message).includes("has been revoked"); } iReckon(sir, errorCaught).asTo('adding pools blocked after revocation').isGonnaBeTrue(); }); }); }); // =========================================================================== // SUITE E: STRUCTURAL EVOLUTION (addPools) // =========================================================================== await respecfully(sir, 'Suite E: Structural Evolution (addPools)', async () => { const service = new KeystoneService_V1(); const aliceSecret = "Alice_Master_Key"; const bobSecret = "Bob_Foreign_Key"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let aliceKeystone: KeystoneIbGib_V1; // Helper to generate a "Foreign" pool (e.g. from Bob) const createForeignPool = async (id: string, verbs: string[] = []): Promise => { const salt = (await getUUID()).substring(0, 16); const config = createStandardPoolConfig({ id, salt }); config.allowedVerbs = verbs; // We use the factory manually here to simulate Bob doing this offline const strategy = KeystoneStrategyFactory.create({ config }); const poolSecret = await strategy.derivePoolSecret({ masterSecret: bobSecret }); const challenges: { [id: string]: any } = {}; for (let i = 0; i < 10; i++) { // Manually replicate ID gen for test const raw = await hash({ s: `${config.salt}${Date.now()}${i}` }); const challengeId = raw.substring(0, 16); const solution = await strategy.generateSolution({ poolSecret, poolId: config.salt, challengeId, }); const challenge = await strategy.generateChallenge({ solution }); challenges[challengeId] = challenge; } return { id, config, challenges, isForeign: true, metadata: { owner: 'Bob' } }; }; firstOfAll(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); // Alice Genesis: Standard pool (allows all verbs, including 'manage') const salt = (await getUUID()).substring(0, 16); const config = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt }); aliceKeystone = await service.genesis({ masterSecret: aliceSecret, configs: [config], metaspace: mockMetaspace, space: mockSpace as any, }); }); await respecfully(sir, 'Happy Path', async () => { await ifWe(sir, 'authorizes and adds a foreign pool', async () => { const bobPool = await createForeignPool("pool_bob", ["post"]); const updatedKeystone = await service.addPools({ latestKeystone: aliceKeystone, masterSecret: aliceSecret, signingPoolId: POOL_ID_DEFAULT, newPools: [bobPool], metaspace: mockMetaspace, space: mockSpace as any, }); // 1. Verify new state iReckon(sir, updatedKeystone).isGonnaBeTruthy(); const pools = updatedKeystone.data!.challengePools; iReckon(sir, pools.length).asTo('pool count increased').willEqual(2); const foundBob = pools.find(p => p.id === "pool_bob"); iReckon(sir, foundBob).asTo('bob pool exists').isGonnaBeTruthy(); iReckon(sir, foundBob!.isForeign).asTo('isForeign flag').isGonnaBeTrue(); // 2. Verify Proof const proof = updatedKeystone.data!.proofs[0]; iReckon(sir, proof.claim.verb).asTo('proof verb').willEqual("manage"); // Alice signed this using HER pool (default), not Bob's iReckon(sir, proof.solutions[0].poolId).willEqual(POOL_ID_DEFAULT); // 3. Verify Validity const errors = await service.validate({ prevIbGib: aliceKeystone, currentIbGib: updatedKeystone, }); iReckon(sir, errors.length).asTo('validation passed').willEqual(0); // Update local ref for next tests aliceKeystone = updatedKeystone; }); }); await respecfully(sir, 'Permissions & Logic', async () => { await ifWe(sir, 'fails if no pool allows "manage" verb', async () => { // 1. Create a restricted keystone let id = "read_only"; const restrictedConfig = createStandardPoolConfig({ id, salt: id }); restrictedConfig.allowedVerbs = ['read']; // No 'manage' const restrictedKeystone = await service.genesis({ masterSecret: aliceSecret, configs: [restrictedConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const newPool = await createForeignPool("pool_test"); let errorCaught = false; try { await service.addPools({ latestKeystone: restrictedKeystone, masterSecret: aliceSecret, signingPoolId: 'read_only', newPools: [newPool], metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e: any) { errorCaught = true; // Should fail in resolveTargetPool or addPools logic // console.log("Caught expected error:", e.message); } iReckon(sir, errorCaught).asTo('permission denied').isGonnaBeTrue(); }); await ifWe(sir, 'fails on ID collision', async () => { // Try to add "pool_bob" again (it was added in Happy Path) const duplicatePool = await createForeignPool("pool_bob"); let errorCaught = false; try { await service.addPools({ latestKeystone: aliceKeystone, // This already has pool_bob masterSecret: aliceSecret, signingPoolId: POOL_ID_DEFAULT, newPools: [duplicatePool], metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e: any) { errorCaught = true; iReckon(sir, e.message).includes("ID collision"); } iReckon(sir, errorCaught).asTo('collision detected').isGonnaBeTrue(); }); }); }); // =========================================================================== // SUITE E: STRUCTURAL EVOLUTION (addPools) // =========================================================================== await respecfully(sir, 'Suite E: Structural Evolution (addPools)', async () => { const service = new KeystoneService_V1(); const aliceSecret = "Alice_Master_Key"; const bobSecret = "Bob_Foreign_Key"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let aliceKeystone: KeystoneIbGib_V1; // Helper to simulate Bob creating a pool "offline" to give to Alice const createForeignPool = async (id: string, verbs: string[] = []): Promise => { const salt = (await getUUID()).substring(0, 16); const config = createStandardPoolConfig({ id, salt }); config.allowedVerbs = verbs; // We use the factory manually here to simulate Bob doing this on his own machine const strategy = KeystoneStrategyFactory.create({ config }); const poolSecret = await strategy.derivePoolSecret({ masterSecret: bobSecret }); const challenges: { [id: string]: any } = {}; // Generate a small set of challenges for (let i = 0; i < 10; i++) { const raw = await hash({ s: `${config.salt}${Date.now()}${i}` }); const challengeId = raw.substring(0, 16); const solution = await strategy.generateSolution({ poolSecret, poolId: config.salt, challengeId, }); const challenge = await strategy.generateChallenge({ solution }); challenges[challengeId] = challenge; } return { id, config, challenges, isForeign: true, metadata: { owner: 'Bob', role: 'Delegate' } }; }; firstOfAll(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); // Alice Genesis: Standard pool (allows all verbs, including 'manage') const salt = (await getUUID()).substring(0, 16); const config = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt, }); aliceKeystone = await service.genesis({ masterSecret: aliceSecret, configs: [config], metaspace: mockMetaspace, space: mockSpace as any, }); }); await respecfully(sir, 'Happy Path', async () => { await ifWe(sir, 'authorizes and adds a foreign pool', async () => { const bobPool = await createForeignPool("pool_bob", ["post"]); const updatedKeystone = await service.addPools({ latestKeystone: aliceKeystone, masterSecret: aliceSecret, signingPoolId: POOL_ID_DEFAULT, newPools: [bobPool], metaspace: mockMetaspace, space: mockSpace as any, }); // 1. Verify new state iReckon(sir, updatedKeystone).isGonnaBeTruthy(); const pools = updatedKeystone.data!.challengePools; iReckon(sir, pools.length).asTo('pool count increased').willEqual(2); const foundBob = pools.find(p => p.id === "pool_bob"); iReckon(sir, foundBob).asTo('bob pool exists').isGonnaBeTruthy(); iReckon(sir, foundBob!.isForeign).asTo('isForeign flag').isGonnaBeTrue(); // 2. Verify Proof const proof = updatedKeystone.data!.proofs[0]; iReckon(sir, proof.claim.verb).asTo('proof verb').willEqual(KEYSTONE_VERB_MANAGE); // Alice signed this using HER pool (default), not Bob's iReckon(sir, proof.solutions[0].poolId).willEqual(POOL_ID_DEFAULT); // 3. Verify Validity const errors = await service.validate({ prevIbGib: aliceKeystone, currentIbGib: updatedKeystone, }); iReckon(sir, errors.length).asTo('validation passed').willEqual(0); // Update local ref for next tests aliceKeystone = updatedKeystone; }); }); await respecfully(sir, 'Permissions & Logic', async () => { await ifWe(sir, 'fails if no pool allows "manage" verb', async () => { // 1. Create a restricted keystone (read-only) let id = "read_only"; const restrictedConfig = createStandardPoolConfig({ id, salt: id }); restrictedConfig.allowedVerbs = ['read']; // No 'manage' const restrictedKeystone = await service.genesis({ masterSecret: aliceSecret, configs: [restrictedConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const newPool = await createForeignPool("pool_test"); let errorCaught = false; try { await service.addPools({ latestKeystone: restrictedKeystone, masterSecret: aliceSecret, signingPoolId: 'read_only', newPools: [newPool], metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e: any) { errorCaught = true; // Optional: Check error message // iReckon(sir, e.message).includes("No local pool found with 'manage'"); } iReckon(sir, errorCaught).asTo('permission denied').isGonnaBeTrue(); }); await ifWe(sir, 'fails on ID collision', async () => { // Try to add "pool_bob" again (it was added in Happy Path) const duplicatePool = await createForeignPool("pool_bob"); let errorCaught = false; try { await service.addPools({ latestKeystone: aliceKeystone, // This already has pool_bob masterSecret: aliceSecret, signingPoolId: POOL_ID_DEFAULT, newPools: [duplicatePool], metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e: any) { errorCaught = true; iReckon(sir, e.message).includes("collision"); } iReckon(sir, errorCaught).asTo('collision detected').isGonnaBeTrue(); }); }); }); // =========================================================================== // SUITE F: DEEP INSPECTION (Granularity & Serialization) // =========================================================================== await respecfully(sir, 'Suite F: Deep Inspection', async () => { const service = new KeystoneService_V1(); const aliceSecret = "Alice_Deep_Inspect"; const poolId = "granularity_pool"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let genesisKeystone: KeystoneIbGib_V1; let signedKeystone: KeystoneIbGib_V1; let hybridConfig: KeystonePoolConfig_HashV1; firstOfAll(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); const salt = (await getUUID()).substring(0, 16); hybridConfig = createStandardPoolConfig({ id: poolId, salt, // 2 FIFO + 2 Random = 4 Total per sign sequential: 2, random: 2, targetBinding: 0, size: 20, // Small enough to track, large enough to be random }) as KeystonePoolConfig_HashV1; genesisKeystone = await service.genesis({ masterSecret: aliceSecret, configs: [hybridConfig], metaspace: mockMetaspace, space: mockSpace as any, }); }); await respecfully(sir, 'Proof Granularity & Math', async () => { await ifWe(sir, 'generates exactly the expected number of solutions', async () => { signedKeystone = await service.sign({ latestKeystone: genesisKeystone, masterSecret: aliceSecret, claim: { verb: "post", target: "data^gib" }, metaspace: mockMetaspace, space: mockSpace as any, }); const proofs = signedKeystone.data!.proofs; iReckon(sir, proofs.length).asTo('proof count').willEqual(1); const solutions = proofs[0].solutions; // 2 Sequential + 2 Random = 4 iReckon(sir, solutions.length).asTo('solution count').willEqual(4); }); await ifWe(sir, 'verifies the math manually (White-box Crypto Check)', async () => { const proof = signedKeystone.data!.proofs[0]; const poolSnapshot = genesisKeystone.data!.challengePools.find(p => p.id === poolId)!; // We iterate every solution in the proof and MANUALLY verify the hash relationship // bypassing the Service's validation logic to ensure the raw math holds up. for (const solution of proof.solutions) { // 1. Find the challenge in the *Previous* frame (Genesis) const challenge = poolSnapshot.challenges[solution.challengeId]; if (!challenge) { throw new Error(`Test Failure: Solution references ID ${solution.challengeId} which was not in Genesis pool.`); } // 2. Re-implement HashReveal V1 verification logic locally in the test // Hash(Salt + Value + Salt) // Note: rounds=1 in standard config const indexSalt = solution.challengeId; const calculatedHash = await hash({ s: `${indexSalt}${solution.value}${indexSalt}`, algorithm: 'SHA-256' }); // 3. Assert iReckon(sir, calculatedHash).asTo(`Manual hash verification for ${solution.challengeId}`).willEqual(challenge.hash); } }); await ifWe(sir, 'verifies FIFO logic (Deterministic Selection)', async () => { const proof = signedKeystone.data!.proofs[0]; const poolSnapshot = genesisKeystone.data!.challengePools.find(p => p.id === poolId)!; // The first N keys in the pool should be the FIFO targets. // Assumption: Object.keys returns insertion order (Standard in modern JS engines) const allIds = Object.keys(poolSnapshot.challenges); const expectedFifoIds = allIds.slice(0, 2); const solvedIds = proof.solutions.map(s => s.challengeId); // Check that our solution list *includes* the expected FIFO IDs const hasFirst = solvedIds.includes(expectedFifoIds[0]); const hasSecond = solvedIds.includes(expectedFifoIds[1]); iReckon(sir, hasFirst).asTo(`Solution includes 1st FIFO ID (${expectedFifoIds[0]})`).isGonnaBeTrue(); iReckon(sir, hasSecond).asTo(`Solution includes 2nd FIFO ID (${expectedFifoIds[1]})`).isGonnaBeTrue(); }); await ifWe(sir, 'verifies Next-Gen Hash-Based Target Binding Selection', async () => { const bindingConfig = createStandardPoolConfig({ id: "binding_pool", salt: "binding_salt", sequential: 0, random: 0, targetBinding: 3, size: 20 }) as KeystonePoolConfig_HashV1; const tempGenesis = await service.genesis({ masterSecret: aliceSecret, configs: [bindingConfig], metaspace: mockMetaspace, space: mockSpace as any, }); // Evolve using the binding pool const evolved = await service.sign({ latestKeystone: tempGenesis, masterSecret: aliceSecret, poolId: "binding_pool", claim: { verb: "sign", target: "some_target_address^gib" }, metaspace: mockMetaspace, space: mockSpace as any, }); const proof = evolved.data!.proofs[0]; iReckon(sir, proof.solutions.length).asTo('proof solutions count').willEqual(3); // Now, let's verify that the selection is perfectly deterministic. // If we run selectChallengeIds manually with the same pool and target, it must return the same IDs. const poolSnapshot = tempGenesis.data!.challengePools.find(p => p.id === "binding_pool")!; const selectedIds = await selectChallengeIds({ pool: poolSnapshot, targetAddr: "some_target_address^gib" }); const proofIds = proof.solutions.map(s => s.challengeId); iReckon(sir, selectedIds.length).asTo('selected IDs count').willEqual(3); for (const id of selectedIds) { iReckon(sir, proofIds.includes(id)).asTo(`proof includes selected ID ${id}`).isGonnaBeTrue(); } }); await ifWe(sir, 'fails validation if total requested challenges >= size', async () => { const invalidConfig = createStandardPoolConfig({ id: "invalid_pool", salt: "invalid_salt", sequential: 5, random: 5, targetBinding: 6, size: 15 // total requested is 5+5+6 = 16 >= 15 }); const errors = await validateChallengePool({ pool: { id: "invalid_pool", config: invalidConfig, challenges: {} } }); iReckon(sir, errors.length > 0).asTo('errors length is positive').isGonnaBeTrue(); const hasCorrectError = errors.some(e => e.includes("Total requested challenges")); iReckon(sir, hasCorrectError).asTo('validation error content').isGonnaBeTrue(); }); }); await respecfully(sir, 'DTO & Serialization', async () => { await ifWe(sir, 'survives a clone/JSON-cycle without corruption', async () => { // 1. Create a DTO (simulate network transmission/storage) // 'clone' does a JSON stringify/parse under the hood (usually) or structured clone. const dto = clone(signedKeystone); // 2. Structural checks iReckon(sir, dto).asTo('dto exists').isGonnaBeTruthy(); iReckon(sir, dto.data).asTo('dto data').isGonnaBeTruthy(); iReckon(sir, dto.data!.proofs).asTo('dto proofs').isGonnaBeTruthy(); // 3. Functional check: Can the service validate this DTO? // This ensures no prototypes or hidden properties were lost that the service depends on. const errors = await service.validate({ prevIbGib: genesisKeystone, currentIbGib: dto, // Passing the DTO, not the original object }); iReckon(sir, errors.length).asTo('DTO validation errors').willEqual(0); }); await ifWe(sir, 'ensures data contains no functions or circular refs', async () => { // A crude but effective test: ensure JSON.stringify doesn't throw // and the result is equal to the object (if we parsed it back). const jsonStr = JSON.stringify(signedKeystone); const parsed = JSON.parse(jsonStr); // Compare specific deep fields const originalSolution = signedKeystone.data!.proofs[0].solutions[0].value; const parsedSolution = parsed.data.proofs[0].solutions[0].value; iReckon(sir, parsedSolution).asTo('deep property survives stringify').willEqual(originalSolution); // Ensure no extra properties were lost // FIX: JSON.stringify removes keys with 'undefined' values. // We must filter the original keys to match this behavior for a fair comparison. const origKeys = Object.keys(signedKeystone.data!) .filter(k => (signedKeystone.data as any)[k] !== undefined); const parsedKeys = Object.keys(parsed.data); iReckon(sir, parsedKeys.length).asTo('key count matches').willEqual(origKeys.length); }); }); await respecfully(sir, 'Keystone Metadata Validation', async () => { await ifWe(sir, 'validates correct username and description', async () => { const service = new KeystoneService_V1(); const space = new MockIbGibSpace(); const metaspace = new MockMetaspaceService(space); const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('alice_123.test') .withDescription('Valid description: yes, it is!') .withDetails({ client: 'respec' }); const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); // Should succeed without error const keystoneIbGib = await service.genesis({ masterSecret: 'mysecret', configs, metaspace: metaspace as any, space: space as any, frameDetails }); const errors = await service.validateGenesisKeystone({ keystoneIbGib }); iReckon(sir, errors.length).asTo('errors count').willEqual(0); }); await ifWe(sir, 'fails validation for invalid username length or character', async () => { const service = new KeystoneService_V1(); const space = new MockIbGibSpace(); const metaspace = new MockMetaspaceService(space); const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('invalid_user_name_that_is_way_too_long_for_the_sixty_three_char_limit_and_will_fail_regex_check') .withDetails({ client: 'respec' }); const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const keystoneIbGib = await service.genesis({ masterSecret: 'mysecret', configs, metaspace: metaspace as any, space: space as any, frameDetails }); const errors = await service.validateGenesisKeystone({ keystoneIbGib }); iReckon(sir, errors.length).asTo('errors count').willEqual(1); iReckon(sir, errors[0]).includes('invalid username'); }); await ifWe(sir, 'fails validation for invalid description characters', async () => { const service = new KeystoneService_V1(); const space = new MockIbGibSpace(); const metaspace = new MockMetaspaceService(space); const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('alice') .withDescription('Invalid desc with weird emoji 🚀') .withDetails({ client: 'respec' }); const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const keystoneIbGib = await service.genesis({ masterSecret: 'mysecret', configs, metaspace: metaspace as any, space: space as any, frameDetails }); const errors = await service.validateGenesisKeystone({ keystoneIbGib }); iReckon(sir, errors.length).asTo('errors count').willEqual(1); iReckon(sir, errors[0]).includes('invalid description'); }); }); }); // =========================================================================== // SUITE E: DELEGATION (Register/Unregister) // =========================================================================== await respecfully(sir, 'Suite E: Delegation (Register/Unregister)', async () => { const service = new KeystoneService_V1(); const parentSecret = "ParentMasterSecret_123"; const delegateSecret = "DelegateMasterSecret_456"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let parentKeystone: KeystoneIbGib_V1; let delegateKeystone: KeystoneIbGib_V1; firstOfEach(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); const salt = (await getUUID()).substring(0, 16); const defaultConfig = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt }); const manageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: salt + "_manage" }); manageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE]; // 1. Create Parent Keystone (with manage pool) parentKeystone = await service.genesis({ masterSecret: parentSecret, configs: [defaultConfig, manageConfig], metaspace: mockMetaspace, space: mockSpace as any, }); // 2. Create Delegate Keystone const delegateConfig = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt: salt + "_delegate" }); delegateKeystone = await service.genesis({ masterSecret: delegateSecret, configs: [delegateConfig], metaspace: mockMetaspace, space: mockSpace as any, }); }); await ifWe(sir, 'registers a delegate keystone and evolves parent using manage pool', async () => { // Register the delegate const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); iReckon(sir, evolvedParent).asTo('evolved parent exists').isGonnaBeTruthy(); iReckon(sir, evolvedParent.data?.delegates).asTo('delegates map exists').isGonnaBeTruthy(); const delegateTjpAddr = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjpAddr) { throw new Error(`(UNEXPECTED) delegateTjpAddr falsy? (E: 312e986ce4b2ed6c084c03e8f45fa826)`); } const delegateInfo = evolvedParent.data?.delegates?.[delegateTjpAddr]; iReckon(sir, delegateInfo).asTo('delegate info registered').isGonnaBeTruthy(); iReckon(sir, delegateInfo?.delegateTjpAddr).asTo('delegate tjp matches').willEqual(delegateTjpAddr); }); await ifWe(sir, 'gets correct delegate status via parent TJP address', async () => { const parentTjpAddr = getTjpAddr({ ibGib: parentKeystone }); if (!parentTjpAddr) { throw new Error(`(UNEXPECTED) parentTjpAddr falsy? (E: b7ce2835ccd951d8c99257328be3b826)`); } const delegateTjpAddr = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjpAddr) { throw new Error(`(UNEXPECTED) delegateTjpAddr falsy? (E: 3e4878ea19dd8034e827466a8bf09526)`); } // Before registration const statusBefore = await service.getDelegateStatus({ parentTjpAddr: parentTjpAddr, delegateTjpAddr: delegateTjpAddr, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, statusBefore.registered).asTo('initially unregistered').isGonnaBeFalse(); // Register const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); // After registration const statusAfter = await service.getDelegateStatus({ parentTjpAddr: parentTjpAddr, delegateTjpAddr: delegateTjpAddr, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, statusAfter.registered).asTo('registered status').isGonnaBeTrue(); iReckon(sir, statusAfter.delegateInfo?.delegateTjpAddr).asTo('status tjp matches').willEqual(delegateTjpAddr); }); await ifWe(sir, 'unregisters a registered delegate keystone', async () => { // Register first const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); const delegateTjpAddr = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjpAddr) { throw new Error(`(UNEXPECTED) delegateTjpAddr falsy? (E: 486b486a8c984a52b8d2b22418c20d26)`); } // Unregister const finalParent = await service.unregisterDelegate({ parentKeystone: evolvedParent, delegateTjpAddr, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, finalParent).asTo('final evolved parent exists').isGonnaBeTruthy(); const info = finalParent.data?.delegates?.[delegateTjpAddr]; iReckon(sir, info).asTo('delegate info removed').isGonnaBeUndefined(); }); await ifWe(sir, 'throws if parent does not have a manage pool', async () => { // Create a parent WITHOUT a manage pool const salt = (await getUUID()).substring(0, 16); const defaultConfig = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt }); const restrictedParent = await service.genesis({ masterSecret: parentSecret, configs: [defaultConfig], metaspace: mockMetaspace, space: mockSpace as any, }); let errorCaught = false; try { await service.registerDelegate({ parentKeystone: restrictedParent, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); } catch (e: any) { errorCaught = true; iReckon(sir, e.message).includes('does not contain signing pool'); } iReckon(sir, errorCaught).asTo('delegation rejected').isGonnaBeTrue(); }); }); await respecfully(sir, 'Suite G: Delegate & IB Validation', async () => { const service = new KeystoneService_V1(); const parentSecret = "ParentMasterSecret_SuiteG"; const delegateSecret = "DelegateMasterSecret_SuiteG"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; let parentKeystone: KeystoneIbGib_V1; let delegateKeystone: KeystoneIbGib_V1; firstOfEach(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); const salt1 = (await getUUID()).substring(0, 16); const salt2 = (await getUUID()).substring(0, 16); const manageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: salt2 }); manageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE]; const configs = [ createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt: salt1 }), manageConfig ]; parentKeystone = await service.genesis({ masterSecret: parentSecret, configs, metaspace: mockMetaspace, space: mockSpace as any, }); delegateKeystone = await service.genesis({ masterSecret: delegateSecret, configs: [createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt: salt1 })], metaspace: mockMetaspace, space: mockSpace as any, }); }); await ifWe(sir, 'validateKeystoneIb returns true for valid keystone ib and false for others', async () => { iReckon(sir, await validateKeystoneIb({ ib: 'keystone' })).isGonnaBeTrue(); iReckon(sir, await validateKeystoneIb({ ib: 'keystone user info' })).isGonnaBeTrue(); iReckon(sir, await validateKeystoneIb({ ib: 'invalidAtom' })).isGonnaBeFalse(); iReckon(sir, await validateKeystoneIb({ ib: 'not_keystone sub_atom' })).isGonnaBeFalse(); }); await ifWe(sir, 'validateGenesisKeystone fails validation if ib is invalid', async () => { const invalidGenesis = { ...parentKeystone, ib: 'not_a_keystone^' + parentKeystone.gib, }; const errors = await validateGenesisKeystone({ keystoneIbGib: invalidGenesis }); iReckon(sir, errors.length > 0).isGonnaBeTrue(); iReckon(sir, errors[0]).includes('invalid keystone ib'); }); await ifWe(sir, 'validateKeystoneTransition passes for valid delegate registration', async () => { const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); const errors = await validateKeystoneTransition({ currentIbGib: evolvedParent, prevIbGib: parentKeystone, }); iReckon(sir, errors.length).willEqual(0); }); await ifWe(sir, 'validateKeystoneTransition fails if delegates map is mutated without manage proof', async () => { const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); const tamperedParent = JSON.parse(JSON.stringify(evolvedParent)) as KeystoneIbGib_V1; // Remove the manage verb proof by converting it to sign for (const proof of tamperedParent.data.proofs) { if (proof.claim) { proof.claim.verb = 'sign'; } } const errors = await validateKeystoneTransition({ currentIbGib: tamperedParent, prevIbGib: parentKeystone, }); iReckon(sir, errors.length > 0).isGonnaBeTrue(); iReckon(sir, errors.some(e => e.includes('Policy Violation: Delegates map was mutated'))).isGonnaBeTrue(); }); await ifWe(sir, 'validateKeystoneTransition fails if delegate key does not match delegateTjpAddr', async () => { const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); const tamperedParent = JSON.parse(JSON.stringify(evolvedParent)) as KeystoneIbGib_V1; const delegateTjpAddr = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjpAddr) { throw new Error(`delegateTjpAddr falsy?`); } const info = tamperedParent.data.delegates![delegateTjpAddr]; delete tamperedParent.data.delegates![delegateTjpAddr]; tamperedParent.data.delegates!['mismatched_key'] = info; const errors = await validateKeystoneTransition({ currentIbGib: tamperedParent, prevIbGib: parentKeystone, }); iReckon(sir, errors.length > 0).isGonnaBeTrue(); iReckon(sir, errors.some(e => e.includes('does not match delegateTjpAddr'))).isGonnaBeTrue(); }); await ifWe(sir, 'validateKeystoneTransition fails if delegate addresses have invalid keystone ib', async () => { const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); const tamperedParent = JSON.parse(JSON.stringify(evolvedParent)) as KeystoneIbGib_V1; const delegateTjpAddr = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjpAddr) { throw new Error(`delegateTjpAddr falsy?`); } tamperedParent.data.delegates![delegateTjpAddr].delegateAddr = 'invalid_ib^12345'; const errors = await validateKeystoneTransition({ currentIbGib: tamperedParent, prevIbGib: parentKeystone, }); iReckon(sir, errors.length > 0).isGonnaBeTrue(); iReckon(sir, errors.some(e => e.includes('not a valid keystone address'))).isGonnaBeTrue(); }); await ifWe(sir, 'validateKeystoneTransition fails if thisAddr is not in the parent timeline history', async () => { const evolvedParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: parentSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); const tamperedParent = JSON.parse(JSON.stringify(evolvedParent)) as KeystoneIbGib_V1; const delegateTjpAddr = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjpAddr) { throw new Error(`delegateTjpAddr falsy?`); } tamperedParent.data.delegates![delegateTjpAddr].thisAddr = 'keystone^randomgib'; const errors = await validateKeystoneTransition({ currentIbGib: tamperedParent, prevIbGib: parentKeystone, }); iReckon(sir, errors.length > 0).isGonnaBeTrue(); iReckon(sir, errors.some(e => e.includes('not a valid historical address in the parent keystone timeline'))).isGonnaBeTrue(); }); }); // =========================================================================== // SUITE G: COMBINED POOLS & PASSWORD ROTATION // =========================================================================== await respecfully(sir, 'Suite G: Combined Pools & Password Rotation', async () => { const service = new KeystoneService_V1(); const userSecret = "UserMasterSecret_123"; const custodianSecret = "CustodianSecret_456"; let mockSpace: MockIbGibSpace; let mockMetaspace: any; firstOfEach(sir, async () => { mockSpace = new MockIbGibSpace(); mockMetaspace = new MockMetaspaceService(mockSpace); }); await ifWe(sir, 'revokes a keystone using a separate revocation pool', async () => { const lc = `[revokes a keystone using a separate revocation pool]`; try { if (logalot) { console.log(`${lc} starting... (I: 8efbb3af6a483aa4c1205118bd481926)`); } const stdSalt = "std_salt"; const revokeSalt = "revoke_salt"; const stdConfig = createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt: stdSalt }); const revokeConfig = createStandardPoolConfig({ id: POOL_ID_REVOKE, salt: revokeSalt }); revokeConfig.allowedVerbs = [KEYSTONE_VERB_REVOKE]; revokeConfig.behavior.replenish = KeystoneReplenishStrategy.deleteAll; const keystone = await service.genesis({ masterSecret: userSecret, configs: [stdConfig, revokeConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const revoked = await service.revoke({ latestKeystone: keystone, masterSecret: userSecret, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, revoked.data?.revocationInfo).asTo('revocationInfo present').isGonnaBeTruthy(); const revokePool = revoked.data?.challengePools.find(p => p.id === POOL_ID_REVOKE)!; iReckon(sir, Object.keys(revokePool.challenges).length).asTo('revoke pool depleted').willEqual(0); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'revokes a keystone using a combined manage/revoke pool and empties it', async () => { const lc = `[revokes a keystone using a combined manage/revoke pool and empties it]`; try { if (logalot) { console.log(`${lc} starting... (I: 31d8bc860b7cb09893ccaac3d2cf4826)`); } const salt = "combined_salt"; const manageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt }); manageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; const keystone = await service.genesis({ masterSecret: userSecret, configs: [manageConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const revoked = await service.revoke({ latestKeystone: keystone, masterSecret: userSecret, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, revoked.data?.revocationInfo).asTo('revocationInfo present').isGonnaBeTruthy(); const managePool = revoked.data?.challengePools.find(p => p.id === POOL_ID_MANAGE)!; iReckon(sir, Object.keys(managePool.challenges).length).asTo('combined manage pool depleted').willEqual(0); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'rotates user password successfully when signed by the user manage pool', async () => { const lc = `[rotates user password successfully when signed by the user manage pool]`; try { if (logalot) { console.log(`${lc} starting... (I: 580b0bbdc7f80e35d8ee2339ac0eb526)`); } const salt = "manage_salt"; const manageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt }); manageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; const keystone = await service.genesis({ masterSecret: userSecret, configs: [manageConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const newSecret = "NewUserSecret_999"; const { newKeystone: rotated } = await service.changePassword({ keystoneIbGib: keystone, newMasterSecret: newSecret, signingSecret: userSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, rotated).isGonnaBeTruthy(); // 1. Try to sign using the new secret (should succeed) const claim = { verb: KEYSTONE_VERB_MANAGE, target: "test_target" }; const signedNew = await service.sign({ latestKeystone: rotated, masterSecret: newSecret, claim, poolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, signedNew).isGonnaBeTruthy(); // 2. Try to sign using the old secret (should fail) let errorCaught = false; try { await service.sign({ latestKeystone: rotated, masterSecret: userSecret, claim, poolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); } catch { errorCaught = true; } iReckon(sir, errorCaught).asTo('old secret signing rejected').isGonnaBeTrue(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'recovers user password successfully when signed by the custodian manage pool', async () => { const lc = `[recovers user password successfully when signed by the custodian manage pool]`; try { if (logalot) { console.log(`${lc} starting... (I: 409df8ee1ae81d8b45c4a9c98e6e7626)`); } const userSalt = "user_salt"; const custodianSalt = "custodian_salt"; const userManageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: userSalt }); userManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; const custodianManageConfig = createStandardPoolConfig({ id: POOL_ID_CUSTODIAN_MANAGE, salt: custodianSalt }); custodianManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; // We simulate constructing the custodian pool "offline" by the server const strategy = KeystoneStrategyFactory.create({ config: custodianManageConfig }); const poolSecret = await strategy.derivePoolSecret({ masterSecret: custodianSecret }); const challenges: { [id: string]: any } = {}; for (let i = 0; i < custodianManageConfig.behavior.size; i++) { const raw = await hash({ s: `${custodianManageConfig.salt}${Date.now()}${i}` }); const challengeId = raw.substring(0, 16); const solution = await strategy.generateSolution({ poolSecret, poolId: custodianManageConfig.id, challengeId }); challenges[challengeId] = await strategy.generateChallenge({ solution }); } const custodianPool: KeystoneChallengePool = { id: POOL_ID_CUSTODIAN_MANAGE, config: custodianManageConfig, challenges, isForeign: true }; const keystone = await service.genesis({ masterSecret: userSecret, configs: [userManageConfig], metaspace: mockMetaspace, space: mockSpace as any, }); // Add the custodian pool to the keystone const keystoneWithCustodian = await service.addPools({ latestKeystone: keystone, masterSecret: userSecret, signingPoolId: POOL_ID_MANAGE, newPools: [custodianPool], metaspace: mockMetaspace, space: mockSpace as any, }); // The user forgets their secret. Recover using custodianSecret! const recoveredSecret = "RecoveredUserSecret_777"; const { newKeystone: recoveredKeystone } = await service.changePassword({ keystoneIbGib: keystoneWithCustodian, newMasterSecret: recoveredSecret, signingSecret: custodianSecret, signingPoolId: POOL_ID_CUSTODIAN_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, recoveredKeystone).isGonnaBeTruthy(); // Verify we can sign with recovered secret const claim = { verb: KEYSTONE_VERB_MANAGE, target: "test_target" }; const signedNew = await service.sign({ latestKeystone: recoveredKeystone, masterSecret: recoveredSecret, claim, poolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, signedNew).isGonnaBeTruthy(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'rotates custodian manage pool successfully', async () => { const lc = `[rotates custodian manage pool successfully]`; try { if (logalot) { console.log(`${lc} starting... (I: 76d9a76dc2487949d7deb31696d3e126)`); } const userSalt = "user_salt"; const custodianSalt = "custodian_salt"; const userManageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: userSalt }); userManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; const custodianManageConfig = createStandardPoolConfig({ id: POOL_ID_CUSTODIAN_MANAGE, salt: custodianSalt }); custodianManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; // Custodian Pool genesis const strategy = KeystoneStrategyFactory.create({ config: custodianManageConfig }); const poolSecret = await strategy.derivePoolSecret({ masterSecret: custodianSecret }); const challenges: { [id: string]: any } = {}; for (let i = 0; i < custodianManageConfig.behavior.size; i++) { const raw = await hash({ s: `${custodianManageConfig.salt}${Date.now()}${i}` }); const challengeId = raw.substring(0, 16); const solution = await strategy.generateSolution({ poolSecret, poolId: custodianManageConfig.id, challengeId }); challenges[challengeId] = await strategy.generateChallenge({ solution }); } const custodianPool: KeystoneChallengePool = { id: POOL_ID_CUSTODIAN_MANAGE, config: custodianManageConfig, challenges, isForeign: true }; const keystone = await service.genesis({ masterSecret: userSecret, configs: [userManageConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const keystoneWithCustodian = await service.addPools({ latestKeystone: keystone, masterSecret: userSecret, signingPoolId: POOL_ID_MANAGE, newPools: [custodianPool], metaspace: mockMetaspace, space: mockSpace as any, }); // Rotate custodian credentials to new secret const newCustodianSecret = "NewCustodianSecret_888"; const newCustodianConfig = createStandardPoolConfig({ id: POOL_ID_CUSTODIAN_MANAGE, salt: "new_custodian_salt" }); newCustodianConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; const newStrategy = KeystoneStrategyFactory.create({ config: newCustodianConfig }); const newPoolSecret = await newStrategy.derivePoolSecret({ masterSecret: newCustodianSecret }); const newChallenges: { [id: string]: any } = {}; for (let i = 0; i < newCustodianConfig.behavior.size; i++) { const raw = await hash({ s: `${newCustodianConfig.salt}${Date.now()}${i}` }); const challengeId = raw.substring(0, 16); const solution = await newStrategy.generateSolution({ poolSecret: newPoolSecret, poolId: newCustodianConfig.id, challengeId }); newChallenges[challengeId] = await newStrategy.generateChallenge({ solution }); } const newCustodianPool: KeystoneChallengePool = { id: POOL_ID_CUSTODIAN_MANAGE, config: newCustodianConfig, challenges: newChallenges, isForeign: true }; // Rotate signed by user manage pool const rotated = await service.replacePool({ latestKeystone: keystoneWithCustodian, newPool: newCustodianPool, signingSecret: userSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, rotated).isGonnaBeTruthy(); // Verify we can sign with new custodian secret const claim = { verb: KEYSTONE_VERB_MANAGE, target: "test_target" }; const signedNew = await service.sign({ latestKeystone: rotated, masterSecret: newCustodianSecret, claim, poolId: POOL_ID_CUSTODIAN_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, signedNew).isGonnaBeTruthy(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'rotates all non-foreign pools during changePassword by default', async () => { const lc = `[rotates all non-foreign pools during changePassword by default]`; try { if (logalot) { console.log(`${lc} starting... (I: 8449682eda6389e9d514888f9ce86f26)`); } const userSalt = "user_salt"; const custodianSalt = "custodian_salt"; const secondarySalt = "secondary_salt"; const userManageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: userSalt }); userManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; // Another native/non-foreign pool const secondaryNativeConfig = createStandardPoolConfig({ id: "secondary-native", salt: secondarySalt }); secondaryNativeConfig.allowedVerbs = [KEYSTONE_VERB_SYNC]; // A custodian/foreign pool const custodianManageConfig = createStandardPoolConfig({ id: POOL_ID_CUSTODIAN_MANAGE, salt: custodianSalt }); custodianManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; // Custodian Pool genesis const strategy = KeystoneStrategyFactory.create({ config: custodianManageConfig }); const poolSecret = await strategy.derivePoolSecret({ masterSecret: custodianSecret }); const challenges: { [id: string]: any } = {}; for (let i = 0; i < custodianManageConfig.behavior.size; i++) { const raw = await hash({ s: `${custodianManageConfig.salt}${Date.now()}${i}` }); const challengeId = raw.substring(0, 16); const solution = await strategy.generateSolution({ poolSecret, poolId: custodianManageConfig.id, challengeId }); challenges[challengeId] = await strategy.generateChallenge({ solution }); } const custodianPool: KeystoneChallengePool = { id: POOL_ID_CUSTODIAN_MANAGE, config: custodianManageConfig, challenges, isForeign: true }; const keystone = await service.genesis({ masterSecret: userSecret, configs: [userManageConfig, secondaryNativeConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const keystoneWithCustodian = await service.addPools({ latestKeystone: keystone, masterSecret: userSecret, signingPoolId: POOL_ID_MANAGE, newPools: [custodianPool], metaspace: mockMetaspace, space: mockSpace as any, }); // Rotate password/password const newPassword = "SuperNewSecretPassword_999"; const { newKeystone: rotated } = await service.changePassword({ keystoneIbGib: keystoneWithCustodian, newMasterSecret: newPassword, signingSecret: userSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, rotated).isGonnaBeTruthy(); const data = rotated.data!; const rotatedManage = data.challengePools.find(p => p.id === POOL_ID_MANAGE)!; const rotatedSecondary = data.challengePools.find(p => p.id === "secondary-native")!; const rotatedCustodian = data.challengePools.find(p => p.id === POOL_ID_CUSTODIAN_MANAGE)!; // Verify native pools rotated (salt changed) iReckon(sir, rotatedManage.config.salt).not.willEqual(userSalt); iReckon(sir, rotatedSecondary.config.salt).not.willEqual(secondarySalt); // Verify foreign pool was not modified (salt identical) iReckon(sir, rotatedCustodian.config.salt).willEqual(custodianSalt); // Verify we can validate transition const errors = await service.validate({ prevIbGib: keystoneWithCustodian, currentIbGib: rotated }); iReckon(sir, errors.length).willEqual(0); // Verify we can sign using the rotated 'manage' pool with the new password const manageClaim = { verb: KEYSTONE_VERB_MANAGE, target: "test_target_manage" }; const signedWithNewManage = await service.sign({ latestKeystone: rotated, masterSecret: newPassword, claim: manageClaim, poolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, signedWithNewManage).isGonnaBeTruthy(); // Verify we can sign using the rotated 'secondary-native' pool with the new password const syncClaim = { verb: KEYSTONE_VERB_SYNC, target: "test_target_sync" }; const signedWithNewSync = await service.sign({ latestKeystone: rotated, masterSecret: newPassword, claim: syncClaim, poolId: "secondary-native", metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, signedWithNewSync).isGonnaBeTruthy(); // Verify signing with the OLD master secret fails on both pools let oldManageFailed = false; try { await service.sign({ latestKeystone: rotated, masterSecret: userSecret, claim: manageClaim, poolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); } catch { oldManageFailed = true; } iReckon(sir, oldManageFailed).isGonnaBeTrue(); let oldSyncFailed = false; try { await service.sign({ latestKeystone: rotated, masterSecret: userSecret, claim: syncClaim, poolId: "secondary-native", metaspace: mockMetaspace, space: mockSpace as any, }); } catch { oldSyncFailed = true; } iReckon(sir, oldSyncFailed).isGonnaBeTrue(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'fails validation if password rotation details or constraints are violated', async () => { const lc = `[fails validation if password rotation details or constraints are violated]`; try { if (logalot) { console.log(`${lc} starting... (I: b497f8486c58b25922d28b5efbd24826)`); } // Construct invalid change-password transition const userManageConfig = createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: "salt1" }); userManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; const custodianManageConfig = createStandardPoolConfig({ id: POOL_ID_CUSTODIAN_MANAGE, salt: "salt2" }); custodianManageConfig.allowedVerbs = [KEYSTONE_VERB_MANAGE, KEYSTONE_VERB_REVOKE]; // Custodian Pool genesis const strategy = KeystoneStrategyFactory.create({ config: custodianManageConfig }); const poolSecret = await strategy.derivePoolSecret({ masterSecret: custodianSecret }); const challenges: { [id: string]: any } = {}; for (let i = 0; i < custodianManageConfig.behavior.size; i++) { const raw = await hash({ s: `${custodianManageConfig.salt}${Date.now()}${i}` }); const challengeId = raw.substring(0, 16); const solution = await strategy.generateSolution({ poolSecret, poolId: custodianManageConfig.id, challengeId }); challenges[challengeId] = await strategy.generateChallenge({ solution }); } const custodianPool: KeystoneChallengePool = { id: POOL_ID_CUSTODIAN_MANAGE, config: custodianManageConfig, challenges, isForeign: true }; const keystone = await service.genesis({ masterSecret: userSecret, configs: [userManageConfig], metaspace: mockMetaspace, space: mockSpace as any, }); const keystoneWithCustodian = await service.addPools({ latestKeystone: keystone, masterSecret: userSecret, signingPoolId: POOL_ID_MANAGE, newPools: [custodianPool], metaspace: mockMetaspace, space: mockSpace as any, }); // Create an invalid frame manually where a foreign pool is rotated during change-password const badRotatedPool = await rotatePoolChallenges({ prevPool: custodianPool, newMasterSecret: "bad_secret" }); const { newKeystone: evolved } = await service.changePassword({ keystoneIbGib: keystoneWithCustodian, newMasterSecret: "new_pass", signingSecret: userSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, }); // Inject the foreign pool rotation manually to simulate an attacker const attackerData = { ...evolved.data!, challengePools: evolved.data!.challengePools.map(p => p.id === POOL_ID_CUSTODIAN_MANAGE ? badRotatedPool : p) }; // Update details claim to say we rotated custodian-manage attackerData.proofs[0].claim.details = { type: KeystoneClaimType.change_password, info: { change: [POOL_ID_MANAGE, POOL_ID_CUSTODIAN_MANAGE] } as ClaimDetails_ChangePassword }; const attackerKeystone = { ...evolved, data: attackerData }; const errors = await service.validate({ prevIbGib: keystoneWithCustodian, currentIbGib: attackerKeystone }); iReckon(sir, errors.length > 0).isGonnaBeTrue(); const hasForeignViolation = errors.some(e => e.includes("Security Violation") && e.includes("foreign pool")); iReckon(sir, hasForeignViolation).isGonnaBeTrue(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'verifies signing secrets correctly for a pool', async () => { const lc = `[verifies signing secrets correctly for a pool]`; try { if (logalot) { console.log(`${lc} starting... (I: 343eb84f5768ff0adcf2308c68404826)`); } const userSecret = "alice_secret_123"; const builder = KeystoneProfileBuilder.buildKeystone('sync-profile.dev') .withUsername('alice') .withEmail('alice@example.com') .withDescription('Alice test keystone'); const configs = await builder.compileConfigs(); const keystone = await service.genesis({ masterSecret: userSecret, configs, frameDetails: builder.getFrameDetails(), metaspace: mockMetaspace, space: mockSpace as any, }); // 1. Correct secret on manage pool const isCorrectManage = await service.verifySigningSecret({ keystoneIbGib: keystone, signingSecret: userSecret, poolId: POOL_ID_MANAGE }); iReckon(sir, isCorrectManage).asTo('correct manage secret').isGonnaBeTrue(); // 2. Incorrect secret on manage pool const isWrongManage = await service.verifySigningSecret({ keystoneIbGib: keystone, signingSecret: "wrong_secret", poolId: POOL_ID_MANAGE }); iReckon(sir, isWrongManage).asTo('incorrect manage secret').isGonnaBeFalse(); // 3. Correct secret on default/sign pool const isCorrectDefault = await service.verifySigningSecret({ keystoneIbGib: keystone, signingSecret: userSecret, poolId: 'default' }); iReckon(sir, isCorrectDefault).asTo('correct default secret').isGonnaBeTrue(); // 4. Invalid/non-existent pool ID const isInvalidPool = await service.verifySigningSecret({ keystoneIbGib: keystone, signingSecret: userSecret, poolId: 'invalid_pool_id_123' }); iReckon(sir, isInvalidPool).asTo('invalid pool id').isGonnaBeFalse(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'removes pools successfully, validating transitions and auth', async () => { const lc = `[removes pools successfully, validating transitions and auth]`; try { if (logalot) { console.log(`${lc} starting... (I: 2e2e747d6808b05c1e452a680d94b726)`); } const userSecret = "alice_secret_123"; const customPoolId = "custodian-manage-google"; const configs = [ createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: "manage_salt", }), createStandardPoolConfig({ id: customPoolId, salt: "custodian_salt", }) ]; const keystone = await service.genesis({ masterSecret: userSecret, configs, metaspace: mockMetaspace, space: mockSpace as any, }); // 1. Success path: remove customPoolId using correct secret const evolvedKeystone = await service.removePools({ latestKeystone: keystone, masterSecret: userSecret, signingPoolId: POOL_ID_MANAGE, poolIds: [customPoolId], metaspace: mockMetaspace, space: mockSpace as any, }); iReckon(sir, evolvedKeystone).asTo('evolved keystone exists').isGonnaBeTruthy(); iReckon(sir, evolvedKeystone.data?.challengePools.length).asTo('pool count reduced').willEqual(1); iReckon(sir, evolvedKeystone.data?.challengePools[0].id).asTo('manage pool remains').willEqual(POOL_ID_MANAGE); // Verify transition is fully valid const errors = await service.validate({ prevIbGib: keystone, currentIbGib: evolvedKeystone }); iReckon(sir, errors.length).asTo('transition validation succeeds').willEqual(0); // 2. Sad path: invalid master secret let cryptoErrorCaught = false; try { await service.removePools({ latestKeystone: keystone, masterSecret: "wrong_secret", signingPoolId: POOL_ID_MANAGE, poolIds: [customPoolId], metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e: any) { if (e.message.includes('Crypto Violation')) { cryptoErrorCaught = true; } } iReckon(sir, cryptoErrorCaught).asTo('forgery check prevents removal').isGonnaBeTrue(); // 3. Sad path: non-existent pool ID let notFoundErrorCaught = false; try { await service.removePools({ latestKeystone: keystone, masterSecret: userSecret, signingPoolId: POOL_ID_MANAGE, poolIds: ["non-existent-pool"], metaspace: mockMetaspace, space: mockSpace as any, }); } catch (e: any) { if (e.message.includes('not found in keystone')) { notFoundErrorCaught = true; } } iReckon(sir, notFoundErrorCaught).asTo('non-existent pool ID rejected').isGonnaBeTrue(); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); await ifWe(sir, 'rotates registered delegate keystone challenge pools when changing user password', async () => { const lc = `[rotates registered delegate keystone challenge pools when changing user password]`; try { if (logalot) { console.log(`${lc} starting...`); } const userSecret = "alice_initial_pass_123"; const newSecret = "alice_new_pass_456"; // 1. Create primary keystone const parentConfigs = [ createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: "parent_manage_salt" }), createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt: "parent_default_salt" }) ]; const parentKeystone = await service.genesis({ masterSecret: userSecret, configs: parentConfigs, metaspace: mockMetaspace, space: mockSpace as any, }); // 2. Create delegate keystone using derived delegateSecret from userSecret (matching real app creation behavior) const delegateSecret = await deriveDelegateSecret({ masterSecret: userSecret }); const delegateConfigs = [ createStandardPoolConfig({ id: POOL_ID_MANAGE, salt: "delegate_manage_salt" }), createStandardPoolConfig({ id: "delegate_sync_pool", salt: "delegate_sync_salt" }) ]; const delegateKeystone = await service.genesis({ masterSecret: delegateSecret, configs: delegateConfigs, metaspace: mockMetaspace, space: mockSpace as any, }); const delegateTjp = getTjpAddr({ ibGib: delegateKeystone }); if (!delegateTjp) { throw new Error('delegateTjp missing'); } // 3. Register delegate under primary keystone const registeredParent = await service.registerDelegate({ parentKeystone, delegateKeystone, masterSecret: userSecret, signingPoolId: POOL_ID_MANAGE, metaspace: mockMetaspace, space: mockSpace as any, allowedVerbs: [KEYSTONE_VERB_SYNC], }); // 4. Change user password on parent keystone. // Note: We explicitly set `poolIds: undefined` to reinforce that passing undefined // instructs changePassword to rotate all non-foreign pools on the primary keystone // AND all registered outward delegates. (In production caller code, poolIds parameter can simply be omitted). const { newKeystone: evolvedParent, newDelegates } = await service.changePassword({ keystoneIbGib: registeredParent, newMasterSecret: newSecret, signingSecret: userSecret, signingPoolId: POOL_ID_MANAGE, poolIds: undefined, metaspace: mockMetaspace, space: mockSpace as any, }); // 5. Retrieve latest delegate keystone from metaspace/space if (newDelegates && newDelegates.length === 1) { const latestDelegate = newDelegates[0]; // 6. Verify primary keystone challenge pools have rotated to new secret for (const pool of evolvedParent.data!.challengePools) { if (!pool.isForeign) { const oldValid = await service.verifySigningSecret({ keystoneIbGib: evolvedParent, signingSecret: userSecret, poolId: pool.id }); iReckon(sir, oldValid).asTo(`parent pool ${pool.id} old secret invalid`).isGonnaBeFalse(); const newValid = await service.verifySigningSecret({ keystoneIbGib: evolvedParent, signingSecret: newSecret, poolId: pool.id }); iReckon(sir, newValid).asTo(`parent pool ${pool.id} new secret valid`).isGonnaBeTrue(); } } // 7. Verify delegate keystone challenge pools have rotated to new secret const oldDelegateSecret = await deriveDelegateSecret({ masterSecret: userSecret }); const newDelegateSecret = await deriveDelegateSecret({ masterSecret: newSecret }); for (const pool of latestDelegate.data!.challengePools) { if (!pool.isForeign) { const oldValid = await service.verifySigningSecret({ keystoneIbGib: latestDelegate, signingSecret: oldDelegateSecret, poolId: pool.id }); iReckon(sir, oldValid).asTo(`delegate pool ${pool.id} old secret invalid`).isGonnaBeFalse(); const newValid = await service.verifySigningSecret({ keystoneIbGib: latestDelegate, signingSecret: newDelegateSecret, poolId: pool.id }); iReckon(sir, newValid).asTo(`delegate pool ${pool.id} new secret valid`).isGonnaBeTrue(); } } } else { iReckon(sir, true).asTo('newDelegates should have had length 1 but is empty/falsy').isGonnaBeFalse(); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }); }); await respecfully(sir, 'Generic Keystone Expiration Enforcement', async () => { const space = new MockIbGibSpace(); const metaspace = new MockMetaspaceService(space) as any; const service = new KeystoneService_V1(); const masterSecret = "AlicePassphrase"; await ifWe(sir, 'signing with an expired keystone throws explicit expiration error', async () => { const pastDate = new Date(Date.now() - 1000 * 3600).toISOString(); const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('alice') .withExpiration(pastDate); const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const expiredKeystone = await service.genesis({ masterSecret, configs, frameDetails, metaspace, space: space as any, isPrimary: true }); await metaspace.registerNewIbGib({ ibGib: expiredKeystone }); let errorThrown = false; let errorMessage = ''; try { await service.sign({ latestKeystone: expiredKeystone, masterSecret, claim: { target: 'test^gib', verb: KEYSTONE_VERB_SYNC }, metaspace, space: space as any }); } catch (error) { errorThrown = true; errorMessage = extractErrorMsg(error); } iReckon(sir, errorThrown).asTo('error thrown on expired keystone sign').isGonnaBeTrue(); iReckon(sir, errorMessage.includes('expired')).asTo('error message mentions expiration').isGonnaBeTrue(); }); await ifWe(sir, 'signing with an active future expiration keystone succeeds', async () => { const futureDate = new Date(Date.now() + 1000 * 3600 * 24).toISOString(); const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('alice') .withExpiration(futureDate); const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const activeKeystone = await service.genesis({ masterSecret, configs, frameDetails, metaspace, space: space as any, isPrimary: true }); await metaspace.registerNewIbGib({ ibGib: activeKeystone }); const evolved = await service.sign({ latestKeystone: activeKeystone, masterSecret, claim: { target: 'test^gib', verb: KEYSTONE_VERB_MANAGE }, metaspace, space: space as any }); iReckon(sir, !!evolved).asTo('evolved keystone exists').isGonnaBeTrue(); iReckon(sir, evolved.data.n).asTo('n counter incremented').willEqual(1); }); await ifWe(sir, 'validateGenesisKeystone rejects malformed expirationUTC string', async () => { const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('alice') .withDetails({ expirationUTC: 'invalid-date-format' }); const configs = await builder.compileConfigs(); const frameDetails = builder.getFrameDetails(); const invalidKeystone = await service.genesis({ masterSecret, configs, frameDetails, metaspace, space: space as any, isPrimary: true }); const errors = await validateGenesisKeystone({ keystoneIbGib: invalidKeystone }); iReckon(sir, errors.some(e => e.includes('invalid expirationUTC'))).asTo('detects malformed expirationUTC').isGonnaBeTrue(); }); });