/** * @module keystone/device/device-identity-service-base-v1.respec * * Respec tests for DeviceIdentityServiceBase_V1 verifying substrate-agnostic * identity initialization, two-phase server synchronization, local resolution, * and delegate lifecycle management. */ 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 { DeviceIdentityServiceBase_V1 } from './device-identity-service-base-v1.mjs'; import { SPECIAL_KEYSTONES_INDEX_TYPE, KeystoneApiClient, } from './device-identity-types.mjs'; const sir = `[${import.meta.url}]`; class MockTestSpace { store = new Map(); ib: string = 'witness space mock-test-space mock_space_id user'; 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 MockTestMetaspaceService { timelineHeads = new Map(); specialIndexes = new Map(); constructor(public space: MockTestSpace) { } async getLocalUserSpace(): Promise { return this.space; } async put(args: any): Promise { const target = args.space || this.space; if (args.ibGib) { await target.put({ ibGib: args.ibGib }); } else if (args.ibGibs) { for (const ibGib of args.ibGibs) { await target.put({ ibGib }); } } } 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 getSpecialIbGib(args: { type: string; space?: any; initialize?: boolean; dontWarnIfNotExist?: boolean }): Promise { if (!this.specialIndexes.has(args.type) && args.initialize) { const initialIndex: IbGib_V1 = { ib: `special ${args.type}`, gib: `${args.type}_gib`, data: {}, rel8ns: {}, }; this.specialIndexes.set(args.type, initialIndex); await this.space.put({ ibGib: initialIndex }); } return this.specialIndexes.get(args.type); } async rel8ToSpecialIbGib(args: { type: string; rel8nName: string; ibGibsToRel8: IbGib_V1[]; space?: any; linked?: boolean }): Promise { let index = this.specialIndexes.get(args.type); if (!index) { index = { ib: `special ${args.type}`, gib: `${args.type}_gib`, data: {}, rel8ns: {}, }; this.specialIndexes.set(args.type, index); } index.rel8ns ??= {}; const rel8nList = index.rel8ns[args.rel8nName] ??= []; for (const item of args.ibGibsToRel8) { const addr = getIbGibAddr({ ibGib: item }); if (!rel8nList.includes(addr)) { rel8nList.push(addr); } await this.space.put({ ibGib: item }); } await this.space.put({ ibGib: index }); } async getLatestAddr({ addr, tjpAddr, space }: { addr?: string; tjpAddr?: string; space?: any }): Promise { const targetAddr = tjpAddr || addr; if (!targetAddr) return undefined; 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); } return targetAddr; } } class TestDeviceIdentityService extends DeviceIdentityServiceBase_V1 { public persistedSecrets = new Map(); public persistedSiteHandle: string | undefined; public async persistDelegateSecret(opts: { delegateTjpAddr: string; delegateSecret: string; role: string }): Promise { this.persistedSecrets.set(opts.delegateTjpAddr, opts.delegateSecret); } public async getPersistedDelegateSecret(opts: { delegateTjpAddr: string; role: string }): Promise { return this.persistedSecrets.get(opts.delegateTjpAddr); } public async clearPersistedDelegateSecrets(): Promise { this.persistedSecrets.clear(); } public async persistSiteHandle(opts: { siteUsername: string }): Promise { this.persistedSiteHandle = opts.siteUsername; } public async getPersistedSiteHandle(): Promise { return this.persistedSiteHandle; } protected getDefaultDeviceTag(): string { return 'test-device-tag'; } } await respecfully(sir, 'DeviceIdentityServiceBase_V1 Spec', async () => { await ifWe(sir, 'initializes sovereign identity locally with clean genesis and evolved delegates', async () => { const space = new MockTestSpace(); const metaspace = new MockTestMetaspaceService(space) as any; const service = new TestDeviceIdentityService(); const res = await service.initDeviceIdentity({ masterSecret: 'SuperSecretMasterPassphrase456!', username: 'AliceTester', siteUsername: '@alice_tester', deviceName: 'alice-macbook', metaspace, space: space as any, }); // 1. Genesis primary keystone must have n=0 and zero proofs iReckon(sir, res.hasIdentity).isGonnaBeTrue(); iReckon(sir, !!res.genesisPrimaryKeystone).isGonnaBeTrue(); iReckon(sir, (res.genesisPrimaryKeystone?.data as any)?.n).willEqual(0); iReckon(sir, res.genesisPrimaryKeystone?.data?.proofs?.length ?? 0).willEqual(0); // 2. Primary keystone must be evolved to n=2 with both Author and Sync delegates registered iReckon(sir, !!res.primaryKeystone).isGonnaBeTrue(); iReckon(sir, (res.primaryKeystone?.data as any)?.n).willEqual(2); iReckon(sir, res.primaryKeystone?.data?.proofs?.length).willEqual(1); // latest proof in frame iReckon(sir, !!res.primaryTjpAddr).isGonnaBeTrue(); // 3. Delegates created and secrets persisted iReckon(sir, !!res.authorDelegateKeystone).isGonnaBeTrue(); iReckon(sir, !!res.syncDelegateKeystone).isGonnaBeTrue(); iReckon(sir, typeof res.authorDelegateSecret === 'string').isGonnaBeTrue(); iReckon(sir, typeof res.syncDelegateSecret === 'string').isGonnaBeTrue(); iReckon(sir, res.siteUsername).willEqual('alice_tester'); iReckon(sir, service.persistedSiteHandle).willEqual('alice_tester'); // 4. Special 'keystones' index was initialized and populated const index = await metaspace.getSpecialIbGib({ type: SPECIAL_KEYSTONES_INDEX_TYPE }); iReckon(sir, index?.rel8ns?.keystone?.length).willEqual(3); }); await ifWe(sir, 'executes exact two-phase server sync (Phase 1 Genesis, Phase 2 Evolve)', async () => { const space = new MockTestSpace(); const metaspace = new MockTestMetaspaceService(space) as any; const service = new TestDeviceIdentityService(); const apiCalls: { type: string; payload: any }[] = []; const mockApiClient: KeystoneApiClient = { async checkSiteUsernameAvailability({ siteUsername }) { apiCalls.push({ type: 'check', payload: { siteUsername } }); return { available: true }; }, async postGenesisKeystone({ keystoneIbGib, siteUsername }) { apiCalls.push({ type: 'postGenesis', payload: { keystoneIbGib, siteUsername } }); return { success: true, addr: getIbGibAddr({ ibGib: keystoneIbGib }) }; }, async putEvolveKeystone({ domainAddr, keystoneIbGib, relatedKeystoneIbGibs }) { apiCalls.push({ type: 'putEvolve', payload: { domainAddr, keystoneIbGib, relatedKeystoneIbGibs } }); return { success: true }; }, }; const res = await service.initDeviceIdentity({ masterSecret: 'SuperSecretMasterPassphrase456!', username: 'BobTester', siteUsername: 'bob_tester', metaspace, space: space as any, apiClient: mockApiClient, }); iReckon(sir, res.hasIdentity).isGonnaBeTrue(); // Verify call order: 4 sequential calls iReckon(sir, apiCalls.length).willEqual(4); iReckon(sir, apiCalls[0].type).willEqual('check'); iReckon(sir, apiCalls[0].payload.siteUsername).willEqual('bob_tester'); // Phase 1: Genesis keystone (n=0, zero proofs) was posted iReckon(sir, apiCalls[1].type).willEqual('postGenesis'); iReckon(sir, (apiCalls[1].payload.keystoneIbGib.data as any).n).willEqual(0); iReckon(sir, apiCalls[1].payload.keystoneIbGib.data.proofs?.length ?? 0).willEqual(0); iReckon(sir, apiCalls[1].payload.siteUsername).willEqual('bob_tester'); // Phase 2a: Author delegate evolution (n=1) iReckon(sir, apiCalls[2].type).willEqual('putEvolve'); iReckon(sir, (apiCalls[2].payload.keystoneIbGib.data as any).n).willEqual(1); iReckon(sir, apiCalls[2].payload.relatedKeystoneIbGibs.length).willEqual(1); // Phase 2b: Sync delegate evolution (n=2) iReckon(sir, apiCalls[3].type).willEqual('putEvolve'); iReckon(sir, (apiCalls[3].payload.keystoneIbGib.data as any).n).willEqual(2); iReckon(sir, apiCalls[3].payload.relatedKeystoneIbGibs.length).willEqual(1); }); await ifWe(sir, 'resolves existing device identity and handles logout', async () => { const space = new MockTestSpace(); const metaspace = new MockTestMetaspaceService(space) as any; const service = new TestDeviceIdentityService(); await service.initDeviceIdentity({ masterSecret: 'MasterSecret789!', username: 'Charlie', siteUsername: 'charlie', metaspace, space: space as any, }); // Resolve active identity const resolved = await service.resolveDeviceIdentity({ metaspace, space: space as any, }); iReckon(sir, resolved.hasIdentity).isGonnaBeTrue(); iReckon(sir, resolved.username).willEqual('Charlie'); iReckon(sir, resolved.siteUsername).willEqual('charlie'); iReckon(sir, resolved.genesisPrimaryKeystone).isGonnaBeTruthy(); iReckon(sir, (resolved.genesisPrimaryKeystone?.data as any)?.n).willEqual(0); iReckon(sir, resolved.primaryKeystone).isGonnaBeTruthy(); iReckon(sir, (resolved.primaryKeystone?.data as any)?.n).willEqual(2); iReckon(sir, resolved.syncDelegateSecret).isGonnaBeTruthy(); // Logout await service.logoutDeviceIdentity(); const resolvedAfterLogout = await service.resolveDeviceIdentity({ metaspace, space: space as any, }); iReckon(sir, resolvedAfterLogout.hasIdentity).isGonnaBeTrue(); iReckon(sir, resolvedAfterLogout.syncDelegateSecret).isGonnaBeUndefined(); }); });