/** * @module keystone/device/device-identity-service-base-v1 * * Substrate-agnostic base service for managing device-level sovereign identity * lifecycles, keystone genesis, delegate creation, in-band indexing, and two-phase * server synchronization across Web and Node.js runtimes. */ import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { IbGib_V1 } from '@ibgib/ts-gib/dist/V1/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../core-constants.mjs'; import { getTjpAddr, getIbGibFromSpace, getTimelinesGroupedByTjp } from '../../common/other/ibgib-helper.mjs'; import { KeystoneService_V1 } from '../keystone-service-v1.mjs'; import { KeystoneIbGib_V1 } from '../keystone-types.mjs'; import { POOL_ID_DEFAULT, POOL_ID_MANAGE, KEYSTONE_VERB_AUTHOR, KEYSTONE_VERB_SYNC, } from '../keystone-constants.mjs'; import { createStandardPoolConfig, createManagePoolConfig, } from '../keystone-config-builder.mjs'; import { deriveDelegateSecret, createAuthorDelegateKeystone, createSyncDelegateKeystone, } from '../delegate/delegate-helpers.mjs'; import { KEYSTONE_ROLE_AUTHOR_DELEGATE, KEYSTONE_ROLE_SYNC_DELEGATE, } from '../delegate/delegate-constants.mjs'; import { SPECIAL_KEYSTONES_INDEX_TYPE, DeviceIdentityInitOpts, DeviceIdentitySignInOpts, DeviceIdentityResolveOpts, ResolvedDeviceIdentity, } from './device-identity-types.mjs'; const logalot = GLOBAL_LOG_A_LOT; export abstract class DeviceIdentityServiceBase_V1 { protected lc: string = `[${DeviceIdentityServiceBase_V1.name}]`; // #region Abstract Substrate-Specific Storage & Tag Hooks /** Persists a derived short-lived delegate secret in substrate-specific secure storage */ public abstract persistDelegateSecret(opts: { delegateTjpAddr: string; delegateSecret: string; role: string; }): Promise; /** Retrieves a stored delegate secret from substrate-specific storage */ public abstract getPersistedDelegateSecret(opts: { delegateTjpAddr: string; role: string; }): Promise; /** Clears all stored delegate secrets upon logout */ public abstract clearPersistedDelegateSecrets(): Promise; /** Persists the device's unique site handle (@handle) in substrate configuration */ public abstract persistSiteHandle(opts: { siteUsername: string }): Promise; /** Retrieves the persisted site handle from substrate configuration */ public abstract getPersistedSiteHandle(): Promise; /** Returns the default device descriptor tag (e.g. hostname or browser user-agent) */ protected abstract getDefaultDeviceTag(): string; // #endregion // #region Core Substrate-Agnostic Workflows /** * Initializes a brand-new sovereign primary identity, derives and registers * local Author and Sync delegates, indexes them in the local space, and optionally * synchronizes both genesis and evolution with a remote server. */ public async initDeviceIdentity(opts: DeviceIdentityInitOpts): Promise { const lc = `${this.lc}[${this.initDeviceIdentity.name}]`; const { masterSecret, username, siteUsername, metaspace, space, apiClient, emails, } = opts; try { if (!masterSecret) { throw new Error(`${lc} masterSecret is required (E: c6a689d0115d35a9bfa78debab376f05)`); } if (!username) { throw new Error(`${lc} username is required (E: 2aeb538f6757e4786a9ef0c46c803da8)`); } // Pre-flight handle availability check if API client is provided const cleanSiteUsername = siteUsername ? siteUsername.replace(/^@/, '').trim() : undefined; if (apiClient && cleanSiteUsername) { const checkRes = await apiClient.checkSiteUsernameAvailability({ siteUsername: cleanSiteUsername }); if (!checkRes.available) { throw new Error(`Site handle '@${cleanSiteUsername}' is not available: ${checkRes.message || 'Already taken'}`); } } const keystoneService = new KeystoneService_V1(); const salt = (await getUUID()).substring(0, 16); const deviceTag = opts.deviceName || this.getDefaultDeviceTag(); // 1. Genesis Primary Identity (n=0, zero proofs) const genesisPrimaryKeystone = await keystoneService.genesis({ masterSecret, configs: [ createStandardPoolConfig({ id: POOL_ID_DEFAULT, salt }), createManagePoolConfig({ id: POOL_ID_MANAGE, salt: `${salt}_manage` }), ], frameDetails: { username, isPrimary: true }, emails, metaspace, space, isPrimary: true, }); const primaryTjpAddr = getTjpAddr({ ibGib: genesisPrimaryKeystone })!; // 2. Remote Server Sync Phase 1: Publish clean genesis stone to claim handle if (apiClient) { const genRes = await apiClient.postGenesisKeystone({ keystoneIbGib: genesisPrimaryKeystone, siteUsername: cleanSiteUsername, siteUsernameExceptionKey: opts.siteUsernameExceptionKey, }); if (!genRes.success && genRes.statusCode !== 409) { throw new Error(`Failed to publish genesis keystone to server: ${genRes.message || 'Unknown error'}`); } // If email was provided and genesis is quarantined pending email verification (status 202) if ((genRes as any).pending && emails && emails.length > 0 && apiClient.postVerifyCode) { const primaryEmail = emails[0]; let code = opts.verificationCode; if (!code && opts.onVerifyEmailCode) { code = await opts.onVerifyEmailCode(primaryEmail, primaryTjpAddr); } if (!code) { throw new Error(`Email verification code is required to complete identity initialization for ${primaryEmail}. (E: e73ed6f2fa856cb0146f53293863c9a3)`); } const verifyRes = await apiClient.postVerifyCode({ email: primaryEmail, primaryTjpAddr, code, }); if (!verifyRes.success) { throw new Error(`Email verification failed: ${verifyRes.message || 'Invalid verification code'} (E: d96b40145d58c7110fd0db252652ed7c)`); } } } // 3. Local Delegate Derivation const delegateSecret = await deriveDelegateSecret({ masterSecret }); // 4. Create & Register Author Delegate const authorDelegate = await createAuthorDelegateKeystone({ username, deviceTag, primaryTjpAddr, delegateSecret, metaspace, space, }); const evolvedPrimary1 = await keystoneService.registerDelegate({ parentKeystone: genesisPrimaryKeystone, delegateKeystone: authorDelegate, masterSecret, signingPoolId: POOL_ID_MANAGE, metaspace, space, allowedVerbs: [KEYSTONE_VERB_AUTHOR], deviceName: deviceTag, }); // Remote Server Sync Phase 2a: Publish Author delegate evolution (n=1) if (apiClient) { const evolve1Res = await apiClient.putEvolveKeystone({ domainAddr: primaryTjpAddr, keystoneIbGib: evolvedPrimary1, relatedKeystoneIbGibs: [authorDelegate], }); if (!evolve1Res.success) { throw new Error(`Failed to publish Author delegate evolution to server: ${evolve1Res.message || 'Unknown error'}`); } } // 5. Create & Register Sync Delegate const syncDelegate = await createSyncDelegateKeystone({ profileName: 'sync-profile.dev', username, deviceTag, primaryTjpAddr, delegateSecret, metaspace, space, }); const evolvedPrimary2 = await keystoneService.registerDelegate({ parentKeystone: evolvedPrimary1, delegateKeystone: syncDelegate, masterSecret, signingPoolId: POOL_ID_MANAGE, metaspace, space, allowedVerbs: [KEYSTONE_VERB_SYNC], deviceName: deviceTag, }); // Remote Server Sync Phase 2b: Publish Sync delegate evolution (n=2) if (apiClient) { const evolve2Res = await apiClient.putEvolveKeystone({ domainAddr: primaryTjpAddr, keystoneIbGib: evolvedPrimary2, relatedKeystoneIbGibs: [syncDelegate], }); if (!evolve2Res.success) { throw new Error(`Failed to publish Sync delegate evolution to server: ${evolve2Res.message || 'Unknown error'}`); } } // 6. In-Band Indexing in local space await metaspace.getSpecialIbGib({ type: SPECIAL_KEYSTONES_INDEX_TYPE, space, initialize: true, }); await metaspace.rel8ToSpecialIbGib({ type: SPECIAL_KEYSTONES_INDEX_TYPE, rel8nName: 'keystone', ibGibsToRel8: [evolvedPrimary2, authorDelegate, syncDelegate], space, linked: false, }); // 7. Persist Delegate Secrets & Site Handle in substrate storage const authorTjp = getTjpAddr({ ibGib: authorDelegate })!; const syncTjp = getTjpAddr({ ibGib: syncDelegate })!; await this.persistDelegateSecret({ delegateTjpAddr: authorTjp, delegateSecret, role: KEYSTONE_ROLE_AUTHOR_DELEGATE, }); await this.persistDelegateSecret({ delegateTjpAddr: syncTjp, delegateSecret, role: KEYSTONE_ROLE_SYNC_DELEGATE, }); if (cleanSiteUsername) { await this.persistSiteHandle({ siteUsername: cleanSiteUsername }); } if (logalot) { console.log(`${lc} Successfully initialized device identity for ${username} (handle: @${cleanSiteUsername || 'none'}) on device "${deviceTag}"`); } return { hasIdentity: true, genesisPrimaryKeystone, primaryKeystone: evolvedPrimary2, primaryTjpAddr, authorDelegateKeystone: authorDelegate, authorDelegateSecret: delegateSecret, syncDelegateKeystone: syncDelegate, syncDelegateSecret: delegateSecret, username, siteUsername: cleanSiteUsername, deviceName: deviceTag, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 30bff804337d3a0c2202235aa2a61f43)`); throw error; } } /** * Signs into an existing sovereign primary identity on this device. * Ingests the public identity graph, verifies the master passphrase locally, * derives local Author and Sync delegates, evolves the primary keystone, * publishes the evolution and registers the sync delegate with the remote server, * and indexes all credentials in-band in local storage. */ public async signInDeviceIdentity(opts: DeviceIdentitySignInOpts): Promise { const lc = `${this.lc}[${this.signInDeviceIdentity.name}]`; const { masterSecret, metaspace, space, apiClient, siteUsername, } = opts; try { if (!masterSecret) { throw new Error(`${lc} masterSecret is required (E: 917cbcd316ca4518524ce62af9f7fde6)`); } let primaryTjpAddr = opts.primaryTjpAddr; let primaryGraph = opts.primaryGraph; let primaryKeystone = opts.primaryKeystone; // 1. Fetch graph from server if not provided but primaryTjpAddr and apiClient exist if (!primaryGraph && primaryTjpAddr && apiClient?.getKeystoneGraph) { const graphRes = await apiClient.getKeystoneGraph({ domainAddr: primaryTjpAddr }); if (graphRes.success && graphRes.graph) { primaryGraph = graphRes.graph; } } // 2. Ingest identity graph into local CAS space let activePrimaryKeystone = primaryKeystone; let genesisPrimaryKeystone: KeystoneIbGib_V1 | undefined; if (primaryGraph) { const graphIbGibs = Object.values(primaryGraph) as IbGib_V1[]; await metaspace.put({ ibGibs: graphIbGibs, space }); const timelinesMap = getTimelinesGroupedByTjp({ ibGibs: graphIbGibs }); for (const tjpKey of Object.keys(timelinesMap)) { for (const frame of timelinesMap[tjpKey]) { await metaspace.registerNewIbGib({ ibGib: frame, space }); } } const resolvedTjp = primaryTjpAddr || Object.keys(timelinesMap)[0]; const domainTimeline = timelinesMap[resolvedTjp]; if (domainTimeline && domainTimeline.length > 0) { genesisPrimaryKeystone = domainTimeline[0] as KeystoneIbGib_V1; activePrimaryKeystone = domainTimeline[domainTimeline.length - 1] as KeystoneIbGib_V1; if (!primaryTjpAddr) { primaryTjpAddr = resolvedTjp; } } } else if (activePrimaryKeystone) { await metaspace.put({ ibGibs: [activePrimaryKeystone], space }); await metaspace.registerNewIbGib({ ibGib: activePrimaryKeystone, space }); if (!primaryTjpAddr) { primaryTjpAddr = getTjpAddr({ ibGib: activePrimaryKeystone }); } } if (!activePrimaryKeystone || !primaryTjpAddr) { throw new Error(`${lc} Unable to resolve active primary keystone or TJP address for identity sign-in (E: 93a021aabe5c4b9c7f82883431d0d614)`); } if (!genesisPrimaryKeystone && primaryTjpAddr) { genesisPrimaryKeystone = await getIbGibFromSpace({ addr: primaryTjpAddr, space, }) ?? activePrimaryKeystone; } // 3. Local Zero-Knowledge Verification: Solve master passphrase proof const keystoneService = new KeystoneService_V1(); const isValid = await keystoneService.verifySigningSecret({ keystoneIbGib: activePrimaryKeystone, signingSecret: masterSecret, poolId: POOL_ID_MANAGE, }); if (!isValid) { throw new Error(`Master passphrase verification failed. Incorrect passphrase for '${siteUsername || primaryTjpAddr}'. (E: a4fa20a9bcc8e537050875bcb3f60742)`); } const cleanSiteUsername = siteUsername ? siteUsername.replace(/^@/, '').trim() : undefined; const username = genesisPrimaryKeystone?.data?.frameDetails?.username || cleanSiteUsername || activePrimaryKeystone.data?.frameDetails?.username || 'user'; const deviceTag = opts.deviceName || this.getDefaultDeviceTag(); // 4. Derive local device delegate secret const delegateSecret = await deriveDelegateSecret({ masterSecret }); // 5. Create & Register Author Delegate const authorDelegate = await createAuthorDelegateKeystone({ username, deviceTag, primaryTjpAddr, delegateSecret, metaspace, space, }); const evolvedPrimary1 = await keystoneService.registerDelegate({ parentKeystone: activePrimaryKeystone, delegateKeystone: authorDelegate, masterSecret, signingPoolId: POOL_ID_MANAGE, metaspace, space, allowedVerbs: [KEYSTONE_VERB_AUTHOR], deviceName: deviceTag, }); // Remote Server Sync Phase 1: Publish Author delegate evolution (linear step 1) if (apiClient?.putEvolveKeystone) { const put1Res = await apiClient.putEvolveKeystone({ domainAddr: primaryTjpAddr, keystoneIbGib: evolvedPrimary1, relatedKeystoneIbGibs: [authorDelegate], }); if (!put1Res.success) { throw new Error(`Failed to publish Author delegate evolution to server: ${put1Res.message || 'Unknown error'}`); } } // 6. Create & Register Sync Delegate const sovereignSyncProfileName = process.env.KEYSTONE_PROFILE_SOVEREIGN_SYNC || 'sync-profile.dev'; const syncDelegate = await createSyncDelegateKeystone({ profileName: sovereignSyncProfileName as any, username, deviceTag, primaryTjpAddr, delegateSecret, metaspace, space, }); const evolvedPrimary2 = await keystoneService.registerDelegate({ parentKeystone: evolvedPrimary1, delegateKeystone: syncDelegate, masterSecret, signingPoolId: POOL_ID_MANAGE, metaspace, space, allowedVerbs: [KEYSTONE_VERB_SYNC], deviceName: deviceTag, }); // Remote Server Sync Phase 2: Publish Sync delegate evolution (linear step 2) if (apiClient?.putEvolveKeystone) { const put2Res = await apiClient.putEvolveKeystone({ domainAddr: primaryTjpAddr, keystoneIbGib: evolvedPrimary2, relatedKeystoneIbGibs: [syncDelegate], }); if (!put2Res.success) { throw new Error(`Failed to publish Sync delegate evolution to server: ${put2Res.message || 'Unknown error'}`); } } // 9. In-band indexing in local space await metaspace.getSpecialIbGib({ type: SPECIAL_KEYSTONES_INDEX_TYPE, space, initialize: true, }); await metaspace.rel8ToSpecialIbGib({ type: SPECIAL_KEYSTONES_INDEX_TYPE, rel8nName: 'keystone', ibGibsToRel8: [evolvedPrimary2, authorDelegate, syncDelegate], space, linked: false, }); // 10. Persist delegate secrets and site handle const authorTjp = getTjpAddr({ ibGib: authorDelegate })!; const syncTjp = getTjpAddr({ ibGib: syncDelegate })!; await this.persistDelegateSecret({ delegateTjpAddr: authorTjp, delegateSecret, role: KEYSTONE_ROLE_AUTHOR_DELEGATE, }); await this.persistDelegateSecret({ delegateTjpAddr: syncTjp, delegateSecret, role: KEYSTONE_ROLE_SYNC_DELEGATE, }); if (cleanSiteUsername) { await this.persistSiteHandle({ siteUsername: cleanSiteUsername }); } // Fetch genesis primary keystone if not already resolved if (!genesisPrimaryKeystone) { genesisPrimaryKeystone = await getIbGibFromSpace({ addr: primaryTjpAddr, space, }) ?? evolvedPrimary2; } if (logalot) { console.log(`${lc} Successfully signed in device identity for ${username} (handle: @${cleanSiteUsername || 'none'}) on device "${deviceTag}"`); } return { hasIdentity: true, genesisPrimaryKeystone, primaryKeystone: evolvedPrimary2, primaryTjpAddr, authorDelegateKeystone: authorDelegate, authorDelegateSecret: delegateSecret, syncDelegateKeystone: syncDelegate, syncDelegateSecret: delegateSecret, username, siteUsername: cleanSiteUsername, deviceName: deviceTag, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: e731b816501fc734c709face2366ed05)`); throw error; } } /** * Inspects the local space and substrate storage to resolve the active * sovereign device identity and active delegate tokens. */ public async resolveDeviceIdentity(opts: DeviceIdentityResolveOpts): Promise { const lc = `${this.lc}[${this.resolveDeviceIdentity.name}]`; const { metaspace, space, masterSecret } = opts; try { const keystonesIndex = await metaspace.getSpecialIbGib({ type: SPECIAL_KEYSTONES_INDEX_TYPE, space, initialize: false, dontWarnIfNotExist: true, }); if (!keystonesIndex || !keystonesIndex.rel8ns?.keystone || keystonesIndex.rel8ns.keystone.length === 0) { return { hasIdentity: false }; } const keystoneAddrs = keystonesIndex.rel8ns.keystone; const keystoneService = new KeystoneService_V1(); let primaryKeystone: KeystoneIbGib_V1 | undefined; let authorDelegateKeystone: KeystoneIbGib_V1 | undefined; let syncDelegateKeystone: KeystoneIbGib_V1 | undefined; for (const addr of keystoneAddrs) { if (!addr) { continue; } try { let ibGib = await keystoneService.getLatestKeystone({ addr, metaspace, space }) .catch(() => getIbGibFromSpace({ addr, space })); if (!ibGib || !ibGib.data) { continue; } const aggregateDetails = await keystoneService.getAggregateDetails({ latestKeystone: ibGib, metaspace, space, }).catch(() => undefined); const frameDetails = (ibGib.data as any).frameDetails; const role = aggregateDetails?.role || frameDetails?.role || (ibGib.data as any).role; const isPrimary = aggregateDetails?.isPrimary ?? frameDetails?.isPrimary; if (isPrimary) { primaryKeystone = ibGib; } else if (role === KEYSTONE_ROLE_AUTHOR_DELEGATE || role === 'author-delegate' || role === 'author_delegate') { authorDelegateKeystone = ibGib; } else if (role === KEYSTONE_ROLE_SYNC_DELEGATE || role === 'sync-delegate' || role === 'sync_delegate') { syncDelegateKeystone = ibGib; } } catch { // Suppress individual address lookup failure in index } } if (!primaryKeystone) { return { hasIdentity: false }; } const primaryTjpAddr = getTjpAddr({ ibGib: primaryKeystone })!; // Fetch the genesis primary keystone (at punctiliar primaryTjpAddr) const genesisPrimaryKeystone = await getIbGibFromSpace({ addr: primaryTjpAddr, space, }) ?? primaryKeystone; const siteUsername = await this.getPersistedSiteHandle(); const username = genesisPrimaryKeystone.data?.frameDetails?.username || primaryKeystone.data?.frameDetails?.username || siteUsername || 'user'; const authorTjp = authorDelegateKeystone ? getTjpAddr({ ibGib: authorDelegateKeystone }) : undefined; const syncTjp = syncDelegateKeystone ? getTjpAddr({ ibGib: syncDelegateKeystone }) : undefined; let authorDelegateSecret: string | undefined; let syncDelegateSecret: string | undefined; if (authorTjp) { authorDelegateSecret = await this.getPersistedDelegateSecret({ delegateTjpAddr: authorTjp, role: KEYSTONE_ROLE_AUTHOR_DELEGATE, }); } if (syncTjp) { syncDelegateSecret = await this.getPersistedDelegateSecret({ delegateTjpAddr: syncTjp, role: KEYSTONE_ROLE_SYNC_DELEGATE, }); } // Fallback: Re-derive delegate secrets if masterSecret is provided and secrets are missing if (masterSecret && (!authorDelegateSecret || !syncDelegateSecret)) { const derived = await deriveDelegateSecret({ masterSecret }); if (!authorDelegateSecret && authorTjp) { authorDelegateSecret = derived; await this.persistDelegateSecret({ delegateTjpAddr: authorTjp, delegateSecret: derived, role: KEYSTONE_ROLE_AUTHOR_DELEGATE, }); } if (!syncDelegateSecret && syncTjp) { syncDelegateSecret = derived; await this.persistDelegateSecret({ delegateTjpAddr: syncTjp, delegateSecret: derived, role: KEYSTONE_ROLE_SYNC_DELEGATE, }); } } return { hasIdentity: true, genesisPrimaryKeystone, primaryKeystone, primaryTjpAddr, authorDelegateKeystone, authorDelegateSecret, syncDelegateKeystone, syncDelegateSecret, username, siteUsername, deviceName: this.getDefaultDeviceTag(), }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); return { hasIdentity: false }; } } /** * Clears local persisted delegate credentials. */ public async logoutDeviceIdentity(): Promise { await this.clearPersistedDelegateSecrets(); } // #endregion }