cp.nvim/lua/cp/credentials.lua
Barrett Ruth 06f5e24ebc
feat(credentials): validate login via scraper before caching
Problem: `credentials.lua` cached username/password immediately on
input without any server-side validation. `scraper.lua` only used the
browser/FHS path for the `submit` subcommand.

Solution: rewrite `M.login()` to call `scraper.login()` with ndjson
status callbacks and only cache credentials on success. Generalize the
four submit-only guards in `run_scraper` to a `needs_browser` flag
covering both `submit` and `login` subcommands.
2026-03-05 15:00:38 -05:00

85 lines
2.4 KiB
Lua

local M = {}
local cache = require('cp.cache')
local constants = require('cp.constants')
local logger = require('cp.log')
local state = require('cp.state')
local STATUS_MESSAGES = {
checking_login = 'Checking existing session...',
logging_in = 'Logging in...',
installing_browser = 'Installing browser...',
}
function M.login(platform)
platform = platform or state.get_platform()
if not platform then
logger.log(
'No platform specified. Usage: :CP <platform> login',
{ level = vim.log.levels.ERROR }
)
return
end
local display = constants.PLATFORM_DISPLAY_NAMES[platform] or platform
vim.ui.input({ prompt = platform .. ' username: ' }, function(username)
if not username or username == '' then
logger.log('Cancelled', { level = vim.log.levels.WARN })
return
end
vim.fn.inputsave()
local password = vim.fn.inputsecret(platform .. ' password: ')
vim.fn.inputrestore()
if not password or password == '' then
logger.log('Cancelled', { level = vim.log.levels.WARN })
return
end
cache.load()
local existing = cache.get_credentials(platform) or {}
local credentials = {
username = username,
password = password,
}
if existing.token then
credentials.token = existing.token
end
local scraper = require('cp.scraper')
scraper.login(platform, credentials, function(ev)
vim.schedule(function()
local msg = STATUS_MESSAGES[ev.status] or ev.status
logger.log(display .. ': ' .. msg, { level = vim.log.levels.INFO, override = true })
end)
end, function(result)
vim.schedule(function()
if result.success then
logger.log(
display .. ' login successful',
{ level = vim.log.levels.INFO, override = true }
)
else
local err = result.error or 'unknown error'
logger.log(display .. ' login failed: ' .. err, { level = vim.log.levels.ERROR })
end
end)
end)
end)
end
function M.logout(platform)
platform = platform or state.get_platform()
if not platform then
logger.log(
'No platform specified. Usage: :CP <platform> logout',
{ level = vim.log.levels.ERROR }
)
return
end
cache.load()
cache.clear_credentials(platform)
logger.log(platform .. ' credentials cleared', { level = vim.log.levels.INFO, override = true })
end
return M