package EPrints::KlarasConnect::Util;

# Small, dependency-free helpers: JSON, base64url, HMAC, constant-time
# comparison, secure random bytes. Perl 5.10.1 compatible.

use strict;
use warnings;

use Digest::SHA ();
use MIME::Base64 ();

use Exporter 'import';
our @EXPORT_OK = qw(
	json_encode json_decode
	b64url_encode b64url_decode
	hmac_hex hmac_raw sha256_hex
	secure_equals random_hex uuid_v4
	is_uuid is_hex
);

my $JSON;

sub _json
{
	return $JSON if defined $JSON;

	# JSON.pm picks JSON::XS when present. EPrints 3.3 bundles JSON.pm in
	# perl_lib/, 3.4 requires it; JSON::PP is core from Perl 5.14.
	foreach my $class (qw( JSON::XS JSON JSON::PP ))
	{
		my $ok = eval "require $class; 1";
		next if !$ok;
		$JSON = $class->new->utf8->canonical->allow_nonref;
		last;
	}
	die "klaras_connect: no JSON module available\n" if !defined $JSON;
	return $JSON;
}

# Returns UTF-8 encoded bytes.
sub json_encode
{
	my( $data ) = @_;
	return _json()->encode( $data );
}

# Takes UTF-8 bytes. Returns undef on malformed input, never dies.
sub json_decode
{
	my( $bytes ) = @_;
	return undef if !defined $bytes || !length $bytes;
	my $data = eval { _json()->decode( $bytes ) };
	return $@ ? undef : $data;
}

sub b64url_encode
{
	my( $bytes ) = @_;
	my $s = MIME::Base64::encode_base64( $bytes, '' );
	$s =~ tr{+/}{-_};
	$s =~ s/=+\z//;
	return $s;
}

# Returns undef unless $s is strictly base64url (no padding, no other chars).
sub b64url_decode
{
	my( $s ) = @_;
	return undef if !defined $s || $s !~ /\A[A-Za-z0-9_-]*\z/;
	return undef if length( $s ) % 4 == 1;
	( my $t = $s ) =~ tr{-_}{+/};
	$t .= '=' x ( ( 4 - length( $t ) % 4 ) % 4 );
	return MIME::Base64::decode_base64( $t );
}

sub hmac_hex
{
	my( $data, $key ) = @_;
	return Digest::SHA::hmac_sha256_hex( $data, $key );
}

sub hmac_raw
{
	my( $data, $key ) = @_;
	return Digest::SHA::hmac_sha256( $data, $key );
}

sub sha256_hex
{
	my( $data ) = @_;
	return Digest::SHA::sha256_hex( $data );
}

# Constant-time string comparison. Lengths are not secret here (every
# value compared has a fixed, public length), so a length mismatch returns
# early.
sub secure_equals
{
	my( $x, $y ) = @_;
	return 0 if !defined $x || !defined $y;
	return 0 if length( $x ) != length( $y );
	my $diff = 0;
	for my $i ( 0 .. length( $x ) - 1 )
	{
		$diff |= ord( substr( $x, $i, 1 ) ) ^ ord( substr( $y, $i, 1 ) );
	}
	return $diff == 0 ? 1 : 0;
}

# Cryptographically secure random bytes from the OS. Dies rather than
# falling back to rand(): a predictable secret is worse than an error.
sub random_bytes
{
	my( $n ) = @_;
	open( my $fh, '<:raw', '/dev/urandom' )
		or die "klaras_connect: cannot read /dev/urandom: $!\n";
	my $buf = '';
	while( length( $buf ) < $n )
	{
		my $got = sysread( $fh, $buf, $n - length( $buf ), length( $buf ) );
		die "klaras_connect: short read from /dev/urandom\n" if !$got;
	}
	close( $fh );
	return $buf;
}

sub random_hex
{
	my( $bytes ) = @_;
	return unpack( 'H*', random_bytes( $bytes ) );
}

sub uuid_v4
{
	my @b = unpack( 'C16', random_bytes( 16 ) );
	$b[6] = ( $b[6] & 0x0f ) | 0x40;
	$b[8] = ( $b[8] & 0x3f ) | 0x80;
	my $h = join '', map { sprintf '%02x', $_ } @b;
	return join '-', substr( $h, 0, 8 ), substr( $h, 8, 4 ), substr( $h, 12, 4 ),
		substr( $h, 16, 4 ), substr( $h, 20, 12 );
}

sub is_uuid
{
	my( $s ) = @_;
	return defined $s && $s =~ /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ ? 1 : 0;
}

sub is_hex
{
	my( $s, $len ) = @_;
	return 0 if !defined $s;
	return $s =~ /\A[0-9a-f]+\z/ && ( !defined $len || length( $s ) == $len ) ? 1 : 0;
}

1;
