bitwarden.el 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. ;;; bitwarden.el --- Bitwarden command wrapper -*- lexical-binding: t -*-
  2. ;; Copyright (C) 2018 Sean Farley
  3. ;; Author: Sean Farley
  4. ;; URL: https://github.com/seanfarley/emacs-bitwarden
  5. ;; Version: 0.1.3
  6. ;; Created: 2018-09-04
  7. ;; Package-Requires: ((emacs "25.1"))
  8. ;; Keywords: extensions processes bw bitwarden
  9. ;;; License
  10. ;; This program is free software: you can redistribute it and/or modify
  11. ;; it under the terms of the GNU General Public License as published by
  12. ;; the Free Software Foundation, either version 3 of the License, or
  13. ;; (at your option) any later version.
  14. ;; This program is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. ;; GNU General Public License for more details.
  18. ;; You should have received a copy of the GNU General Public License
  19. ;; along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. ;;; Commentary:
  21. ;; This package wraps the bitwarden command-line program.
  22. ;;; Code:
  23. (require 'auth-source)
  24. (require 'json)
  25. (require 'seq)
  26. (require 'subr-x)
  27. (require 'tree-widget)
  28. ;=============================== custom variables ==============================
  29. (defgroup bitwarden nil
  30. "Bitwarden functions and settings."
  31. :group 'external
  32. :tag "bitwarden"
  33. :prefix "bitwarden-")
  34. (defcustom bitwarden-bw-executable (executable-find "bw")
  35. "The bw cli executable used by Bitwarden."
  36. :group 'bitwarden
  37. :type 'string)
  38. (defcustom bitwarden-data-file
  39. (expand-file-name "Bitwarden CLI/data.json"
  40. (cond
  41. ((getenv "BITWARDENCLI_APPDATA_DIR")
  42. (getenv "BITWARDENCLI_APPDATA_DIR"))
  43. ((eq system-type 'darwin)
  44. "~/Library/Application Support")
  45. ((eq system-type 'windows-nt)
  46. (getenv "APPDATA"))
  47. ((getenv "XDG_CONFIG_HOME")
  48. (getenv "XDG_CONFIG_HOME"))
  49. (t
  50. "~/.config")))
  51. "The bw data file used by Bitwarden."
  52. :group 'bitwarden
  53. :type 'string)
  54. (defcustom bitwarden-user nil
  55. "Bitwarden user e-mail."
  56. :group 'bitwarden
  57. :type 'string)
  58. (defcustom bitwarden-automatic-unlock nil
  59. "Optional function to be called to attempt to unlock the vault.
  60. Set this to a function that will evaluate to a password. For
  61. example, this can be the :secret plist from
  62. `auth-source-search'."
  63. :group 'bitwarden
  64. :type 'function)
  65. (defcustom bitwarden-api-secret-key nil
  66. "Optional function to be called to return API secret key.
  67. Set this to a function that will evaluate to a string (the API secret key)."
  68. :group 'bitwarden
  69. :type 'function)
  70. (defcustom bitwarden-api-client-id nil
  71. "Optional function to be called to return the API client id..
  72. Set this to a function that will evaluate to a string (the API client id)."
  73. :group 'bitwarden
  74. :type 'function)
  75. (defconst bitwarden--err-logged-in "you are not logged in")
  76. (defconst bitwarden--err-multiple "more than one result found")
  77. (defconst bitwarden--err-locked "vault is locked")
  78. (defconst bitwarden--err-unknown "unrecognized bw error: "
  79. "Prefix marking a `bw' failure that does not match a known error string.
  80. `bitwarden-runcmd' prepends this so `bitwarden--auto-cmd' can still tell the
  81. result apart from a successful command, while keeping the raw `bw' output
  82. attached for diagnosis.")
  83. ;===================================== util ====================================
  84. (defun bitwarden-logged-in-p ()
  85. "Check if `bitwarden-user' is logged in.
  86. Returns nil if not logged in."
  87. (let* ((ret (apply #'bitwarden--raw-runcmd "login" '("--check")))
  88. (exit-code (nth 0 ret)))
  89. (eq exit-code 0)))
  90. (defun bitwarden-unlocked-p ()
  91. "Check if `bitwarden-user' is loged in.
  92. Returns nil if not unlocked."
  93. (let* ((ret (apply #'bitwarden--raw-runcmd "unlock" '("--check")))
  94. (exit-code (nth 0 ret)))
  95. (eq exit-code 0)))
  96. (defun bitwarden--raw-runcmd (cmd &rest args)
  97. "Run bw command CMD with ARGS.
  98. Returns a list with the first element being the exit code and the
  99. second element being the output."
  100. (with-temp-buffer
  101. (list (apply 'call-process
  102. bitwarden-bw-executable
  103. nil ;; input
  104. (list
  105. (current-buffer) ;; stdout
  106. t) ;; merge stderr into stdout so callers see the real bw error text
  107. nil ;; re-display buffer
  108. (cons cmd args))
  109. (replace-regexp-in-string "\n$" ""
  110. (buffer-string)))))
  111. (defun bitwarden-runcmd (cmd &rest args)
  112. "Run bw command CMD with ARGS.
  113. This is a wrapper for `bitwarden--raw-runcmd' that also checks
  114. for common errors."
  115. (if (bitwarden-logged-in-p)
  116. (if (bitwarden-unlocked-p)
  117. (let* ((ret (apply #'bitwarden--raw-runcmd cmd args))
  118. (exit-code (nth 0 ret))
  119. (output (nth 1 ret)))
  120. (if (eq exit-code 0)
  121. output
  122. (cond ((string-match "^More than one result was found." output)
  123. bitwarden--err-multiple)
  124. (t (concat bitwarden--err-unknown output)))))
  125. bitwarden--err-locked)
  126. bitwarden--err-logged-in))
  127. (defun bitwarden--login-proc-filter (proc string print-message)
  128. "Interacts with PROC by sending line-by-line STRING.
  129. If PRINT-MESSAGE is set then messages are printed to minibuffer."
  130. ;; read username if not defined
  131. (when (string-match "^? Email address:" string)
  132. (let ((user (read-string "Bitwarden email: ")))
  133. ;; if we are here then the user forgot to fill in this field so let's do
  134. ;; that now
  135. (setq bitwarden-user user)
  136. (process-send-string proc (concat bitwarden-user "\n"))))
  137. ;; read master password
  138. (when (string-match "^? Master password:.*" string)
  139. (process-send-string
  140. proc (concat (read-passwd "Bitwarden master password: ") "\n")))
  141. ;; check for bad password
  142. (when (string-match "^Username or password is incorrect" string)
  143. (bitwarden--message "incorrect master password" nil print-message))
  144. ;; if trying to unlock, check if logged in
  145. (when (string-match "^You are not logged in" string)
  146. (bitwarden--message "cannot unlock: not logged in" nil print-message))
  147. ;; read the 2fa code
  148. (when (string-match "^? Two-step login code:" string)
  149. (process-send-string
  150. proc (concat (read-passwd "Bitwarden two-step login code: ") "\n")))
  151. ;; check for bad code
  152. (when (string-match "^Login failed" string)
  153. (bitwarden--message "incorrect two-step code" nil print-message))
  154. ;; check for already logged in
  155. (when (string-match "^You are already logged in" string)
  156. (string-match "You are already logged in as \\(.*\\)\\." string)
  157. (bitwarden--message
  158. "already logged in as %s" (match-string 1 string) print-message))
  159. ;; success! now save the BW_SESSION into the environment so spawned processes
  160. ;; inherit it
  161. (when (string-match "^\\(You are logged in\\|Your vault is now unlocked\\)"
  162. string)
  163. ;; set the session env variable so spawned processes inherit
  164. (string-match "export BW_SESSION=\"\\(.*\\)\"" string)
  165. (setenv "BW_SESSION" (match-string 1 string))
  166. (bitwarden--message
  167. "successfully logged in as %s" bitwarden-user print-message)))
  168. (defun bitwarden--raw-unlock (cmd print-message)
  169. "Raw CMD to either unlock a vault or login.
  170. The only difference between unlock and login is just the name of
  171. the command and whether to pass the user.
  172. If PRINT-MESSAGE is set then messages are printed to minibuffer."
  173. (when (get-process "bitwarden")
  174. (delete-process "bitwarden"))
  175. (make-process :name "bitwarden"
  176. :buffer nil
  177. :connection-type 'pipe
  178. :command (append (list bitwarden-bw-executable)
  179. cmd)
  180. :filter (lambda (proc string)
  181. (bitwarden--login-proc-filter
  182. proc string print-message)))
  183. ;; suppress output to the minibuffer when running this programatically
  184. nil)
  185. ;================================= interactive =================================
  186. (defun bitwarden-unlock (&optional print-message)
  187. "Unlock bitwarden vault.
  188. It is not sufficient to check the env variable for BW_SESSION
  189. since that could be set yet could be expired or incorrect.
  190. If run interactively PRINT-MESSAGE gets set and messages are
  191. printed to minibuffer."
  192. (interactive "p")
  193. (let ((pass (if bitwarden-automatic-unlock
  194. (funcall bitwarden-automatic-unlock)
  195. "")))
  196. (bitwarden--raw-unlock (list "unlock" pass) print-message)))
  197. ;;;###autoload
  198. (defun bitwarden-login (&optional print-message)
  199. "Prompt user for password if not logged in.
  200. If run interactively PRINT-MESSAGE gets set and messages are
  201. printed to minibuffer."
  202. (interactive "p")
  203. (if (and bitwarden-api-client-id bitwarden-api-secret-key)
  204. (progn
  205. (setenv "BW_CLIENTID" (funcall bitwarden-api-client-id))
  206. (setenv "BW_CLIENTSECRET" (funcall bitwarden-api-secret-key))
  207. (bitwarden--raw-unlock (list "login") print-message))
  208. (unless bitwarden-user
  209. (setq bitwarden-user (read-string "Bitwarden email: ")))
  210. (let ((pass (if bitwarden-automatic-unlock
  211. (funcall bitwarden-automatic-unlock)
  212. "")))
  213. (bitwarden--raw-unlock (list "login" bitwarden-user pass "--method" "3") print-message))))
  214. (defun bitwarden-lock ()
  215. "Lock the bw vault. Does not ask for confirmation."
  216. (interactive)
  217. (bitwarden-runcmd "lock")
  218. (setenv "BW_SESSION" nil))
  219. (defun bitwarden-logout ()
  220. "Log out bw. Does not ask for confirmation."
  221. (interactive)
  222. (when (bitwarden-logged-in-p)
  223. (bitwarden-runcmd "logout")
  224. (bitwarden-lock)))
  225. (defun bitwarden--message (msg args &optional print-message)
  226. "Print MSG using `message' and `format' with ARGS if non-nil.
  227. PRINT-MESSAGE is an optional parameter to control whether this
  228. method should print at all. If nil then nothing will be printed
  229. at all.
  230. This method will prepend \='Bitwarden: \=' before each MSG as a
  231. convenience. Also, return a value of nil so that no strings
  232. are mistaken as a password (e.g. accidentally interpreting
  233. \='Bitwarden: error\=' as the password when in fact, it was an error
  234. message but happens to be last on the method stack)."
  235. (when print-message
  236. (let ((msg (if args (format msg args) msg)))
  237. (message (concat "Bitwarden: " msg))))
  238. nil)
  239. (defun bitwarden--handle-message (msg &optional print-message)
  240. "Handle return MSG of `bitwarden--auto-cmd'.
  241. Since `bitwarden--auto-cmd' returns a list of (err-code message),
  242. this function exists to handle that.
  243. If the error code is 0, then print the password based on
  244. PRINT-MESSAGE or just return it.
  245. If the error code is non-zero, signal a `user-error' naming the underlying
  246. cause instead of returning nil. A silent nil here is indistinguishable from
  247. a genuinely empty result (e.g. no matching vault items), which previously let
  248. a locked vault or a failed automatic unlock masquerade as \"nothing found\"
  249. all the way up through `bitwarden-search' and any `auth-source' caller built
  250. on it. `user-error' reports cleanly both interactively (echo area, no
  251. debugger) and non-interactively (e.g. `emacsclient --eval', which surfaces it
  252. as `*ERROR*: ...' to the calling process).
  253. PRINT-MESSAGE is an optional parameter to control whether this
  254. method should print at all. If nil then nothing will be printed
  255. at all but password will be returned (e.g. when run
  256. non-interactively)."
  257. (let* ((err (nth 0 msg))
  258. (pass (nth 1 msg)))
  259. (if (eq err 0)
  260. (if print-message
  261. (message "%s" pass)
  262. pass)
  263. (user-error "Bitwarden: %s" (or pass "unknown error")))))
  264. (defun bitwarden--auto-cmd (cmd &optional retried)
  265. "Run Bitwarden CMD, retrying once via automatic unlock if the vault is locked.
  266. RETRIED is non-nil only on the internal retry call, and prevents a second
  267. retry so a lock that automatic unlock cannot clear is reported instead of
  268. recursing forever. Do not pass it when calling this directly; it used to
  269. double as the retry's pre-computed result, which meant a lock still present
  270. after the retry fell through every branch below and returned nil instead of
  271. an error tuple, indistinguishable downstream from an empty search result.
  272. Returns a tuple of the error code and the error message or password if
  273. successful; never nil."
  274. (let* ((res (apply #'bitwarden-runcmd cmd)))
  275. (cond
  276. ((string-match bitwarden--err-locked res)
  277. (cond
  278. ;; no automatic unlock configured: report the lock directly
  279. ((not bitwarden-automatic-unlock)
  280. (list 1 (format "error: %s" res)))
  281. ;; already retried once and still locked: automatic unlock failed
  282. (retried
  283. (list 1 "error: vault is still locked after automatic unlock"))
  284. (t
  285. ;; because I don't understand how emacs is asyncronous here nor
  286. ;; how to tell it to wait until the process is done, we do so here
  287. ;; manually
  288. (bitwarden-unlock)
  289. (while (get-process "bitwarden")
  290. (sleep-for 0.1))
  291. (bitwarden--auto-cmd cmd t))))
  292. ((or (string-match bitwarden--err-logged-in res)
  293. (string-match bitwarden--err-multiple res))
  294. (list 2 (format "error: %s" res)))
  295. ((string-match bitwarden--err-unknown res)
  296. (list 1 (format "error: %s" res)))
  297. (t (list 0 res)))))
  298. ;;;###autoload
  299. (defun bitwarden-getpass (account &optional print-message)
  300. "Get password associated with ACCOUNT.
  301. If run interactively PRINT-MESSAGE gets set and password is
  302. printed to minibuffer."
  303. (interactive "Bitwarden account name: \np")
  304. (bitwarden--handle-message
  305. (bitwarden--auto-cmd (list "get" "password" account))
  306. print-message))
  307. ;;;###autoload
  308. (defun bitwarden-search (&optional search-str)
  309. "Search for vault for items containing SEARCH-STR.
  310. Returns a vector of hashtables of the results."
  311. (let* ((args (and search-str (list "--search" search-str)))
  312. (ret (bitwarden--auto-cmd (append (list "list" "items") args)))
  313. (result (bitwarden--handle-message ret)))
  314. (when result
  315. (let* ((json-object-type 'hash-table)
  316. (json-key-type 'string)
  317. (json (json-read-from-string result)))
  318. json))))
  319. ;;;###autoload
  320. (defun bitwarden-get-info-by-id (id)
  321. "The id can be found using the bitwarden CLI, e.g. `bw list items --pretty'.
  322. To access the account password: `(gethash \"password\" (gethash \"login\" ))'"
  323. (let* ((result (bitwarden--handle-message (bitwarden--auto-cmd (list "get" "item" id)))))
  324. (when result
  325. (let* ((json-object-type 'hash-table)
  326. (json-key-type 'string)
  327. (json (json-read-from-string result)))
  328. (json-read-from-string result)))))
  329. (defun bitwarden-folders ()
  330. "List bitwarden folders."
  331. (let* ((ret (bitwarden--auto-cmd (list "list" "folders")))
  332. (result (bitwarden--handle-message ret)))
  333. (when result
  334. (let* ((json-object-type 'hash-table)
  335. (json-key-type 'string)
  336. (json (json-read-from-string result)))
  337. json))))
  338. (defun bitwarden-sync (&optional print-message)
  339. "Sync local store with server."
  340. (interactive)
  341. (let ((res (bitwarden--auto-cmd (list "sync"))))
  342. (bitwarden--message (nth 1 res) nil print-message)))
  343. ;================================= auth-source =================================
  344. (defun bitwarden--users-account-p (account usernames)
  345. "Check if ACCOUNT belongs to any of the given USERNAMES."
  346. (let* ((login (gethash "login" account))
  347. (account-username (when login (gethash "username" login))))
  348. (when account-username
  349. (seq-contains-p usernames account-username #'string=))))
  350. (defun bitwarden--account-login-p (account)
  351. "Check if ACCOUNT has login information."
  352. (gethash "login" account))
  353. (defun bitwarden-auth-source-search (&rest spec)
  354. "Search Bitwarden according to SPEC.
  355. See `auth-source-search' for a description of the plist SPEC."
  356. (let* ((hosts (ensure-list (plist-get spec :host)))
  357. (maxes (ensure-list (plist-get spec :max)))
  358. (users (ensure-list (plist-get spec :user)))
  359. (all-accounts
  360. (if hosts
  361. (seq-mapcat #'bitwarden-search hosts)
  362. (bitwarden-search)))
  363. (login-accounts
  364. (seq-filter #'bitwarden--account-login-p all-accounts))
  365. (users-accounts
  366. (if users
  367. (seq-filter
  368. (lambda (account)
  369. (bitwarden--users-account-p account users))
  370. login-accounts)
  371. login-accounts))
  372. (formatted-results
  373. (seq-map 'bitwarden-auth-source--build-result users-accounts)))
  374. (message "Bitwarden: auth search parameters %s" spec)
  375. (seq-take formatted-results (seq-max maxes))))
  376. (defun bitwarden-auth-source--build-result (account)
  377. "Build a auth-source result for ACCOUNT.
  378. This is meant to be used by `bitwarden-auth-source-search' to format the final
  379. results."
  380. (let* ((host (gethash "name" account))
  381. (login (gethash "login" account)) ;; always present since
  382. ;; `bitwarden-search-filter-username'
  383. ;; tests for it
  384. (user (gethash "username" login))
  385. (pass (gethash "password" login)))
  386. `(:host ,host
  387. :user ,user
  388. :secret (lambda () ,pass))))
  389. (defvar bitwarden-auth-source-backend
  390. (auth-source-backend :type 'bitwarden
  391. :source "." ;; not used
  392. :search-function #'bitwarden-auth-source-search)
  393. "Auth-source backend variable for Bitwarden.")
  394. (defun bitwarden-auth-source-backend-parse (entry)
  395. "Create auth-source backend from ENTRY."
  396. (when (eq entry 'bitwarden)
  397. (auth-source-backend-parse-parameters entry bitwarden-auth-source-backend)))
  398. ;; advice to add custom auth-source function
  399. (if (boundp 'auth-source-backend-parser-functions)
  400. (add-hook 'auth-source-backend-parser-functions
  401. #'bitwarden-auth-source-backend-parse)
  402. (advice-add 'auth-source-backend-parse
  403. :before-until #'bitwarden-auth-source-backend-parse))
  404. ;;;###autoload
  405. (defun bitwarden-auth-source-enable ()
  406. "Enable Bitwarden auth-source by adding it to `auth-sources'."
  407. (interactive)
  408. (add-to-list 'auth-sources 'bitwarden)
  409. (auth-source-forget-all-cached)
  410. (message "Bitwarden: auth-source enabled"))
  411. ;================================= widget utils ================================
  412. (defun bitwarden-list-next ()
  413. "Move to the next item."
  414. (interactive)
  415. (forward-line)
  416. (beginning-of-line)
  417. (widget-forward 1))
  418. (defun bitwarden-list-prev ()
  419. "Move to the previous item."
  420. (interactive)
  421. (widget-backward 2)
  422. (beginning-of-line)
  423. (widget-forward 1))
  424. ;; bitwarden-list-dialog-mode
  425. (defvar bitwarden-list-dialog-mode-map
  426. (let ((map (make-sparse-keymap)))
  427. (set-keymap-parent map widget-keymap)
  428. (define-key map "n" 'bitwarden-list-next)
  429. (define-key map "p" 'bitwarden-list-prev)
  430. (define-key map "q" 'bitwarden-list-cancel-dialog)
  431. map)
  432. "Keymap used in recentf dialogs.")
  433. (define-derived-mode bitwarden-list-dialog-mode nil "bitwarden-list-dialog"
  434. "Major mode of recentf dialogs.
  435. \\{bitwarden-list-dialog-mode-map}"
  436. :syntax-table nil
  437. :abbrev-table nil
  438. (setq truncate-lines t))
  439. (defsubst bitwarden-list-all-get-item-at-pos ()
  440. "Get hashtable from widget at current pos in dialog widget."
  441. (let ((widget (get-char-property (point) 'button)))
  442. (widget-value widget)))
  443. (defsubst bitwarden-list-all-make-spaces (spaces)
  444. "Create a string with SPACES number of whitespaces."
  445. (mapconcat 'identity (make-list spaces " ") ""))
  446. (defsubst bitwarden-pad-to-width (item width)
  447. "Create a string with ITEM padded to WIDTH."
  448. (if (= (length item) width)
  449. item
  450. (if (>= (length item) width)
  451. (concat (substring item 0 (- width 1)) "…")
  452. (concat item (bitwarden-list-all-make-spaces (- width (length item)))))))
  453. ;================================ widget actions ===============================
  454. ;; Dialog settings and actions
  455. (defun bitwarden-list-cancel-dialog (&rest _ignore)
  456. "Cancel the current dialog.
  457. IGNORE arguments."
  458. (interactive)
  459. (kill-buffer (current-buffer))
  460. (bitwarden--message "dialog canceled" nil t))
  461. (defun bitwarden-list-all-kill-ring-save (&optional widget-item)
  462. "Bitwarden `kill-ring-save', insert password to kill ring.
  463. If WIDGET-ITEM is not supplied then look for the widget at the
  464. current point."
  465. (interactive)
  466. (let* ((item (or widget-item
  467. (bitwarden-list-all-get-item-at-pos)))
  468. (type (gethash "type" item))
  469. (login (gethash "login" item)))
  470. (if (not (eq type 1))
  471. (bitwarden--message "error: not a login item" nil t)
  472. (kill-new (gethash "password" login))
  473. (message "Password added to kill ring"))))
  474. (defun bitwarden-list-all-item-action (widget &rest _ignore)
  475. "Do action to element associated with WIDGET's value.
  476. IGNORE other arguments."
  477. (bitwarden-list-all-kill-ring-save (widget-value widget))
  478. (kill-buffer (current-buffer)))
  479. ;=================================== widgets ===================================
  480. (defmacro bitwarden-list-dialog (name &rest forms)
  481. "Show a dialog buffer with NAME, setup with FORMS."
  482. (declare (indent 1) (debug t))
  483. `(with-current-buffer (get-buffer-create ,name)
  484. ;; Cleanup buffer
  485. (let ((inhibit-read-only t)
  486. (ol (overlay-lists)))
  487. (mapc 'delete-overlay (car ol))
  488. (mapc 'delete-overlay (cdr ol))
  489. (erase-buffer))
  490. (bitwarden-list-dialog-mode)
  491. ,@forms
  492. (widget-setup)
  493. (switch-to-buffer (current-buffer))))
  494. (defsubst bitwarden-list-all-make-element (item)
  495. "Create a new cons list from ITEM."
  496. (let* ((folder-id (gethash "folderId" item))
  497. (login-item (gethash "login" item)))
  498. (cons folder-id
  499. (list (cons (concat
  500. (bitwarden-pad-to-width (gethash "name" item) 40)
  501. (bitwarden-pad-to-width
  502. (if login-item (gethash "username" login-item) "")
  503. 32)
  504. (format-time-string
  505. "%Y-%m-%d %T"
  506. (date-to-time (bitwarden-pad-to-width
  507. (gethash "revisionDate" item) 24))))
  508. item)))))
  509. (defun bitwarden-list-all-tree (key val)
  510. "Return a `tree-widget' of folders.
  511. Creates a widget with text KEY and items VAL."
  512. ;; Represent a sub-menu with a tree widget
  513. `(tree-widget
  514. :open t
  515. :match ignore
  516. :node (item :tag ,key
  517. :sample-face bold
  518. :format "%{%t%}\n")
  519. ,@(mapcar 'bitwarden-list-all-item val)))
  520. (defun bitwarden-list-all-item (pass-element)
  521. "Return a widget to display PASS-ELEMENT in a dialog buffer."
  522. ;; Represent a single file with a link widget
  523. `(link :tag ,(car pass-element)
  524. :button-prefix ""
  525. :button-suffix ""
  526. :button-face default
  527. :format "%[%t\n%]"
  528. :help-echo ,(concat "Viewing item " (gethash "id" (cdr pass-element)))
  529. :action bitwarden-list-all-item-action
  530. ,(cdr pass-element)))
  531. (defun bitwarden-list-all-items (items)
  532. "Return a list of widgets to display ITEMS in a dialog buffer."
  533. (let* ((folders (mapcar (lambda (e)
  534. (cons
  535. (gethash "id" e)
  536. (gethash "name" e)))
  537. (bitwarden-folders)))
  538. (hash (make-hash-table :test 'equal)))
  539. ;; create hash table where the keys are the folders and each value is a list
  540. ;; of the password items
  541. (dolist (x (mapcar 'bitwarden-list-all-make-element items))
  542. (let* ((folder-id (car x))
  543. (key (cdr (assoc folder-id folders)))
  544. (val (cdr x))
  545. (klist (gethash key hash)))
  546. (puthash key (append klist val) hash)))
  547. (mapcar (lambda (key)
  548. (bitwarden-list-all-tree key (gethash key hash)))
  549. (sort (hash-table-keys hash) #'string<))))
  550. ;;;###autoload
  551. (defun bitwarden-list-all ()
  552. "Show a dialog, listing all entries associated with `bitwarden-user'.
  553. If optional argument GROUP is given, only entries in GROUP will be listed."
  554. (interactive)
  555. (if (bitwarden-unlocked-p)
  556. (bitwarden-list-dialog "*bitwarden-list*"
  557. ;; Use a L&F that looks like the recentf menu.
  558. (tree-widget-set-theme "folder")
  559. (apply 'widget-create
  560. `(group
  561. :indent 0
  562. :format "%v\n"
  563. ,@(bitwarden-list-all-items
  564. (bitwarden-search))))
  565. (widget-create
  566. 'push-button
  567. :notify 'bitwarden-list-cancel-dialog
  568. "Cancel")
  569. (goto-char (point-min)))
  570. (bitwarden--message "vault not unlocked!" nil t)))
  571. (provide 'bitwarden)
  572. ;;; bitwarden.el ends here