import { respecfully, iReckon, ifWe, ifWeMight } from '@ibgib/helper-gib/dist/respec-gib/respec-gib.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { KeystoneService_V1 } from '../keystone-service-v1.mjs'; import { KeystoneProfileBuilder } from '../policy/keystone-profile-builder.mjs'; import { KeystoneIbGib_V1 } from '../keystone-types.mjs'; import { deriveDelegateSecret, deriveDeviceDelegateSecret, createSyncDelegateKeystone, isDelegateExpired, isSsoProviderLinked, getKeystoneCapabilities } from './delegate-helpers.mjs'; import { DelegateKeystoneInfo } from './delegate-types.mjs'; const sir = `[${import.meta.url}]`; 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))); } 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 as any)?.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; } } class MockMetaspaceService { timelineHeads = new Map(); constructor(public space: MockIbGibSpace) { } async getLocalUserSpace({ lock }: { lock?: boolean } = {}): Promise { return this.space; } async put(args: any): Promise { const target = args.space || this.space; return target.put(args); } async get(args: { addr?: string; addrs?: string[]; space?: any }): Promise<{ success: boolean; ibGibs?: IbGib_V1[] }> { const target = args.space || this.space; if (args.addr) { const x = await target.get({ addr: args.addr }); return { success: !!x, ibGibs: x ? [x] : [], }; } if (args.addrs) { const ibGibs: IbGib_V1[] = []; for (const addr of args.addrs) { const x = await target.get({ addr }); if (x) { ibGibs.push(x); } } return { success: ibGibs.length > 0, ibGibs, }; } return { success: false, ibGibs: [] }; } async registerNewIbGib(args: { ibGib: IbGib_V1; space?: any }): Promise { const { ibGib } = args; const targetSpace = args.space || this.space; await targetSpace.put({ ibGib }); const gib = ibGib.gib || ''; let tjpGib = gib; if (gib.includes('.')) { const parts = gib.split('.'); tjpGib = parts.slice(1).join('.'); } const addr = getIbGibAddr({ ibGib }); this.timelineHeads.set(tjpGib, addr); } 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; } } await respecfully(sir, 'Symmetric Keystone Delegation & Expiration', async () => { const space = new MockIbGibSpace(); const metaspace = new MockMetaspaceService(space) as any; const keystoneService = new KeystoneService_V1(); await ifWe(sir, 'deriveDelegateSecret produces deterministic KDF outputs', async () => { const masterSecret = 'MySuperSecurePassphrase123!'; const derived1 = await deriveDelegateSecret({ masterSecret }); const derived2 = await deriveDelegateSecret({ masterSecret }); iReckon(sir, typeof derived1 === 'string' && derived1.length > 32).willEqual(true); iReckon(sir, derived1).willEqual(derived2); }); await ifWe(sir, 'deriveDeviceDelegateSecret generates high-entropy secrets', async () => { const primaryTjpAddr = 'keystone^alice_tjp_123'; const secretA = await deriveDeviceDelegateSecret({ primaryTjpAddr, deviceTag: 'laptop' }); const secretB = await deriveDeviceDelegateSecret({ primaryTjpAddr, deviceTag: 'laptop' }); iReckon(sir, typeof secretA === 'string' && secretA.length === 128).willEqual(true); iReckon(sir, secretA !== secretB).willEqual(true); }); await ifWe(sir, 'isDelegateExpired accurately evaluates timestamps', async () => { const futureDate = new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(); const pastDate = new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(); const activeInfo: DelegateKeystoneInfo = { delegateTjpAddr: 'keystone^d1', delegateAddr: 'keystone^d1', thisAddr: 'keystone^p1', expirationUTC: futureDate }; const expiredInfo: DelegateKeystoneInfo = { delegateTjpAddr: 'keystone^d2', delegateAddr: 'keystone^d2', thisAddr: 'keystone^p1', expirationUTC: pastDate }; const indefiniteInfo: DelegateKeystoneInfo = { delegateTjpAddr: 'keystone^d3', delegateAddr: 'keystone^d3', thisAddr: 'keystone^p1' }; iReckon(sir, isDelegateExpired({ delegateInfo: activeInfo })).willEqual(false); iReckon(sir, isDelegateExpired({ delegateInfo: expiredInfo })).willEqual(true); iReckon(sir, isDelegateExpired({ delegateInfo: indefiniteInfo })).willEqual(false); }); await ifWe(sir, 'createSyncDelegateKeystone builds a valid outward delegate', async () => { const primaryTjpAddr = 'keystone^alice_primary_tjp'; const delegateSecret = await deriveDeviceDelegateSecret({ primaryTjpAddr, deviceTag: 'work-pc' }); const delegate = await createSyncDelegateKeystone({ profileName: 'sync-profile.dev', username: 'alice', deviceTag: 'work-pc', primaryTjpAddr, delegateSecret, metaspace, space: space as any }); iReckon(sir, !!delegate).willEqual(true); iReckon(sir, !!delegate.data?.frameDetails).willEqual(true); iReckon(sir, delegate.data?.frameDetails?.role).willEqual('sync-delegate'); iReckon(sir, delegate.data?.frameDetails?.deviceTag).willEqual('work-pc'); iReckon(sir, delegate.data?.frameDetails?.primaryTjpAddr).willEqual(primaryTjpAddr); iReckon(sir, !!delegate.data?.frameDetails?.expirationUTC).willEqual(true); }); await ifWe(sir, 'registerDelegate and getDelegateStatus enforce expirationUTC correctly', async () => { const masterSecret = 'RootMasterSecret'; const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('alice'); const configs = await builder.compileConfigs(); const parentKeystone = await keystoneService.genesis({ masterSecret, configs, metaspace, space: space as any, isPrimary: true }); await metaspace.registerNewIbGib({ ibGib: parentKeystone }); const primaryTjpAddr = getIbGibAddr({ ibGib: parentKeystone }); const delegateSecret = await deriveDeviceDelegateSecret({ primaryTjpAddr, deviceTag: 'phone' }); const delegateKeystone = await createSyncDelegateKeystone({ profileName: 'sync-profile.dev', username: 'alice', deviceTag: 'phone', primaryTjpAddr, delegateSecret, metaspace, space: space as any }); await metaspace.registerNewIbGib({ ibGib: delegateKeystone }); const delegateTjpAddr = getIbGibAddr({ ibGib: delegateKeystone }); // 1. Register with future expiration const futureExpiration = new Date(Date.now() + 1000 * 3600).toISOString(); const evolvedParent = await keystoneService.registerDelegate({ parentKeystone, delegateKeystone, masterSecret, signingPoolId: 'manage', allowedVerbs: ['sync'], deviceName: 'phone', expirationUTC: futureExpiration, metaspace, space: space as any }); await metaspace.registerNewIbGib({ ibGib: evolvedParent }); const activeStatus = await keystoneService.getDelegateStatus({ parentTjpAddr: primaryTjpAddr, delegateTjpAddr, metaspace, space: space as any }); iReckon(sir, activeStatus.registered).willEqual(true); iReckon(sir, activeStatus.delegateInfo?.expirationUTC).willEqual(futureExpiration); // 2. Register expired delegate const pastExpiration = new Date(Date.now() - 1000 * 3600).toISOString(); const evolvedParentExpired = await keystoneService.registerDelegate({ parentKeystone: evolvedParent, delegateKeystone, masterSecret, signingPoolId: 'manage', allowedVerbs: ['sync'], deviceName: 'phone', expirationUTC: pastExpiration, metaspace, space: space as any }); await metaspace.registerNewIbGib({ ibGib: evolvedParentExpired }); const expiredStatus = await keystoneService.getDelegateStatus({ parentTjpAddr: primaryTjpAddr, delegateTjpAddr, metaspace, space: space as any }); iReckon(sir, expiredStatus.registered).willEqual(false); }); await ifWe(sir, 'registerDelegate automatically inherits expirationUTC from delegate keystone frameDetails', async () => { const masterSecret = 'RootMasterSecret'; const builder = KeystoneProfileBuilder.buildKeystone('primary-profile.dev') .withUsername('alice'); const configs = await builder.compileConfigs(); const parentKeystone = await keystoneService.genesis({ masterSecret, configs, metaspace, space: space as any, isPrimary: true }); await metaspace.registerNewIbGib({ ibGib: parentKeystone }); const primaryTjpAddr = getIbGibAddr({ ibGib: parentKeystone }); const delegateSecret = await deriveDeviceDelegateSecret({ primaryTjpAddr, deviceTag: 'laptop' }); const explicitExpiration = new Date(Date.now() + 1000 * 7200).toISOString(); const delegateKeystone = await createSyncDelegateKeystone({ profileName: 'sync-profile.dev', username: 'alice', deviceTag: 'laptop', primaryTjpAddr, delegateSecret, expirationUTC: explicitExpiration, metaspace, space: space as any }); await metaspace.registerNewIbGib({ ibGib: delegateKeystone }); const delegateTjpAddr = getIbGibAddr({ ibGib: delegateKeystone }); // Register WITHOUT explicitly passing expirationUTC in opts const evolvedParent = await keystoneService.registerDelegate({ parentKeystone, delegateKeystone, masterSecret, signingPoolId: 'manage', allowedVerbs: ['sync'], deviceName: 'laptop', metaspace, space: space as any }); await metaspace.registerNewIbGib({ ibGib: evolvedParent }); const status = await keystoneService.getDelegateStatus({ parentTjpAddr: primaryTjpAddr, delegateTjpAddr, metaspace, space: space as any }); iReckon(sir, status.registered).willEqual(true); // Assert exact timestamp equality between parent's delegateInfo and delegate frameDetails iReckon(sir, status.delegateInfo?.expirationUTC).willEqual(delegateKeystone.data.frameDetails?.expirationUTC); iReckon(sir, status.delegateInfo?.expirationUTC).willEqual(explicitExpiration); // Assert symmetric expiration evaluation iReckon(sir, isDelegateExpired({ delegateInfo: status.delegateInfo })).willEqual(false); iReckon(sir, isDelegateExpired({ delegateKeystone })).willEqual(false); }); await ifWe(sir, 'getKeystoneCapabilities detects Sovereign, Custodial, and Hybrid states', async () => { const sovereignKeystone: KeystoneIbGib_V1 = { ib: 'keystone', gib: 'sovereign_gib', data: { challengePools: [{ id: 'manage', config: {} as any, challenges: {} }], proofs: [], emails: ['sovereign@example.com'] }, rel8ns: {} }; const custodialKeystone: KeystoneIbGib_V1 = { ib: 'keystone', gib: 'custodial_gib', data: { challengePools: [{ id: 'manage', config: {} as any, challenges: {} }], proofs: [], emails: ['googleuser@example.com'], frameDetails: { custodianProvider: 'google', custodyMode: 'full' } }, rel8ns: {} }; const hybridKeystone: KeystoneIbGib_V1 = { ib: 'keystone', gib: 'hybrid_gib', data: { challengePools: [ { id: 'manage', config: {} as any, challenges: {} }, { id: 'custodian-manage-google', config: {} as any, challenges: {} } ], proofs: [], emails: ['hybrid@example.com'] }, rel8ns: {} }; const capSovereign = getKeystoneCapabilities({ keystone: sovereignKeystone }); const capCustodial = getKeystoneCapabilities({ keystone: custodialKeystone }); const capHybrid = getKeystoneCapabilities({ keystone: hybridKeystone }); iReckon(sir, capSovereign.isSovereign).willEqual(true); iReckon(sir, capSovereign.isCustodial).willEqual(false); iReckon(sir, capCustodial.isSovereign).willEqual(false); iReckon(sir, capCustodial.isCustodial).willEqual(true); iReckon(sir, capCustodial.providers.includes('google')).willEqual(true); iReckon(sir, capHybrid.isSovereign).willEqual(true); iReckon(sir, capHybrid.isCustodial).willEqual(true); iReckon(sir, capHybrid.isHybrid).willEqual(true); iReckon(sir, capHybrid.providers.includes('google')).willEqual(true); }); await ifWe(sir, 'isSsoProviderLinked recognizes origin and foreign pools', async () => { const googleCustodial: KeystoneIbGib_V1 = { ib: 'keystone', gib: 'c1', data: { challengePools: [{ id: 'manage', config: {} as any, challenges: {} }], proofs: [], frameDetails: { custodianProvider: 'google' } }, rel8ns: {} }; const githubLinked: KeystoneIbGib_V1 = { ib: 'keystone', gib: 'c2', data: { challengePools: [ { id: 'manage', config: {} as any, challenges: {} }, { id: 'custodian-manage-github', config: {} as any, challenges: {} } ], proofs: [] }, rel8ns: {} }; iReckon(sir, isSsoProviderLinked({ keystone: googleCustodial, providerId: 'google' })).willEqual(true); iReckon(sir, isSsoProviderLinked({ keystone: googleCustodial, providerId: 'github' })).willEqual(false); iReckon(sir, isSsoProviderLinked({ keystone: githubLinked, providerId: 'github' })).willEqual(true); // Test on evolved frame where frameDetails is undefined but aggregatedDetails contains custodianProvider const evolvedGoogleCustodial: KeystoneIbGib_V1 = { ib: 'keystone', gib: 'c1_evolved_n2', data: { n: 2, challengePools: [{ id: 'manage', config: {} as any, challenges: {} }], proofs: [], frameDetails: undefined }, rel8ns: {} }; const aggregatedDetails = { custodianProvider: 'google', custodyMode: 'full' }; iReckon(sir, isSsoProviderLinked({ keystone: evolvedGoogleCustodial, aggregatedDetails, providerId: 'google' })).willEqual(true); iReckon(sir, isSsoProviderLinked({ keystone: evolvedGoogleCustodial, providerId: 'google' })).willEqual(false); // Without aggregatedDetails, differential frame has undefined const capEvolved = getKeystoneCapabilities({ keystone: evolvedGoogleCustodial, aggregatedDetails }); iReckon(sir, capEvolved.isCustodial).willEqual(true); iReckon(sir, capEvolved.isSovereign).willEqual(false); iReckon(sir, capEvolved.providers.includes('google')).willEqual(true); }); await ifWe(sir, 'registerCustomProfile and fromTemplate build custom policy templates', async () => { const customTemplate: any = { metadata: { name: 'custom-enterprise-sync.test', description: 'Custom enterprise sync policy for testing', defaultTtlSeconds: 42 }, pools: { sync: { id: 'sync', allowedVerbs: ['sync'], algo: 'SHA-256', rounds: 1, behavior: { size: 10, replenish: 'top-up', selectSequentially: 1, selectRandomly: 1, targetBindingCount: 2 } } } }; // 1. Test registerCustomProfile KeystoneProfileBuilder.registerCustomProfile({ name: 'custom-enterprise-sync.test', template: customTemplate }); const builderFromRegistry = KeystoneProfileBuilder.buildKeystone('custom-enterprise-sync.test') .withUsername('enterprise-bot'); const configsFromRegistry = await builderFromRegistry.compileConfigs(); iReckon(sir, configsFromRegistry.length).willEqual(1); iReckon(sir, configsFromRegistry[0].id).willEqual('sync'); // 2. Test fromTemplate const builderFromTemplate = KeystoneProfileBuilder.fromTemplate(customTemplate) .withUsername('direct-bot'); const configsFromTemplate = await builderFromTemplate.compileConfigs(); iReckon(sir, configsFromTemplate.length).willEqual(1); iReckon(sir, configsFromTemplate[0].id).willEqual('sync'); KeystoneProfileBuilder.clearCustomProfiles(); }); await ifWe(sir, 'createSyncDelegateKeystone supports test-short-ttl profile and profileTemplate', async () => { const primaryTjpAddr = 'keystone^alice_short_ttl_primary'; const delegateSecret = await deriveDeviceDelegateSecret({ primaryTjpAddr, deviceTag: 'test-device' }); // 1. Test with sync-profile.test-short-ttl (defaultTtlSeconds = 10) const delegateShortTtl = await createSyncDelegateKeystone({ profileName: 'sync-profile.test-short-ttl', username: 'alice', deviceTag: 'test-device', primaryTjpAddr, delegateSecret, metaspace, space: space as any }); iReckon(sir, !!delegateShortTtl).willEqual(true); const expStr = delegateShortTtl.data?.frameDetails?.expirationUTC; iReckon(sir, !!expStr).willEqual(true); const expMs = Date.parse(expStr!); const nowMs = Date.now(); // Should expire approximately 10 seconds in the future (+- 5 seconds tolerance) iReckon(sir, expMs > nowMs && expMs <= nowMs + 15000).willEqual(true); // 2. Test with explicit profileTemplate const customTemplate: any = { metadata: { name: 'sync-profile.custom-adhoc.test', defaultTtlSeconds: 20 }, pools: { sync: { id: 'sync', allowedVerbs: ['sync'], algo: 'SHA-256', rounds: 1, behavior: { size: 10, replenish: 'top-up', selectSequentially: 1, selectRandomly: 1, targetBindingCount: 2 } } } }; const delegateFromTemplate = await createSyncDelegateKeystone({ profileTemplate: customTemplate, username: 'alice', deviceTag: 'custom-device', primaryTjpAddr, delegateSecret, metaspace, space: space as any }); iReckon(sir, !!delegateFromTemplate).willEqual(true); iReckon(sir, delegateFromTemplate.data?.frameDetails?.deviceTag).willEqual('custom-device'); const customExpStr = delegateFromTemplate.data?.frameDetails?.expirationUTC; iReckon(sir, !!customExpStr).willEqual(true); const customExpMs = Date.parse(customExpStr!); iReckon(sir, customExpMs > nowMs && customExpMs <= nowMs + 25000).willEqual(true); }); });