import { namelib } from 'buckyos/node' import { type Environment, readEnvironment, type ResolvedConfig } from './config.ts' import { EXIT_AUTH, EXIT_PERMISSION, ToolError, UsageError } from './errors.ts' import { getHost, isHostError } from '../runtime/host.ts' const join = (...parts: string[]) => getHost().path.join(...parts) const LOCAL_NODE_GATEWAY_ENDPOINT = 'http://127.0.0.1:3180' export interface IdentityMaterial { did: string subject: string issuer: string principalKind: 'user' | 'device' publicRoot: string securityRoot: string documentPath: string privateKeyPath: string privateKeyPem: string source: IdentityRootPair['source'] } export interface IdentityRootPair { publicRoot: string securityRoot: string source: 'buckyos-home' | 'buckycli-home' | 'current-device' } export interface IdentityRootOptions { includeOperations?: boolean includeDeveloper?: boolean } export const IDENTITY_CANDIDATE_LIMIT = 8 export const IDENTITY_REJECTION_CODES = Object.freeze([ 'IDENTITY_KIND_NOT_ACCEPTED', 'AUTHENTICATION_REJECTED', ]) export interface IdentityCandidate { material: IdentityMaterial source: IdentityRootPair['source'] directory: string } export interface IdentityCandidateScan { order: readonly IdentityRootPair['source'][] limit: number candidates: IdentityCandidate[] skipped: Array<{ source: IdentityRootPair['source'] identity?: string path: string reason: string }> } export async function applyImplicitDeviceIdentity( config: ResolvedConfig, environment: Environment = readEnvironment(), ): Promise { if ( config.sessionToken || config.sessionTokenFile || config.identity || config.zone || config.endpoint ) { return config } const device = await readCurrentDeviceIdentity(environment) if (!device) return config return { ...config, identity: device.did, zone: device.zoneDid, endpoint: LOCAL_NODE_GATEWAY_ENDPOINT, identityRoot: device.publicRoot, securityRoot: device.securityRoot, defaultProtocol: 'http://', implicitDeviceIdentity: device, sources: { ...config.sources, identity: 'current-device', zone: 'current-device', endpoint: 'local-node-gateway', identity_root: 'current-device', security_root: 'current-device', }, } } export async function readCurrentDeviceIdentity( environment: Environment = readEnvironment(), ): Promise | undefined> { if ( getHost().policy.distribution === 'developer' && environment.BUCKYOS_ROOT === undefined ) return undefined const buckyosRoot = environment.BUCKYOS_ROOT ?? defaultBuckyOSRoot(environment) const nodeIdentityPath = join(buckyosRoot, 'etc', 'node_identity.json') let value: unknown try { value = JSON.parse(await getHost().readTextFile(nodeIdentityPath)) } catch (error) { if (isHostError(error, 'NotFound')) return undefined if (isHostError(error, 'PermissionDenied')) { throw new ToolError( 'DEVICE_IDENTITY_READ_FAILED', `permission denied reading current device identity: ${nodeIdentityPath}`, EXIT_PERMISSION, ) } throw new ToolError( 'DEVICE_IDENTITY_READ_FAILED', `failed to read current device identity: ${nodeIdentityPath}`, EXIT_AUTH, ) } if (!value || typeof value !== 'object' || Array.isArray(value)) { throw invalidDeviceIdentity(nodeIdentityPath) } const document = value as Record const did = nonEmptyString(document.device_did) const name = nonEmptyString(document.device_name) const zoneDid = nonEmptyString(document.zone_did) if (document.schema !== 'buckyos.node_identity.v2' || !did || !name || !zoneDid) { throw invalidDeviceIdentity(nodeIdentityPath) } try { namelib.DID.fromStr(did) namelib.DID.fromStr(zoneDid) } catch { throw invalidDeviceIdentity(nodeIdentityPath) } return { did, name, zoneDid, buckyosRoot, nodeIdentityPath, publicRoot: join(buckyosRoot, 'local', 'identity'), securityRoot: join(buckyosRoot, 'security'), } } export function identityRootPairs( config: ResolvedConfig, environment: Environment = readEnvironment(), options: IdentityRootOptions = {}, ): IdentityRootPair[] { const device = config.implicitDeviceIdentity if (device) { return [{ publicRoot: device.publicRoot, securityRoot: device.securityRoot, source: 'current-device', }] } const home = environment.HOME ?? environment.USERPROFILE ?? getHost().homeDir() const pairs: IdentityRootPair[] = [] if (options.includeOperations ?? true) { pairs.push({ publicRoot: join(home, '.buckyos', 'local', 'identity'), securityRoot: join(home, '.buckyos', 'security'), source: 'buckyos-home', }) } if (options.includeDeveloper ?? false) { pairs.push({ publicRoot: join(home, '.buckycli', 'local', 'identity'), securityRoot: join(home, '.buckycli', 'security'), source: 'buckycli-home', }) } return deduplicatePairs(pairs) } export async function resolveIdentityMaterial( selectedIdentity: string, config: ResolvedConfig, environment: Environment = readEnvironment(), options: IdentityRootOptions = {}, ): Promise { const selected = selectedIdentity.trim() if (!selected) throw new UsageError('IDENTITY_REQUIRED', 'identity is empty') for (const roots of identityRootPairs(config, environment, options)) { for (const directory of await candidateDirectories(roots.publicRoot, selected)) { const material = await loadIdentityMaterial(roots, directory, selected) if (material) return material } } throw new ToolError( 'IDENTITY_NOT_FOUND', `no usable authentication material found for identity ${selected}`, EXIT_AUTH, ) } export async function scanIdentityCandidates( config: ResolvedConfig, environment: Environment = readEnvironment(), options: IdentityRootOptions = {}, ): Promise { const candidates: IdentityCandidate[] = [] const skipped: IdentityCandidateScan['skipped'] = [] const seen = new Set() const roots = identityRootPairs(config, environment, options) for (const pair of roots) { let directories: string[] try { directories = await candidateDirectories(pair.publicRoot, '') } catch (error) { if (isHostError(error, 'PermissionDenied')) { skipped.push({ source: pair.source, path: pair.publicRoot, reason: 'policy-denied' }) continue } throw error } for (const directory of directories) { if (candidates.length >= IDENTITY_CANDIDATE_LIMIT) break const documentPath = join(pair.publicRoot, directory, 'did.json') try { const material = await loadIdentityMaterial(pair, directory) if (!material) { skipped.push({ source: pair.source, path: documentPath, reason: 'not-usable' }) continue } if (seen.has(material.did)) { skipped.push({ source: pair.source, identity: material.did, path: documentPath, reason: 'duplicate', }) continue } seen.add(material.did) candidates.push({ material, source: pair.source, directory }) } catch (error) { if (isHostError(error, 'PermissionDenied')) { skipped.push({ source: pair.source, path: documentPath, reason: 'policy-denied' }) continue } if (error instanceof ToolError && error.code === 'IDENTITY_KEYREF_UNSUPPORTED') { skipped.push({ source: pair.source, identity: typeof error.details.identity === 'string' ? error.details.identity : undefined, path: documentPath, reason: 'key-reference-unsupported', }) continue } throw error } } if (candidates.length >= IDENTITY_CANDIDATE_LIMIT) break } return { order: Object.freeze(roots.map((pair) => pair.source)), limit: IDENTITY_CANDIDATE_LIMIT, candidates, skipped, } } export async function identityCandidateView( config: ResolvedConfig, environment: Environment = readEnvironment(), developerModeEnabled = false, ): Promise> { if (config.identity) { try { const material = await resolveIdentityMaterial(config.identity, config, environment, { includeDeveloper: developerModeEnabled, }) return { mode: 'explicit', order: [material.did], limit: 1, candidates: [{ identity: material.did, source: config.sources.identity ?? 'explicit', document_path: material.documentPath, }], skipped: [], } } catch (error) { return { mode: 'explicit', order: [config.identity], limit: 1, candidates: [], skipped: [{ identity: config.identity, reason: error instanceof ToolError ? error.code : 'unavailable', }], } } } const scan = await scanIdentityCandidates(config, environment, { includeDeveloper: developerModeEnabled, }) return { mode: 'search', order: scan.order, limit: scan.limit, candidates: scan.candidates.map((candidate) => ({ identity: candidate.material.did, source: candidate.source, document_path: candidate.material.documentPath, })), skipped: scan.skipped, } } async function loadIdentityMaterial( roots: IdentityRootPair, directory: string, selected?: string, ): Promise { const documentPath = join(roots.publicRoot, directory, 'did.json') const document = await readIdentityDocument(documentPath) if (!document || selected && !identityMatches(document, selected)) return undefined const did = typeof document.id === 'string' ? document.id : '' const subject = typeof document.name === 'string' && document.name.trim() ? document.name.trim() : did if (!did || !subject) return undefined const privateKeyPath = join(roots.securityRoot, directory, 'authentication.private.pem') try { const privateKeyPem = (await getHost().readTextFile(privateKeyPath)).trim() if (!privateKeyPem) return undefined return { did, subject, issuer: subject, principalKind: typeof document.device_type === 'string' ? 'device' : 'user', publicRoot: roots.publicRoot, securityRoot: roots.securityRoot, documentPath, privateKeyPath, privateKeyPem, source: roots.source, } } catch (error) { if (!isHostError(error, 'NotFound')) throw error } const keyrefPath = join(roots.securityRoot, directory, 'authentication.keyref.json') try { await getHost().stat(keyrefPath) throw new ToolError( 'IDENTITY_KEYREF_UNSUPPORTED', 'the selected identity uses a key reference unsupported by this runtime', EXIT_AUTH, false, { identity: did, keyref_path: keyrefPath }, ) } catch (error) { if (!isHostError(error, 'NotFound')) throw error } return undefined } async function candidateDirectories(publicRoot: string, identity: string): Promise { if (identity.startsWith('did:')) { try { return [namelib.DID.fromStr(identity).toFilename()] } catch { throw new UsageError('INVALID_IDENTITY', `invalid DID: ${identity}`) } } const directories: string[] = [] try { for (const entry of await getHost().readDir(publicRoot)) { if (entry.isDirectory) directories.push(entry.name) } } catch (error) { if (isHostError(error, 'NotFound')) return [] throw error } return directories.sort() } async function readIdentityDocument(path: string): Promise | null> { try { const value = JSON.parse(await getHost().readTextFile(path)) as unknown return value && typeof value === 'object' && !Array.isArray(value) ? value as Record : null } catch (error) { if (isHostError(error, 'NotFound') || error instanceof SyntaxError) return null throw error } } function identityMatches(document: Record, selected: string): boolean { if (typeof document.id === 'string' && document.id === selected) return true return typeof document.name === 'string' && document.name === selected } export function defaultBuckyOSRoot(environment: Environment = readEnvironment()): string { if (getHost().platform === 'windows') { const appData = environment.APPDATA return appData ? join(appData, 'buckyos') : 'C:\\BuckyOS' } return '/opt/buckyos' } function invalidDeviceIdentity(path: string): ToolError { return new ToolError( 'INVALID_DEVICE_IDENTITY', `current device identity is invalid: ${path}`, EXIT_AUTH, ) } function nonEmptyString(value: unknown): string | undefined { return typeof value === 'string' && value.trim() ? value.trim() : undefined } function deduplicatePairs(pairs: IdentityRootPair[]): IdentityRootPair[] { const seen = new Set() return pairs.filter((pair) => { const key = `${pair.publicRoot}\0${pair.securityRoot}` if (seen.has(key)) return false seen.add(key) return true }) }