How can I return the logged in user from inside a pkg which is running as root?

The stat command is run with the -f%Su parameter, where -f means that an output format follows, and %Su means that it should output (%) a string (S) which is the user ID (u) of the file's owner.

Your command then provides the username to the id command in order to get to the username - which seems to be a way roundabout way of getting that, as you could just have asked stat for it initially like this:

stat -f%Uu /dev/console

Doing it like this means you won't have to call id and cut.

The stat command is completely reliable in returning the user id/name of the owner of the /dev/console file (or actually character device). The question is just whether this user is the one, you're looking for. In general, it will work - but you might see a different behaviour than you're expecting when users are also logged in via Remote Desktop. In that case, the last login performed will be returned (i.e. when multiple user's are logged in at the same time).

There's also a different method of getting the currently logged in user by asking the System Configuration Daemon:

scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }'

The difference between the two is that looking at /dev/console cannot distinguish between root being logged in (i.e. root logins have been enabled by the user), or the computer being sat at the login window - both will return root as the owner of the file. Whether or not this is a problem for you depends on your specific use-case.