1/*  sms_otp_parse: pull one-time passcodes out of SMS text.
    2
    3    MIT licence. Copyright (c) 2026 CryptoeSIM.io
    4*/
    5
    6:- module(sms_otp_parse,
    7          [ otp_code/2,              % +Text, -Code
    8            otp_candidates/2,        % +Text, -Candidates
    9            otp_service/2,           % +Text, -Service
   10            otp_expiry_minutes/2,    % +Text, -Minutes
   11            sms_retriever_hash/2,    % +Text, -Hash
   12            otp_message/2            % +Text, -Dict
   13          ]).   14:- use_module(library(lists)).   15:- use_module(library(apply)).

Extract one-time passcodes from verification SMS

Verification texts come in many shapes: "G-482913 is your Google verification code", "[Bank] Code: 482 913. Expires in 10 minutes", "<#> 4829 is your code\nFA+9qCX9VSu". This library finds the code, the sending service, the stated expiry and the Android SMS Retriever hash, while skipping phone numbers, prices, dates, times and percentages that often sit in the same message.

A candidate is a run of 4 to 8 digits, or two groups of three digits joined by a single space or hyphen ("482 913", "482-913"). Runs that touch other digit groups (phone numbers, dates), start with "+", or sit next to a currency sign, a percent sign, a colon (times) or a decimal point (amounts) are dropped. Remaining candidates are scored: a code keyword in the 60 characters before it (code, OTP, passcode, PIN, verification, ...) adds 3, or 2 if the keyword only follows it; six digits adds 1, a 4-digit value that looks like a year (1900-2099) loses 2. The best score wins; ties go to the earliest candidate.

 otp_code(+Text, -Code:atom) is semidet
Code is the most likely one-time passcode in Text, as an atom of digits with any space or hyphen removed.
   42otp_code(Text, Code) :-
   43    otp_candidates(Text, Cands),
   44    Cands \== [],
   45    best_candidate(Cands, otp(Code, _, _)).
   46
   47best_candidate([C|Cs], Best) :-
   48    foldl(better, Cs, C, Best).
   49
   50better(otp(C,S,P), otp(C0,S0,P0), B) :-
   51    (   S > S0
   52    ->  B = otp(C,S,P)
   53    ;   B = otp(C0,S0,P0)
   54    ).
 otp_candidates(+Text, -Candidates:list) is det
Candidates is a list of otp(Code, Score, Offset) terms in the order they appear in Text.
   61otp_candidates(Text, Cands) :-
   62    text_codes(Text, Codes0),
   63    maplist(lower, Codes0, Lower),
   64    runs(Codes0, 0, Runs),
   65    convlist(run_candidate(Codes0, Lower), Runs, Cands).
   66
   67lower(C, L) :- ( code_type(C, upper(L0)) -> L = L0 ; L = C ).
   68
   69% runs(+Codes, +Offset, -Runs): Runs is a list of run(Start, End, Groups)
   70% where Groups is a list of digit code lists separated in the text by
   71% exactly one space or hyphen.
   72
   73runs([], _, []).
   74runs([C|Cs], I, Runs) :-
   75    (   code_type(C, digit)
   76    ->  run_groups([C|Cs], I, Groups, Rest, End),
   77        Runs = [run(I, End, Groups)|More],
   78        runs(Rest, End, More)
   79    ;   I1 is I+1,
   80        runs(Cs, I1, Runs)
   81    ).
   82
   83run_groups(Codes, I, [G|Gs], Rest, End) :-
   84    digits(Codes, G, After),
   85    length(G, N),
   86    I1 is I+N,
   87    (   After = [Sep,D|_],
   88        memberchk(Sep, `- `),
   89        code_type(D, digit)
   90    ->  After = [_|After1],
   91        I2 is I1+1,
   92        run_groups(After1, I2, Gs, Rest, End)
   93    ;   Gs = [],
   94        Rest = After,
   95        End = I1
   96    ).
   97
   98digits([C|Cs], [C|Ds], Rest) :-
   99    code_type(C, digit), !,
  100    digits(Cs, Ds, Rest).
  101digits(Rest, [], Rest).
  102
  103run_candidate(All, Lower, run(S, E, Groups), otp(Code, Score, S)) :-
  104    candidate_digits(Groups, Ds),
  105    length(Ds, N),
  106    N >= 4, N =< 8,
  107    \+ blocked_before(All, S),
  108    \+ blocked_after(All, E),
  109    atom_codes(Code, Ds),
  110    score(Lower, S, E, Ds, Score).
  111
  112candidate_digits([G], G).
  113candidate_digits([A,B], Ds) :-
  114    length(A, 3), length(B, 3),
  115    append(A, B, Ds).
  116
  117blocked_before(All, S) :-
  118    S > 0,
  119    P is S-1,
  120    nth0(P, All, C),
  121    (   memberchk(C, `+£$€/:%`)
  122    ->  true
  123    ;   memberchk(C, `.,`),
  124        P > 0,
  125        P2 is P-1,
  126        nth0(P2, All, D),
  127        code_type(D, digit)
  128    ).
  129
  130blocked_after(All, E) :-
  131    nth0(E, All, C),
  132    (   memberchk(C, `%/€£`)
  133    ->  true
  134    ;   memberchk(C, `.,:`),
  135        E1 is E+1,
  136        nth0(E1, All, D),
  137        code_type(D, digit)
  138    ).
  139
  140score(Lower, S, E, Ds, Score) :-
  141    B0 is max(0, S-60),
  142    LenB is S-B0,
  143    sub_list(Lower, B0, LenB, Before),
  144    length(Lower, Len),
  145    LenA is min(40, Len-E),
  146    sub_list(Lower, E, LenA, After),
  147    ( has_keyword(Before) -> K0 = 3 ; has_keyword(After) -> K0 = 2 ; K0 = 0 ),
  148    length(Ds, N),
  149    ( N =:= 6 -> K2 = 1 ; K2 = 0 ),
  150    ( year_like(Ds) -> K3 = -2 ; K3 = 0 ),
  151    Score is K0+K2+K3.
  152
  153has_keyword(Window) :-
  154    keyword(K),
  155    append(_, Rest, Window),
  156    append(K, _, Rest), !.
  157
  158sub_list(List, Skip, Len, Sub) :-
  159    length(Pre, Skip),
  160    append(Pre, Rest, List),
  161    length(Sub, Len),
  162    append(Sub, _, Rest).
  163
  164year_like([0'1,0'9,_,_]).
  165year_like([0'2,0'0,_,_]).
  166
  167keyword(`code`).
  168keyword(`otp`).
  169keyword(`passcode`).
  170keyword(`pin`).
  171keyword(`verif`).
  172keyword(`one-time`).
  173keyword(`one time`).
  174keyword(`kod`).
  175keyword(`codigo`).
  176keyword(`código`).
  177keyword(`token`).
 otp_service(+Text, -Service:atom) is semidet
Service is the sender named in the message: a leading "[Name]", "<#> Name:" or "Name:" prefix, or the word after "your" in "your Name verification code".
  185otp_service(Text, Service) :-
  186    text_codes(Text, Codes0),
  187    strip_retriever_prefix(Codes0, Codes),
  188    (   phrase(bracket_name(Name), Codes, _)
  189    ->  true
  190    ;   phrase(colon_name(Name), Codes, _)
  191    ->  true
  192    ;   your_name(Codes, Name)
  193    ),
  194    atom_codes(Service, Name).
  195
  196strip_retriever_prefix(Codes0, Codes) :-
  197    (   append(`<#>`, Rest, Codes0)
  198    ->  drop_blanks(Rest, Codes)
  199    ;   drop_blanks(Codes0, Codes)
  200    ).
  201
  202drop_blanks([C|Cs], Rest) :- code_type(C, space), !, drop_blanks(Cs, Rest).
  203drop_blanks(Rest, Rest).
  204
  205bracket_name(Name) -->
  206    "[", name_chars(Name), { Name \== [] }, "]".
  207colon_name(Name) -->
  208    word(Name), { Name \== [], \+ all_digits(Name), \+ generic(Name) }, ":".
  209
  210your_name(Codes, Name) :-
  211    maplist(lower, Codes, Lower),
  212    append(Pre, Rest, Lower),
  213    append(`your `, _, Rest),
  214    length(Pre, P),
  215    P5 is P+5,
  216    length(Skip, P5),
  217    append(Skip, Orig, Codes),
  218    phrase(word(Name), Orig, Tail),
  219    Name \== [],
  220    \+ generic(Name),
  221    maplist(lower, Tail, LTail),
  222    drop_blanks(LTail, T1),
  223    ( append(`verification`, _, T1)
  224    ; append(`security`, _, T1)
  225    ; append(`login`, _, T1)
  226    ; append(`code`, _, T1)
  227    ; append(`one-time`, _, T1)
  228    ), !.
  229
  230generic(Name) :-
  231    maplist(lower, Name, L),
  232    memberchk(L, [`code`, `otp`, `pin`, `verification`, `your`, `the`,
  233                  `use`, `enter`, `security`, `login`, `one-time`]).
  234
  235all_digits(Cs) :- forall(member(C, Cs), code_type(C, digit)).
  236
  237name_chars([C|Cs]) --> [C], { C =\= 93, C =\= 10 }, !, name_chars(Cs).   % 93 = ']'
  238name_chars([]) --> [].
  239
  240word([C|Cs]) --> [C], { code_type(C, alnum) ; C == 0'- ; C == 0'. }, !, word(Cs).
  241word([]) --> [].
 otp_expiry_minutes(+Text, -Minutes:integer) is semidet
Minutes is the validity stated in Text ("expires in 10 minutes", "valid for 1 hour", "valid for 90 seconds" gives 2, rounded up).
  248otp_expiry_minutes(Text, Minutes) :-
  249    text_codes(Text, Codes0),
  250    maplist(lower, Codes0, Codes),
  251    append(_, Rest, Codes),
  252    digits(Rest, Ds, After), Ds \== [],
  253    drop_blanks(After, A1),
  254    unit(A1, Factor, Div), !,
  255    number_codes(N, Ds),
  256    Minutes is (N*Factor + Div - 1) // Div.
  257
  258unit(Cs, 1, 1)  :- append(`min`, _, Cs).
  259unit(Cs, 60, 1) :- ( append(`hour`, _, Cs) ; append(`hr`, _, Cs) ).
  260unit(Cs, 1, 60) :- ( append(`sec`, _, Cs) ; append(`s `, _, Cs) ).
 sms_retriever_hash(+Text, -Hash:atom) is semidet
Hash is the 11-character app hash that Android's SMS Retriever API expects as the last token of the message.
  267sms_retriever_hash(Text, Hash) :-
  268    split_string(Text, " \n\t", " \n\t", Parts0),
  269    exclude(==(""), Parts0, Parts),
  270    last(Parts, Last),
  271    string_codes(Last, Cs),
  272    length(Cs, 11),
  273    forall(member(C, Cs), ( code_type(C, alnum) ; C == 0'+ ; C == 0'/ )),
  274    \+ all_digits(Cs),
  275    include([C]>>code_type(C, upper), Cs, Up), Up \== [],
  276    include([C]>>code_type(C, lower), Cs, Lo), Lo \== [],
  277    atom_string(Hash, Last).
 otp_message(+Text, -Info:dict) is det
Info is otp{code:C, service:S, expiry_minutes:M, retriever_hash:H}; a field is the atom none when it cannot be found.
  284otp_message(Text, otp{code:C, service:S, expiry_minutes:M, retriever_hash:H}) :-
  285    ( otp_code(Text, C0) -> C = C0 ; C = none ),
  286    ( otp_service(Text, S0) -> S = S0 ; S = none ),
  287    ( otp_expiry_minutes(Text, M0) -> M = M0 ; M = none ),
  288    ( sms_retriever_hash(Text, H0) -> H = H0 ; H = none ).
  289
  290text_codes(Text, Codes) :-
  291    (   is_list(Text) -> Codes = Text
  292    ;   string_codes(Text, Codes)
  293    )