decodePublishableKey function
Validate a publishable key and extract its project id.
Throws PublishableKeyException with PublishableKeyErrorReason.secretKey
for anything starting sk_. That check runs FIRST, before any shape
validation: a secret key must never be reported as merely "malformed",
because the fix is to rotate it, not correct a typo.
Implementation
PublishableKey decodePublishableKey(String key) {
if (key.isEmpty) {
throw const PublishableKeyException(
'publishableKey is required',
PublishableKeyErrorReason.missing,
);
}
if (_secretKey.hasMatch(key)) {
throw const PublishableKeyException(
'A secret key was passed where a publishable key was expected. '
'Never embed secret keys in client code.',
PublishableKeyErrorReason.secretKey,
);
}
final match = _publishableKey.firstMatch(key);
if (match == null) {
throw const PublishableKeyException(
'publishableKey is malformed; expected pk_(live|test)_<uuid>_<base62>',
PublishableKeyErrorReason.malformed,
);
}
return PublishableKey(
prefix: match.group(1)!.toLowerCase(),
env: match.group(2)!.toLowerCase() == 'live'
? AuthOwlEnvironment.live
: AuthOwlEnvironment.test,
projectId: match.group(3)!,
);
}