add vapid key and application server key generators

This commit is contained in:
Mike Macgirvin 2023-11-06 21:17:48 +11:00
parent 19d42dbb9f
commit 16867ac567

View file

@ -40,7 +40,7 @@ class Channel
*
* This action is pluggable.
* We're currently only checking for an empty name or one that exceeds our
* storage limit (191 chars). 191 chars is probably going to create a mess on
* storage limit (256 chars). 256 chars is probably going to create a mess on
* some pages.
* Plugins can set additional policies such as full name requirements, character
* sets, multi-byte length, etc.
@ -55,7 +55,7 @@ class Channel
return t('Empty name');
}
if (mb_strlen($name) > 191) {
if (mb_strlen($name) > 256) {
return t('Name too long');
}
@ -73,6 +73,46 @@ class Channel
}
}
public static function getVapidKey()
{
$private_key = openssl_pkey_new([
'private_key_type' => OPENSSL_KEYTYPE_EC,
'curve_name' => 'prime256v1',
]);
$details = openssl_pkey_get_details($private_key);
$private_key_raw = $details['ec']['d'];
$public_key_raw = $details['ec']['x'] . $details['ec']['y'];
$auth_token = base64_encode(openssl_random_pseudo_bytes(16));
$vapid = [
'private_key' => rtrim(strtr(base64_encode($private_key_raw), '+/', '-_'), '='),
'public_key' => rtrim(strtr(base64_encode($public_key_raw), '+/', '-_'), '='),
'auth_token' => $auth_token,
];
return json_encode($vapid);
}
public static function getApplicationServerKey($vapid)
{
$publicKey = $vapid['public_key'];
$public_key_bytes = base64_decode($publicKey);
// Check that the public key has the correct format
if (strlen($public_key_bytes) != 65 || ord($public_key_bytes[0]) != 4) {
// The public key has an incorrect format
// Handle the error here
}
// Extract the x and y coordinates of the point
$x = substr($public_key_bytes, 1, 32);
$y = substr($public_key_bytes, 33, 32);
// Pack the bytes of the public key in the correct order
$application_server_key = "\x04" . $x . $y;
return base64_encode($application_server_key);
}
/**
* @brief Create a system channel - which has no account attached.
@ -566,8 +606,8 @@ class Channel
q(
"update channel set channel_default_group = '%s', channel_allow_gid = '%s' where channel_id = %d",
dbesc(isset($group_hash) ? $group_hash : ''),
dbesc(isset($default_collection_str) ? $default_collection_str : EMPTY_STR),
dbesc($group_hash ?? ''),
dbesc($default_collection_str ?? ''),
intval($newuid)
);