R/utils__base64url.R

Defines functions base64url_decode base64url_decode_raw base64url_encode

# This file contains the low-level base64url helpers used by JWT, DPoP, sealed
# state, and related code
# Base64url is the URL-safe version of base64 used by many OAuth and OpenID
# Connect formats
# Used for encoding and decoding binary data in that format

# 1 Base64url helpers ----------------------------------------------------------

## 1.1 Encode and decode -------------------------------------------------------

#' Internal base64url helpers
#'
#' Canonical helpers used across JWT, JWKS, state encryption, DPoP, and mTLS:
#' - base64url_encode(raw|character) -> base64url string (no padding)
#' - base64url_decode_raw(string) -> raw vector
#' - base64url_decode(string) -> UTF-8 text with embedded-NUL rejection
#' Used by JWT, JWKS, DPoP, and sealed-state helpers.
#'
#' @param raw_bytes Raw vector to encode.
#' @return Base64url-encoded string without padding.
#' @keywords internal
#' @noRd
base64url_encode <- function(raw_bytes) {
  # Disable line breaks to avoid embedded newlines in long encodings
  s <- openssl::base64_encode(raw_bytes, linebreak = FALSE)
  # Defensive: strip any CR/LF that might slip through from upstream inputs
  s <- gsub("[\r\n]", "", s, perl = TRUE)
  s <- sub("=+$", "", s)
  chartr("+/", "-_", s)
}

#' Decode a base64url string into raw bytes
#'
#' Used by JWT, JWKS, and cryptographic helpers.
#'
#' @param x Base64url-encoded string.
#' @return Raw vector.
#' @keywords internal
#' @noRd
base64url_decode_raw <- function(x) {
  x <- chartr("-_", "+/", x)
  pad <- (4 - (nchar(x) %% 4)) %% 4
  if (pad > 0L) {
    x <- paste0(x, strrep("=", pad))
  }
  openssl::base64_decode(x)
}

#' Decode a base64url string into text
#'
#' Rejects embedded NUL bytes before converting the decoded payload to text.
#' Used when base64url content must become text safely.
#'
#' @param x Base64url-encoded string.
#' @return Character string.
#' @keywords internal
#' @noRd
base64url_decode <- function(x) {
  raw_bytes <- base64url_decode_raw(x)
  # Guard against embedded NUL bytes which would cause rawToChar() to silently
  # truncate the output. Mirrors the NUL hardening in utils__crypt.R.
  if (any(raw_bytes == as.raw(0))) {
    err_parse("base64url payload contains embedded NUL byte")
  }
  text <- rawToChar(raw_bytes)
  if (!isTRUE(validUTF8(text))) {
    err_parse("base64url payload is not valid UTF-8")
  }
  Encoding(text) <- "UTF-8"
  text
}

Try the shinyOAuth package in your browser

Any scripts or data that you put into this service are public.

shinyOAuth documentation built on May 23, 2026, 9:06 a.m.