Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions KeeperSdk/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "keeper-sdk",
"version": "1.0.0",
"description": "High-level wrapper for Keeper Security JavaScript SDK",
"main": "src/index.ts",
"scripts": {
"build": "tsc",
"clean": "rm -rf dist",
"link-local": "npm link ../keeperapi",
"format": "prettier --write .",
"format:check": "prettier --check .",
"test": "jest",
"types": "tsc --watch",
"types:ci": "tsc"
},
"dependencies": {
"@keeper-security/keeperapi": "17.1.0",
"@types/node": "^20.9.1",
"ts-node": "^10.7.0",
"typescript": "^4.6.3"
}
}
157 changes: 157 additions & 0 deletions KeeperSdk/src/auth/ConsoleAuthUI.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import readline from 'readline/promises'
import { setTimeout as delay } from 'timers/promises'
import type { AuthUI3, DeviceApprovalChannel, TwoFactorChannelData } from '@keeper-security/keeperapi'
import { Authentication } from '@keeper-security/keeperapi'
import { logger, extractErrorMessage, KeeperSdkError, AuthDefaults, ResultCodes } from '../utils'

export class ConsoleAuthUI implements AuthUI3 {
private static readonly DEVICE_VERIFICATION = {
Email: 0,
KeeperPush: 1,
TFA: 2,
AdminApproval: 3,
} as const

private static channelName(channel: number): string {
switch (channel) {
case ConsoleAuthUI.DEVICE_VERIFICATION.Email:
return 'Email Verification'
case ConsoleAuthUI.DEVICE_VERIFICATION.KeeperPush:
return 'Keeper Push'
case ConsoleAuthUI.DEVICE_VERIFICATION.TFA:
return 'Two-Factor Authentication'
case ConsoleAuthUI.DEVICE_VERIFICATION.AdminApproval:
return 'Admin Approval'
default:
return `Channel ${channel}`
}
}

private static twoFactorChannelName(channelType: Authentication.TwoFactorChannelType): string {
switch (channelType) {
case Authentication.TwoFactorChannelType.TWO_FA_CT_TOTP:
return 'Authenticator App (TOTP)'
case Authentication.TwoFactorChannelType.TWO_FA_CT_SMS:
return 'SMS'
case Authentication.TwoFactorChannelType.TWO_FA_CT_DUO:
return 'Duo Security'
case Authentication.TwoFactorChannelType.TWO_FA_CT_RSA:
return 'RSA SecurID'
case Authentication.TwoFactorChannelType.TWO_FA_CT_DNA:
return 'Keeper DNA'
case Authentication.TwoFactorChannelType.TWO_FA_CT_U2F:
return 'U2F Security Key'
case Authentication.TwoFactorChannelType.TWO_FA_CT_WEBAUTHN:
return 'WebAuthn Security Key'
case Authentication.TwoFactorChannelType.TWO_FA_CT_KEEPER:
return 'Keeper'
default:
throw new KeeperSdkError(`Unsupported 2FA channel type: ${channelType}`, ResultCodes.UNSUPPORTED_2FA_CHANNEL)
}
}

private static async waitWithCancel(timeoutMs: number, cancel?: Promise<void>): Promise<void> {
if (!cancel) {
await delay(timeoutMs)
return
}
await Promise.race([delay(timeoutMs), cancel])
}

public async waitForDeviceApproval(channels: DeviceApprovalChannel[], isCloud: boolean): Promise<boolean> {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })

try {
logger.info('\n--- Device Approval Required ---')
logger.info('This device needs to be approved before you can log in.')
logger.info('Available verification methods:')
channels.forEach((ch, i) => {
logger.info(` ${i + 1}. ${ConsoleAuthUI.channelName(ch.channel)}`)
})

const choice = (await rl.question('\nSelect method (number): ')).trim()
const idx = parseInt(choice, 10) - 1

if (isNaN(idx) || idx < 0 || idx >= channels.length) {
logger.warn('Invalid selection, cancelling.')
return false
}

const selected = channels[idx]
logger.info(`\nSending ${ConsoleAuthUI.channelName(selected.channel)} request...`)
await selected.sendApprovalRequest()

if (selected.validateCode) {
const code = (await rl.question('Enter verification code: ')).trim()
if (!code) return false
await selected.validateCode(code)
} else {
logger.info('Approval request sent. Waiting for approval on your other device...')
await ConsoleAuthUI.waitWithCancel(AuthDefaults.APPROVAL_TIMEOUT_MS)
}

return true
} catch (e) {
logger.error('Device approval error:', extractErrorMessage(e))
return false
} finally {
rl.close()
}
}

public async waitForTwoFactorCode(channels: TwoFactorChannelData[], cancel: Promise<void>): Promise<boolean> {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })

try {
logger.info('\n--- Two-Factor Authentication Required ---')
logger.info('Available 2FA methods:')
channels.forEach((ch, i) => {
const name = ConsoleAuthUI.twoFactorChannelName(ch.channel.channelType!)
logger.info(` ${i + 1}. ${name}`)
})

const choice = (await rl.question('\nSelect method (number): ')).trim()
const idx = parseInt(choice, 10) - 1

if (isNaN(idx) || idx < 0 || idx >= channels.length) {
logger.warn('Invalid selection, cancelling.')
return false
}

const selected = channels[idx]
const name = ConsoleAuthUI.twoFactorChannelName(selected.channel.channelType!)

if (selected.availablePushes && selected.availablePushes.length > 0) {
const pushChoice = (await rl.question(`Send push notification for ${name}? (y/n): `)).trim()
if (pushChoice.toLowerCase() === 'y' && selected.sendPush) {
selected.sendPush(selected.availablePushes[0])
logger.info('Push sent. Waiting for approval...')
await ConsoleAuthUI.waitWithCancel(AuthDefaults.APPROVAL_TIMEOUT_MS, cancel)
return true
}
}

const code = (await rl.question(`Enter ${name} code: `)).trim()
if (!code) return false

selected.sendCode(code)
await ConsoleAuthUI.waitWithCancel(AuthDefaults.CODE_VALIDATION_DELAY_MS, cancel)
return true
} catch (e) {
logger.error('2FA error:', extractErrorMessage(e))
return false
} finally {
rl.close()
}
}

public async getPassword(isAlternate: boolean): Promise<string> {
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
try {
const label = isAlternate ? 'alternate master password' : 'master password'
return (await rl.question(`Enter your ${label}: `)).trim()
} finally {
rl.close()
}
}
}
Loading
Loading