(str: string)
| 317 | * @since 2.0.0 |
| 318 | */ |
| 319 | export const decodeBase64Url = (str: string): Result.Result<Uint8Array, EncodingError> => { |
| 320 | const stripped = stripCrlf(str) |
| 321 | const length = stripped.length |
| 322 | if (length % 4 === 1) { |
| 323 | return Result.fail( |
| 324 | new EncodingError({ |
| 325 | module: "Base64Url", |
| 326 | kind: "Decode", |
| 327 | input: stripped, |
| 328 | message: `Length should be a multiple of 4, but is ${length}` |
| 329 | }) |
| 330 | ) |
| 331 | } |
| 332 | |
| 333 | if (!/^[-_A-Z0-9]*?={0,2}$/i.test(stripped)) { |
| 334 | return Result.fail( |
| 335 | new EncodingError({ |
| 336 | module: "Base64Url", |
| 337 | kind: "Decode", |
| 338 | input: stripped, |
| 339 | message: "Invalid input" |
| 340 | }) |
| 341 | ) |
| 342 | } |
| 343 | |
| 344 | // Some variants allow or require omitting the padding '=' signs |
| 345 | let sanitized = length % 4 === 2 ? `${stripped}==` : length % 4 === 3 ? `${stripped}=` : stripped |
| 346 | sanitized = sanitized.replace(/-/g, "+").replace(/_/g, "/") |
| 347 | |
| 348 | return decodeBase64(sanitized) |
| 349 | } |
| 350 | |
| 351 | /** |
| 352 | * Decodes a URL-safe base64 string into a UTF-8 string safely. |
no test coverage detected