mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
refactor: one base64 decoder, from the base64 crate
paint::tile::b64_decode, plugin.install, the macOS monitor-profile reader
and the font SRI helper each hand-rolled base64. The shared decoder took
"====" as one zero byte and padding mid-string ("QQ==QUJD"), and
plugin.install alone took unpadded input. All now use the base64 crate
(already in the tree): standard alphabet, padding optional, whitespace
ignored, anything else refused.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
d7d138b1e5
commit
efb2a6cbc7
8 files changed
+31
-150
No files matched your search
Generated
+2
@@ -5453,6 +5453,7 @@ dependencies = [
|
||||
name = "photocraft-paint"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"photocraft-cms",
|
||||
"photocraft-color",
|
||||
"photocraft-geom",
|
||||
@@ -5545,6 +5546,7 @@ dependencies = [
|
||||
name = "photocraft-text"
|
||||
version = "0.20.1"
|
||||
dependencies = [
|
||||
"base64 0.23.1",
|
||||
"flate2",
|
||||
"parley",
|
||||
"photocraft-color",
|
||||
|
||||
@@ -372,7 +372,7 @@ fn parse_reply(out: &str) -> Detection {
|
||||
let b64 = b64.trim();
|
||||
// An ICC profile starts with its size and carries `acsp` at offset 36; anything else is
|
||||
// treated as no profile (the engine then says the display has none).
|
||||
let icc = (!b64.is_empty()).then(|| base64_decode(b64)).flatten().filter(|b| b.len() >= 132 && b.get(36..40) == Some(b"acsp"));
|
||||
let icc = (!b64.is_empty()).then(|| photocraft_engine::paint::tile::b64_decode(b64)).flatten().filter(|b| b.len() >= 132 && b.get(36..40) == Some(b"acsp"));
|
||||
let profile_name = Some(profile_name.trim().to_string()).filter(|n| !n.is_empty());
|
||||
displays.push(Display { id, name, frame: [x, top, w, h], profile_name, icc: icc.map(std::sync::Arc::new) });
|
||||
}
|
||||
@@ -400,51 +400,10 @@ fn display_id(s: &str) -> Option<u32> {
|
||||
})
|
||||
}
|
||||
|
||||
/// Standard base64 (RFC 4648, with padding) → bytes; `None` on any invalid character.
|
||||
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
|
||||
fn base64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let val = |c: u8| -> Option<u32> {
|
||||
Some(match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return None,
|
||||
} as u32)
|
||||
};
|
||||
let s = s.trim_end_matches('=').as_bytes();
|
||||
let mut out = Vec::with_capacity(s.len() * 3 / 4);
|
||||
for chunk in s.chunks(4) {
|
||||
let mut acc = 0u32;
|
||||
for (i, c) in chunk.iter().enumerate() {
|
||||
acc |= val(*c)? << (18 - 6 * i);
|
||||
}
|
||||
let n = match chunk.len() {
|
||||
4 => 3,
|
||||
3 => 2,
|
||||
2 => 1,
|
||||
_ => return None,
|
||||
};
|
||||
out.extend_from_slice(&acc.to_be_bytes()[1..1 + n]);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base64() {
|
||||
assert_eq!(base64_decode("aGVsbG8=").as_deref(), Some(&b"hello"[..]));
|
||||
assert_eq!(base64_decode("aGVsbG8h").as_deref(), Some(&b"hello!"[..]));
|
||||
assert_eq!(base64_decode("aGk=").as_deref(), Some(&b"hi"[..]));
|
||||
assert_eq!(base64_decode("").as_deref(), Some(&b""[..]));
|
||||
assert!(base64_decode("a").is_none());
|
||||
assert!(base64_decode("a$==").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_replies() {
|
||||
// Only the ICC signature is checked here; parsing is the engine's job.
|
||||
@@ -510,18 +469,7 @@ mod tests {
|
||||
}
|
||||
|
||||
fn base64_encode(b: &[u8]) -> String {
|
||||
const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut s = String::new();
|
||||
for c in b.chunks(3) {
|
||||
let n = c.iter().enumerate().fold(0u32, |n, (i, v)| n | u32::from(*v) << (16 - 8 * i));
|
||||
for i in 0..=c.len() {
|
||||
s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
|
||||
}
|
||||
}
|
||||
while !s.len().is_multiple_of(4) {
|
||||
s.push('=');
|
||||
}
|
||||
s
|
||||
photocraft_engine::paint::tile::b64_encode(b)
|
||||
}
|
||||
|
||||
/// On a Mac, every display is read, and the profiles parse as RGB profiles.
|
||||
|
||||
@@ -160,33 +160,6 @@ pub(crate) fn apply_to_surface(command: &str, params: &Value, surf: &Surface, se
|
||||
/// Largest base64 payload `plugin.install` accepts (the module limit, encoded).
|
||||
const MAX_DATA_CHARS: usize = (32 << 20) / 3 * 4 + 4;
|
||||
|
||||
fn b64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let val = |c: u8| -> Option<u32> {
|
||||
Some(u32::from(match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' | b'-' => 62,
|
||||
b'/' | b'_' => 63,
|
||||
_ => return None,
|
||||
}))
|
||||
};
|
||||
let clean: Vec<u8> = s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').collect();
|
||||
if clean.len() % 4 == 1 {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(clean.len() / 4 * 3 + 2);
|
||||
for chunk in clean.chunks(4) {
|
||||
let mut n = 0u32;
|
||||
for (i, &c) in chunk.iter().enumerate() {
|
||||
n |= val(c)? << (18 - 6 * i);
|
||||
}
|
||||
let bytes = [(n >> 16) as u8, (n >> 8) as u8, n as u8];
|
||||
out.extend_from_slice(bytes.get(..chunk.len() - 1)?);
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
fn install(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "plugin.install";
|
||||
let plugin = if let Some(data) = p.get("data") {
|
||||
@@ -194,7 +167,7 @@ fn install(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
if data.len() > MAX_DATA_CHARS {
|
||||
return Err(bad(CMD, "`data` is larger than the module limit"));
|
||||
}
|
||||
let bytes = b64_decode(data).ok_or_else(|| bad(CMD, "`data` is not valid base64"))?;
|
||||
let bytes = photocraft_paint::tile::b64_decode(data).ok_or_else(|| bad(CMD, "`data` is not valid base64"))?;
|
||||
Plugin::load(&bytes, photocraft_plugins::Limits::default()).map_err(err)?
|
||||
} else if let Some(path) = p.get("path") {
|
||||
let path = path.as_str().filter(|s| !s.is_empty()).ok_or_else(|| bad(CMD, "`path` must be a file path"))?;
|
||||
|
||||
@@ -6,15 +6,7 @@ const INVERT: &[u8] = include_bytes!("../../../../plugins/tests/fixtures/invert.
|
||||
const INVERT_ID: &str = "org.photocraft.example.invert";
|
||||
|
||||
fn b64(b: &[u8]) -> String {
|
||||
const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut out = String::new();
|
||||
for c in b.chunks(3) {
|
||||
let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0));
|
||||
for i in 0..4 {
|
||||
out.push(if i <= c.len() { T[(n >> (18 - 6 * i)) as usize & 63] as char } else { '=' });
|
||||
}
|
||||
}
|
||||
out
|
||||
photocraft_paint::tile::b64_encode(b)
|
||||
}
|
||||
|
||||
/// A WAT plug-in with its own `id` whose `pc_filter` body is `filter`.
|
||||
@@ -324,9 +316,6 @@ fn bad_params_are_errors_not_panics() {
|
||||
}
|
||||
// No document: running is disabled.
|
||||
assert!(Session::new().execute("plugin.run", json!({"id": "x"})).is_err());
|
||||
assert_eq!(b64_decode("aGk="), Some(b"hi".to_vec()));
|
||||
assert_eq!(b64_decode("aGk"), Some(b"hi".to_vec()));
|
||||
assert_eq!(b64_decode("a"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -13,6 +13,8 @@ photocraft-color = { workspace = true }
|
||||
photocraft-raster = { workspace = true }
|
||||
serde = { workspace = true }
|
||||
rustc-hash = { workspace = true }
|
||||
# The tile serde form and commands that take file bytes as base64 text.
|
||||
base64 = "0.23"
|
||||
|
||||
# Large tips rasterize, accumulate and composite in parallel (the same pixels as serially).
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
|
||||
+20
-40
@@ -174,53 +174,21 @@ impl<'de> Deserialize<'de> for GrayTile {
|
||||
}
|
||||
}
|
||||
|
||||
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
/// Base64 with the standard alphabet; decoding takes padded or unpadded input.
|
||||
const B64: base64::engine::GeneralPurpose = base64::engine::GeneralPurpose::new(
|
||||
&base64::alphabet::STANDARD,
|
||||
base64::engine::GeneralPurposeConfig::new().with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent),
|
||||
);
|
||||
|
||||
/// Standard base64 with padding (the tile serde form; commands taking file bytes).
|
||||
pub fn b64_encode(b: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(b.len().div_ceil(3) * 4);
|
||||
for c in b.chunks(3) {
|
||||
let n = (u32::from(c[0]) << 16) | (u32::from(*c.get(1).unwrap_or(&0)) << 8) | u32::from(*c.get(2).unwrap_or(&0));
|
||||
out.push(B64[(n >> 18) as usize & 63] as char);
|
||||
out.push(B64[(n >> 12) as usize & 63] as char);
|
||||
out.push(if c.len() > 1 { B64[(n >> 6) as usize & 63] as char } else { '=' });
|
||||
out.push(if c.len() > 2 { B64[n as usize & 63] as char } else { '=' });
|
||||
}
|
||||
out
|
||||
base64::Engine::encode(&B64, b)
|
||||
}
|
||||
|
||||
/// Decode standard base64 (whitespace ignored); `None` on invalid input.
|
||||
/// Decode standard base64, padded or not (whitespace ignored); `None` on invalid input.
|
||||
pub fn b64_decode(s: &str) -> Option<Vec<u8>> {
|
||||
let val = |c: u8| -> Option<u32> {
|
||||
Some(match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
_ => return None,
|
||||
} as u32)
|
||||
};
|
||||
let s: Vec<u8> = s.bytes().filter(|c| !c.is_ascii_whitespace()).collect();
|
||||
if !s.len().is_multiple_of(4) {
|
||||
return None;
|
||||
}
|
||||
let mut out = Vec::with_capacity(s.len() / 4 * 3);
|
||||
for c in s.chunks(4) {
|
||||
let pad = c.iter().rev().take_while(|&&x| x == b'=').count();
|
||||
let mut n = 0u32;
|
||||
for (i, &x) in c.iter().enumerate() {
|
||||
n = (n << 6) | if i >= 4 - pad { 0 } else { val(x)? };
|
||||
}
|
||||
out.push((n >> 16) as u8);
|
||||
if pad < 2 {
|
||||
out.push((n >> 8) as u8);
|
||||
}
|
||||
if pad < 1 {
|
||||
out.push(n as u8);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
base64::Engine::decode(&B64, s).ok()
|
||||
}
|
||||
|
||||
// ---------- sampling ----------
|
||||
@@ -331,6 +299,18 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_rejects_bad_padding_and_takes_unpadded() {
|
||||
assert_eq!(b64_decode("aGk=").as_deref(), Some(&b"hi"[..]));
|
||||
assert_eq!(b64_decode("aGk").as_deref(), Some(&b"hi"[..]));
|
||||
assert_eq!(b64_decode(" aG\nk= ").as_deref(), Some(&b"hi"[..]));
|
||||
assert_eq!(b64_decode("").as_deref(), Some(&b""[..]));
|
||||
assert_eq!(b64_decode("===="), None);
|
||||
assert_eq!(b64_decode("QQ==QUJD"), None);
|
||||
assert_eq!(b64_decode("a"), None);
|
||||
assert_eq!(b64_decode("a$=="), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tile_serde_round_trip_and_float_form() {
|
||||
let t = GrayTile::from_fn(5, 3, |x, y| (x + y) as f32 / 6.0);
|
||||
|
||||
@@ -20,6 +20,8 @@ photocraft-psd = { workspace = true }
|
||||
parley = { version = "0.11", default-features = false, features = ["std"] }
|
||||
skrifa = "0.44"
|
||||
flate2 = { workspace = true }
|
||||
# Subresource Integrity values for served fonts.
|
||||
base64 = "0.23"
|
||||
|
||||
# ICU dictionary data for Japanese word boundaries and complex-script (Thai, Lao, Khmer, Burmese)
|
||||
# line breaking. Native only: the CJK dictionary alone is 3.8 MB of wasm, and the web build must
|
||||
|
||||
@@ -166,22 +166,7 @@ fn sri(hex: &str) -> Option<String> {
|
||||
return None;
|
||||
}
|
||||
let bytes: Option<Vec<u8>> = (0..32).map(|i| hex.get(2 * i..2 * i + 2).and_then(|h| u8::from_str_radix(h, 16).ok())).collect();
|
||||
Some(format!("sha256-{}", base64(&bytes?)))
|
||||
}
|
||||
|
||||
/// Standard base64 (RFC 4648, with padding).
|
||||
fn base64(data: &[u8]) -> String {
|
||||
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
let mut s = String::with_capacity(data.len().div_ceil(3) * 4);
|
||||
for chunk in data.chunks(3) {
|
||||
let b = |i: usize| u32::from(chunk.get(i).copied().unwrap_or(0));
|
||||
let n = (b(0) << 16) | (b(1) << 8) | b(2);
|
||||
for k in 0..4 {
|
||||
let six = ((n >> (18 - 6 * k)) & 63) as usize;
|
||||
s.push(if k <= chunk.len() { TABLE.get(six).map_or('=', |&c| char::from(c)) } else { '=' });
|
||||
}
|
||||
}
|
||||
s
|
||||
Some(format!("sha256-{}", base64::Engine::encode(&base64::engine::general_purpose::STANDARD, bytes?)))
|
||||
}
|
||||
|
||||
struct State {
|
||||
|
||||
Reference in new issue
Block a user