Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/check-results.R
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ cat("Testing checked build:", find.package(pkg), expected, "\n")
cat("Crypto build:", find.package("mx.crypto"),
as.character(utils::packageVersion("mx.crypto")), "\n")
for (file in c("test_sas.R", "test_sas_identity.R", "test_sas_own_device.R",
"test_sas_transport.R", "test_user_verification.R")) {
"test_sas_transport.R", "test_user_verification.R", "test_encrypted_media.R")) {
result <- tinytest::run_test_file(file.path("inst", "tinytest", file),
at_home = FALSE, verbose = 0, color = FALSE)
print(result)
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ jobs:
# older binary. The helper reads the floors from DESCRIPTION.
- name: Install Matrix development dependencies
env:
# mx.crypto 0.2.2, with the reviewed SAS implementation.
MX_CRYPTO_REF: "5f67d5531fec8f476f20345d70d95cfc9eaaa502"
# mx.crypto 0.2.2.2, including Matrix v2 attachment primitives.
MX_CRYPTO_REF: "74980d6453b71bc6eac9639416e0ec96df971ba9"
run: |
Rscript -e 'install.packages(c("curl", "jsonlite"))'
Rscript .github/install-matrix-deps.R
Expand Down
6 changes: 3 additions & 3 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Package: mx.client
Type: Package
Title: Stateful Matrix Client Helpers
Version: 0.2.1.3
Date: 2026-10-07
Version: 0.2.1.4
Date: 2026-10-26
Authors@R: c(
person("Troy", "Hernandez", role = c("aut", "cre"),
email = "troy@cornball.ai",
Expand All @@ -28,7 +28,7 @@ Imports:
utils
Suggests:
livekitr,
mx.crypto (>= 0.2.2),
mx.crypto (>= 0.2.2.2),
simplermarkdown,
tinytest
VignetteBuilder: simplermarkdown
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ export(mx_crypto_sessions_save)
export(mx_crypto_store_dir)
export(mx_crypto_user_trust)
export(mx_crypto_verify_user)
export(mx_download_encrypted)
export(mx_extract_invite_records)
export(mx_extract_invites)
export(mx_extract_media_events)
Expand Down Expand Up @@ -72,6 +73,7 @@ export(mx_send_to_device_encrypted)
export(mx_set_displayname)
export(mx_sync_update)
export(mx_table_html)
export(mx_upload_encrypted)
export(mx_verify_console)
export(mx_with_relogin)

Expand Down
9 changes: 9 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
# mx.client 0.2.1.4

- Add encrypted attachment upload and verified download helpers using
mx.crypto's Matrix v2 primitives. Uploads expose only ciphertext with a
generic filename; downloads verify integrity before replacing the destination.
- Refuse plaintext `mx_send_media()` uploads to encrypted rooms before
transferring any file. Callers retain ownership of their live crypto sessions
and send the returned attachment metadata through `mx_send_encrypted()`.

# mx.client 0.2.1.3

* Fix: keep every inbound Olm session per peer, not just the latest. A
Expand Down
119 changes: 119 additions & 0 deletions R/media-encrypted.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
#' Upload an encrypted Matrix attachment
#'
#' Uploads ciphertext only, with a generic filename and content type.
#' Returns content to pass to \code{mx_send_encrypted()} using the caller's
#' existing account and sessions. The return value includes a secret key:
#' never post it in an unencrypted event. Does not open a crypto store.
#' @param client Matrix client config.
#' @param path Path of the file to upload.
#' @param body Display filename or caption, inside the encrypted event.
#' @param msgtype Media message type, or NULL to derive it from the MIME type.
#' @param content_type MIME type, or NULL to guess from the file extension.
#' @param info Extra media metadata, inside the encrypted event.
#' @param max_bytes Maximum plaintext size in bytes, default 25 MiB. Encryption
#' uses memory; larger files require an explicit higher limit.
#' @return Matrix message content with \code{file} instead of \code{url}.
#' @export
mx_upload_encrypted <- function(client, path, body = basename(path),
msgtype = NULL, content_type = NULL,
info = list(), max_bytes = 25 * 1024^2) {
mx_require_attachment_crypto()
size <- mx_attachment_size(path, max_bytes)
content_type <- content_type %||% mx.api::mx_guess_mime(path)
if (is.null(msgtype)) {
family <- sub("/.*", "", content_type)
msgtype <- if (family %in% c("image", "audio", "video")) {
paste0("m.", family)
} else "m.file"
}
if (!msgtype %in% c("m.file", "m.image", "m.audio", "m.video")) {
stop("mx.client: invalid media message type", call. = FALSE)
}
# Read one extra byte to catch growth between stat and read.
bytes <- readBin(path, "raw", n = size + 1)
if (length(bytes) != size) {
stop("mx.client: attachment changed while reading", call. = FALSE)
}
encrypted <- mx.crypto::mxc_attachment_encrypt(bytes)
tmp <- tempfile("mx-attachment-")
dir.create(tmp, mode = "0700")
on.exit(unlink(tmp, recursive = TRUE), add = TRUE)
payload <- file.path(tmp, "encrypted")
writeBin(encrypted$data, payload)
uri <- mx.api::mx_upload(mx_client_session(client), payload,
content_type = "application/octet-stream",
filename = "encrypted")
if (!is.character(uri) || length(uri) != 1L || is.na(uri) ||
!grepl("^mxc://[^/]+/.+", uri)) {
stop("mx.client: upload returned no media URI", call. = FALSE)
}
encrypted$file$url <- uri
list(msgtype = msgtype, body = body, file = encrypted$file,
info = utils::modifyList(info, list(mimetype = content_type, size = size)))
}

#' Download and verify an encrypted Matrix attachment
#'
#' Downloads ciphertext into a private temporary directory, verifies its
#' SHA-256 digest and decrypts it before replacing the destination. Failure
#' leaves an existing destination unchanged. Metadata must come from an
#' authenticated encrypted room event. Does not open a crypto store.
#' @param client Matrix client config.
#' @param file Matrix v2 encrypted-file metadata, including its \code{url}.
#' @param dest Destination path. Its parent directory must exist.
#' @param max_bytes Maximum downloaded size to read into memory, default 25
#' MiB. This is checked on disk before decryption, not a network transfer cap.
#' @return Destination path, invisibly.
#' @export
mx_download_encrypted <- function(client, file, dest,
max_bytes = 25 * 1024^2) {
mx_require_attachment_crypto()
if (!is.list(file) || !is.character(file$url) || length(file$url) != 1L ||
is.na(file$url) || !grepl("^mxc://[^/]+/.+", file$url)) {
stop("mx.client: encrypted attachment has no media URI", call. = FALSE)
}
tmp <- tempfile("mx-attachment-")
dir.create(tmp, mode = "0700")
on.exit(unlink(tmp, recursive = TRUE), add = TRUE)
payload <- file.path(tmp, "encrypted")
mx.api::mx_download(mx_client_session(client), file$url, payload)
size <- mx_attachment_size(payload, max_bytes)
bytes <- readBin(payload, "raw", n = size)
plaintext <- mx.crypto::mxc_attachment_decrypt(bytes, file)
staged <- tempfile(".mx-attachment-", tmpdir = dirname(dest))
on.exit(unlink(staged), add = TRUE)
# Create private before writing plaintext, including with a permissive umask.
if (!file.create(staged) || !Sys.chmod(staged, "0600")) {
stop("mx.client: cannot create private attachment destination", call. = FALSE)
}
writeBin(plaintext, staged)
if (!file.rename(staged, dest)) {
stop("mx.client: cannot replace attachment destination", call. = FALSE)
}
invisible(dest)
}

mx_require_attachment_crypto <- function() {
if (!requireNamespace("mx.crypto", quietly = TRUE) ||
!all(c("mxc_attachment_encrypt", "mxc_attachment_decrypt") %in%
getNamespaceExports("mx.crypto"))) {
stop("mx.client: encrypted attachments require mx.crypto >= 0.2.2.2",
call. = FALSE)
}
}

mx_attachment_size <- function(path, max_bytes) {
if (!is.numeric(max_bytes) || length(max_bytes) != 1L ||
is.na(max_bytes) || !is.finite(max_bytes) || max_bytes < 0 ||
max_bytes > .Machine$integer.max - 1) {
stop("mx.client: invalid attachment size limit", call. = FALSE)
}
stat <- file.info(path)
if (nrow(stat) != 1L || is.na(stat$size) || isTRUE(stat$isdir)) {
stop("mx.client: attachment must be a readable file", call. = FALSE)
}
if (stat$size > max_bytes) {
stop("mx.client: attachment exceeds the size limit", call. = FALSE)
}
stat$size
}
8 changes: 7 additions & 1 deletion R/messages.R
Original file line number Diff line number Diff line change
Expand Up @@ -542,7 +542,9 @@ mx_extract_reaction_verdict <- function(sync_resp, room_id, self_id,
#'
#' Client-layer wrapper over \code{mx.api::mx_send_media()}: resolves the
#' room by name (or falls back to the config's default room), builds the
#' session from the client config, and uploads + posts in one call. The
#' session from the client config, and uploads + posts in one call. Refuses
#' encrypted rooms before upload; use \code{mx_upload_encrypted()} followed
#' by \code{mx_send_encrypted()} with the caller's live crypto context. The
#' msgtype is derived from the file's MIME type unless given.
#'
#' If you attach mx.api and mx.client together, namespace-qualify -- the
Expand Down Expand Up @@ -578,6 +580,10 @@ mx_send_media <- function(client, path, room = NULL, body = basename(path),
content_type %||% mx.api::mx_guess_mime(path), ")")
return(invisible(NULL))
}
if (mx_room_encrypted(client, rid)) {
stop("mx.client: encrypted room requires mx_upload_encrypted() and ",
"mx_send_encrypted(); no file was uploaded", call. = FALSE)
}
mx.api::mx_send_media(mx_client_session(client), rid, path,
body = body, msgtype = msgtype,
content_type = content_type, info = info)
Expand Down
73 changes: 73 additions & 0 deletions inst/tinytest/test_encrypted_media.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
library(mx.client)
if (!requireNamespace("mx.crypto", quietly = TRUE) ||
!"mxc_attachment_encrypt" %in% getNamespaceExports("mx.crypto")) {
exit_file("encrypted attachments require mx.crypto >= 0.2.2.2")
}
local({
root <- tempfile("media-test-")
dir.create(root)
on.exit(unlink(root, recursive = TRUE), add = TRUE)
path <- file.path(root, "fixture.png")
bytes <- as.raw(0:255)
writeBin(bytes, path)
cfg <- list(server = "https://example.invalid", token = "fixture-token",
user_id = "@bot:example.invalid", device_id = "FIXTURE")
old_upload <- mx.api::mx_upload
old_download <- mx.api::mx_download
old_state <- mx.api::mx_get_state
old_media <- mx.api::mx_send_media
on.exit({
assignInNamespace("mx_upload", old_upload, "mx.api")
assignInNamespace("mx_download", old_download, "mx.api")
assignInNamespace("mx_get_state", old_state, "mx.api")
assignInNamespace("mx_send_media", old_media, "mx.api")
}, add = TRUE)
uploaded <- NULL
assignInNamespace("mx_upload", function(session, path, content_type, filename) {
expect_identical(session$token, "fixture-token")
expect_identical(content_type, "application/octet-stream")
expect_identical(filename, "encrypted")
uploaded <<- readBin(path, "raw", file.size(path))
"mxc://example.invalid/fixture"
}, "mx.api")
content <- mx_upload_encrypted(cfg, path)
expect_identical(content$msgtype, "m.image")
expect_identical(content$body, "fixture.png")
expect_identical(content$info$mimetype, "image/png")
expect_equal(content$info$size, 256)
expect_null(content$url)
expect_false(identical(uploaded, bytes))
expect_identical(mx.crypto::mxc_attachment_decrypt(uploaded, content$file), bytes)
expect_error(mx_upload_encrypted(cfg, path, max_bytes = 255), "size limit")
expect_error(mx_upload_encrypted(cfg, root), "readable file")
expect_error(mx_upload_encrypted(cfg, path, max_bytes = Inf), "size limit")
assignInNamespace("mx_download", function(session, mxc_url, dest) {
expect_identical(session$token, "fixture-token")
expect_identical(mxc_url, content$file$url)
writeBin(uploaded, dest)
invisible(dest)
}, "mx.api")
dest <- file.path(root, "received.png")
expect_identical(mx_download_encrypted(cfg, content$file, dest), dest)
expect_identical(readBin(dest, "raw", 256), bytes)
# A failed integrity/size check leaves the existing destination intact.
uploaded[1] <- as.raw(bitwXor(as.integer(uploaded[1]), 1L))
expect_error(mx_download_encrypted(cfg, content$file, dest), "integrity")
expect_identical(readBin(dest, "raw", 256), bytes)
expect_error(mx_download_encrypted(cfg, content$file, dest, max_bytes = 255), "size limit")
expect_identical(readBin(dest, "raw", 256), bytes)
expect_error(mx_download_encrypted(cfg, list(url = "https://example.invalid"), dest), "media URI")
# The old convenience sender must never upload plaintext to an encrypted
# room, including when state cannot be determined.
sends <- 0L
assignInNamespace("mx_send_media", function(...) { sends <<- sends + 1L; "$plain" }, "mx.api")
assignInNamespace("mx_get_state", function(...) list(algorithm = "m.megolm.v1.aes-sha2"), "mx.api")
expect_error(mx_send_media(cfg, path, "!room:example.invalid"), "encrypted room")
expect_identical(sends, 0L)
assignInNamespace("mx_get_state", function(...) stop("state unavailable"), "mx.api")
expect_error(mx_send_media(cfg, path, "!room:example.invalid"), "state unavailable")
expect_identical(sends, 0L)
assignInNamespace("mx_get_state", function(...) NULL, "mx.api")
expect_identical(mx_send_media(cfg, path, "!room:example.invalid"), "$plain")
expect_identical(sends, 1L)
})
26 changes: 26 additions & 0 deletions man/mx_download_encrypted.Rd
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
% tinyrox says don't edit this manually, but it can't stop you!
\name{mx_download_encrypted}
\alias{mx_download_encrypted}
\title{Download and verify an encrypted Matrix attachment}
\usage{
mx_download_encrypted(client, file, dest, max_bytes = 25 * 1024^2)
}
\arguments{
\item{client}{Matrix client config.}

\item{file}{Matrix v2 encrypted-file metadata, including its \code{url}.}

\item{dest}{Destination path. Its parent directory must exist.}

\item{max_bytes}{Maximum downloaded size to read into memory, default 25
MiB. This is checked on disk before decryption, not a network transfer cap.}
}
\value{
Destination path, invisibly.
}
\description{
Downloads ciphertext into a private temporary directory, verifies its
SHA-256 digest and decrypts it before replacing the destination. Failure
leaves an existing destination unchanged. Metadata must come from an
authenticated encrypted room event. Does not open a crypto store.
}
4 changes: 3 additions & 1 deletion man/mx_send_media.Rd
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ Event id, or NULL on dry-run.
\description{
Client-layer wrapper over \code{mx.api::mx_send_media()}: resolves the
room by name (or falls back to the config's default room), builds the
session from the client config, and uploads + posts in one call. The
session from the client config, and uploads + posts in one call. Refuses
encrypted rooms before upload; use \code{mx_upload_encrypted()} followed
by \code{mx_send_encrypted()} with the caller's live crypto context. The
msgtype is derived from the file's MIME type unless given.
}
\details{
Expand Down
40 changes: 40 additions & 0 deletions man/mx_upload_encrypted.Rd
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
% tinyrox says don't edit this manually, but it can't stop you!
\name{mx_upload_encrypted}
\alias{mx_upload_encrypted}
\title{Upload an encrypted Matrix attachment}
\usage{
mx_upload_encrypted(
client,
path,
body = basename(path),
msgtype = NULL,
content_type = NULL,
info = list(),
max_bytes = 25 * 1024^2
)
}
\arguments{
\item{client}{Matrix client config.}

\item{path}{Path of the file to upload.}

\item{body}{Display filename or caption, inside the encrypted event.}

\item{msgtype}{Media message type, or NULL to derive it from the MIME type.}

\item{content_type}{MIME type, or NULL to guess from the file extension.}

\item{info}{Extra media metadata, inside the encrypted event.}

\item{max_bytes}{Maximum plaintext size in bytes, default 25 MiB. Encryption
uses memory; larger files require an explicit higher limit.}
}
\value{
Matrix message content with \code{file} instead of \code{url}.
}
\description{
Uploads ciphertext only, with a generic filename and content type.
Returns content to pass to \code{mx_send_encrypted()} using the caller's
existing account and sessions. The return value includes a secret key:
never post it in an unencrypted event. Does not open a crypto store.
}
Loading