OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-identity / lib / auth / providers / keet-identity.js

63 lines · javascript ref:
import { BaseProvider } from '../base-provider.js'

/**
 * KeetIdentityProvider — BIP39 mnemonic-based authentication
 *
 * Uses keet-identity-key for mnemonic → identity keypair verification.
 */
export class KeetIdentityProvider extends BaseProvider {
  constructor (identityRegistry, opts = {}) {
    super('keet-identity')
    this.registry = identityRegistry
    this._IdentityKey = opts.IdentityKey || null
  }

  async extractCredentials (req) {
    const identityProof = req.headers['x-identity-proof']
    if (!identityProof) return null

    try {
      const proof = JSON.parse(identityProof)
      return { proof }
    } catch {
      return null
    }
  }

  async authenticate (credentials) {
    if (!this._IdentityKey) throw new Error('keet-identity-key not configured')

    const { proof } = credentials

    // Verify proof chain
    const verified = this._IdentityKey.verify(proof)
    if (!verified) throw new Error('Invalid identity proof')

    const publicKey = proof.publicKey || proof.identityPublicKey
    if (!publicKey) throw new Error('No public key in proof')

    // Look up identity
    let identity = await this.registry.getIdentityByPublicKey(publicKey)

    if (!identity) {
      // Auto-register
      const identityId = publicKey
      await this.registry.registerIdentity({
        identityId,
        method: 'keet-identity',
        publicKey,
        createdAt: Date.now()
      })
      identity = { identityId, method: 'keet-identity', publicKey }
    }

    return {
      identityId: identity.identityId,
      method: 'keet-identity',
      credentials: { publicKey, proof }
    }
  }
}

export default KeetIdentityProvider