Files
2026-11-22 18:19:16 +01:00

246 lines
7.7 KiB
OCaml
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
open Console
open View
type params = {
secret : string;
hash : string;
digits : int;
period : int;
issuer : string option;
}
let uri_re = Re.Perl.compile_pat "^otpauth://([A-Za-z]+)/([^?]*)\\?(.*)$"
let pair_re = Re.Perl.compile_pat "([^&=]+)=([^&]*)"
let pct_re = Re.Perl.compile_pat "%([0-9A-Fa-f][0-9A-Fa-f])"
let junk_re = Re.Perl.compile_pat "[ =]"
let base32_re = Re.Perl.compile_pat "^[A-Za-z2-7]+$"
let percent_decode s =
Re.replace pct_re s ~f:(fun g ->
String.make 1 (Char.chr (int_of_string ("0x" ^ Re.Group.get g 1))))
let clean_secret s = Re.replace_string junk_re ~by:"" s
let ( let* ) = Result.bind
let check_secret secret =
if secret = "" then Error "The secret can’t be void!"
else if not (Re.execp base32_re secret) then
Error
"The secret can only contain the following characters: 'a'..'z', \
'A'..'Z' or '2'..'7'!"
else Ok secret
let default =
{ secret = ""; hash = "SHA1"; digits = 6; period = 30; issuer = None }
let parse_int name ~allowed s =
match int_of_string_opt s with
| Some n when allowed n -> Ok n
| _ -> Error (Fmt.str "Invalid %s: %S" name s)
let parse_uri kind label query =
if String.lowercase_ascii kind <> "totp" then
Error "Only otpauth://totp/ URIs are supported!"
else
let params =
Re.all pair_re query
|> List.map (fun g ->
( String.lowercase_ascii (Re.Group.get g 1),
percent_decode (Re.Group.get g 2) ))
in
let get k = List.assoc_opt k params in
let* secret =
match get "secret" with
| Some s -> check_secret (clean_secret s)
| None -> Error "No secret in the URI!"
in
let* hash =
match Option.map String.uppercase_ascii (get "algorithm") with
| None -> Ok default.hash
| Some (("SHA1" | "SHA256" | "SHA512") as h) -> Ok h
| Some h -> Error (Fmt.str "Unsupported algorithm: %s" h)
in
let* digits =
match get "digits" with
| None -> Ok default.digits
| Some d -> parse_int "digits" ~allowed:(fun n -> n = 6 || n = 8) d
in
let* period =
match get "period" with
| None -> Ok default.period
| Some p -> parse_int "period" ~allowed:(fun n -> n > 0) p
in
let issuer =
match get "issuer" with
| Some _ as i -> i
| None -> (
match String.index_opt (percent_decode label) ':' with
| Some i -> Some (String.sub (percent_decode label) 0 i)
| None -> None)
in
Ok { secret; hash; digits; period; issuer }
let parse input =
match Re.exec_opt uri_re input with
| Some g -> parse_uri (Re.Group.get g 1) (Re.Group.get g 2) (Re.Group.get g 3)
| None ->
let* secret = check_secret (clean_secret input) in
Ok { default with secret }
let hmac hash ~key msg =
match hash with
| "SHA1" -> Digestif.SHA1.(to_raw_string (hmac_string ~key msg))
| "SHA256" -> Digestif.SHA256.(to_raw_string (hmac_string ~key msg))
| "SHA512" -> Digestif.SHA512.(to_raw_string (hmac_string ~key msg))
| h -> invalid_arg ("hmac: " ^ h)
let rec pow10 = function 0 -> 1 | n -> 10 * pow10 (n - 1)
let totp p ~drift =
let counter = Int64.of_float (Unix.time () /. float_of_int p.period) in
let msg = Bytes.create 8 in
Bytes.set_int64_be msg 0 (Int64.add counter (Int64.of_int drift));
let h =
hmac p.hash ~key:(Totpin_base32.decode p.secret) (Bytes.to_string msg)
in
let o = Char.code h.[String.length h - 1] land 0xf in
let byte i = Char.code h.[o + i] in
let n =
((byte 0 land 0x7f) lsl 24)
lor (byte 1 lsl 16)
lor (byte 2 lsl 8)
lor byte 3
in
Printf.sprintf "%0*d" p.digits (n mod pow10 p.digits)
let fail msg =
Fmt.epr "%a@." pp (styled Style.(fg Color.red) (text msg));
exit 1
let question = "Input your TOTP secret or otpauth:// URI: "
let clear_prompt ~len =
if Unix.isatty Unix.stderr then begin
let cols =
match Console_tty.size Fmt.stderr with
| Some size -> fst (size ())
| None -> 80
in
let rows = max 1 ((String.length question + len + cols - 1) / cols) in
Fmt.epr "\027[%dA\027[J%!" rows
end
let help =
{|Usage: totpin [-h] [-v] [--licenses]
Compute TOTP codes from a secret or an otpauth:// URI.
totpin asks for a base32 secret, or a full otpauth://totp/... URI (which also
gives the algorithm, the number of digits and the period), without echoing it.
Two codes are then shown, the current one and the next one, each with its
countdown. Press any key (or Ctrl-C) to quit. Nothing is stored.
Options:
-h, --help Show this help, then exit.
-v, --version Show the version, then exit.
--licenses Show the license of totpin and the licenses of the libraries
it uses, then exit.
License: ISC, Copyright (c) 2026 Matthieu Dubuget.
|}
let () =
match List.tl (Array.to_list Sys.argv) with
| [] -> ()
| [ ("-h" | "--help") ] ->
print_string help;
exit 0
| [ "--licenses" ] ->
print_string Licenses.own;
print_newline ();
print_string Licenses.third_party;
exit 0
| [ ("-v" | "--version") ] ->
print_endline Version.v;
exit 0
| _ ->
prerr_string "totpin: invalid arguments\n\n";
prerr_string help;
exit 2
let () =
Console_tty.setup ();
Eio_main.run @@ fun env ->
let prompt = Console_eio.Prompt.v (Eio.Stdenv.stdin env) in
Fmt.epr "%a%!" pp (styled Style.(fg Color.green) (text question));
match Console_eio.Prompt.secret prompt "" with
| Error e -> fail (Fmt.str "%a" Console_eio.Prompt.pp_error e)
| Ok input -> (
match parse input with
| Error msg -> fail msg
| Ok p ->
clear_prompt ~len:(String.length input);
let clock = Eio.Stdenv.clock env in
let period = p.period in
let current = totp p ~drift:0 in
let next = totp p ~drift:1 in
let remaining =
ref ((2 * period) - (int_of_float (Unix.time ()) mod period))
in
let row color code left =
let left = max left 0 in
let label = if left = 0 then "expired" else Fmt.str "%2d s" left in
View.(
styled
Style.(fg color)
(hcat ~gap:1
[
text code;
Bar.horizontal ~width:30
(float_of_int left /. float_of_int period);
text label;
]))
in
let header =
match p.issuer with
| Some i -> [ styled Style.bold (text i) ]
| None -> []
in
let lines = List.length header + 2 in
let frame () =
View.vcat
(header
@ [
row
(if !remaining > period then Color.blue
else Color.bright_black)
current (!remaining - period);
row Color.yellow next !remaining;
])
in
let up = Fmt.str "\r\027[%dA\027[J" lines in
Fmt.pr "%a@." View.pp (frame ());
let clear () = Fmt.pr "%s%!" up in
let on_signal code =
Sys.Signal_handle
(fun _ ->
clear ();
exit code)
in
Sys.set_signal Sys.sigint (on_signal 130);
Sys.set_signal Sys.sigterm (on_signal 143);
let countdown () =
while !remaining > 0 do
Eio.Time.sleep clock 1.0;
decr remaining;
Fmt.pr "%s%a@." up View.pp (frame ())
done
in
let any_key () =
match Console_eio.Prompt.keys prompt Eio.Buf_read.any_char with
| Ok _ -> ()
| Error _ -> Eio.Fiber.await_cancel ()
in
Eio.Fiber.first countdown any_key;
clear ())