Copy 2FA code from received iMessage/Text on MacOS

CJKm, Dirk, Hirvi74, tree_frog and others’ development of sqlite3 data aquisition from Messages’ chat database is wonderful!

A clumsier method, that I have employed using UI scripting in Messages, delimited text from the first chat in the Messages app. It might be an alternative if the more direct data aquisition method fails.


tell application "System Events"

	#	Get text of  last convesation of chat 1 in Message's UI Window
		set ConversationDescription to description of group 1 of ¬
		UI element 1 of group 1 of group 1 of group 1 of group 2 ¬
		of group 1 of group 1 of group 1 of group 2 of group 1 ¬
		of group 1 of group 1 of group 1 of group 1 of group 1 ¬
		of group 1 of ¬
		window 1 of application process "Messages"
end tell

#	set text item delimiters list to text that delimits the authentication or verification code. In this case, text item delimiters were set to a list {" authentication code is ", ".,"}, which were the text item delimiters that preceeded and followed the code. 
set text item delimiters to {" authentication code is ", ".,"}

# 	You might need to change your specific text items to fit the text items that delimit your authentication or verification code.
set AutheticationVerificationCode to text item 2 of ConversationDescription

The text item delimiter portion in the enclosed UI AppleScript, perhaps, may be applied to the sqlite3 data aquisition script.

This AppleScript extracts the code from the last incoming message and copies it to the clipboard. The code must be 4-6 characters long and the text (before the code) must contain Code, code, Pin or pin and immediately before the code there must be a colon or the word is or ist or lautet followed by a space.

Examples:

  • Your Apple Account code is: 561583. Do not share it with anyone.

  • PayPal: Your security-code is: 370626. Do not give this code to anyone.

  • Amazon: Your code is 458319, do not share it. You did not request it? Decline here: …

  • Authorize the purchase of 0.0 EUR with your card ***5588. Enter the following code followed by your 3D-Secure code: 7654

  • Your pin is 458319.

  • PayPal: Ihr Sicherheitscode lautet: 686747. Geben Sie diesen Code nicht weiter.

  • Telekom Login: Ihr angeforderter Bestätigungscode lautet 534703. Bitte geben Sie diesen in das Eingabefeld ein. Ihre Telekom

use framework "Foundation"
use scripting additions

property NSData : a reference to current application's NSData
property NSArray : a reference to current application's NSArray
property NSString : a reference to current application's NSString
property NSUnarchiver : a reference to current application's NSUnarchiver
property NSRegularExpression : a reference to current application's NSRegularExpression

set hexString to do shell script "sqlite3 ~/Library/Messages/chat.db 'SELECT HEX(attributedBody) FROM message WHERE is_from_me = 0 ORDER BY date DESC LIMIT 1'"
set theData to (NSArray's arrayWithObject:(run script "«data rdat" & hexString & "»"))'s firstObject()'s |data|()
set {theMessage, theError} to (NSUnarchiver's alloc's initForReadingWithData:theData)'s decodeTopLevelObjectAndReturnError:(reference)
if theError is missing value then
	set theString to theMessage's |string|
	set thePattern to "(?:(?:Code|code|Pin|pin).*(?:\\:|is|ist|lautet)\\s)(\\d{4,6})"
	set theRegEx to NSRegularExpression's regularExpressionWithPattern:thePattern options:0 |error|:(missing value)
	set regExResults to theRegEx's matchesInString:theString options:0 range:{location:0, |length|:theString's |length|()}
	if regExResults's |count|() > 0 then
		set aMatch to regExResults's objectAtIndex:0
		if aMatch's numberOfRanges as integer > 1 then
			set theRange to (aMatch's rangeAtIndex:1) -- Group 1
			if theRange's |length| > 0 then
				set theResult to (theString's substringWithRange:theRange) as string
				set the clipboard to {text:(theResult as string), Unicode text:theResult}
				display notification "Code: " & theResult & " copied." with title "Verification Code"
				return
			end if
		end if
	end if
end if
display notification "No code found." with title "Verification Code"

Note: The regex pattern could probably be more optimized, but it works. It’s not necessarily my thing… :wink:

Dirk, I enjoyed viewing your Regex addition to match a number pattern in the message text. As verification codes are six digits, would it be more succinct to set a regex pattern for six digits?

set thePattern to “\d{6}”

with the resulting block of code as

if theError is missing value then
	set theString to theMessage's |string|
	set thePattern to "\\d{6}"
	set theRegEx to NSRegularExpression's regularExpressionWithPattern:thePattern options:0 |error|:(missing value)
	set regExResults to theRegEx's matchesInString:theString options:0 range:{location:0, |length|:theString's |length|()}
end if

Dirk, I also like your approach to detecting matched ranges and copying them as text to the clipboard. I however was unable to run your script without substituting 0 for 1 in both

aMatch’s numberOfRanges as integer > 1
aMatch’s rangeAtIndex:1

With the resulting Applescript lines of:

if aMatch's numberOfRanges as integer > 0 then
			set theRange to (aMatch's rangeAtIndex:0) -- Group 1

My script already recognizes codes with a 4-6 digit number: (\\d{4,6})

My script first checks whether the text contains Code, Pin etc. and whether there is a colon etc. in front of the code. The result is then output in a group (in this case Group 1). It must therefore be 1.

If you change the pattern to a simple match, you must of course use 0. In this case, however, no check is performed and RegEx simply searches for a 6-digit number. In my opinion, it would be better to adjust the above-mentioned condition in the pattern accordingly if necessary.

You can check the pattern:
(?:(?:Code|code|Pin|pin).*(?:\:|is|ist|lautet)\s)(\d{4,6})
here: https://regex101.com

Dirk, I now understand your method, using your regex pattern, which was to capture various but identifiable texts preceding the 4-6 digit code, and also the 4-6 digit code itself.

1 Like